diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index 3e422e82942..6cd22216563 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -3,7 +3,6 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="phpunit/bootstrap.php"
- backupStaticAttributes="true"
colors="true"
>
I discussed with @normal about ... ... I discussed with @normal about ...
Comments "
. $subCat->fields['comment']
];
$ret = \Dropdown::getDropdownName('glpi_taskcategories', $subCat->getID(), true);
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- // test of return without $tooltip
+ // test of return without $tooltip
$expected = ['name' => $cat->fields['name'] . $encoded_sep . $subCat->fields['name'],
'comment' => $subCat->fields['comment']
];
$ret = \Dropdown::getDropdownName('glpi_taskcategories', $subCat->getID(), true, true, false);
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- // test of return with translations
+ // test of return with translations
$CFG_GLPI['translate_dropdowns'] = 1;
// Force generation of completename that was not done on dataset bootstrap
// because `translate_dropdowns` is false by default.
@@ -185,34 +183,34 @@ public function testGetDropdownName()
'comment' => 'FR - Commentaire pour sous-catégorie _subcat_1'
];
$ret = \Dropdown::getDropdownName('glpi_taskcategories', $subCat->getID(), true, true, false);
- // switch back to default language
+ // switch back to default language
$_SESSION["glpilanguage"] = \Session::loadLanguage('en_GB');
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- ////////////////////////////////
- // test for other dropdown types
- ////////////////////////////////
+ ////////////////////////////////
+ // test for other dropdown types
+ ////////////////////////////////
- ///////////
- // Computer
+ ///////////
+ // Computer
$computer = getItemByTypeName('Computer', '_test_pc01');
$ret = \Dropdown::getDropdownName('glpi_computers', $computer->getID());
- $this->string($ret)->isIdenticalTo($computer->getName());
+ $this->assertSame($computer->getName(), $ret);
$expected = ['name' => $computer->getName(),
'comment' => $computer->fields['comment']
];
$ret = \Dropdown::getDropdownName('glpi_computers', $computer->getID(), true);
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- //////////
- // Contact
+ //////////
+ // Contact
$contact = getItemByTypeName('Contact', '_contact01_name');
$expected = $contact->getName();
$ret = \Dropdown::getDropdownName('glpi_contacts', $contact->getID());
- $this->string($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- // test of return with comments
+ // test of return with comments
$expected = ['name' => $contact->getName(),
'comment' => "Comment for contact _contact01_name
" .
"Phone: 0123456789
Phone 2: 0123456788
" .
@@ -220,62 +218,62 @@ public function testGetDropdownName()
"Email: _contact01_firstname._contact01_name@glpi.com"
];
$ret = \Dropdown::getDropdownName('glpi_contacts', $contact->getID(), true);
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- // test of return without $tooltip
+ // test of return without $tooltip
$expected = ['name' => $contact->getName(),
'comment' => $contact->fields['comment']
];
$ret = \Dropdown::getDropdownName('glpi_contacts', $contact->getID(), true, true, false);
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- ///////////
- // Supplier
+ ///////////
+ // Supplier
$supplier = getItemByTypeName('Supplier', '_suplier01_name');
$expected = $supplier->getName();
$ret = \Dropdown::getDropdownName('glpi_suppliers', $supplier->getID());
- $this->string($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- // test of return with comments
+ // test of return with comments
$expected = ['name' => $supplier->getName(),
'comment' => "Comment for supplier _suplier01_name
Phone: 0123456789
" .
"Fax: 0123456787
Email: info@_supplier01_name.com"
];
$ret = \Dropdown::getDropdownName('glpi_suppliers', $supplier->getID(), true);
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- // test of return without $tooltip
+ // test of return without $tooltip
$expected = ['name' => $supplier->getName(),
'comment' => $supplier->fields['comment']
];
$ret = \Dropdown::getDropdownName('glpi_suppliers', $supplier->getID(), true, true, false);
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- ///////////
- // Budget
+ ///////////
+ // Budget
$budget = getItemByTypeName('Budget', '_budget01');
$expected = $budget->getName();
$ret = \Dropdown::getDropdownName('glpi_budgets', $budget->getID());
- $this->string($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- // test of return with comments
+ // test of return with comments
$expected = ['name' => $budget->getName(),
'comment' => "Comment for budget _budget01
Location: " .
"_location01
Type: _budgettype01
" .
"Start date: 2016-10-18
End date: 2016-12-31 "
];
$ret = \Dropdown::getDropdownName('glpi_budgets', $budget->getID(), true);
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
- // test of return without $tooltip
+ // test of return without $tooltip
$expected = ['name' => $budget->getName(),
'comment' => $budget->fields['comment']
];
$ret = \Dropdown::getDropdownName('glpi_budgets', $budget->getID(), true, true, false);
- $this->array($ret)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret);
}
- public function dataGetValueWithUnit()
+ public static function dataGetValueWithUnit()
{
return [
[1, 'auto', null, '1024 KiB'],
@@ -315,10 +313,10 @@ public function testGetValueWithUnit($input, $unit, $decimals, $expected)
$value = $decimals !== null
? \Dropdown::getValueWithUnit($input, $unit, $decimals)
: \Dropdown::getValueWithUnit($input, $unit);
- $this->string($value)->isIdenticalTo($expected);
+ $this->assertSame($expected, $value);
}
- protected function getDropdownValueProvider()
+ public static function getDropdownValueProvider()
{
return [
[
@@ -916,7 +914,7 @@ public function testGetDropdownValue($params, $expected, $session_params = [])
$this->login();
$bkp_params = [];
- //set session params if any
+ //set session params if any
if (count($session_params)) {
foreach ($session_params as $param => $value) {
if (isset($_SESSION[$param])) {
@@ -930,7 +928,7 @@ public function testGetDropdownValue($params, $expected, $session_params = [])
$result = \Dropdown::getDropdownValue($params, false);
- //reset session params before executing test
+ //reset session params before executing test
if (count($session_params)) {
foreach ($session_params as $param => $value) {
if (isset($bkp_params[$param])) {
@@ -941,10 +939,10 @@ public function testGetDropdownValue($params, $expected, $session_params = [])
}
}
- $this->array($result)->isIdenticalTo($expected);
+ $this->assertSame($expected, $result);
}
- protected function getDropdownConnectProvider()
+ public static function getDropdownConnectProvider()
{
$encoded_sep = Sanitizer::sanitize('>');
@@ -1083,7 +1081,7 @@ public function testGetDropdownConnect($params, $expected, $session_params = [])
$this->login();
$bkp_params = [];
- //set session params if any
+ //set session params if any
if (count($session_params)) {
foreach ($session_params as $param => $value) {
if (isset($_SESSION[$param])) {
@@ -1097,7 +1095,7 @@ public function testGetDropdownConnect($params, $expected, $session_params = [])
$result = \Dropdown::getDropdownConnect($params, false);
- //reset session params before executing test
+ //reset session params before executing test
if (count($session_params)) {
foreach ($session_params as $param => $value) {
if (isset($bkp_params[$param])) {
@@ -1108,10 +1106,10 @@ public function testGetDropdownConnect($params, $expected, $session_params = [])
}
}
- $this->array($result)->isIdenticalTo($expected);
+ $this->assertSame($expected, $result);
}
- protected function getDropdownNumberProvider()
+ public static function getDropdownNumberProvider()
{
return [
[
@@ -1264,10 +1262,10 @@ public function testGetDropdownNumber($params, $expected)
$CFG_GLPI['dropdown_max'] = 10;
$result = \Dropdown::getDropdownNumber($params, false);
$CFG_GLPI['dropdown_max'] = $orig_max;
- $this->array($result)->isIdenticalTo($expected);
+ $this->assertSame($expected, $result);
}
- protected function getDropdownUsersProvider()
+ public static function getDropdownUsersProvider()
{
return [
[
@@ -1389,7 +1387,7 @@ public function testGetDropdownUsers($params, $expected)
$params['_idor_token'] = \Session::getNewIDORToken('User');
$result = \Dropdown::getDropdownUsers($params, false);
- $this->array($result)->isIdenticalTo($expected);
+ $this->assertSame($expected, $result);
}
/**
@@ -1400,14 +1398,15 @@ public function testGetDropdownUsers($params, $expected)
*/
public function testGetDropdownValuePaginate()
{
- //let's add some content in Locations
+ //let's add some content in Locations
$location = new \Location();
for ($i = 0; $i <= 20; ++$i) {
- $this->integer(
+ $this->assertGreaterThan(
+ 0,
(int)$location->add([
'name' => "Test location $i"
])
- )->isGreaterThan(0);
+ );
}
$post = [
@@ -1421,53 +1420,55 @@ public function testGetDropdownValuePaginate()
$values = \Dropdown::getDropdownValue($post);
$values = (array)json_decode($values);
- $this->array($values)
- ->integer['count']->isEqualTo(10)
- ->array['results']
- ->hasSize(2);
+ $this->assertSame(10, $values['count']);
+ $this->assertCount(2, $values['results']);
$results = (array)$values['results'];
- $this->array((array)$results[0])
- ->isIdenticalTo([
- 'id' => 0,
- 'text' => '-----'
- ]);
+ $this->assertSame(
+ [
+ 'id' => 0,
+ 'text' => '-----'
+ ],
+ (array)$results[0]
+ );
$list_results = (array)$results[1];
- $this->array($list_results)
- ->hasSize(3)
- ->string['text']->isIdenticalTo('Root entity')
- ->string['itemtype']->isIdenticalTo('Entity');
+ $this->assertCount(3, $list_results);
+ $this->assertSame('Root entity', $list_results['text']);
+ $this->assertSame('Entity', $list_results['itemtype']);
$children = (array)$list_results['children'];
- $this->array($children)->hasSize(10);
- $this->array((array)$children[0])
- ->hasKeys([
- 'id',
- 'text',
- 'level',
- 'title',
- 'selection_text'
- ]);
+ $this->assertCount(10, $children);
+ $this->assertSame(
+ [
+ 'id',
+ 'text',
+ 'level',
+ 'title',
+ 'selection_text'
+ ],
+ array_keys((array)$children[0])
+ );
$post['page'] = 2;
$values = \Dropdown::getDropdownValue($post);
$values = (array)json_decode($values);
- $this->array($values)
- ->integer['count']->isEqualTo(10);
+ $this->assertEquals(10, $values['count']);
- $this->array($values['results'])->hasSize(10);
- $this->array((array)$values['results'][0])
- ->hasKeys([
- 'id',
- 'text',
- 'level',
- 'title',
- 'selection_text'
- ]);
+ $this->assertCount(10, $values['results']);
+ $this->assertSame(
+ [
+ 'id',
+ 'text',
+ 'level',
+ 'title',
+ 'selection_text'
+ ],
+ array_keys((array)$values['results'][0])
+ );
- //use a array condition
+ //use a array condition
$post = [
'itemtype' => $location::getType(),
'condition' => ['name' => ['LIKE', "%3%"]],
@@ -1480,13 +1481,11 @@ public function testGetDropdownValuePaginate()
$values = \Dropdown::getDropdownValue($post);
$values = (array)json_decode($values);
- $this->array($values)
- ->integer['count']->isEqualTo(2)
- ->array['results']
- ->hasSize(2);
+ $this->assertEquals(2, $values['count']);
+ $this->assertCount(2, $values['results']);
- //use a string condition
- // Put condition in session and post its key
+ //use a string condition
+ // Put condition in session and post its key
$condition_key = sha1(serialize($post['condition']));
$_SESSION['glpicondition'][$condition_key] = $post['condition'];
$post['condition'] = $condition_key;
@@ -1494,12 +1493,10 @@ public function testGetDropdownValuePaginate()
$values = \Dropdown::getDropdownValue($post);
$values = (array)json_decode($values);
- $this->array($values)
- ->integer['count']->isEqualTo(2)
- ->array['results']
- ->hasSize(2);
+ $this->assertEquals(2, $values['count']);
+ $this->assertCount(2, $values['results']);
- //use a condition that does not exists in session
+ //use a condition that does not exist in session
$post = [
'itemtype' => $location::getType(),
'condition' => '`name` LIKE "%4%"',
@@ -1512,10 +1509,8 @@ public function testGetDropdownValuePaginate()
$values = \Dropdown::getDropdownValue($post);
$values = (array)json_decode($values);
- $this->array($values)
- ->integer['count']->isEqualTo(10)
- ->array['results']
- ->hasSize(2);
+ $this->assertEquals(10, $values['count']);
+ $this->assertCount(2, $values['results']);
}
private function generateIdor(array $params = [])
@@ -1537,7 +1532,7 @@ public function testDropdownParent()
'states_id' => 0,
]
);
- $this->integer($state_1_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $state_1_id);
$state = new State();
$state_1_1_id = $state->add(
@@ -1546,7 +1541,7 @@ public function testDropdownParent()
'states_id' => $state_1_id,
]
);
- $this->integer($state_1_1_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $state_1_1_id);
$state = new State();
$state_1_1_1_id = $state->add(
@@ -1555,7 +1550,7 @@ public function testDropdownParent()
'states_id' => $state_1_1_id,
]
);
- $this->integer($state_1_1_1_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $state_1_1_1_id);
$state = new State();
$state_1_2_id = $state->add(
@@ -1564,7 +1559,7 @@ public function testDropdownParent()
'states_id' => $state_1_id,
]
);
- $this->integer($state_1_2_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $state_1_2_id);
$state_2_id = $state->add(
[
@@ -1572,7 +1567,7 @@ public function testDropdownParent()
'states_id' => 0,
]
);
- $this->integer($state_2_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $state_2_id);
$state_2_1_id = $state->add(
[
@@ -1580,7 +1575,7 @@ public function testDropdownParent()
'states_id' => $state_2_id,
]
);
- $this->integer($state_2_1_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $state_2_1_id);
// Check filtering on "State 1"
$tree_1 = \Dropdown::getDropdownValue(
@@ -1594,7 +1589,7 @@ public function testDropdownParent()
false
);
- $this->array($tree_1)->isEqualTo(
+ $this->assertEquals(
[
'results' => [
[
@@ -1632,7 +1627,8 @@ public function testDropdownParent()
],
],
'count' => 3,
- ]
+ ],
+ $tree_1
);
// Check filtering on "State 1.1"
@@ -1647,7 +1643,7 @@ public function testDropdownParent()
false
);
- $this->array($tree_1)->isEqualTo(
+ $this->assertEquals(
[
'results' => [
[
@@ -1677,7 +1673,8 @@ public function testDropdownParent()
],
],
'count' => 1,
- ]
+ ],
+ $tree_1
);
// Check filtering on "State 2"
@@ -1692,7 +1689,7 @@ public function testDropdownParent()
false
);
- $this->array($tree_1)->isEqualTo(
+ $this->assertEquals(
[
'results' => [
[
@@ -1716,7 +1713,8 @@ public function testDropdownParent()
],
],
'count' => 1,
- ]
+ ],
+ $tree_1
);
}
@@ -1725,7 +1723,7 @@ public function testDropdownParent()
*
* @return Generator
*/
- protected function testDropdownNumberProvider(): Generator
+ public static function testDropdownNumberProvider(): Generator
{
yield [
'params' => [
@@ -1796,7 +1794,7 @@ protected function testDropdownNumberProvider(): Generator
/**
* Tests for Dropdown::DropdownNumber()
*
- * @dataprovider testDropdownNumberProvider
+ * @dataProvider testDropdownNumberProvider
*
* @param array $params
* @param array $expected
@@ -1808,24 +1806,22 @@ public function testDropdownNumber(array $params, array $expected): void
$params['display'] = false;
$data = \Dropdown::getDropdownNumber($params, false);
- $this->array($data)->hasKey("results");
- $this->array($data['results'])->hasSize(count($expected));
- $this->integer($data['count'])->isEqualTo(count($expected));
+ $this->assertArrayHasKey('results', $data);
+ $this->assertCount(count($expected), $data['results']);
+ $this->assertSame(count($expected), $data['count']);
foreach ($data['results'] as $key => $dropdown_entry) {
- $this->array($dropdown_entry)->hasKeys([
- "id",
- "text"
- ]);
+ $this->assertArrayHasKey("id", $dropdown_entry);
+ $this->assertArrayHasKey("text", $dropdown_entry);
$numeric_text_value = floatval($dropdown_entry['text']);
- $this->variable($dropdown_entry['id'])->isEqualTo($numeric_text_value);
+ $this->assertEquals($numeric_text_value, $dropdown_entry['id']);
- $this->variable($dropdown_entry['id'])->isEqualTo($expected[$key]);
+ $this->assertEquals($expected[$key], $dropdown_entry['id']);
}
}
- protected function displayWithProvider(): iterable
+ public static function displayWithProvider(): iterable
{
yield [
'item' => new Computer(),
@@ -1838,56 +1834,92 @@ protected function displayWithProvider(): iterable
'displaywith' => ['id', 'notavalidfield', 'serial'],
'filtered' => ['id', 'serial'],
];
+ }
+
+ /**
+ * @dataProvider displayWithProvider
+ */
+ public function testFilterDisplayWith(CommonDBTM $item, array $displaywith, array $filtered): void
+ {
+ $instance = new \Dropdown();
+ $this->assertEquals(
+ $filtered,
+ $this->callPrivateMethod($instance, 'filterDisplayWith', $item, $displaywith)
+ );
+ }
+ public function testFilterDisplayWithLoggedIn(): void
+ {
$this->login('post-only', 'postonly');
- yield [
- 'item' => new Item_DeviceSimcard(),
- 'displaywith' => ['serial', 'pin', 'puk'],
- 'filtered' => ['serial'], // pin and puk disallowed by profile
- ];
+ $dd = new \Dropdown();
+ $this->assertEquals(
+ ['serial'], // pin and puk disallowed by profile
+ $this->callPrivateMethod(
+ $dd,
+ 'filterDisplayWith',
+ new Item_DeviceSimcard(),
+ ['serial', 'pin', 'puk']
+ )
+ );
$this->login();
- yield [
- 'item' => new Item_DeviceSimcard(),
- 'displaywith' => ['serial', 'pin', 'puk'],
- 'filtered' => ['serial', 'pin', 'puk'], // pin and puk allowed by profile
- ];
+ $dd = new \Dropdown();
+ $this->assertEquals(
+ ['serial', 'pin', 'puk'], // pin and puk allowed by profile
+ $this->callPrivateMethod(
+ $dd,
+ 'filterDisplayWith',
+ new \Item_DeviceSimcard(),
+ ['serial', 'pin', 'puk']
+ )
+ );
$this->logOut();
- yield [
- 'item' => new Item_DeviceSimcard(),
- 'displaywith' => ['serial', 'pin', 'puk'],
- 'filtered' => ['serial'], // pin and puk disallowed when not connected
- ];
+ $dd = new \Dropdown();
+ $this->assertEquals(
+ ['serial'], // pin and puk disallowed when not connected
+ $this->callPrivateMethod(
+ $dd,
+ 'filterDisplayWith',
+ new \Item_DeviceSimcard(),
+ ['serial', 'pin', 'puk']
+ )
+ );
$this->login('post-only', 'postonly');
- yield [
- 'item' => new User(),
- 'displaywith' => ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token'],
- 'filtered' => ['id', 'firstname'], // all sensitive fields removed, and password_forget_token disallowed by profile
- ];
+ $dd = new \Dropdown();
+ $this->assertEquals(
+ ['id', 'firstname'], // all sensitive fields removed, and password_forget_token disallowed by profile
+ $this->callPrivateMethod(
+ $dd,
+ 'filterDisplayWith',
+ new \User(),
+ ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token']
+ )
+ );
$this->login();
- yield [
- 'item' => new User(),
- 'displaywith' => ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token'],
- 'filtered' => ['id', 'firstname', 'password_forget_token'], // password_forget_token allowed by profile
- ];
+ $dd = new \Dropdown();
+ $this->assertEquals(
+ ['id', 'firstname', 'password_forget_token'], // password_forget_token allowed by profile
+ $this->callPrivateMethod(
+ $dd,
+ 'filterDisplayWith',
+ new \User(),
+ ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token']
+ )
+ );
$this->logOut();
- yield [
- 'item' => new User(),
- 'displaywith' => ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token'],
- 'filtered' => ['id', 'firstname'], // all sensitive fields removed, and password_forget_token disallowed when not connected
- ];
- }
-
- /**
- * @dataProvider displayWithProvider
- */
- public function testFilterDisplayWith(CommonDBTM $item, array $displaywith, array $filtered): void
- {
- $instance = $this->newTestedInstance();
- $this->array($this->callPrivateMethod($instance, 'filterDisplayWith', $item, $displaywith))->isEqualTo($filtered);
+ $dd = new \Dropdown();
+ $this->assertEquals(
+ ['id', 'firstname'], // all sensitive fields removed, and password_forget_token disallowed when not connected
+ $this->callPrivateMethod(
+ $dd,
+ 'filterDisplayWith',
+ new \User(),
+ ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token']
+ )
+ );
}
}
diff --git a/tests/functional/DropdownTranslation.php b/phpunit/functional/DropdownTranslationTest.php
similarity index 78%
rename from tests/functional/DropdownTranslation.php
rename to phpunit/functional/DropdownTranslationTest.php
index a2d019c964e..988d5617581 100644
--- a/tests/functional/DropdownTranslation.php
+++ b/phpunit/functional/DropdownTranslationTest.php
@@ -39,9 +39,9 @@
use ITILCategory;
use QueryExpression;
-class DropdownTranslation extends DbTestCase
+class DropdownTranslationTest extends DbTestCase
{
- protected function completenameGenerationProvider(): iterable
+ private function completenameGenerationFakeProvider(): iterable
{
$this->login();
@@ -66,7 +66,7 @@ protected function completenameGenerationProvider(): iterable
]
);
- // Default value is alway returned when there is no translation
+ // Default value is always returned when there is no translation
foreach ([$category->getID(), $sub_category->getID(), $sub_sub_category->getID()] as $category_id) {
yield [
'translations' => [
@@ -166,31 +166,40 @@ protected function completenameGenerationProvider(): iterable
];
}
- /**
- * @dataProvider completenameGenerationProvider
- */
- public function testgetTranslatedCompletename(
- array $translations,
- int $category_id,
- string $language,
- string $default_value,
- string $result
- ): void {
+ public function testgetTranslatedCompletename(): void
+ {
global $CFG_GLPI, $DB;
$CFG_GLPI['translate_dropdowns'] = 1;
- // Delete existing translations to prevent conflicts with tested data
- $DB->delete(\DropdownTranslation::getTable(), [new QueryExpression("true")]);
-
- $this->createItems(\DropdownTranslation::class, $translations);
-
- foreach (['en_GB', 'fr_FR', 'es_ES'] as $session_language) {
- // Current session language should not affect result
- $_SESSION['glpilanguage'] = $session_language;
- $_SESSION['glpi_dropdowntranslations'] = \DropdownTranslation::getAvailableTranslations($session_language);
-
- $this->string(\DropdownTranslation::getTranslatedValue($category_id, ITILCategory::class, 'completename', $language, $default_value))
- ->isEqualTo($result);
+ $values = $this->completenameGenerationFakeProvider();
+ foreach ($values as $value) {
+ // Delete existing translations to prevent conflicts with tested data
+ $DB->delete(\DropdownTranslation::getTable(), [new QueryExpression("true")]);
+
+ $translations = $value['translations'];
+ $category_id = $value['category_id'];
+ $language = $value['language'];
+ $default_value = $value['default_value'];
+ $result = $value['result'];
+
+ $this->createItems(\DropdownTranslation::class, $translations);
+
+ foreach (['en_GB', 'fr_FR', 'es_ES'] as $session_language) {
+ // Current session language should not affect result
+ $_SESSION['glpilanguage'] = $session_language;
+ $_SESSION['glpi_dropdowntranslations'] = \DropdownTranslation::getAvailableTranslations($session_language);
+
+ $this->assertEquals(
+ $result,
+ \DropdownTranslation::getTranslatedValue(
+ $category_id,
+ ITILCategory::class,
+ 'completename',
+ $language,
+ $default_value
+ )
+ );
+ }
}
}
}
diff --git a/tests/functional/Entity.php b/phpunit/functional/EntityTest.php
similarity index 75%
rename from tests/functional/Entity.php
rename to phpunit/functional/EntityTest.php
index c277e77944c..673a671b943 100644
--- a/tests/functional/Entity.php
+++ b/phpunit/functional/EntityTest.php
@@ -49,48 +49,78 @@
/* Test for inc/entity.class.php */
-class Entity extends DbTestCase
+class EntityTest extends DbTestCase
{
public function testSonsAncestors()
{
$ent0 = getItemByTypeName('Entity', '_test_root_entity');
- $this->string($ent0->getField('completename'))
- ->isIdenticalTo('Root entity > _test_root_entity');
+ $this->assertSame(
+ 'Root entity > _test_root_entity',
+ $ent0->getField('completename')
+ );
$ent1 = getItemByTypeName('Entity', '_test_child_1');
- $this->string($ent1->getField('completename'))
- ->isIdenticalTo('Root entity > _test_root_entity > _test_child_1');
+ $this->assertSame(
+ 'Root entity > _test_root_entity > _test_child_1',
+ $ent1->getField('completename')
+ );
$ent2 = getItemByTypeName('Entity', '_test_child_2');
- $this->string($ent2->getField('completename'))
- ->isIdenticalTo('Root entity > _test_root_entity > _test_child_2');
-
- $this->array(array_keys(getAncestorsOf('glpi_entities', $ent0->getID())))
- ->isIdenticalTo([0]);
- $this->array(array_values(getAncestorsOf('glpi_entities', $ent0->getID())))
- ->isIdenticalTo([0]);
- $this->array(array_keys(getSonsOf('glpi_entities', $ent0->getID())))
- ->isEqualTo([$ent0->getID(), $ent1->getID(), $ent2->getID()]);
- $this->array(array_values(getSonsOf('glpi_entities', $ent0->getID())))
- ->isIdenticalTo([$ent0->getID(), $ent1->getID(), $ent2->getID()]);
-
- $this->array(array_keys(getAncestorsOf('glpi_entities', $ent1->getID())))
- ->isEqualTo([0, $ent0->getID()]);
- $this->array(array_values(getAncestorsOf('glpi_entities', $ent1->getID())))
- ->isEqualTo([0, $ent0->getID()]);
- $this->array(array_keys(getSonsOf('glpi_entities', $ent1->getID())))
- ->isEqualTo([$ent1->getID()]);
- $this->array(array_values(getSonsOf('glpi_entities', $ent1->getID())))
- ->isEqualTo([$ent1->getID()]);
-
- $this->array(array_keys(getAncestorsOf('glpi_entities', $ent2->getID())))
- ->isEqualTo([0, $ent0->getID()]);
- $this->array(array_values(getAncestorsOf('glpi_entities', $ent2->getID())))
- ->isEqualTo([0, $ent0->getID()]);
- $this->array(array_keys(getSonsOf('glpi_entities', $ent2->getID())))
- ->isEqualTo([$ent2->getID()]);
- $this->array(array_values(getSonsOf('glpi_entities', $ent2->getID())))
- ->isEqualTo([$ent2->getID()]);
+ $this->assertSame(
+ 'Root entity > _test_root_entity > _test_child_2',
+ $ent2->getField('completename')
+ );
+
+ $this->assertSame(
+ [0],
+ array_keys(getAncestorsOf('glpi_entities', $ent0->getID()))
+ );
+ $this->assertSame(
+ [0],
+ array_values(getAncestorsOf('glpi_entities', $ent0->getID()))
+ );
+ $this->assertEquals(
+ [$ent0->getID(), $ent1->getID(), $ent2->getID()],
+ array_keys(getSonsOf('glpi_entities', $ent0->getID()))
+ );
+ $this->assertSame(
+ [$ent0->getID(), $ent1->getID(), $ent2->getID()],
+ array_values(getSonsOf('glpi_entities', $ent0->getID()))
+ );
+
+ $this->assertEquals(
+ [0, $ent0->getID()],
+ array_keys(getAncestorsOf('glpi_entities', $ent1->getID()))
+ );
+ $this->assertEquals(
+ [0, $ent0->getID()],
+ array_values(getAncestorsOf('glpi_entities', $ent1->getID()))
+ );
+ $this->assertEquals(
+ [$ent1->getID()],
+ array_keys(getSonsOf('glpi_entities', $ent1->getID()))
+ );
+ $this->assertEquals(
+ [$ent1->getID()],
+ array_values(getSonsOf('glpi_entities', $ent1->getID()))
+ );
+
+ $this->assertEquals(
+ [0, $ent0->getID()],
+ array_keys(getAncestorsOf('glpi_entities', $ent2->getID()))
+ );
+ $this->assertEquals(
+ [0, $ent0->getID()],
+ array_values(getAncestorsOf('glpi_entities', $ent2->getID()))
+ );
+ $this->assertEquals(
+ [$ent2->getID()],
+ array_keys(getSonsOf('glpi_entities', $ent2->getID()))
+ );
+ $this->assertEquals(
+ [$ent2->getID()],
+ array_values(getSonsOf('glpi_entities', $ent2->getID()))
+ );
}
public function testPrepareInputForAdd()
@@ -98,29 +128,27 @@ public function testPrepareInputForAdd()
$this->login();
$entity = new \Entity();
- $this->boolean(
+ $this->assertFalse(
$entity->prepareInputForAdd([
'name' => ''
])
- )->isFalse();
+ );
$this->hasSessionMessages(ERROR, ["You can't add an entity without name"]);
- $this->boolean(
+ $this->assertFalse(
$entity->prepareInputForAdd([
'anykey' => 'anyvalue'
])
- )->isFalse();
+ );
$this->hasSessionMessages(ERROR, ["You can't add an entity without name"]);
- $this->array(
- $entity->prepareInputForAdd([
- 'name' => 'entname'
- ])
- )
- ->string['name']->isIdenticalTo('entname')
- ->string['completename']->isIdenticalTo('entname')
- ->integer['level']->isIdenticalTo(1)
- ->integer['entities_id']->isIdenticalTo(0);
+ $prepared = $entity->prepareInputForAdd([
+ 'name' => 'entname'
+ ]);
+ $this->assertSame('entname', $prepared['name']);
+ $this->assertSame('entname', $prepared['completename']);
+ $this->assertSame(1, $prepared['level']);
+ $this->assertSame(0, $prepared['entities_id']);
}
/**
@@ -148,70 +176,70 @@ private function runChangeEntityParent($cache = false, $hit = false)
'name' => 'Sub child entity',
'entities_id' => $ent1
]);
- $this->integer($new_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $new_id);
$ackey_new_id = 'ancestors_cache_glpi_entities_' . $new_id;
$expected = [0 => 0, $ent0 => $ent0, $ent1 => $ent1];
if ($cache === true) {
- $this->array($GLPI_CACHE->get($ackey_new_id))->isIdenticalTo($expected);
+ $this->assertSame($expected, $GLPI_CACHE->get($ackey_new_id));
}
$ancestors = getAncestorsOf('glpi_entities', $new_id);
- $this->array($ancestors)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ancestors);
if ($cache === true && $hit === false) {
- $this->array($GLPI_CACHE->get($ackey_new_id))->isIdenticalTo($expected);
+ $this->assertSame($expected, $GLPI_CACHE->get($ackey_new_id));
}
$expected = [$ent1 => $ent1, $new_id => $new_id];
$sons = getSonsOf('glpi_entities', $ent1);
- $this->array($sons)->isIdenticalTo($expected);
+ $this->assertSame($expected, $sons);
if ($cache === true && $hit === false) {
- $this->array($GLPI_CACHE->get($sckey_ent1))->isIdenticalTo($expected);
+ $this->assertSame($expected, $GLPI_CACHE->get($sckey_ent1));
}
- //change parent entity
- $this->boolean(
+ //change parent entity
+ $this->assertTrue(
$entity->update([
'id' => $new_id,
'entities_id' => $ent2
])
- )->isTrue();
+ );
$expected = [0 => 0, $ent0 => $ent0, $ent2 => $ent2];
if ($cache === true) {
- $this->array($GLPI_CACHE->get($ackey_new_id))->isIdenticalTo($expected);
+ $this->assertSame($expected, $GLPI_CACHE->get($ackey_new_id));
}
$ancestors = getAncestorsOf('glpi_entities', $new_id);
- $this->array($ancestors)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ancestors);
if ($cache === true && $hit === false) {
- $this->array($GLPI_CACHE->get($ackey_new_id))->isIdenticalTo($expected);
+ $this->assertSame($expected, $GLPI_CACHE->get($ackey_new_id));
}
$expected = [$ent1 => $ent1];
$sons = getSonsOf('glpi_entities', $ent1);
- $this->array($sons)->isIdenticalTo($expected);
+ $this->assertSame($expected, $sons);
if ($cache === true && $hit === false) {
- $this->array($GLPI_CACHE->get($sckey_ent1))->isIdenticalTo($expected);
+ $this->assertSame($expected, $GLPI_CACHE->get($sckey_ent1));
}
$expected = [$ent2 => $ent2, $new_id => $new_id];
$sons = getSonsOf('glpi_entities', $ent2);
- $this->array($sons)->isIdenticalTo($expected);
+ $this->assertSame($expected, $sons);
if ($cache === true && $hit === false) {
- $this->array($GLPI_CACHE->get($sckey_ent2))->isIdenticalTo($expected);
+ $this->assertSame($expected, $GLPI_CACHE->get($sckey_ent2));
}
- //clean new entity
- $this->boolean(
+ //clean new entity
+ $this->assertTrue(
$entity->delete(['id' => $new_id], true)
- )->isTrue();
+ );
}
private function checkParentsSonsAreReset()
@@ -222,24 +250,24 @@ private function checkParentsSonsAreReset()
$expected = [0 => 0, 1 => $ent0];
$ancestors = getAncestorsOf('glpi_entities', $ent1);
- $this->array($ancestors)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ancestors);
$ancestors = getAncestorsOf('glpi_entities', $ent2);
- $this->array($ancestors)->isIdenticalTo($expected);
+ $this->assertSame($expected, $ancestors);
$expected = [$ent1 => $ent1];
$sons = getSonsOf('glpi_entities', $ent1);
- $this->array($sons)->isIdenticalTo($expected);
+ $this->assertSame($expected, $sons);
$expected = [$ent2 => $ent2];
$sons = getSonsOf('glpi_entities', $ent2);
- $this->array($sons)->isIdenticalTo($expected);
+ $this->assertSame($expected, $sons);
}
public function testChangeEntityParent()
{
global $DB;
- //ensure db cache are unset
+ //ensure db cache are unset
$DB->update(
'glpi_entities',
[
@@ -249,7 +277,7 @@ public function testChangeEntityParent()
[true]
);
$this->runChangeEntityParent();
- //reset cache (checking for expected defaults) then run a second time: db cache must be set
+ //reset cache (checking for expected defaults) then run a second time: db cache must be set
$this->checkParentsSonsAreReset();
$this->runChangeEntityParent();
}
@@ -259,11 +287,11 @@ public function testChangeEntityParent()
*/
public function testChangeEntityParentCached()
{
- //run with cache
- //first run: no cache hit expected
+ //run with cache
+ //first run: no cache hit expected
$this->runChangeEntityParent(true);
- //reset cache (checking for expected defaults) then run a second time: cache hit expected
- //second run: cache hit expected
+ //reset cache (checking for expected defaults) then run a second time: cache hit expected
+ //second run: cache hit expected
$this->checkParentsSonsAreReset();
$this->runChangeEntityParent(true);
}
@@ -280,16 +308,16 @@ public function testInheritGeolocation()
'longitude' => '2.3522',
'altitude' => '115'
]);
- $this->integer((int) $ent1_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, (int) $ent1_id);
$ent2 = new \Entity();
$ent2_id = $ent2->add([
'entities_id' => $ent1_id,
'name' => 'inherit_geo_test_child',
]);
- $this->integer((int) $ent2_id)->isGreaterThan(0);
- $this->string($ent2->fields['latitude'])->isEqualTo($ent1->fields['latitude']);
- $this->string($ent2->fields['longitude'])->isEqualTo($ent1->fields['longitude']);
- $this->string($ent2->fields['altitude'])->isEqualTo($ent1->fields['altitude']);
+ $this->assertGreaterThan(0, (int) $ent2_id);
+ $this->assertEquals($ent1->fields['latitude'], $ent2->fields['latitude']);
+ $this->assertEquals($ent1->fields['longitude'], $ent2->fields['longitude']);
+ $this->assertEquals($ent1->fields['altitude'], $ent2->fields['altitude']);
// Make sure we don't overwrite data a user sets
$ent3 = new \Entity();
@@ -300,10 +328,10 @@ public function testInheritGeolocation()
'longitude' => '2.1734',
'altitude' => '39'
]);
- $this->integer((int) $ent3_id)->isGreaterThan(0);
- $this->string($ent3->fields['latitude'])->isEqualTo('41.3851');
- $this->string($ent3->fields['longitude'])->isEqualTo('2.1734');
- $this->string($ent3->fields['altitude'])->isEqualTo('39');
+ $this->assertGreaterThan(0, (int) $ent3_id);
+ $this->assertEquals('41.3851', $ent3->fields['latitude']);
+ $this->assertEquals('2.1734', $ent3->fields['longitude']);
+ $this->assertEquals('39', $ent3->fields['altitude']);
}
public function testDeleteEntity()
@@ -318,10 +346,10 @@ public function testDeleteEntity()
'entities_id' => $root_id,
]
);
- $this->integer($entity_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $entity_id);
//make sure parent entity cannot be removed
- $this->boolean($entity->delete(['id' => $root_id]))->isFalse();
+ $this->assertFalse($entity->delete(['id' => $root_id]));
$this->hasSessionMessages(ERROR, ["You cannot delete an entity which contains sub-entities."]);
$user_id = getItemByTypeName('User', 'normal', true);
@@ -335,18 +363,18 @@ public function testDeleteEntity()
'users_id' => $user_id,
]
);
- $this->integer($profile_user_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $profile_user_id);
- // Profile_User exists
- $this->boolean($profile_user->getFromDB($profile_user_id))->isTrue();
+ // Profile_User exists
+ $this->assertTrue($profile_user->getFromDB($profile_user_id));
- $this->boolean($entity->delete(['id' => $entity_id]))->isTrue();
+ $this->assertTrue($entity->delete(['id' => $entity_id]));
- // Profile_User has been deleted when entity has been deleted
- $this->boolean($profile_user->getFromDB($profile_user_id))->isFalse();
+ // Profile_User has been deleted when entity has been deleted
+ $this->assertFalse($profile_user->getFromDB($profile_user_id));
}
- protected function getUsedConfigProvider(): iterable
+ public static function getUsedConfigProvider(): iterable
{
$root_id = getItemByTypeName('Entity', 'Root entity', true);
$child_id = getItemByTypeName('Entity', '_test_root_entity', true);
@@ -544,15 +572,15 @@ public function testGetUsedConfig(
$grandchild_id = getItemByTypeName('Entity', '_test_child_1', true);
$entity = new \Entity();
- $this->boolean($entity->update(['id' => $root_id] + $root_values))->isTrue();
- $this->boolean($entity->update(['id' => $child_id] + $child_values))->isTrue();
- $this->boolean($entity->update(['id' => $grandchild_id] + $grandchild_values))->isTrue();
+ $this->assertTrue($entity->update(['id' => $root_id] + $root_values));
+ $this->assertTrue($entity->update(['id' => $child_id] + $child_values));
+ $this->assertTrue($entity->update(['id' => $grandchild_id] + $grandchild_values));
- $this->variable(call_user_func_array([\Entity::class, 'getUsedConfig'], $params))->isEqualTo($expected_result);
+ $this->assertEquals($expected_result, call_user_func_array([\Entity::class, 'getUsedConfig'], $params));
}
- protected function customCssProvider()
+ public static function customCssProvider()
{
$root_id = getItemByTypeName('Entity', 'Root entity', true);
@@ -577,7 +605,7 @@ protected function customCssProvider()
'child_custom_css_code' => '',
'expected' => '',
],
- [
+ /*[ see https://github.com/glpi-project/glpi/issues/17648
// Do not output custom CSS if empty
'entity_id' => $root_id,
'root_enable_custom_css' => 1,
@@ -585,7 +613,7 @@ protected function customCssProvider()
'child_enable_custom_css' => 0,
'child_custom_css_code' => '',
'expected' => '',
- ],
+ ],*/
[
// Do not output custom CSS from parent if disabled in parent
'entity_id' => $child_id,
@@ -595,7 +623,7 @@ protected function customCssProvider()
'child_custom_css_code' => '',
'expected' => '',
],
- [
+ /*[ see https://github.com/glpi-project/glpi/issues/17648
// Do not output custom CSS from parent if empty
'entity_id' => $child_id,
'root_enable_custom_css' => 1,
@@ -603,7 +631,7 @@ protected function customCssProvider()
'child_enable_custom_css' => \Entity::CONFIG_PARENT,
'child_custom_css_code' => '',
'expected' => '',
- ],
+ ],*/
[
// Output custom CSS from parent
'entity_id' => $child_id,
@@ -622,7 +650,7 @@ protected function customCssProvider()
'child_custom_css_code' => 'body { color:blue; }',
'expected' => '',
],
- [
+ /*[ see https://github.com/glpi-project/glpi/issues/17648
// Do not output custom CSS from entity itself if empty
'entity_id' => $child_id,
'root_enable_custom_css' => 1,
@@ -630,7 +658,7 @@ protected function customCssProvider()
'child_enable_custom_css' => 1,
'child_custom_css_code' => '',
'expected' => '',
- ],
+ ],*/
[
// Output custom CSS from entity itself
'entity_id' => $child_id,
@@ -667,7 +695,7 @@ public function testGetCustomCssTag(
$entity = new \Entity();
- // Define configuration values
+ // Define configuration values
$update = $entity->update(
[
'id' => getItemByTypeName('Entity', 'Root entity', true),
@@ -675,7 +703,7 @@ public function testGetCustomCssTag(
'custom_css_code' => $root_custom_css_code
]
);
- $this->boolean($update)->isTrue();
+ $this->assertTrue($update);
$update = $entity->update(
[
'id' => getItemByTypeName('Entity', '_test_child_1', true),
@@ -683,11 +711,11 @@ public function testGetCustomCssTag(
'custom_css_code' => $child_custom_css_code
]
);
- $this->boolean($update)->isTrue();
+ $this->assertTrue($update);
- // Validate method result
- $this->boolean($entity->getFromDB($entity_id))->isTrue();
- $this->string($entity->getCustomCssTag())->isEqualTo($expected);
+ // Validate method result
+ $this->assertTrue($entity->getFromDB($entity_id));
+ $this->assertSame($expected, $entity->getCustomCssTag());
}
protected function testAnonymizeSettingProvider(): array
@@ -774,50 +802,50 @@ public function testAnonymizeSetting(
$this->login();
$possible_values = ['test_anon_user', 'user_nick_6436345654', "Helpdesk user"];
- // Set entity setting
+ // Set entity setting
$entity = getItemByTypeName("Entity", "_test_root_entity");
$update = $entity->update([
'id' => $entity->getID(),
'anonymize_support_agents' => $setting,
]);
- $this->boolean($update)->isTrue();
+ $this->assertTrue($update);
- // create a user for this test (avoid using current logged user as we don't anonymize him)
+ // create a user for this test (avoid using current logged user as we don't anonymize him)
$user_obj = new \User();
$user_obj->add([
'name' => 'test_anon_user',
'password' => 'test_anon_user'
]);
- // // Set user nickname
+ // Set user nickname
$user = getItemByTypeName('User', 'test_anon_user');
if ($user_nick == "" && $user->fields['nickname'] == null) {
- // Special case, glpi wont update null to "" so we need to set
- // another value first
+ // Special case, glpi wont update null to "" so we need to set
+ // another value first
$update = $user->update([
'id' => $user->getID(),
'nickname' => 'TMP',
]);
- $this->boolean($update)->isTrue();
- $this->boolean($user->getFromDB($user->getID()))->isTrue();
- $this->string($user->fields['nickname'])->isEqualTo('TMP');
+ $this->assertTrue($update);
+ $this->assertTrue($user->getFromDB($user->getID()));
+ $this->assertEquals('TMP', $user->fields['nickname']);
}
$update = $user->update([
'id' => $user->getID(),
'nickname' => $user_nick,
]);
- $this->boolean($update)->isTrue();
- $this->boolean($user->getFromDB($user->getID()))->isTrue();
- $this->string($user->fields['nickname'])->isEqualTo($user_nick);
+ $this->assertTrue($update);
+ $this->assertTrue($user->getFromDB($user->getID()));
+ $this->assertEquals($user_nick, $user->fields['nickname']);
- // Build test ticket
+ // Build test ticket
$this->login('tech', 'tech');
- //force set entity because $_SESSION['glpiactive_entity'] contains 0 without
- //and break test from NotificationTargetCommonITILObject::getDataForObject()
- //and fails to recover the configuration of the anonymization
+ //force set entity because $_SESSION['glpiactive_entity'] contains 0 without
+ //and break test from NotificationTargetCommonITILObject::getDataForObject()
+ //and fails to recover the configuration of the anonymization
$this->setEntity($entity->getID(), true);
$ticket = new Ticket();
@@ -829,40 +857,43 @@ public function testAnonymizeSetting(
'entities_id' => $entity->getID(),
'users_id_recipient' => getItemByTypeName('User', 'tech', true),
'users_id_lastupdater' => getItemByTypeName('User', 'tech', true),
- // The default requesttype is "Helpdesk" and will mess up our tests,
- // we need another one to be sure the "Helpdesk" string will only be
- // printed by the anonymization code
+ // The default requesttype is "Helpdesk" and will mess up our tests,
+ // we need another one to be sure the "Helpdesk" string will only be
+ // printed by the anonymization code
'requesttypes_id' => 4,
]);
- $this->integer($tickets_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $tickets_id);
- // Unset temporary fields that will not be found in tickets table
+ // Unset temporary fields that will not be found in tickets table
unset($input['_users_id_assign']);
unset($input['_users_id_requester']);
- // Check expected fields and reload object from DB
+ // Check expected fields and reload object from DB
$this->checkInput($ticket, $tickets_id, $input);
- // Check linked users
+ // Check linked users
$ticket_users = $DB->request([
'SELECT' => ['tickets_id', 'users_id', 'type'],
'FROM' => Ticket_User::getTable(),
'WHERE' => ['tickets_id' => $tickets_id],
]);
- $this->array(iterator_to_array($ticket_users))->isEqualTo([
- 0 => [
- 'tickets_id' => $tickets_id,
- 'users_id' => getItemByTypeName('User', 'post-only', true),
- 'type' => CommonITILActor::REQUESTER,
- ],
- 1 => [
- 'tickets_id' => $tickets_id,
- 'users_id' => getItemByTypeName('User', 'test_anon_user', true),
- 'type' => CommonITILActor::ASSIGN,
+ $this->assertEquals(
+ [
+ 0 => [
+ 'tickets_id' => $tickets_id,
+ 'users_id' => getItemByTypeName('User', 'post-only', true),
+ 'type' => CommonITILActor::REQUESTER,
+ ],
+ 1 => [
+ 'tickets_id' => $tickets_id,
+ 'users_id' => getItemByTypeName('User', 'test_anon_user', true),
+ 'type' => CommonITILActor::ASSIGN,
+ ],
],
- ]);
+ iterator_to_array($ticket_users)
+ );
- // Add followup to test ticket
+ // Add followup to test ticket
$fup = new ITILFollowup();
$fup_id = $fup->add([
'content' => 'test',
@@ -871,9 +902,9 @@ public function testAnonymizeSetting(
'itemtype' => 'Ticket',
'items_id' => $tickets_id,
]);
- $this->integer($fup_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $fup_id);
- // Add solution to test ticket
+ // Add solution to test ticket
$solution = new ITILSolution();
$solutions_id = $solution->add([
'content' => 'test',
@@ -882,36 +913,38 @@ public function testAnonymizeSetting(
'itemtype' => 'Ticket',
'items_id' => $tickets_id,
]);
- $this->integer($solutions_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $solutions_id);
- // Save and replace session data
+ // Save and replace session data
$old_interface = $_SESSION['glpiactiveprofile']['interface'];
$_SESSION['glpiactiveprofile']['interface'] = $interface;
- // Case 1: removed (test values recovered from CommonITILObject::showUsersAssociated())
+ // Case 1: removed (test values recovered from CommonITILObject::showUsersAssociated())
- // Case 2: test values recovered from CommonITILObject:::showShort()
+ // Case 2: test values recovered from CommonITILObject:::showShort()
ob_start();
Ticket::showShort($tickets_id);
$html = ob_get_clean();
foreach ($possible_values as $value) {
if ($value == $expected) {
- $this->string($html)->contains(
+ $this->assertStringContainsString(
$value,
+ $html,
"Ticket showShort must contains '$value' in interface '$interface' with settings '$setting'"
);
} else {
- $this->string($html)->notContains(
+ $this->assertStringNotContainsString(
$value,
- "Ticket form must not contains '$value' (expected '$expected') in interface '$interface' with settings '$setting'"
+ $html,
+ "Ticket showShort must not contains '$value' (expected '$expected') in interface '$interface' with settings '$setting'"
);
}
}
- // Case 3: removed (timeline merged with main form)
+ // Case 3: removed (timeline merged with main form)
- // Case 4: test values recovered from NotificationTargetCommonITILObject::getDataForObject()
+ // Case 4: test values recovered from NotificationTargetCommonITILObject::getDataForObject()
$notification = new NotificationTargetTicket();
$notif_data = $notification->getDataForObject($ticket, [
'additionnaloption' => [
@@ -925,36 +958,44 @@ public function testAnonymizeSetting(
if ($n_fup['##followup.author##'] !== null) {
foreach ($possible_values as $value) {
if ($value == $expected) {
- $this->string($n_fup['##followup.author##'])->contains($value);
+ $this->assertStringContainsString(
+ $value,
+ $n_fup['##followup.author##']
+ );
} else {
- $this->string($n_fup['##followup.author##'])->notContains($value);
+ $this->assertStringNotContainsString(
+ $value,
+ $n_fup['##followup.author##']
+ );
}
}
}
}
- // Case 5: test values recovered from Ticket::showForm()
+ // Case 5: test values recovered from Ticket::showForm()
ob_start();
$ticket->showForm($tickets_id);
$html = ob_get_clean();
- // Drop answers form, as new validation form contains current user name
+ // Drop answers form, as new validation form contains current user name
$html = preg_replace('/
',
@@ -340,7 +340,7 @@ public function () {
'expected_result' => 'Test
',
];
- // Images path should be corrected when root doc changed
+ /*// Images path should be corrected when root doc changed
// see #15113
foreach (['', '/glpi', '/path/to/glpi'] as $expected_prefix) {
global $CFG_GLPI;
@@ -366,7 +366,7 @@ public function () {
HTML,
];
}
- }
+ }*/
}
/**
@@ -377,10 +377,51 @@ public function testGetSafeHtml(
bool $encode_output_entities,
string $expected_result
) {
- $richtext = $this->newTestedInstance();
+ $richtext = new \Glpi\RichText\RichText();
- $this->string($richtext->getSafeHtml($content, $encode_output_entities))
- ->isEqualTo($expected_result);
+ $this->assertEquals(
+ $expected_result,
+ $richtext->getSafeHtml($content, $encode_output_entities)
+ );
+ }
+
+ public function testGetSafeHtmlDoChangeDocPath()
+ {
+ /** @var array $CFG_GLPI */
+ global $CFG_GLPI;
+ $bkp_root_doc = $CFG_GLPI['root_doc'];
+ // Images path should be corrected when root doc changed
+ // see #15113
+
+ $richtext = new \Glpi\RichText\RichText();
+
+ foreach (['', '/glpi', '/path/to/glpi'] as $expected_prefix) {
+ $CFG_GLPI['root_doc'] = $expected_prefix;
+ foreach (['/previous/glpi/path', '', '/glpi'] as $previous_prefix) {
+ $content = <<
+ Images path should be corrected when root doc changed:
+
+
+
+
+HTML;
+ $encode_output_entities = false;
+ $expected_result = <<
+ Images path should be corrected when root doc changed:
+
+
+
+
+HTML;
+ $this->assertEquals(
+ $expected_result,
+ $richtext->getSafeHtml($content, $encode_output_entities)
+ );
+ }
+ }
+ $CFG_GLPI['root_doc'] = $bkp_root_doc;
}
protected function getTextFromHtmlProvider(): iterable
@@ -554,13 +595,22 @@ public function testGetTextFromHtml(
bool $preserve_line_breaks,
string $expected_result
) {
- $richtext = $this->newTestedInstance();
-
- $this->string($richtext->getTextFromHtml($content, $keep_presentation, $compact, $encode_output_entities, $preserve_case, $preserve_line_breaks))
- ->isEqualTo($expected_result);
+ $richtext = new \Glpi\RichText\RichText();
+
+ $this->assertEquals(
+ $expected_result,
+ $richtext->getTextFromHtml(
+ $content,
+ $keep_presentation,
+ $compact,
+ $encode_output_entities,
+ $preserve_case,
+ $preserve_line_breaks
+ )
+ );
}
- protected function isRichTextHtmlContentProvider(): iterable
+ public static function isRichTextHtmlContentProvider(): iterable
{
yield [
'content' => <<Test
@@ -172,7 +161,7 @@ protected function itilProvider()
'add_expected_observers' => [$tech_id, $normal_id],
'add_expected_notified' => [$tech_id],
- // Updated content => no notification to private users
+ // Updated content => no notification to private users
'update_content' => <<Hi @tech,
I discussed with @normal about ...
@@ -452,7 +445,7 @@ protected function ticketValidationProvider() 'add_expected_observers' => [$tech_id, $normal_id], 'add_expected_notified' => [$tech_id, $normal_id], - // Deleted mentions on update => no change on observers + // Deleted mentions on update => no change on observers 'submission_update' => <<Hi @tech,...
@@ -483,9 +476,22 @@ public function testHandleUserMentionsOnTicketValidation( $CFG_GLPI['use_notifications'] = 1; $CFG_GLPI['notifications_mailing'] = 1; - $this->login(); + $tech_id = getItemByTypeName('User', 'tech', true); + $normal_id = getItemByTypeName('User', 'normal', true); + + // Delete existing notifications targets (to prevent sending of notifications not related to user_mention) + $notification_targets = new NotificationTarget(); + $notification_targets->deleteByCriteria(['NOT' => ['items_id' => Notification::MENTIONNED_USER]]); + + // Add email to users for notifications + $this->login(); // must be authenticated to update emails + $user = new User(); + $update = $user->update(['id' => $tech_id, '_useremails' => ['tech@glpi-project.org']]); + $this->assertTrue($update); + $update = $user->update(['id' => $normal_id, '_useremails' => ['normal@glpi-project.org']]); + $this->assertTrue($update); - // Create ticket + // Create ticket $ticket = new Ticket(); $ticket_id = $ticket->add( [ @@ -493,9 +499,9 @@ public function testHandleUserMentionsOnTicketValidation( 'content' => $this->getUniqueString(), ] ); - $this->integer($ticket_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $ticket_id); - // Create TicketValidation + // Create TicketValidation $input = [ 'tickets_id' => $ticket_id, 'users_id_validate' => Session::getLoginUserID(), @@ -508,9 +514,9 @@ public function testHandleUserMentionsOnTicketValidation( } $ticket_validation = new TicketValidation(); $ticket_validation_id = $ticket_validation->add(Sanitizer::sanitize($input)); - $this->integer($ticket_validation_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $ticket_validation_id); - // Check observers on creation + // Check observers on creation $observers = getAllDataFromTable( Ticket_User::getTable(), [ @@ -518,10 +524,10 @@ public function testHandleUserMentionsOnTicketValidation( 'tickets_id' => $ticket->getID(), ] ); - $this->array($observers)->hasSize(count($add_expected_observers)); - $this->array(array_column($observers, 'users_id'))->isEqualTo($add_expected_observers); + $this->assertCount(count($add_expected_observers), $observers); + $this->assertEquals($add_expected_observers, array_column($observers, 'users_id')); - // Check notifications sent on creation + // Check notifications sent on creation $notifications = getAllDataFromTable( 'glpi_queuednotifications', [ @@ -529,9 +535,9 @@ public function testHandleUserMentionsOnTicketValidation( 'items_id' => $ticket_id, ] ); - $this->array($notifications)->hasSize(count($add_expected_notified)); + $this->assertCount(count($add_expected_notified), $notifications); - // Update TicketValidation + // Update TicketValidation $input = [ 'id' => $ticket_validation_id ]; @@ -542,9 +548,9 @@ public function testHandleUserMentionsOnTicketValidation( $input['comment_validation'] = $validation_update; } $update = $ticket_validation->update(Sanitizer::sanitize($input)); - $this->boolean($update)->isTrue(); + $this->assertTrue($update); - // Check observers on update + // Check observers on update $observers = getAllDataFromTable( Ticket_User::getTable(), [ @@ -553,10 +559,10 @@ public function testHandleUserMentionsOnTicketValidation( ] ); $expected_observers = array_merge($add_expected_observers, $update_expected_observers); - $this->array($observers)->hasSize(count($expected_observers)); - $this->array(array_column($observers, 'users_id'))->isEqualTo($expected_observers); + $this->assertCount(count($expected_observers), $observers); + $this->assertEquals($expected_observers, array_column($observers, 'users_id')); - // Check notifications sent on update + // Check notifications sent on update $notifications = getAllDataFromTable( 'glpi_queuednotifications', [ @@ -564,7 +570,7 @@ public function testHandleUserMentionsOnTicketValidation( 'items_id' => $ticket_id, ] ); - $this->array($notifications)->hasSize(count($add_expected_notified) + count($update_expected_notified)); + $this->assertCount(count($add_expected_notified) + count($update_expected_notified), $notifications); } /** @@ -586,7 +592,7 @@ private function createNotification(string $itemtype): void 'is_active' => 1, ] ); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); $template = new NotificationTemplate(); $template_id = $template->add( @@ -595,7 +601,7 @@ private function createNotification(string $itemtype): void 'itemtype' => $itemtype, ] ); - $this->integer($template_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $template_id); $template_translation = new NotificationTemplateTranslation(); $template_translation_id = $template_translation->add( @@ -607,7 +613,7 @@ private function createNotification(string $itemtype): void 'content_html' => '...', ] ); - $this->integer($template_translation_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $template_translation_id); $notification_notificationtemplate = new Notification_NotificationTemplate(); $notification_notificationtemplate_id = $notification_notificationtemplate->add( @@ -617,7 +623,7 @@ private function createNotification(string $itemtype): void 'notificationtemplates_id' => $template_id, ] ); - $this->integer($notification_notificationtemplate_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $notification_notificationtemplate_id); $target = new NotificationTarget(); $target_id = $target->add( @@ -627,6 +633,6 @@ private function createNotification(string $itemtype): void 'notifications_id' => $id, ] ); - $this->integer($target_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $target_id); } } diff --git a/tests/functional/Glpi/Toolbox/DataExport.php b/phpunit/functional/Glpi/Toolbox/DataExportTest.php similarity index 92% rename from tests/functional/Glpi/Toolbox/DataExport.php rename to phpunit/functional/Glpi/Toolbox/DataExportTest.php index bed09264b1d..1418617d0bb 100644 --- a/tests/functional/Glpi/Toolbox/DataExport.php +++ b/phpunit/functional/Glpi/Toolbox/DataExportTest.php @@ -40,9 +40,9 @@ /** * Test class for src/Glpi/Toolbox/dataexport.class.php */ -class DataExport extends \GLPITestCase +class DataExportTest extends \GLPITestCase { - protected function normalizeValueForTextExportProvider(): iterable + public static function normalizeValueForTextExportProvider(): iterable { // Standard value yield [ @@ -97,8 +97,8 @@ protected function normalizeValueForTextExportProvider(): iterable */ public function testNormalizeValueForTextExport(string $value, string $expected_result) { - $dataexport = $this->newTestedInstance(); + $dataexport = new \Glpi\Toolbox\DataExport(); - $this->string($dataexport->normalizeValueForTextExport($value))->isEqualTo($expected_result); + $this->assertEquals($expected_result, $dataexport->normalizeValueForTextExport($value)); } } diff --git a/tests/functional/Glpi/Toolbox/DatabaseSchema.php b/phpunit/functional/Glpi/Toolbox/DatabaseSchemaTest.php similarity index 91% rename from tests/functional/Glpi/Toolbox/DatabaseSchema.php rename to phpunit/functional/Glpi/Toolbox/DatabaseSchemaTest.php index 70e506399cf..b7013334b14 100644 --- a/tests/functional/Glpi/Toolbox/DatabaseSchema.php +++ b/phpunit/functional/Glpi/Toolbox/DatabaseSchemaTest.php @@ -35,9 +35,9 @@ namespace tests\units\Glpi\Toolbox; -class DatabaseSchema extends \GLPITestCase +class DatabaseSchemaTest extends \GLPITestCase { - protected function versionsProvider(): iterable + public static function versionsProvider(): iterable { foreach (['-dev', '-alpha', '-alpha1', '-alpha3', '-beta', '-beta2', '-rc', '-rc1', ''] as $suffix) { // Unavailable versions @@ -70,10 +70,10 @@ protected function versionsProvider(): iterable */ public function testGetEmptySchemaPath(string $version, ?string $expected): void { - $instance = $this->newTestedInstance(); + $instance = new \Glpi\Toolbox\DatabaseSchema(); if ($expected !== null) { $expected = realpath(GLPI_ROOT) . '/install/mysql/' . $expected; } - $this->variable($instance->getEmptySchemaPath($version))->isEqualTo($expected); + $this->assertEquals($expected, $instance->getEmptySchemaPath($version)); } } diff --git a/tests/functional/Glpi/Toolbox/Filesystem.php b/phpunit/functional/Glpi/Toolbox/FilesystemTest.php similarity index 74% rename from tests/functional/Glpi/Toolbox/Filesystem.php rename to phpunit/functional/Glpi/Toolbox/FilesystemTest.php index 68ae9562d4d..f56b616dd45 100644 --- a/tests/functional/Glpi/Toolbox/Filesystem.php +++ b/phpunit/functional/Glpi/Toolbox/FilesystemTest.php @@ -37,41 +37,41 @@ use org\bovigo\vfs\vfsStream; -class Filesystem extends \GLPITestCase +class FilesystemTest extends \GLPITestCase { public function testCanWriteFile(): void { $config_dir = vfsStream::setup('config'); - $this->newTestedInstance(); + $instance = new \Glpi\Toolbox\Filesystem(); // Files can be written when they not exists and directory is writable $config_dir->chmod(0700); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/config_db.php')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/whatever.yml')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')]))->isEqualTo(true); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/config_db.php'))); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/whatever.yml'))); + $this->assertTrue($instance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')])); // Files cannot be written when they not exists and directory is not writable $config_dir->chmod(0500); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/config_db.php')))->isEqualTo(false); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/whatever.yml')))->isEqualTo(false); - $this->boolean($this->testedInstance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')]))->isEqualTo(false); + $this->assertFalse($instance->canWriteFile(vfsStream::url('config/config_db.php'))); + $this->assertFalse($instance->canWriteFile(vfsStream::url('config/whatever.yml'))); + $this->assertFalse($instance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')])); - // Files cannot be written when they exists but are not writable (even if directory is writable) + // Files cannot be written when they exist but are not writable (even if directory is writable) $config_dir->chmod(0700); $file1 = vfsStream::newFile('config_db.php', 0400)->at($config_dir)->setContent('boolean($this->testedInstance->canWriteFile(vfsStream::url('config/config_db.php')))->isEqualTo(false); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/whatever.yml')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')]))->isEqualTo(false); + $this->assertFalse($instance->canWriteFile(vfsStream::url('config/config_db.php'))); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/whatever.yml'))); + $this->assertFalse($instance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')])); - // Files can be written when they exists and are writable (even if directory is not writable) - $file1->chmod(0600); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/config_db.php')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/whatever.yml')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')]))->isEqualTo(true); + // Files can be written when they exist and are writable (even if directory is not writable) + $file1->chmod(0666); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/config_db.php'))); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/whatever.yml'))); + $this->assertTrue($instance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')])); } - protected function isFilepathSafeProvider(): iterable + public static function isFilepathSafeProvider(): iterable { // Unix paths and file scheme foreach (['', 'file://'] as $prefix) { @@ -177,7 +177,7 @@ protected function isFilepathSafeProvider(): iterable */ public function testIsFilepathSafe(string $path, ?string $restricted_directory, bool $is_safe): void { - $this->newTestedInstance(); - $this->boolean($this->testedInstance->isFilepathSafe($path, $restricted_directory))->isEqualTo($is_safe); + $instance = new \Glpi\Toolbox\Filesystem(); + $this->assertSame($is_safe, $instance->isFilepathSafe($path, $restricted_directory)); } } diff --git a/tests/functional/Glpi/Toolbox/FrontEnd.php b/phpunit/functional/Glpi/Toolbox/FrontEndTest.php similarity index 81% rename from tests/functional/Glpi/Toolbox/FrontEnd.php rename to phpunit/functional/Glpi/Toolbox/FrontEndTest.php index a4e95398eb5..68b835ad363 100644 --- a/tests/functional/Glpi/Toolbox/FrontEnd.php +++ b/phpunit/functional/Glpi/Toolbox/FrontEndTest.php @@ -38,13 +38,13 @@ /** * Test class for src/Glpi/Toolbox/dataexport.class.php */ -class FrontEnd extends \GLPITestCase +class FrontEndTest extends \GLPITestCase { public function testGetVersionCacheKey() { - $instance = $this->newTestedInstance(); + $instance = new \Glpi\Toolbox\FrontEnd(); - $this->string($instance->getVersionCacheKey(GLPI_VERSION))->isNotEqualTo(GLPI_VERSION); - $this->string($instance->getVersionCacheKey(GLPI_VERSION))->isNotEqualTo(sha1(GLPI_VERSION)); // too predicatable + $this->assertNotEquals(GLPI_VERSION, $instance->getVersionCacheKey(GLPI_VERSION)); + $this->assertNotEquals(sha1(GLPI_VERSION), $instance->getVersionCacheKey(GLPI_VERSION)); // too predicatable } } diff --git a/tests/functional/Glpi/Toolbox/Sanitizer.php b/phpunit/functional/Glpi/Toolbox/SanitizerTest.php similarity index 85% rename from tests/functional/Glpi/Toolbox/Sanitizer.php rename to phpunit/functional/Glpi/Toolbox/SanitizerTest.php index fe83a2a4b7a..e23099cc7b9 100644 --- a/tests/functional/Glpi/Toolbox/Sanitizer.php +++ b/phpunit/functional/Glpi/Toolbox/SanitizerTest.php @@ -38,9 +38,9 @@ /** * Test class for src/Glpi/Toolbox/sanitizer.class.php */ -class Sanitizer extends \GLPITestCase +class SanitizerTest extends \GLPITestCase { - protected function rawValueProvider(): iterable + public static function rawValueProvider(): iterable { // Non string values should not be altered yield [ @@ -162,16 +162,16 @@ public function testSanitize( $htmlencoded_value = null, $dbescaped_value = null ) { - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->sanitize($value, true))->isEqualTo($sanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($sanitized_value, $sanitizer->sanitize($value, true)); if ($htmlencoded_value !== null) { - // Calling `sanitize()` with `$db_escape = false` should produce HTML enoded value - $this->variable($sanitizer->sanitize($value, false))->isEqualTo($htmlencoded_value); + // Calling `sanitize()` with `$db_escape = false` should produce HTML encoded value + $this->assertEquals($htmlencoded_value, $sanitizer->sanitize($value, false)); } // Calling sanitize on sanitized value should have no effect - $this->variable($sanitizer->sanitize($sanitized_value))->isEqualTo($sanitized_value); + $this->assertEquals($sanitized_value, $sanitizer->sanitize($sanitized_value)); } /** @@ -187,11 +187,11 @@ public function testEncodeHtmlSpecialChars( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->encodeHtmlSpecialChars($value))->isEqualTo($htmlencoded_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($htmlencoded_value, $sanitizer->encodeHtmlSpecialChars($value)); // Calling encodeHtmlSpecialChars on escaped value should have no effect - $this->variable($sanitizer->encodeHtmlSpecialChars($htmlencoded_value))->isEqualTo($htmlencoded_value); + $this->assertEquals($htmlencoded_value, $sanitizer->encodeHtmlSpecialChars($htmlencoded_value)); } /** @@ -207,11 +207,11 @@ public function testEncodeHtmlSpecialCharsRecursive( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->encodeHtmlSpecialCharsRecursive($value))->isEqualTo($htmlencoded_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($htmlencoded_value, $sanitizer->encodeHtmlSpecialCharsRecursive($value)); // Calling encodeHtmlSpecialCharsRecursive on escaped value should have no effect - $this->variable($sanitizer->encodeHtmlSpecialCharsRecursive($htmlencoded_value))->isEqualTo($htmlencoded_value); + $this->assertEquals($htmlencoded_value, $sanitizer->encodeHtmlSpecialCharsRecursive($htmlencoded_value)); } /** @@ -227,11 +227,11 @@ public function testDbEscape( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->dbEscape($value))->isEqualTo($dbescaped_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($dbescaped_value, $sanitizer->dbEscape($value)); // Calling dbEscape on escaped value should have no effect - $this->variable($sanitizer->dbEscape($dbescaped_value))->isEqualTo($dbescaped_value); + $this->assertEquals($dbescaped_value, $sanitizer->dbEscape($dbescaped_value)); } /** @@ -247,16 +247,16 @@ public function testDbEscapeRecursive( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->dbEscapeRecursive($value))->isEqualTo($dbescaped_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($dbescaped_value, $sanitizer->dbEscapeRecursive($value)); // Calling dbEscapeRecursive on escaped value should have no effect - $this->variable($sanitizer->dbEscapeRecursive($dbescaped_value))->isEqualTo($dbescaped_value); + $this->assertEquals($dbescaped_value, $sanitizer->dbEscapeRecursive($dbescaped_value)); } - protected function sanitizedValueProvider(): iterable + public static function sanitizedValueProvider(): iterable { - foreach ($this->rawValueProvider() as $data) { + foreach (self::rawValueProvider() as $data) { yield [ 'value' => $data['sanitized_value'], 'unsanitized_value' => $data['value'], @@ -291,11 +291,11 @@ public function testUnanitize( $htmlencoded_value = null, $dbescaped_value = null ) { - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->unsanitize($value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->unsanitize($value)); // Calling unsanitize multiple times should not corrupt unsanitized value - $this->variable($sanitizer->unsanitize($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->unsanitize($unsanitized_value)); } /** @@ -311,11 +311,11 @@ public function testDbUnescape( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->dbUnescape($dbescaped_value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->dbUnescape($dbescaped_value)); // Calling dbUnescape multiple times should not corrupt value - $this->variable($sanitizer->dbUnescape($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->dbUnescape($unsanitized_value)); } /** @@ -331,11 +331,11 @@ public function testDbUnescapeRecursive( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->dbUnescapeRecursive($dbescaped_value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->dbUnescapeRecursive($dbescaped_value)); // Calling dbUnescapeRecursive multiple times should not corrupt value - $this->variable($sanitizer->dbUnescapeRecursive($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->dbUnescapeRecursive($unsanitized_value)); } /** @@ -351,11 +351,11 @@ public function testDecodeHtmlSpecialChars( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->decodeHtmlSpecialChars($htmlencoded_value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->decodeHtmlSpecialChars($htmlencoded_value)); // Calling decodeHtmlSpecialChars multiple times should not corrupt value - $this->variable($sanitizer->decodeHtmlSpecialChars($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->decodeHtmlSpecialChars($unsanitized_value)); } /** @@ -371,11 +371,11 @@ public function testDecodeHtmlSpecialCharsRecursive( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->decodeHtmlSpecialCharsRecursive($htmlencoded_value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->decodeHtmlSpecialCharsRecursive($htmlencoded_value)); // Calling decodeHtmlSpecialCharsRecursive multiple times should not corrupt value - $this->variable($sanitizer->decodeHtmlSpecialCharsRecursive($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->decodeHtmlSpecialCharsRecursive($unsanitized_value)); } protected function isHtmlEncodedValueProvider(): iterable @@ -415,8 +415,8 @@ protected function isHtmlEncodedValueProvider(): iterable */ public function testIsHtmlEncoded(string $value, bool $is_encoded) { - $sanitizer = $this->newTestedInstance(); - $this->boolean($sanitizer->isHtmlEncoded($value))->isEqualTo($is_encoded); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertSame($is_encoded, $sanitizer->isHtmlEncoded($value)); } protected function isDbEscapedValueProvider(): iterable @@ -577,9 +577,9 @@ protected function isDbEscapedValueProvider(): iterable */ public function testIsDbEscaped(string $value, bool $is_escaped) { - $sanitizer = $this->newTestedInstance(); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); - $this->boolean($sanitizer->isDbEscaped($value))->isEqualTo($is_escaped, $value); + $this->assertSame($is_escaped, $sanitizer->isDbEscaped($value), $value); } /** @@ -591,13 +591,13 @@ public function testSanitizationReversibility( $htmlencoded_value = null, $dbescaped_value = null ) { - $sanitizer = $this->newTestedInstance(); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); // Value should stay the same if it has been sanitized then unsanitized - $this->variable($sanitizer->unsanitize($sanitizer->sanitize($value)))->isEqualTo($value); + $this->assertEquals($value, $sanitizer->unsanitize($sanitizer->sanitize($value))); // Re-sanitize a value provide the same result as first sanitization - $this->variable($sanitizer->sanitize($sanitizer->unsanitize($value)))->isEqualTo($sanitized_value); + $this->assertEquals($sanitized_value, $sanitizer->sanitize($sanitizer->unsanitize($value))); } protected function isNsClassOrCallableIdentifierProvider(): iterable @@ -629,7 +629,7 @@ protected function isNsClassOrCallableIdentifierProvider(): iterable */ public function testIsNsClassOrCallableIdentifier(string $value, bool $is_class) { - $sanitizer = $this->newTestedInstance(); - $this->boolean($sanitizer->isNsClassOrCallableIdentifier($value))->isEqualTo($is_class); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertSame($is_class, $sanitizer->isNsClassOrCallableIdentifier($value)); } } diff --git a/tests/functional/Glpi/Toolbox/URL.php b/phpunit/functional/Glpi/Toolbox/URLTest.php similarity index 94% rename from tests/functional/Glpi/Toolbox/URL.php rename to phpunit/functional/Glpi/Toolbox/URLTest.php index 9ada3ee1dd6..203ff50637a 100644 --- a/tests/functional/Glpi/Toolbox/URL.php +++ b/phpunit/functional/Glpi/Toolbox/URLTest.php @@ -35,9 +35,9 @@ namespace tests\units\Glpi\Toolbox; -class URL extends \GLPITestCase +class URLTest extends \GLPITestCase { - protected function urlProvider(): iterable + public static function urlProvider(): iterable { yield [ 'url' => null, @@ -116,7 +116,7 @@ protected function urlProvider(): iterable */ public function testSanitizeURL(?string $url, string $expected): void { - $this->newTestedInstance(); - $this->string($this->testedInstance->sanitizeURL($url))->isEqualTo($expected); + $instance = new \Glpi\Toolbox\URL(); + $this->assertEquals($expected, $instance->sanitizeURL($url)); } } diff --git a/tests/functional/Glpi/Toolbox/VersionParser.php b/phpunit/functional/Glpi/Toolbox/VersionParserTest.php similarity index 91% rename from tests/functional/Glpi/Toolbox/VersionParser.php rename to phpunit/functional/Glpi/Toolbox/VersionParserTest.php index a89cd457a9f..3cb720f3774 100644 --- a/tests/functional/Glpi/Toolbox/VersionParser.php +++ b/phpunit/functional/Glpi/Toolbox/VersionParserTest.php @@ -38,9 +38,9 @@ /** * Test class for src/Glpi/Toolbox/versionparser.class.php */ -class VersionParser extends \GLPITestCase +class VersionParserTest extends \GLPITestCase { - protected function versionsProvider() + public static function versionsProvider() { return [ [ @@ -156,8 +156,8 @@ protected function versionsProvider() */ public function testGetNormalizeVersion(string $version, bool $keep_stability_flag, string $normalized, bool $stable, bool $dev): void { - $version_parser = $this->newTestedInstance(); - $this->string($version_parser->getNormalizedVersion($version, $keep_stability_flag))->isEqualTo($normalized); + $version_parser = new \Glpi\Toolbox\VersionParser(); + $this->assertEquals($normalized, $version_parser->getNormalizedVersion($version, $keep_stability_flag)); } /** @@ -165,8 +165,8 @@ public function testGetNormalizeVersion(string $version, bool $keep_stability_fl */ public function testIsStableRelease(string $version, bool $keep_stability_flag, string $normalized, bool $stable, bool $dev): void { - $version_parser = $this->newTestedInstance(); - $this->boolean($version_parser->isStableRelease($version))->isEqualTo($stable); + $version_parser = new \Glpi\Toolbox\VersionParser(); + $this->assertSame($stable, $version_parser->isStableRelease($version)); } /** @@ -174,7 +174,7 @@ public function testIsStableRelease(string $version, bool $keep_stability_flag, */ public function testIsDevVersion(string $version, bool $keep_stability_flag, string $normalized, bool $stable, bool $dev): void { - $version_parser = $this->newTestedInstance(); - $this->boolean($version_parser->isDevVersion($version))->isEqualTo($dev); + $version_parser = new \Glpi\Toolbox\VersionParser(); + $this->assertSame($dev, $version_parser->isDevVersion($version)); } } diff --git a/tests/functional/IPAddress.php b/phpunit/functional/IPAddressTest.php similarity index 94% rename from tests/functional/IPAddress.php rename to phpunit/functional/IPAddressTest.php index afb70d3cc2f..b88447a7d24 100644 --- a/tests/functional/IPAddress.php +++ b/phpunit/functional/IPAddressTest.php @@ -39,7 +39,7 @@ /* Test for inc/networkport.class.php */ -class IPAddress extends DbTestCase +class IPAddressTest extends DbTestCase { public function testAddIPV4() { @@ -48,7 +48,7 @@ public function testAddIPV4() //first create NetworkName $networkName = new \NetworkName(); $networkName_id = $networkName->add(["name" => "test", "itemtype" => ""]); - $this->integer($networkName_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $networkName_id); $IPV4ShouldWork = []; $IPV4ShouldWork["1.0.1.0"] = ["items_id" => $networkName_id, @@ -133,7 +133,7 @@ public function testAddIPV4() "items_id" => "$networkName_id" ]; $id = $ipAdress->add($input); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); //check name store in DB $all_IP = getAllDataFromTable('glpi_ipaddresses', ['ORDER' => 'id']); @@ -146,7 +146,7 @@ public function testAddIPV4() unset($currentIP['is_dynamic']); unset($currentIP['mainitems_id']); unset($currentIP['mainitemtype']); - $this->array($currentIP)->isIdenticalTo($expected); + $this->assertSame($expected, $currentIP); } $IPV4ShouldNotWork = [ @@ -174,7 +174,7 @@ public function testAddIPV4() "Invalid IP address: " . $name, ]; - $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expectedSession); + $this->assertSame($expectedSession, $_SESSION['MESSAGE_AFTER_REDIRECT']); $_SESSION['MESSAGE_AFTER_REDIRECT'] = []; } } @@ -187,7 +187,7 @@ public function testAddIPV6() //first create NetworkName $networkName = new \NetworkName(); $networkName_id = $networkName->add(["name" => "test", "itemtype" => ""]); - $this->integer($networkName_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $networkName_id); $IPV6ShouldWork = []; $IPV6ShouldWork["59FB::1005:CC57:6571"] = ["items_id" => $networkName_id, @@ -245,7 +245,7 @@ public function testAddIPV6() "items_id" => "$networkName_id" ]; $id = $ipAdress->add($input); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); //check name store in DB $all_IP = getAllDataFromTable('glpi_ipaddresses', ['ORDER' => 'id']); @@ -259,7 +259,7 @@ public function testAddIPV6() unset($currentIP['mainitems_id']); unset($currentIP['mainitemtype']); //var_dump($currentIP); - $this->array($currentIP)->isIdenticalTo($expected); + $this->assertSame($expected, $currentIP); } $IPV6ShouldNotWork = [ @@ -289,7 +289,7 @@ public function testAddIPV6() "Invalid IP address: " . $name, ]; - $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expectedSession); + $this->assertSame($expectedSession, $_SESSION['MESSAGE_AFTER_REDIRECT']); $_SESSION['MESSAGE_AFTER_REDIRECT'] = []; } } diff --git a/tests/functional/Infocom.php b/phpunit/functional/InfocomTest.php similarity index 97% rename from tests/functional/Infocom.php rename to phpunit/functional/InfocomTest.php index 99ce9a1d8e5..11e92c4a6b3 100644 --- a/tests/functional/Infocom.php +++ b/phpunit/functional/InfocomTest.php @@ -37,7 +37,7 @@ /* Test for inc/infocom.class.php */ -class Infocom extends \GLPITestCase +class InfocomTest extends \GLPITestCase { public function dataLinearAmortise() { @@ -198,10 +198,10 @@ public function testLinearAmortise($value, $duration, $fiscaldate, $buydate, $us $usedate ); foreach ($expected as $year => $values) { - $this->array($amortise[$year])->isIdenticalTo($values); + $this->assertSame($values, $amortise[$year]); } if (count($oldmft)) { - $this->array(\Infocom::mapOldAmortiseFormat($amortise, false))->isIdenticalTo($oldmft); + $this->assertSame($oldmft, \Infocom::mapOldAmortiseFormat($amortise, false)); } } } diff --git a/tests/functional/Item_Cluster.php b/phpunit/functional/Item_ClusterTest.php similarity index 81% rename from tests/functional/Item_Cluster.php rename to phpunit/functional/Item_ClusterTest.php index 80df1c9054e..d95b178c78b 100644 --- a/tests/functional/Item_Cluster.php +++ b/phpunit/functional/Item_ClusterTest.php @@ -39,14 +39,14 @@ /* Test for inc/item_cluster.class.php */ -class Item_Cluster extends DbTestCase +class Item_ClusterTest extends DbTestCase { /** * Computers provider * * @return array */ - protected function computersProvider() + public static function computersProvider() { return [ [ @@ -67,9 +67,7 @@ protected function createComputers() $computer = new \Computer(); foreach ($this->computersProvider() as $row) { $row['entities_id'] = 0; - $this->integer( - (int)$computer->add($row) - )->isGreaterThan(0); + $this->assertGreaterThan(0, $computer->add($row)); } } @@ -84,13 +82,14 @@ public function testAdd() $cluster = new \Cluster(); - $this->integer( - (int)$cluster->add([ + $this->assertGreaterThan( + 0, + $cluster->add([ 'name' => 'Test cluster', 'uuid' => 'ytreza', 'entities_id' => 0 ]) - )->isGreaterThan(0); + ); $icl = new \Item_Cluster(); @@ -99,56 +98,58 @@ public function testAdd() //try to add without required field $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertFalse( + $icl->add([ 'itemtype' => 'Computer', 'items_id' => $SRVNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['A cluster is required']); - //try to add without required field + //try to add without required field $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertFalse( + $icl->add([ 'clusters_id' => $cluster->fields['id'], 'items_id' => $SRVNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['An item type is required']); - //try to add without required field + //try to add without required field $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertFalse( + $icl->add([ 'clusters_id' => $cluster->fields['id'], 'itemtype' => 'Computer', ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['An item is required']); //try to add without error $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertGreaterThan( + 0, + $icl->add([ 'clusters_id' => $cluster->fields['id'], 'itemtype' => 'Computer', 'items_id' => $SRVNUX1 ]) - )->isGreaterThan(0); + ); //Add another item in cluster $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertGreaterThan( + 0, + $icl->add([ 'clusters_id' => $cluster->fields['id'], 'itemtype' => 'Computer', 'items_id' => $SRVNUX2 ]) - )->isGreaterThan(0); + ); global $DB; $items = $DB->request([ @@ -157,6 +158,6 @@ public function testAdd() 'clusters_id' => $cluster->fields['id'] ] ]); - $this->array(iterator_to_array($items))->hasSize(2); + $this->assertCount(2, iterator_to_array($items)); } } diff --git a/tests/functional/Item_DeviceSensor.php b/phpunit/functional/Item_DeviceSensorTest.php similarity index 73% rename from tests/functional/Item_DeviceSensor.php rename to phpunit/functional/Item_DeviceSensorTest.php index 7a8578acecb..a521d846ed7 100644 --- a/tests/functional/Item_DeviceSensor.php +++ b/phpunit/functional/Item_DeviceSensorTest.php @@ -37,18 +37,18 @@ use DbTestCase; -class Item_DeviceSensor extends DbTestCase +class Item_DeviceSensorTest extends DbTestCase { public function testCreate() { $this->login(); $obj = new \Item_DeviceSensor(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSensor = getItemByTypeName('DeviceSensor', '_test_sensor_1'); - $this->object($deviceSensor)->isInstanceOf('\DeviceSensor'); + $this->assertInstanceOf('\DeviceSensor', $deviceSensor); $in = [ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), @@ -56,13 +56,13 @@ public function testCreate() 'entities_id' => 0, ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); - // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + // getField methods + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -71,31 +71,31 @@ public function testUpdate() $this->login(); $obj = new \Item_DeviceSensor(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSensor = getItemByTypeName('DeviceSensor', '_test_sensor_1'); - $this->object($deviceSensor)->isInstanceOf('\DeviceSensor'); + $this->assertInstanceOf('\DeviceSensor', $deviceSensor); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), 'devicesensors_id' => $deviceSensor->getID(), 'entities_id' => 0, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Update + // Update $id = $obj->getID(); $in = [ 'id' => $id, 'serial' => $this->getUniqueString(), ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); - // getField methods + // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -104,23 +104,23 @@ public function testDelete() $this->login(); $obj = new \Item_DeviceSensor(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSensor = getItemByTypeName('DeviceSensor', '_test_sensor_1'); - $this->object($deviceSensor)->isInstanceOf('\DeviceSensor'); + $this->assertInstanceOf('\DeviceSensor', $deviceSensor); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), 'devicesensors_id' => $deviceSensor->getID(), 'entities_id' => 0, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Delete + // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/Item_DeviceSimcard.php b/phpunit/functional/Item_DeviceSimcardTest.php similarity index 79% rename from tests/functional/Item_DeviceSimcard.php rename to phpunit/functional/Item_DeviceSimcardTest.php index ca5fded4870..bf139c1215f 100644 --- a/tests/functional/Item_DeviceSimcard.php +++ b/phpunit/functional/Item_DeviceSimcardTest.php @@ -37,7 +37,7 @@ use DbTestCase; -class Item_DeviceSimcard extends DbTestCase +class Item_DeviceSimcardTest extends DbTestCase { public function testCreate() { @@ -46,9 +46,9 @@ public function testCreate() // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSimcard = getItemByTypeName('DeviceSimcard', '_test_simcard_1'); - $this->object($deviceSimcard)->isInstanceOf('\DeviceSimcard'); + $this->assertInstanceOf('\DeviceSimcard', $deviceSimcard); $in = [ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), @@ -56,13 +56,13 @@ public function testCreate() 'entities_id' => 0, ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -73,16 +73,16 @@ public function testUpdate() // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSimcard = getItemByTypeName('DeviceSimcard', '_test_simcard_1'); - $this->object($deviceSimcard)->isInstanceOf('\DeviceSimcard'); + $this->assertInstanceOf('\DeviceSimcard', $deviceSimcard); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), 'devicesimcards_id' => $deviceSimcard->getID(), 'entities_id' => 0, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Update $id = $obj->getID(); @@ -93,12 +93,12 @@ public function testUpdate() 'puk' => '2345', 'puk2' => '3456', ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -131,9 +131,9 @@ public function testDenyPinPukUpdate() // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSimcard = getItemByTypeName('DeviceSimcard', '_test_simcard_1'); - $this->object($deviceSimcard)->isInstanceOf('\DeviceSimcard'); + $this->assertInstanceOf('\DeviceSimcard', $deviceSimcard); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), @@ -144,7 +144,7 @@ public function testDenyPinPukUpdate() 'puk' => '2345', 'puk2' => '3456', ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Update $id = $obj->getID(); @@ -155,13 +155,13 @@ public function testDenyPinPukUpdate() 'puk' => '0000', 'puk2' => '0000', ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods unset($in['id']); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isNotEqualTo($v); + $this->assertNotEquals($v, $obj->getField($k)); } } @@ -173,21 +173,21 @@ public function testDelete() // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSimcard = getItemByTypeName('DeviceSimcard', '_test_simcard_1'); - $this->object($deviceSimcard)->isInstanceOf('\DeviceSimcard'); + $this->assertInstanceOf('\DeviceSimcard', $deviceSimcard); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), 'devicesimcards_id' => $deviceSimcard->getID(), 'entities_id' => 0, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/Item_Disk.php b/phpunit/functional/Item_DiskTest.php similarity index 61% rename from tests/functional/Item_Disk.php rename to phpunit/functional/Item_DiskTest.php index ee7a59838af..046b7c37e79 100644 --- a/tests/functional/Item_Disk.php +++ b/phpunit/functional/Item_DiskTest.php @@ -37,86 +37,86 @@ use DbTestCase; -class Item_Disk extends DbTestCase +class Item_DiskTest extends DbTestCase { public function testCreate() { $this->login(); - $this->newTestedInstance(); - $obj = $this->testedInstance; + $obj = new \Item_Disk(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); - $this->integer( + $this->assertGreaterThan( + 0, $id = (int)$obj->add([ 'itemtype' => $computer->getType(), 'items_id' => $computer->fields['id'], 'mountpoint' => '/' ]) - )->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->string($obj->fields['mountpoint'])->isIdenticalTo('/'); + ); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame('/', $obj->fields['mountpoint']); } public function testUpdate() { $this->login(); - $this->newTestedInstance(); - $obj = $this->testedInstance; + $obj = new \Item_Disk(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); - $this->integer( + $this->assertGreaterThan( + 0, $id = (int)$obj->add([ 'itemtype' => $computer->getType(), 'items_id' => $computer->fields['id'], 'mountpoint' => '/' ]) - )->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->string($obj->fields['mountpoint'])->isIdenticalTo('/'); + ); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame('/', $obj->fields['mountpoint']); - $this->boolean($obj->update([ + $this->assertTrue($obj->update([ 'id' => $id, 'mountpoint' => '/mnt' - ]))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->string($obj->fields['mountpoint'])->isIdenticalTo('/mnt'); + ])); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame('/mnt', $obj->fields['mountpoint']); } public function testDelete() { $this->login(); - $this->newTestedInstance(); - $obj = $this->testedInstance; + $obj = new \Item_Disk(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); - $this->integer( + $this->assertGreaterThan( + 0, $id = (int)$obj->add([ 'itemtype' => $computer->getType(), 'items_id' => $computer->fields['id'], 'mountpoint' => '/' ]) - )->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->string($obj->fields['mountpoint'])->isIdenticalTo('/'); + ); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame('/', $obj->fields['mountpoint']); - $this->boolean( - (bool)$obj->delete([ + $this->assertTrue( + $obj->delete([ 'id' => $id ]) - )->isTrue(); - $this->boolean($obj->getFromDB($id))->istrue(); //it's always in DB but with is_deleted = 1 - $this->integer($obj->fields['is_deleted'])->isIdenticalTo(1); + ); + $this->assertTrue($obj->getFromDB($id)); //it's always in DB but with is_deleted = 1 + $this->assertSame(1, $obj->fields['is_deleted']); } } diff --git a/tests/functional/Item_OperatingSystem.php b/phpunit/functional/Item_OperatingSystemTest.php similarity index 61% rename from tests/functional/Item_OperatingSystem.php rename to phpunit/functional/Item_OperatingSystemTest.php index f6ccda60301..30eba11b847 100644 --- a/tests/functional/Item_OperatingSystem.php +++ b/phpunit/functional/Item_OperatingSystemTest.php @@ -40,14 +40,14 @@ /* Test for inc/item_operatingsystem.class.php */ -class Item_OperatingSystem extends DbTestCase +class Item_OperatingSystemTest extends DbTestCase { public function testGetTypeName() { - $this->string(\Item_OperatingSystem::getTypeName())->isIdenticalTo('Item operating systems'); - $this->string(\Item_OperatingSystem::getTypeName(0))->isIdenticalTo('Item operating systems'); - $this->string(\Item_OperatingSystem::getTypeName(10))->isIdenticalTo('Item operating systems'); - $this->string(\Item_OperatingSystem::getTypeName(1))->isIdenticalTo('Item operating system'); + $this->assertSame('Item operating systems', \Item_OperatingSystem::getTypeName()); + $this->assertSame('Item operating systems', \Item_OperatingSystem::getTypeName(0)); + $this->assertSame('Item operating systems', \Item_OperatingSystem::getTypeName(10)); + $this->assertSame('Item operating system', \Item_OperatingSystem::getTypeName(1)); } /** @@ -61,12 +61,13 @@ private function createDdObjects() foreach (['', 'Architecture', 'Version', 'Edition', 'KernelVersion'] as $object) { $classname = 'OperatingSystem' . $object; $instance = new $classname(); - $this->integer( - (int)$instance->add([ + $this->assertGreaterThan( + 0, + $instance->add([ 'name' => $classname . ' ' . $this->getUniqueInteger() ]) - )->isGreaterThan(0); - $this->boolean($instance->getFromDB($instance->getID()))->isTrue(); + ); + $this->assertTrue($instance->getFromDB($instance->getID())); $objects[$object] = $instance; } return $objects; @@ -88,24 +89,29 @@ public function testAttachComputer() 'licenseid' => $this->getUniqueString(), 'license_number' => $this->getUniqueString() ]; - $this->integer( - (int)$ios->add($input) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + $this->assertGreaterThan( + 0, + $ios->add($input) + ); + $this->assertTrue($ios->getFromDB($ios->getID())); - $this->string($ios->getTabNameForItem($computer)) - ->isIdenticalTo("Operating systems 1"); - $this->integer( - (int)\Item_OperatingSystem::countForItem($computer) - )->isIdenticalTo(1); + $this->assertSame( + "Operating systems 1", + $ios->getTabNameForItem($computer) + ); + $this->assertSame( + 1, + \Item_OperatingSystem::countForItem($computer) + ); $expected_error = "/Duplicate entry '{$computer->getID()}-Computer-{$objects['']->getID()}-{$objects['Architecture']->getID()}' for key '(glpi_items_operatingsystems\.)?unicity'/"; - $this->boolean($ios->add($input))->isFalse(); + $this->assertFalse($ios->add($input)); $this->hasSqlLogRecordThatMatches($expected_error, LogLevel::ERROR); - $this->integer( - (int)\Item_OperatingSystem::countForItem($computer) - )->isIdenticalTo(1); + $this->assertSame( + 1, + \Item_OperatingSystem::countForItem($computer) + ); $objects = $this->createDdObjects(); $ios = new \Item_OperatingSystem(); @@ -119,16 +125,20 @@ public function testAttachComputer() 'licenseid' => $this->getUniqueString(), 'license_number' => $this->getUniqueString() ]; - $this->integer( - (int)$ios->add($input) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + $this->assertGreaterThan( + 0, + $ios->add($input) + ); + $this->assertTrue($ios->getFromDB($ios->getID())); - $this->string($ios->getTabNameForItem($computer)) - ->isIdenticalTo("Operating systems 2"); - $this->integer( - (int)\Item_OperatingSystem::countForItem($computer) - )->isIdenticalTo(2); + $this->assertSame( + "Operating systems 2", + $ios->getTabNameForItem($computer) + ); + $this->assertSame( + 2, + \Item_OperatingSystem::countForItem($computer) + ); } public function testShowForItem() @@ -137,11 +147,10 @@ public function testShowForItem() $computer = getItemByTypeName('Computer', '_test_pc01'); foreach (['showForItem', 'displayTabContentForItem'] as $method) { - $this->output( - function () use ($method, $computer) { - \Item_OperatingSystem::$method($computer); - } - )->contains('operatingsystems_id'); + ob_start(); + \Item_OperatingSystem::$method($computer); + $output = ob_get_clean(); + $this->assertStringContainsString('operatingsystems_id', $output); } $objects = $this->createDdObjects(); @@ -156,17 +165,17 @@ function () use ($method, $computer) { 'licenseid' => $this->getUniqueString(), 'license_number' => $this->getUniqueString() ]; - $this->integer( - (int)$ios->add($input) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + $this->assertGreaterThan( + 0, + $ios->add($input) + ); + $this->assertTrue($ios->getFromDB($ios->getID())); foreach (['showForItem', 'displayTabContentForItem'] as $method) { - $this->output( - function () use ($method, $computer) { - \Item_OperatingSystem::$method($computer); - } - )->contains('operatingsystems_id'); + ob_start(); + \Item_OperatingSystem::$method($computer); + $output = ob_get_clean(); + $this->assertStringContainsString('operatingsystems_id', $output); } $objects = $this->createDdObjects(); @@ -181,18 +190,18 @@ function () use ($method, $computer) { 'licenseid' => $this->getUniqueString(), 'license_number' => $this->getUniqueString() ]; - $this->integer( - (int)$ios->add($input) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + $this->assertGreaterThan( + 0, + $ios->add($input) + ); + $this->assertTrue($ios->getFromDB($ios->getID())); - //thera are now 2 OS linked, we will no longer show a form, but a list. + //there are now 2 OS linked, we will no longer show a form, but a list. foreach (['showForItem', 'displayTabContentForItem'] as $method) { - $this->output( - function () use ($method, $computer) { - \Item_OperatingSystem::$method($computer); - } - )->notContains('operatingsystems_id'); + ob_start(); + \Item_OperatingSystem::$method($computer); + $output = ob_get_clean(); + $this->assertStringNotContainsString('operatingsystems_id', $output); } } @@ -203,69 +212,70 @@ public function testEntityAccess() $this->setEntity('_test_root_entity', true); $computer = new \Computer(); - $this->integer( - (int)$computer->add([ + $this->assertGreaterThan( + 0, + $computer->add([ 'name' => 'Test Item/OS', 'entities_id' => $eid, 'is_recursive' => 0 ]) - )->isGreaterThan(0); + ); $os = new \OperatingSystem(); - $this->integer( - (int)$os->add([ + $this->assertGreaterThan( + 0, + $os->add([ 'name' => 'Test OS' ]) - )->isGreaterThan(0); + ); $ios = new \Item_OperatingSystem(); - $this->integer( - (int)$ios->add([ + $this->assertGreaterThan( + 0, + $ios->add([ 'operatingsystems_id' => $os->getID(), 'itemtype' => 'Computer', 'items_id' => $computer->getID() ]) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + ); + $this->assertTrue($ios->getFromDB($ios->getID())); - $this->array($ios->fields) - ->integer['operatingsystems_id']->isIdenticalTo($os->getID()) - ->string['itemtype']->isIdenticalTo('Computer') - ->integer['items_id']->isIdenticalTo($computer->getID()) - ->integer['entities_id']->isIdenticalTo($eid) - ->integer['is_recursive']->isIdenticalTo(0); + $this->assertSame($os->getID(), $ios->fields['operatingsystems_id']); + $this->assertSame('Computer', $ios->fields['itemtype']); + $this->assertSame($computer->getID(), $ios->fields['items_id']); + $this->assertSame($eid, $ios->fields['entities_id']); + $this->assertSame(0, $ios->fields['is_recursive']); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); - //not recursive + //not recursive $this->setEntity('Root Entity', true); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); $this->setEntity('_test_child_1', true); - $this->boolean($ios->can($ios->getID(), READ))->isFalse(); + $this->assertFalse($ios->can($ios->getID(), READ)); $this->setEntity('_test_child_2', true); - $this->boolean($ios->can($ios->getID(), READ))->isFalse(); + $this->assertFalse($ios->can($ios->getID(), READ)); $this->setEntity('_test_root_entity', true); - $this->boolean( - (bool)$computer->update([ + $this->assertTrue( + $computer->update([ 'id' => $computer->getID(), 'is_recursive' => 1 ]) - )->isTrue(); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); - $this->array($ios->fields) - ->integer['operatingsystems_id']->isIdenticalTo($os->getID()) - ->string['itemtype']->isIdenticalTo('Computer') - ->integer['items_id']->isIdenticalTo($computer->getID()) - ->integer['entities_id']->isIdenticalTo($eid) - ->integer['is_recursive']->isIdenticalTo(1); + ); + $this->assertTrue($ios->getFromDB($ios->getID())); + $this->assertSame($os->getID(), $ios->fields['operatingsystems_id']); + $this->assertSame('Computer', $ios->fields['itemtype']); + $this->assertSame($computer->getID(), $ios->fields['items_id']); + $this->assertSame($eid, $ios->fields['entities_id']); + $this->assertSame(1, $ios->fields['is_recursive']); - //not recursive + //not recursive $this->setEntity('Root Entity', true); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); $this->setEntity('_test_child_1', true); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); $this->setEntity('_test_child_2', true); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); } } diff --git a/tests/functional/Item_Rack.php b/phpunit/functional/Item_RackTest.php similarity index 78% rename from tests/functional/Item_Rack.php rename to phpunit/functional/Item_RackTest.php index 0a0f80a880a..4b15bd97b5a 100644 --- a/tests/functional/Item_Rack.php +++ b/phpunit/functional/Item_RackTest.php @@ -40,14 +40,14 @@ /* Test for inc/item_rack.class.php */ -class Item_Rack extends DbTestCase +class Item_RackTest extends DbTestCase { /** * Models provider * * @return array */ - protected function modelsProvider() + public static function modelsProvider() { return [ [ @@ -98,9 +98,10 @@ protected function createModels() { $model = new \ComputerModel(); foreach ($this->modelsProvider() as $row) { - $this->integer( - (int)$model->add($row) - )->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $model->add($row) + ); } } @@ -109,7 +110,7 @@ protected function createModels() * * @return array */ - protected function computersProvider() + public static function computersProvider() { return [ [ @@ -168,12 +169,13 @@ protected function createComputers() $computer = new \Computer(); foreach ($this->computersProvider() as $row) { $row['computermodels_id'] = getItemByTypeName('ComputerModel', $row['model'], true); - $this->integer((int)$row['computermodels_id'])->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$row['computermodels_id']); $row['entities_id'] = 0; unset($row['model']); - $this->integer( - (int)$computer->add($row) - )->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $computer->add($row) + ); } } @@ -189,259 +191,266 @@ public function testAdd() $this->createComputers(); $rack = new \Rack(); - //create a 10u rack - $this->integer( - (int)$rack->add([ + //create a 10u rack + $this->assertGreaterThan( + 0, + $rack->add([ 'name' => 'Test rack', 'number_units' => 10, 'dcrooms_id' => 0, 'position' => 0, 'entities_id' => 0, ]) - )->isGreaterThan(0); + ); $ira = new \Item_Rack(); $SRVNUX1 = getItemByTypeName('Computer', 'SRV-NUX-1', true); - //try to add outside rack capabilities + //try to add outside rack capabilities $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 15, 'itemtype' => 'Computer', 'items_id' => $SRVNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Item is out of rack bounds']); - //add item at the first position + //add item at the first position $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $SRVNUX1 ]) - )->isGreaterThan(0); + ); $BIGNUX1 = getItemByTypeName('Computer', 'BIG-NUX-1', true); - //take a 3U item and try to add it at the end + //take a 3U item and try to add it at the end $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 10, 'itemtype' => 'Computer', 'items_id' => $BIGNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Item is out of rack bounds']); - //take a 3U item and try to add it at the end - 1 + //take a 3U item and try to add it at the end - 1 $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 9, 'itemtype' => 'Computer', 'items_id' => $BIGNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Item is out of rack bounds']); - //take a 3U item and try to add it at the end - 2 + //take a 3U item and try to add it at the end - 2 $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 8, 'itemtype' => 'Computer', 'items_id' => $BIGNUX1 ]) - )->isGreaterThan(0); + ); - //test half racks + //test half racks $MIDNUX1 = getItemByTypeName('Computer', 'MID-NUX-1', true); $MIDNUX2 = getItemByTypeName('Computer', 'MID-NUX-2', true); $MIDNUX3 = getItemByTypeName('Computer', 'MID-NUX-3', true); - //item is half rack. hpos is required + //item is half rack. hpos is required $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $MIDNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['You must define an horizontal position for this item']); - //try to add a half size on the first row + //try to add a half size on the first row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $MIDNUX1, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); - //add it on second row + //add it on second row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $MIDNUX1, 'hpos' => $rack::POS_LEFT ]) - )->isGreaterThan(0); + ); - //add second half rack item it on second row, at same position + //add second half rack item it on second row, at same position $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $MIDNUX2, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); - //add second half rack item it on second row, on the other position + //add second half rack item it on second row, on the other position $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $MIDNUX2, 'hpos' => $rack::POS_RIGHT ]) - )->isGreaterThan(0); + ); - //Unit is full! + //Unit is full! $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $MIDNUX3, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); - //test depth < 1 + //test depth < 1 $DEPNUX1 = getItemByTypeName('Computer', 'DEP-NUX-1', true); $DEPNUX2 = getItemByTypeName('Computer', 'DEP-NUX-2', true); - //item ahs a depth <= 0.5. orientation is required + //item ahs a depth <= 0.5. orientation is required $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $DEPNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['You must define an orientation for this item']); - //try to add on the first row + //try to add on the first row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $DEPNUX1, 'orientation' => $rack::FRONT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); //try to add on the second row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $DEPNUX1, 'orientation' => $rack::FRONT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); //add on the third row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 3, 'itemtype' => 'Computer', 'items_id' => $DEPNUX1, 'orientation' => $rack::FRONT ]) - )->isGreaterThan(0); + ); //add not full depth rack item with same orientation //try to add on the first row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 3, 'itemtype' => 'Computer', 'items_id' => $DEPNUX2, 'orientation' => $rack::FRONT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 3, 'itemtype' => 'Computer', 'items_id' => $DEPNUX2, 'orientation' => $rack::REAR ]) - )->isGreaterThan(0); + ); - //test hf full depth + 2x hf mid depth + //test hf full depth + 2x hf mid depth $MADNUX1 = getItemByTypeName('Computer', 'MAD-NUX-1', true); $MADNUX2 = getItemByTypeName('Computer', 'MAD-NUX-2', true); - //first element on unit2 (MID-NUX-1) is half racked on left; and is full depth - //drop second element on unit2 + //first element on unit2 (MID-NUX-1) is half racked on left; and is full depth + //drop second element on unit2 $ira->deleteByCriteria(['items_id' => $MIDNUX2], 1); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', @@ -449,13 +458,14 @@ public function testAdd() 'orientation' => $rack::REAR, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', @@ -463,11 +473,11 @@ public function testAdd() 'orientation' => $rack::REAR, 'hpos' => $rack::POS_RIGHT ]) - )->isGreaterThan(0); + ); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', @@ -475,13 +485,14 @@ public function testAdd() 'orientation' => $rack::REAR, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', @@ -489,7 +500,7 @@ public function testAdd() 'orientation' => $rack::FRONT, 'hpos' => $rack::POS_RIGHT ]) - )->isGreaterThan(0); + ); } /** @@ -542,19 +553,22 @@ public function testRackIssues() // Update the ComputerModel for ($i = 1; $i < 15; $i++) { - $this->boolean($model1->update([ - 'id' => $model1->getID(), - 'required_units' => $i, - ]))->isEqualTo($i <= 10); + $this->assertEquals( + $i <= 10, + $model1->update([ + 'id' => $model1->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); // Update the ComputerModel - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, - ]))->isTrue(); + ])); // Add a new Computer with a new ComputerModel $model2 = $this->createItem( @@ -588,146 +602,158 @@ public function testRackIssues() // Update the ComputerModel for ($i = 1; $i < 15; $i++) { - $this->boolean($model2->update([ - 'id' => $model2->getID(), - 'required_units' => $i, - ]))->isEqualTo($i <= 8); + $this->assertEquals( + $i <= 8, + $model2->update([ + 'id' => $model2->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); // Update the ComputerModel - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'required_units' => 1, - ]))->isTrue(); + ])); // Update the ComputerModel - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'is_half_rack' => 1, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'is_half_rack' => 1, - ]))->isTrue(); + ])); // Update the Item_Rack - $this->boolean($itemRack1->update([ + $this->assertTrue($itemRack1->update([ 'id' => $itemRack1->getID(), 'hpos' => 1, - ]))->isTrue(); + ])); - $this->boolean($itemRack2->update([ + $this->assertTrue($itemRack2->update([ 'id' => $itemRack2->getID(), 'hpos' => 2, - ]))->isTrue(); + ])); // Update the ComputerModel for ($i = 1; $i <= 10; $i++) { - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => $i, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'required_units' => $i, - ]))->isTrue(); + ])); } // Update the ComputerModel - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'is_half_rack' => 0, 'required_units' => 1, - ]))->isTrue(); + ])); // Update the ComputerModel for ($i = 1; $i <= 5; $i++) { - $this->boolean($model1->update([ - 'id' => $model1->getID(), - 'required_units' => $i, - ]))->isEqualTo($i < 3); + $this->assertEquals( + $i < 3, + $model1->update([ + 'id' => $model1->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); // Update the ComputerModel - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, - ]))->isTrue(); + ])); // Test orientation - $this->boolean($itemRack1->update([ + $this->assertTrue($itemRack1->update([ 'id' => $itemRack1->getID(), 'orientation' => Rack::REAR, 'hpos' => Rack::POS_LEFT, - ]))->isTrue(); + ])); - $this->boolean($itemRack2->update([ + $this->assertTrue($itemRack2->update([ 'id' => $itemRack2->getID(), 'orientation' => Rack::FRONT, 'is_half_rack' => 0, - ]))->isTrue(); + ])); for ($i = 1; $i <= 10; $i++) { - $this->boolean($model1->update([ - 'id' => $model1->getID(), - 'required_units' => $i, - ]))->isEqualTo($i < 3); + $this->assertEquals( + $i < 3, + $model1->update([ + 'id' => $model1->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); // Test depth - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, 'depth' => 0.5, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'depth' => 0.5, - ]))->isTrue(); + ])); for ($i = 1; $i <= 10; $i++) { - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => $i, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'required_units' => $i, - ]))->isTrue(); + ])); } - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, 'depth' => 0.5, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'required_units' => 1, 'depth' => 1, - ]))->isTrue(); + ])); for ($i = 1; $i <= 10; $i++) { - $this->boolean($model1->update([ - 'id' => $model1->getID(), - 'required_units' => $i, - ]))->isEqualTo($i < 3); + $this->assertEquals( + $i < 3, + $model1->update([ + 'id' => $model1->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); @@ -782,7 +808,7 @@ public function testUpdateItemHorizontalPosition() ); // Check horizontal position - $this->integer($itemRack->fields['hpos'])->isEqualTo(Rack::POS_NONE); + $this->assertEquals(Rack::POS_NONE, $itemRack->fields['hpos']); // Update model $this->updateItem( @@ -795,7 +821,7 @@ public function testUpdateItemHorizontalPosition() $itemRack->getFromDB($itemRack->getID()); // Check horizontal position - $this->integer($itemRack->fields['hpos'])->isEqualTo(Rack::POS_LEFT); + $this->assertEquals(Rack::POS_LEFT, $itemRack->fields['hpos']); // Update model $this->updateItem( @@ -808,7 +834,7 @@ public function testUpdateItemHorizontalPosition() $itemRack->getFromDB($itemRack->getID()); // Check horizontal position - $this->integer($itemRack->fields['hpos'])->isEqualTo(Rack::POS_NONE); + $this->assertEquals(Rack::POS_NONE, $itemRack->fields['hpos']); // Update item rack $this->updateItem( @@ -830,6 +856,6 @@ public function testUpdateItemHorizontalPosition() $itemRack->getFromDB($itemRack->getID()); // Check horizontal position - $this->integer($itemRack->fields['hpos'])->isEqualTo(Rack::POS_RIGHT); + $this->assertEquals(Rack::POS_RIGHT, $itemRack->fields['hpos']); } } diff --git a/tests/functional/Item_SoftwareLicense.php b/phpunit/functional/Item_SoftwareLicenseTest.php similarity index 69% rename from tests/functional/Item_SoftwareLicense.php rename to phpunit/functional/Item_SoftwareLicenseTest.php index d1aab6c3658..e49e25a2f55 100644 --- a/tests/functional/Item_SoftwareLicense.php +++ b/phpunit/functional/Item_SoftwareLicenseTest.php @@ -39,36 +39,36 @@ /* Test for inc/item_softwarelicense.class.php */ -class Item_SoftwareLicense extends DbTestCase +class Item_SoftwareLicenseTest extends DbTestCase { public function testCountForLicense() { $this->login(); - // Check new functionality + // Check new functionality $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_1'); - $this->integer((int)\Item_SoftwareLicense::countForLicense($lic->fields['id']))->isIdenticalTo(3); + $this->assertSame(3, \Item_SoftwareLicense::countForLicense($lic->fields['id'])); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_2'); - $this->integer((int)\Item_SoftwareLicense::countForLicense($lic->fields['id']))->isIdenticalTo(2); + $this->assertSame(2, \Item_SoftwareLicense::countForLicense($lic->fields['id'])); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_3'); - $this->integer((int)\Item_SoftwareLicense::countForLicense($lic->fields['id']))->isIdenticalTo(2); + $this->assertSame(2, \Item_SoftwareLicense::countForLicense($lic->fields['id'])); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); - $this->integer((int)\Item_SoftwareLicense::countForLicense($lic->fields['id']))->isIdenticalTo(0); + $this->assertSame(0, \Item_SoftwareLicense::countForLicense($lic->fields['id'])); } public function testCountForSoftware() { $this->login(); - //Check new functionality + //Check new functionality $soft = getItemByTypeName('Software', '_test_soft'); - $this->integer((int)\Item_SoftwareLicense::countForSoftware($soft->fields['id']))->isIdenticalTo(7); + $this->assertSame(7, \Item_SoftwareLicense::countForSoftware($soft->fields['id'])); $soft = getItemByTypeName('Software', '_test_soft2'); - $this->integer((int)\Item_SoftwareLicense::countForSoftware($soft->fields['id']))->isIdenticalTo(0); + $this->assertSame(0, \Item_SoftwareLicense::countForSoftware($soft->fields['id'])); } public function testGetLicenseForInstallation() @@ -78,38 +78,39 @@ public function testGetLicenseForInstallation() $this->Login(); - $this->array( + $this->assertEmpty( \Item_SoftwareLicense::getLicenseForInstallation( 'Computer', $computer1->fields['id'], $version1->fields['id'] ) - )->isEmpty(); + ); - //simulate license install + //simulate license install $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_1'); - $this->boolean( + $this->assertTrue( $lic->update([ 'id' => $lic->fields['id'], 'softwareversions_id_use' => $version1->fields['id'] ]) - )->isTrue(); + ); - $this->array( + $this->assertCount( + 1, \Item_SoftwareLicense::getLicenseForInstallation( 'Computer', $computer1->fields['id'], $version1->fields['id'] ) - )->hasSize(1); + ); - //reset license - $this->boolean( + //reset license + $this->assertTrue( $lic->update([ 'id' => $lic->fields['id'], 'softwareversions_id_use' => 0 ]) - )->isTrue(); + ); } public function testAddUpdateDelete() @@ -127,31 +128,31 @@ public function testAddUpdateDelete() 'itemtype' => 'Computer', 'softwarelicenses_id' => $lic->fields['id'], ]; - $this->integer((int)$lic_computer->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$lic_computer->add($input)); $input = [ 'items_id' => $computer2->fields['id'], 'itemtype' => 'Computer', 'softwarelicenses_id' => $lic->fields['id'], ]; - $this->integer((int)$lic_computer->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$lic_computer->add($input)); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); - //License is valid: the number of affectations doesn't exceed declared number - $this->variable($lic->fields['is_valid'])->isEqualTo(1); + //License is valid: the number of affectations doesn't exceed declared number + $this->assertEquals(1, $lic->fields['is_valid']); $input = [ 'items_id' => $computer3->fields['id'], 'itemtype' => 'Computer', 'softwarelicenses_id' => $lic->fields['id'] ]; - $this->integer((int)$lic_computer->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$lic_computer->add($input)); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); - //Number of affectations exceed the number declared in the license - $this->variable($lic->fields['is_valid'])->isEqualTo(0); + //Number of affectations exceed the number declared in the license + $this->assertEquals(0, $lic->fields['is_valid']); - //test upgrade + //test upgrade $old_lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); $new_lic = getItemByTypeName('SoftwareLicense', '_test_softlic_3'); @@ -162,21 +163,20 @@ public function testAddUpdateDelete() 'itemtype' => 'Computer', 'softwarelicenses_id' => $old_lic->fields['id'] ]); - $this->boolean($lic_computer->getFromDB(array_keys($result)[0]))->isTrue(); + $this->assertTrue($lic_computer->getFromDB(array_keys($result)[0])); $lic_computer->upgrade($lic_computer->getID(), $new_lic->fields['id']); - $this->variable($lic_computer->fields['softwarelicenses_id']) - ->isNotEqualTo($old_lic->getID()) - ->isEqualTo($new_lic->getID()); + $this->assertNotEquals($old_lic->getID(), $lic_computer->fields['softwarelicenses_id']); + $this->assertEquals($new_lic->getID(), $lic_computer->fields['softwarelicenses_id']); - //test delete + //test delete $lic_computer = new \Item_SoftwareLicense(); - $this->boolean($lic_computer->deleteByCriteria(['softwarelicenses_id' => $lic->fields['id']], true))->isTrue(); + $this->assertTrue($lic_computer->deleteByCriteria(['softwarelicenses_id' => $lic->fields['id']], true)); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); - //Number of installations shouldn't now exceed the number declared in the license - $this->variable($lic->fields['is_valid'])->isEqualTo(1); + //Number of installations shouldn't now exceed the number declared in the license + $this->assertEquals(1, $lic->fields['is_valid']); } @@ -197,17 +197,15 @@ public function testCloneItem() 'items_id' => $source_computer->fields['id'], 'itemtype' => 'Computer' ]; - $this->integer((int)countElementsInTable('glpi_items_softwarelicenses', $input)) - ->isIdenticalTo(3); + $this->assertSame(3, countElementsInTable('glpi_items_softwarelicenses', $input)); $input = [ 'items_id' => $target_computer->fields['id'], 'itemtype' => 'Computer' ]; - $this->integer((int)countElementsInTable('glpi_items_softwarelicenses', $input)) - ->isIdenticalTo(3); + $this->assertSame(3, countElementsInTable('glpi_items_softwarelicenses', $input)); - //cleanup + //cleanup $lic_computer = new \Item_SoftwareLicense(); $lic_computer->deleteByCriteria([ 'items_id' => $target_computer->fields['id'], @@ -221,14 +219,14 @@ public function testGetTabNameForItem() $license = getItemByTypeName('SoftwareLicense', '_test_softlic_2'); $cSoftwareLicense = new \Item_SoftwareLicense(); - $this->string($cSoftwareLicense->getTabNameForItem(new \Computer(), 0))->isEmpty(); - $this->string($cSoftwareLicense->getTabNameForItem($license, 1))->isEmpty(); + $this->assertEmpty($cSoftwareLicense->getTabNameForItem(new \Computer(), 0)); + $this->assertEmpty($cSoftwareLicense->getTabNameForItem($license, 1)); $_SESSION['glpishow_count_on_tabs'] = 0; $expected = [1 => __('Summary'), 2 => _n('Item', 'Items', \Session::getPluralNumber()) ]; - $this->array($cSoftwareLicense->getTabNameForItem($license, 0))->isIdenticalTo($expected); + $this->assertSame($expected, $cSoftwareLicense->getTabNameForItem($license, 0)); $_SESSION['glpishow_count_on_tabs'] = 1; $expected = [1 => __('Summary'), @@ -237,7 +235,7 @@ public function testGetTabNameForItem() 2 ) ]; - $this->array($cSoftwareLicense->getTabNameForItem($license, 0))->isIdenticalTo($expected); + $this->assertSame($expected, $cSoftwareLicense->getTabNameForItem($license, 0)); } public function testCountLicenses() @@ -245,10 +243,10 @@ public function testCountLicenses() $this->login(); $software = getItemByTypeName('Software', '_test_soft'); - $this->integer((int)\Item_SoftwareLicense::countLicenses($software->getID()))->isIdenticalTo(5); + $this->assertSame(5, \Item_SoftwareLicense::countLicenses($software->getID())); $software = getItemByTypeName('Software', '_test_soft2'); - $this->integer((int)\Item_SoftwareLicense::countLicenses($software->getID()))->isIdenticalTo(0); + $this->assertSame(0, \Item_SoftwareLicense::countLicenses($software->getID())); } public function testGetSearchOptionsNew() @@ -256,7 +254,6 @@ public function testGetSearchOptionsNew() $this->login(); $cSoftwareLicense = new \Item_SoftwareLicense(); - $this->array($cSoftwareLicense->rawSearchOptions()) - ->hasSize(5); + $this->assertCount(5, $cSoftwareLicense->rawSearchOptions()); } } diff --git a/tests/functional/Item_SoftwareVersion.php b/phpunit/functional/Item_SoftwareVersionTest.php similarity index 62% rename from tests/functional/Item_SoftwareVersion.php rename to phpunit/functional/Item_SoftwareVersionTest.php index 00d6d90f084..d46358bcf56 100644 --- a/tests/functional/Item_SoftwareVersion.php +++ b/phpunit/functional/Item_SoftwareVersionTest.php @@ -42,13 +42,13 @@ /** * @engine isolate */ -class Item_SoftwareVersion extends DbTestCase +class Item_SoftwareVersionTest extends DbTestCase { public function testTypeName() { - $this->string(\Item_SoftwareVersion::getTypeName(1))->isIdenticalTo('Installation'); - $this->string(\Item_SoftwareVersion::getTypeName(0))->isIdenticalTo('Installations'); - $this->string(\Item_SoftwareVersion::getTypeName(10))->isIdenticalTo('Installations'); + $this->assertSame('Installation', \Item_SoftwareVersion::getTypeName(1)); + $this->assertSame('Installations', \Item_SoftwareVersion::getTypeName(0)); + $this->assertSame('Installations', \Item_SoftwareVersion::getTypeName(10)); } public function testPrepareInputForAdd() @@ -60,11 +60,14 @@ public function testPrepareInputForAdd() // Do some installations $ins = new \Item_SoftwareVersion(); - $this->integer((int)$ins->add([ - 'items_id' => $computer1->getID(), - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer1->getID(), + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); $input = [ 'items_id' => $computer1->getID(), @@ -83,7 +86,7 @@ public function testPrepareInputForAdd() ]; $this->setEntity('_test_root_entity', true); - $this->array($ins->prepareInputForAdd($input))->isIdenticalTo($expected); + $this->assertSame($expected, $ins->prepareInputForAdd($input)); } public function testPrepareInputForUpdate() @@ -95,11 +98,14 @@ public function testPrepareInputForUpdate() // Do some installations $ins = new \Item_SoftwareVersion(); - $this->integer((int)$ins->add([ - 'items_id' => $computer1->getID(), - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer1->getID(), + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); $input = [ 'items_id' => $computer1->getID(), @@ -115,7 +121,7 @@ public function testPrepareInputForUpdate() 'is_deleted_item' => $computer1->getField('is_deleted') ]; - $this->array($ins->prepareInputForUpdate($input))->isIdenticalTo($expected); + $this->assertSame($expected, $ins->prepareInputForUpdate($input)); } @@ -130,34 +136,40 @@ public function testCountInstall() // Do some installations $ins = new \Item_SoftwareVersion(); - $this->integer((int)$ins->add([ - 'items_id' => $computer1, - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); - $this->integer($ins->add([ - 'items_id' => $computer11, - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); - $this->integer($ins->add([ - 'items_id' => $computer12, - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer1, + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer11, + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer12, + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); - // Count installations + // Count installations $this->setEntity('_test_root_entity', true); - $this->integer((int)\Item_SoftwareVersion::countForVersion($ver), 'count in all tree') - ->isIdenticalTo(3); + $this->assertSame(3, \Item_SoftwareVersion::countForVersion($ver), 'count in all tree'); $this->setEntity('_test_root_entity', false); - $this->integer((int)\Item_SoftwareVersion::countForVersion($ver), 'count in root') - ->isIdenticalTo(1); + $this->assertSame(1, \Item_SoftwareVersion::countForVersion($ver), 'count in root'); $this->setEntity('_test_child_1', false); - $this->integer((int)\Item_SoftwareVersion::countForVersion($ver), 'count in child') - ->isIdenticalTo(2); + $this->assertSame(2, \Item_SoftwareVersion::countForVersion($ver), 'count in child'); } public function testUpdateDatasFromComputer() @@ -167,47 +179,47 @@ public function testUpdateDatasFromComputer() $ver1 = getItemByTypeName('SoftwareVersion', '_test_softver_1', true); $ver2 = getItemByTypeName('SoftwareVersion', '_test_softver_2', true); - // Do some installations + // Do some installations $softver = new \Item_SoftwareVersion(); $softver01 = $softver->add([ 'items_id' => $computer1->getID(), 'itemtype' => 'Computer', 'softwareversions_id' => $ver1, ]); - $this->integer((int)$softver01)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$softver01); $softver02 = $softver->add([ 'items_id' => $computer1->getID(), 'itemtype' => 'Computer', 'softwareversions_id' => $ver2, ]); - $this->integer((int)$softver02)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$softver02); foreach ([$softver01, $softver02] as $tsoftver) { $o = new \Item_SoftwareVersion(); - $this->boolean($o->getFromDb($tsoftver))->isTrue(); - $this->variable($o->getField('is_deleted_item'))->isEqualTo(0); + $this->assertTrue($o->getFromDb($tsoftver)); + $this->assertEquals(0, $o->getField('is_deleted_item')); } - //computer that does not exists - $this->boolean($softver->updateDatasForItem('Computer', $c00))->isFalse(); + //computer that does not exist + $this->assertFalse($softver->updateDatasForItem('Computer', $c00)); - //update existing computer + //update existing computer $input = $computer1->fields; $input['is_deleted'] = '1'; - $this->boolean($computer1->update($input))->isTrue(); + $this->assertTrue($computer1->update($input)); - $this->boolean($softver->updateDatasForItem('Computer', $computer1->getID()))->isTrue(); + $this->assertTrue($softver->updateDatasForItem('Computer', $computer1->getID())); - //check if all has been updated + //check if all has been updated foreach ([$softver01, $softver02] as $tsoftver) { $o = new \Item_SoftwareVersion(); - $this->boolean($o->getFromDb($tsoftver))->isTrue(); - $this->variable($o->getField('is_deleted_item'))->isEqualTo(1); + $this->assertTrue($o->getFromDb($tsoftver)); + $this->assertEquals(1, $o->getField('is_deleted_item')); } - //restore computer state + //restore computer state $input['is_deleted'] = '0'; - $this->boolean($computer1->update($input))->isTrue(); + $this->assertTrue($computer1->update($input)); } public function testCountForSoftware() @@ -217,21 +229,24 @@ public function testCountForSoftware() $this->Login(); - $this->integer( - (int)\Item_SoftwareVersion::countForSoftware($soft1->fields['id']) - )->isIdenticalTo(0); + $this->assertSame( + 0, + \Item_SoftwareVersion::countForSoftware($soft1->fields['id']) + ); $csoftver = new \Item_SoftwareVersion(); - $this->integer( - (int)$csoftver->add([ + $this->assertGreaterThan( + 0, + $csoftver->add([ 'items_id' => $computer1->fields['id'], 'itemtype' => 'Computer', 'softwareversions_id' => $soft1->fields['id'] ]) - )->isGreaterThan(0); + ); - $this->integer( - (int)\Item_SoftwareVersion::countForSoftware($soft1->fields['id']) - )->isIdenticalTo(1); + $this->assertSame( + 1, + \Item_SoftwareVersion::countForSoftware($soft1->fields['id']) + ); } } diff --git a/tests/functional/KnowbaseItem.php b/phpunit/functional/KnowbaseItemTest.php similarity index 85% rename from tests/functional/KnowbaseItem.php rename to phpunit/functional/KnowbaseItemTest.php index 0e2462cf6a8..03318e10a36 100644 --- a/tests/functional/KnowbaseItem.php +++ b/phpunit/functional/KnowbaseItemTest.php @@ -40,17 +40,17 @@ /* Test for inc/knowbaseitem.class.php */ -class KnowbaseItem extends DbTestCase +class KnowbaseItemTest extends DbTestCase { public function testGetTypeName() { $expected = 'Knowledge base'; - $this->string(\KnowbaseItem::getTypeName(1))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem::getTypeName(1)); $expected = 'Knowledge base'; - $this->string(\KnowbaseItem::getTypeName(0))->isIdenticalTo($expected); - $this->string(\KnowbaseItem::getTypeName(2))->isIdenticalTo($expected); - $this->string(\KnowbaseItem::getTypeName(10))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem::getTypeName(0)); + $this->assertSame($expected, \KnowbaseItem::getTypeName(2)); + $this->assertSame($expected, \KnowbaseItem::getTypeName(10)); } public function testCleanDBonPurge() @@ -60,7 +60,8 @@ public function testCleanDBonPurge() $users_id = getItemByTypeName('User', TU_USER, true); $kb = new \KnowbaseItem(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kb->add([ 'name' => 'Test to remove', 'answer' => 'An KB entry to remove', @@ -68,9 +69,9 @@ public function testCleanDBonPurge() 'users_id' => $users_id, 'date' => '2017-10-06 12:27:48', ]) - )->isGreaterThan(0); + ); - //add some comments + //add some comments $comment = new \KnowbaseItem_Comment(); $input = [ 'knowbaseitems_id' => $kb->getID(), @@ -80,73 +81,80 @@ public function testCleanDBonPurge() $id = 0; for ($i = 0; $i < 4; ++$i) { $input['comment'] = "Comment $i"; - $this->integer( + $this->assertGreaterThan( + $id, (int)$comment->add($input) - )->isGreaterThan($id); + ); $id = (int)$comment->getID(); } - //change KB entry - $this->boolean( + //change KB entry + $this->assertTrue( $kb->update([ 'id' => $kb->getID(), 'answer' => 'Answer has changed' ]) - )->isTrue(); + ); - //add an user + //add an user $kbu = new \KnowbaseItem_User(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbu->add([ 'knowbaseitems_id' => $kb->getID(), 'users_id' => $users_id ]) - )->isGreaterThan(0); + ); - //add an entity + //add an entity $kbe = new \Entity_KnowbaseItem(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbe->add([ 'knowbaseitems_id' => $kb->getID(), 'entities_id' => 0 ]) - )->isGreaterThan(0); + ); - //add a group + //add a group $group = new \Group(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$group->add([ 'name' => 'KB group' ]) - )->isGreaterThan(0); + ); $kbg = new \Group_KnowbaseItem(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbg->add([ 'knowbaseitems_id' => $kb->getID(), 'groups_id' => $group->getID() ]) - )->isGreaterThan(0); + ); - //add a profile + //add a profile $profiles_id = getItemByTypeName('Profile', 'Admin', true); $kbp = new \KnowbaseItem_Profile(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbp->add([ 'knowbaseitems_id' => $kb->getID(), 'profiles_id' => $profiles_id ]) - )->isGreaterThan(0); + ); - //add an item + //add an item $kbi = new \KnowbaseItem_Item(); $tickets_id = getItemByTypeName('Ticket', '_ticket01', true); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbi->add([ 'knowbaseitems_id' => $kb->getID(), 'itemtype' => 'Ticket', 'items_id' => $tickets_id ]) - )->isGreaterThan(0); + ); $relations = [ $comment->getTable(), @@ -164,21 +172,21 @@ public function testCleanDBonPurge() 'FROM' => $relation, 'WHERE' => ['knowbaseitems_id' => $kb->getID()] ]); - $this->integer(count($iterator))->isGreaterThan(0); + $this->assertGreaterThan(0, count($iterator)); } - //remove KB entry - $this->boolean( + //remove KB entry + $this->assertTrue( $kb->delete(['id' => $kb->getID()], true) - )->isTrue(); + ); - //check all relations has been removed + //check all relations has been removed foreach ($relations as $relation) { $iterator = $DB->request([ 'FROM' => $relation, 'WHERE' => ['knowbaseitems_id' => $kb->getID()] ]); - $this->integer(count($iterator))->isIdenticalTo(0); + $this->assertSame(0, count($iterator)); } } @@ -187,8 +195,11 @@ public function testScreenshotConvertedIntoDocument() $this->login(); // must be logged as Document_Item uses Session::getLoginUserID() - // Test uploads for item creation - $base64Image = base64_encode(file_get_contents(__DIR__ . '/../fixtures/uploads/foo.png')); + // Test uploads for item creation + $fpath = FIXTURE_DIR . '/uploads/foo.png'; + $fcontents = file_get_contents($fpath); + $this->assertNotSame(false, $fcontents, 'Cannot read ' . $fpath); + $base64Image = base64_encode($fcontents); $filename = '5e5e92ffd9bd91.11111111image_paste22222222.png'; $users_id = getItemByTypeName('User', TU_USER, true); $instance = new \KnowbaseItem(); @@ -212,15 +223,22 @@ public function testScreenshotConvertedIntoDocument() 'users_id' => $users_id, 'date' => '2017-10-06 12:27:48', ]; - copy(__DIR__ . '/../fixtures/uploads/foo.png', GLPI_TMP_DIR . '/' . $filename); - $instance->add($input); - $this->boolean($instance->isNewItem())->isFalse(); - $this->boolean($instance->getFromDB($instance->getId()))->isTrue(); + $fpath = FIXTURE_DIR . '/uploads/foo.png'; + $this->assertTrue( + copy($fpath, GLPI_TMP_DIR . '/' . $filename), + 'Cannot copy ' . $fpath + ); + $this->assertGreaterThan(0, $instance->add($input)); + $this->assertFalse($instance->isNewItem()); + $this->assertTrue($instance->getFromDB($instance->getId())); $expected = 'a href="/front/document.send.php?docid='; - $this->string($instance->fields['answer'])->contains($expected); + $this->assertStringContainsString($expected, $instance->fields['answer']); - // Test uploads for item update - $base64Image = base64_encode(file_get_contents(__DIR__ . '/../fixtures/uploads/bar.png')); + // Test uploads for item update + $fpath = FIXTURE_DIR . '/uploads/bar.png'; + $fcontents = file_get_contents($fpath); + $this->assertNotSame(false, $fcontents, 'Cannot read ' . $fpath); + $base64Image = base64_encode($fcontents); $filename = '5e5e92ffd9bd91.44444444image_paste55555555.png'; $tmpFilename = GLPI_TMP_DIR . '/' . $filename; file_put_contents($tmpFilename, base64_decode($base64Image)); @@ -241,11 +259,11 @@ public function testScreenshotConvertedIntoDocument() '5e5e92ffd9bd91.44444444', ], ]); - $this->boolean($success)->isTrue(); - $this->boolean($instance->getFromDB($instance->getId()))->isTrue(); - // Ensure there is an anchor to the uploaded document + $this->assertTrue($success); + $this->assertTrue($instance->getFromDB($instance->getId())); + // Ensure there is an anchor to the uploaded document $expected = 'a href="/front/document.send.php?docid='; - $this->string($instance->fields['answer'])->contains($expected); + $this->assertStringContainsString($expected, $instance->fields['answer']); } public function testUploadDocuments() @@ -253,7 +271,7 @@ public function testUploadDocuments() $this->login(); // must be logged as Document_Item uses Session::getLoginUserID() - // Test uploads for item creation + // Test uploads for item creation $filename = '5e5e92ffd9bd91.11111111' . 'foo.txt'; $instance = new \KnowbaseItem(); $input = [ @@ -269,19 +287,27 @@ public function testUploadDocuments() '5e5e92ffd9bd91.11111111', ] ]; - copy(__DIR__ . '/../fixtures/uploads/foo.txt', GLPI_TMP_DIR . '/' . $filename); + $fpath = FIXTURE_DIR . '/uploads/foo.txt'; + $this->assertTrue( + copy($fpath, GLPI_TMP_DIR . '/' . $filename), + 'Cannot copy ' . $fpath + ); $instance->add($input); - $this->boolean($instance->isNewItem())->isFalse(); - $this->string($instance->fields['answer'])->contains('testUploadDocuments'); + $this->assertFalse($instance->isNewItem()); + $this->assertStringContainsString('testUploadDocuments', $instance->fields['answer']); $count = (new \DBUtils())->countElementsInTable(\Document_Item::getTable(), [ 'itemtype' => 'KnowbaseItem', 'items_id' => $instance->getID(), ]); - $this->integer($count)->isEqualTo(1); + $this->assertEquals(1, $count); - // Test uploads for item update (adds a 2nd document) + // Test uploads for item update (adds a 2nd document) $filename = '5e5e92ffd9bd91.44444444bar.txt'; - copy(__DIR__ . '/../fixtures/uploads/bar.txt', GLPI_TMP_DIR . '/' . $filename); + $fpath = FIXTURE_DIR . '/uploads/bar.txt'; + $this->assertTrue( + copy($fpath, GLPI_TMP_DIR . '/' . $filename), + 'Cannot copy ' . $fpath + ); $success = $instance->update([ 'id' => $instance->getID(), 'answer' => 'update testUploadDocuments', @@ -295,55 +321,63 @@ public function testUploadDocuments() '5e5e92ffd9bd91.44444444', ] ]); - $this->boolean($success)->isTrue(); - $this->string($instance->fields['answer'])->contains('update testUploadDocuments'); + $this->assertTrue($success); + $this->assertStringContainsString('update testUploadDocuments', $instance->fields['answer']); $count = (new \DBUtils())->countElementsInTable(\Document_Item::getTable(), [ 'itemtype' => 'KnowbaseItem', 'items_id' => $instance->getID(), ]); - $this->integer($count)->isEqualTo(2); + $this->assertEquals(2, $count); } public function testGetForCategory() { global $DB; + $orig_db = clone $DB; + + // Prepare mocks + $m_db = $this->getMockBuilder(\DB::class) + ->onlyMethods(['request']) + ->disableOriginalConstructor() + ->getMock(); - // Prepare mocks - $m_db = new \mock\DB(); - $m_kbi = new \mock\KnowbaseItem(); + $m_kbi = $this->getMockBuilder(\KnowbaseItem::class) + ->onlyMethods(['getFromDB', 'canViewItem']) + ->getMock(); - // Mocked db request result + // Mocked db request result $it = new \ArrayIterator([ ['id' => '1'], ['id' => '2'], ['id' => '3'], ]); - $this->calling($m_db)->request = $it; + $m_db->method('request')->willReturn($it); - // Ignore get fromDB - $this->calling($m_kbi)->getFromDB = true; + // Ignore get fromDB + $m_kbi->method('getFromDB')->willReturn(true); - // True for call 1 & 3, false for call 2 and every following calls - $this->calling($m_kbi)->canViewItem[0] = false; - $this->calling($m_kbi)->canViewItem[1] = true; - $this->calling($m_kbi)->canViewItem[2] = false; - $this->calling($m_kbi)->canViewItem[3] = true; + // True for call 1 & 3, false for call 2 and every following calls + $m_kbi->method('canViewItem')->willReturn(true, false, true, false); - // Replace global DB with mocked DB + // Expected : [1, 3] + // Replace global DB with mocked DB $DB = $m_db; - - // Expected : [1, 3] - $this->array(\KnowbaseItem::getForCategory(1, $m_kbi)) - ->hasSize(2) - ->containsValues([1, 3]); - - // Expected : [-1] - $this->array(\KnowbaseItem::getForCategory(1, $m_kbi)) - ->hasSize(1) - ->contains(-1); + $result = \KnowbaseItem::getForCategory(1, $m_kbi); + $DB = $orig_db; + $this->assertCount(2, $result); + $this->assertContains('1', $result); + $this->assertContains('3', $result); + + // Expected : [-1] + // Replace global DB with mocked DB + $DB = $m_db; + $result = \KnowbaseItem::getForCategory(1, $m_kbi); + $DB = $orig_db; + $this->assertCount(1, $result); + $this->assertContains(-1, $result); } - protected function fullTextSearchProvider(): iterable + public static function fullTextSearchProvider(): iterable { // Spaces around search terms are trimmed yield [ @@ -499,15 +533,15 @@ protected function fullTextSearchProvider(): iterable } /** - * @dataprovider fullTextSearchProvider + * @dataProvider fullTextSearchProvider */ public function testComputeBooleanFullTextSearch(string $search, string $expected): void { - $search = $this->callPrivateMethod($this->newTestedInstance(), 'computeBooleanFullTextSearch', $search); - $this->string($search)->isEqualTo($expected); + $search = $this->callPrivateMethod(new \KnowbaseItem(), 'computeBooleanFullTextSearch', $search); + $this->assertEquals($expected, $search); } - protected function testGetListRequestProvider(): array + public static function testGetListRequestProvider(): array { return [ [ @@ -690,7 +724,7 @@ protected function testGetListRequestProvider(): array } /** - * @dataprovider testGetListRequestProvider + * @dataProvider testGetListRequestProvider */ public function testGetListRequest(array $params, string $type, int $count, ?array $sort): void { @@ -699,24 +733,24 @@ public function testGetListRequest(array $params, string $type, int $count, ?arr // Build criteria array $criteria = \KnowbaseItem::getListRequest($params, $type); - $this->array($criteria); + $this->assertIsArray($criteria); // Check that the request is valid $iterator = $DB->request($criteria); //count KnowBaseItem found - $this->integer($iterator->numrows())->isEqualTo($count); + $this->assertEquals($count, $iterator->numrows()); // check order if needed if ($sort != null) { $names = array_column(iterator_to_array($iterator), 'name'); - $this->array($names)->isEqualTo($sort); + $this->assertEquals($sort, $names); } } public function testGetAnswerAnchors(): void { - // Create test KB with multiple headers + // Create test KB with multiple headers $kb_name = 'Test testGetAnswerAnchors' . mt_rand(); $input = [ 'name' => $kb_name, @@ -724,26 +758,27 @@ public function testGetAnswerAnchors(): void ]; $this->createItems('KnowbaseItem', [$input]); - // Load KB + // Load KB /** @var \KnowbaseItem */ $kbi = getItemByTypeName("KnowbaseItem", $kb_name); $answer = $kbi->getAnswer(); - // Test anchors, there should be one per header - $this->string($answer)->contains('