diff --git a/phpunit/DbTestCase.php b/phpunit/DbTestCase.php
index 0861b34c2a3..5b91d9330d8 100644
--- a/phpunit/DbTestCase.php
+++ b/phpunit/DbTestCase.php
@@ -86,9 +86,8 @@ protected function login(
*/
protected function logOut()
{
- $ctime = $_SESSION['glpi_currenttime'];
\Session::destroy();
- $_SESSION['glpi_currenttime'] = $ctime;
+ \Session::start();
}
/**
@@ -119,7 +118,7 @@ protected function checkInput(CommonDBTM $object, $id = 0, $input = [])
{
$input = Sanitizer::dbUnescapeRecursive($input); // slashes in input should not be stored in DB
- $this->assertGreaterThan(0, (int)$id);
+ $this->assertGreaterThan($object instanceof Entity ? -1 : 0, (int)$id);
$this->assertTrue($object->getFromDB($id));
$this->assertEquals($id, $object->getField('id'));
diff --git a/tests/NotificationSettingInstance.php b/phpunit/NotificationSettingInstance.php
similarity index 100%
rename from tests/NotificationSettingInstance.php
rename to phpunit/NotificationSettingInstance.php
diff --git a/tests/abstracts/AbstractPlanningEvent.php b/phpunit/abstracts/AbstractPlanningEvent.php
similarity index 78%
rename from tests/abstracts/AbstractPlanningEvent.php
rename to phpunit/abstracts/AbstractPlanningEvent.php
index 92487063319..2b3d3af47b6 100644
--- a/tests/abstracts/AbstractPlanningEvent.php
+++ b/phpunit/abstracts/AbstractPlanningEvent.php
@@ -45,9 +45,9 @@ abstract class AbstractPlanningEvent extends \DbTestCase
protected $exdate1 = "";
protected $exdate2 = "";
- public function beforeTestMethod($method)
+ public function setUp(): void
{
- parent::beforeTestMethod($method);
+ parent::setUp();
$this->now = time();
$this->duration = 2 * \HOUR_TIMESTAMP;
@@ -82,18 +82,20 @@ public function testAdd()
$event = new $this->myclass();
$id = $event->add($this->input);
- $this->integer((int) $id)->isGreaterThan(0);
- $this->boolean($event->getFromDB($id))->isTrue();
+ $this->assertGreaterThan(0, (int)$id);
+ $this->assertTrue($event->getFromDB($id));
// check end date
if (isset($event->fields['end'])) {
- $this->string($event->fields['end'])->isEqualTo($this->end);
+ $this->assertEquals($this->end, $event->fields['end']);
}
- // check rrule encoding
+ // check rrule encoding
$exp_exdates = '"exceptions":["' . $this->exdate1 . '","' . $this->exdate2 . '"]';
- $this->string($event->fields['rrule'])
- ->isEqualTo('{"freq":"daily","interval":1,"byweekday":"MO","bymonth":1,' . $exp_exdates . '}');
+ $this->assertEquals(
+ '{"freq":"daily","interval":1,"byweekday":"MO","bymonth":1,' . $exp_exdates . '}',
+ $event->fields['rrule']
+ );
return $event;
}
@@ -126,21 +128,21 @@ public function testUpdate()
'state' => \Planning::INFO,
'background' => 0,
]);
- $this->boolean($event->update($update))->isTrue();
+ $this->assertTrue($event->update($update));
- // check dates (we added duration to both dates on update)
+ // check dates (we added duration to both dates on update)
if (isset($event->fields['begin'])) {
- $this->string($event->fields['begin'])
- ->isEqualTo($new_begin);
+ $this->assertEquals($new_begin, $event->fields['begin']);
}
if (isset($event->fields['end'])) {
- $this->string($event->fields['end'])
- ->isEqualTo($new_end);
+ $this->assertEquals($new_end, $event->fields['end']);
}
- // check rrule encoding
- $this->string($event->fields['rrule'])
- ->isEqualTo('{"freq":"monthly","interval":2,"byweekday":"TU","bymonth":2}');
+ // check rrule encoding
+ $this->assertEquals(
+ '{"freq":"monthly","interval":2,"byweekday":"TU","bymonth":2}',
+ $event->fields['rrule']
+ );
}
@@ -150,11 +152,9 @@ public function testDelete()
$event = new $this->myclass();
$id = $event->add($this->input);
- $this->integer((int)$id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, (int)$id);
- $this->boolean($event->delete([
- 'id' => $id,
- ]))->isTrue();
- $this->boolean($event->getFromDB($id))->isFalse();
+ $this->assertTrue($event->delete(['id' => $id]));
+ $this->assertFalse($event->getFromDB($id));
}
}
diff --git a/phpunit/functional/CommonITILRecurrentTest.php b/phpunit/abstracts/CommonITILRecurrentTest.php
similarity index 100%
rename from phpunit/functional/CommonITILRecurrentTest.php
rename to phpunit/abstracts/CommonITILRecurrentTest.php
diff --git a/phpunit/bootstrap.php b/phpunit/bootstrap.php
index 1e181cd798d..dfa9cac5a7d 100644
--- a/phpunit/bootstrap.php
+++ b/phpunit/bootstrap.php
@@ -98,7 +98,7 @@
//include_once __DIR__ . '/FrontBaseClass.php';
include_once __DIR__ . '/RuleBuilder.php';
include_once __DIR__ . '/InventoryTestCase.php';
-include_once __DIR__ . '/functional/CommonITILRecurrentTest.php';
+include_once __DIR__ . '/abstracts/CommonITILRecurrentTest.php';
//include_once __DIR__ . '/functional/Glpi/ContentTemplates/Parameters/AbstractParameters.php';
include_once __DIR__ . '/AbstractRightsDropdown.php';
diff --git a/phpunit/functional/Calendar_HolidayTest.php b/phpunit/functional/Calendar_HolidayTest.php
index 8206345e573..d8d3f172cad 100644
--- a/phpunit/functional/Calendar_HolidayTest.php
+++ b/phpunit/functional/Calendar_HolidayTest.php
@@ -139,17 +139,17 @@ public function testHolidaysCache()
/*
$calendar = new Calendar();
$calendar_id = $calendar->add(['name' => 'Test']);
- $this->integer($calendar_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $calendar_id);
$this->validateHolidayCacheMatchesMethodResult($calendar_id);
$holiday_id = getItemByTypeName('Holiday', 'Winter holidays', true);
- $this->boolean($calendar_holiday->getFromDBByCrit(['holidays_id' => $holiday_id]))->isTrue();
+ $this->assertTrue($calendar_holiday->getFromDBByCrit(['holidays_id' => $holiday_id]));
$this->boolean(
$calendar_holiday->update(['id' => $calendar_holiday->fields['id'], 'calendars_id' => $calendar_id])
)->isTrue();
- $this->boolean($GLPI_CACHE->has($cache_key))->isFalse(); // Previously associated calendar cache is invalidated
- $this->boolean($GLPI_CACHE->has(sprintf('calendar-%s-holidays', $calendar_id)))->isFalse();
+ $this->assertFalse($GLPI_CACHE->has($cache_key)); // Previously associated calendar cache is invalidated
+ $this->assertFalse($GLPI_CACHE->has(sprintf('calendar-%s-holidays', $calendar_id)));
*/
}
diff --git a/tests/functional/Change.php b/phpunit/functional/ChangeTest.php
similarity index 79%
rename from tests/functional/Change.php
rename to phpunit/functional/ChangeTest.php
index 26695923d6b..1d56f95ba51 100644
--- a/tests/functional/Change.php
+++ b/phpunit/functional/ChangeTest.php
@@ -39,11 +39,11 @@
/* Test for inc/change.class.php */
-class Change extends DbTestCase
+class ChangeTest extends DbTestCase
{
public function testAddFromItem()
{
- // add change from a computer
+ // add change from a computer
$computer = getItemByTypeName('Computer', '_test_pc01');
$change = new \Change();
$changes_id = $change->add([
@@ -53,12 +53,12 @@ public function testAddFromItem()
'_from_itemtype' => 'Computer',
'_from_items_id' => $computer->getID(),
]);
- $this->integer($changes_id)->isGreaterThan(0);
- $this->boolean($change->getFromDB($changes_id))->isTrue();
+ $this->assertGreaterThan(0, $changes_id);
+ $this->assertTrue($change->getFromDB($changes_id));
- // check relation
+ // check relation
$change_item = new \Change_Item();
- $this->boolean($change_item->getFromDBForItems($change, $computer))->isTrue();
+ $this->assertTrue($change_item->getFromDBForItems($change, $computer));
}
public function testAssignFromCategory()
@@ -72,14 +72,14 @@ public function testAssignFromCategory()
'auto_assign_mode' => \Entity::CONFIG_NEVER,
]);
- $this->boolean($entity->isNewID($entityId))->isFalse();
+ $this->assertFalse($entity->isNewID($entityId));
$entity->getFromDB($entityId);
- $this->integer((int) $entity->fields['auto_assign_mode'])->isEqualTo(\Entity::CONFIG_NEVER);
+ $this->assertEquals(\Entity::CONFIG_NEVER, (int)$entity->fields['auto_assign_mode']);
- // Login again to acess the new entity
+ // Login again to acess the new entity
$this->login('glpi', 'glpi');
$success = \Session::changeActiveEntities($entity->getID(), true);
- $this->boolean($success)->isTrue();
+ $this->assertTrue($success);
$group = new \Group();
$group->add([
@@ -88,7 +88,7 @@ public function testAssignFromCategory()
'is_recursive' => '1',
'level' => 0,
]);
- $this->boolean($group->isNewItem())->isFalse();
+ $this->assertFalse($group->isNewItem());
$itilCategory = new \ITILCategory();
$itilCategory->add([
@@ -97,7 +97,7 @@ public function testAssignFromCategory()
'users_id' => 4, // Tech
'groups_id' => $group->getID(),
]);
- $this->boolean($itilCategory->isNewItem())->isFalse();
+ $this->assertFalse($itilCategory->isNewItem());
$change = new \Change();
$change->add([
@@ -105,7 +105,7 @@ public function testAssignFromCategory()
'content' => 'foo',
'itilcategories_id' => $itilCategory->getID(),
]);
- $this->boolean($change->isNewItem())->isFalse();
+ $this->assertFalse($change->isNewItem());
$change->getFromDB($change->getID());
$changeUser = new \Change_User();
$changeGroup = new \Change_Group();
@@ -113,13 +113,13 @@ public function testAssignFromCategory()
'changes_id' => $change->getID(),
'type' => \CommonITILActor::ASSIGN,
]);
- $this->integer(count($rows))->isEqualTo(0);
+ $this->assertCount(0, $rows);
$rows = $changeGroup->find([
'changes_id' => $change->getID(),
'type' => \CommonITILActor::ASSIGN,
]);
- // check Entity::AUTO_ASSIGN_HARDWARE_CATEGORY assignment
+ // check Entity::AUTO_ASSIGN_HARDWARE_CATEGORY assignment
$entity->update([
'id' => $entity->getID(),
'auto_assign_mode' => \Entity::AUTO_ASSIGN_HARDWARE_CATEGORY,
@@ -131,7 +131,7 @@ public function testAssignFromCategory()
'content' => 'foo',
'itilcategories_id' => $itilCategory->getID(),
]);
- $this->boolean($change->isNewItem())->isFalse();
+ $this->assertFalse($change->isNewItem());
$change->getFromDB($change->getID());
$changeUser = new \Change_User();
$changeGroup = new \Change_Group();
@@ -140,14 +140,14 @@ public function testAssignFromCategory()
'users_id' => 4, // Tech
'type' => \CommonITILActor::ASSIGN,
]);
- $this->integer(count($rows))->isEqualTo(0);
+ $this->assertCount(0, $rows);
$rows = $changeGroup->find([
'changes_id' => $change->getID(),
'groups_id' => $group->getID(),
'type' => \CommonITILActor::ASSIGN,
]);
- // check Entity::AUTO_ASSIGN_CATEGORY_HARDWARE assignment
+ // check Entity::AUTO_ASSIGN_CATEGORY_HARDWARE assignment
$entity->update([
'id' => $entity->getID(),
'auto_assign_mode' => \Entity::AUTO_ASSIGN_CATEGORY_HARDWARE,
@@ -159,7 +159,7 @@ public function testAssignFromCategory()
'content' => 'foo',
'itilcategories_id' => $itilCategory->getID(),
]);
- $this->boolean($change->isNewItem())->isFalse();
+ $this->assertFalse($change->isNewItem());
$change->getFromDB($change->getID());
$changeUser = new \Change_User();
$changeGroup = new \Change_Group();
@@ -168,29 +168,28 @@ public function testAssignFromCategory()
'users_id' => 4, // Tech
'type' => \CommonITILActor::ASSIGN,
]);
- $this->integer(count($rows))->isEqualTo(0);
+ $this->assertCount(0, $rows);
$rows = $changeGroup->find([
'changes_id' => $change->getID(),
'groups_id' => $group->getID(),
'type' => \CommonITILActor::ASSIGN,
]);
+ $this->assertCount(0, $rows);
}
public function testGetTeamRoles(): void
{
$roles = \Change::getTeamRoles();
- $this->array($roles)->containsValues([
- \CommonITILActor::ASSIGN,
- \CommonITILActor::OBSERVER,
- \CommonITILActor::REQUESTER,
- ]);
+ $this->assertContains(\CommonITILActor::ASSIGN, $roles);
+ $this->assertContains(\CommonITILActor::OBSERVER, $roles);
+ $this->assertContains(\CommonITILActor::REQUESTER, $roles);
}
public function testGetTeamRoleName(): void
{
$roles = \Change::getTeamRoles();
foreach ($roles as $role) {
- $this->string(\Change::getTeamRoleName($role))->isNotEmpty();
+ $this->assertNotEmpty(\Change::getTeamRoleName($role));
}
}
@@ -206,7 +205,7 @@ public function testAutomaticStatusChange()
]);
// Initial status is new (incoming)
- $this->integer($change->fields['status'])->isIdenticalTo(\CommonITILObject::INCOMING);
+ $this->assertSame(\CommonITILObject::INCOMING, $change->fields['status']);
$change->update([
'id' => $changes_id,
@@ -216,12 +215,12 @@ public function testAutomaticStatusChange()
],
]);
$test_users_id = getItemByTypeName('User', TU_USER, true);
- $this->integer($test_users_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $test_users_id);
// Verify user was assigned and status doesn't change
$change->loadActors();
- $this->integer($change->countUsers(\CommonITILActor::ASSIGN))->isIdenticalTo(1);
- $this->integer($change->fields['status'])->isIdenticalTo(\CommonITILObject::INCOMING);
+ $this->assertSame(1, $change->countUsers(\CommonITILActor::ASSIGN));
+ $this->assertSame(\CommonITILObject::INCOMING, $change->fields['status']);
// Change status to accepted
$change->update([
@@ -236,8 +235,8 @@ public function testAutomaticStatusChange()
'users_id' => getItemByTypeName('User', TU_USER, true),
]);
$change->getFromDB($changes_id);
- $this->integer($change->countUsers(\CommonITILActor::ASSIGN))->isIdenticalTo(0);
- $this->integer($change->fields['status'])->isIdenticalTo(\CommonITILObject::ACCEPTED);
+ $this->assertSame(0, $change->countUsers(\CommonITILActor::ASSIGN));
+ $this->assertSame(\CommonITILObject::ACCEPTED, $change->fields['status']);
}
public function testAddAdditionalActorsDuplicated()
@@ -248,7 +247,7 @@ public function testAddAdditionalActorsDuplicated()
'name' => "test add additional actors duplicated",
'content' => "test add additional actors duplicated",
]);
- $this->integer($changes_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $changes_id);
$users_id = getItemByTypeName('User', TU_USER, true);
@@ -261,7 +260,7 @@ public function testAddAdditionalActorsDuplicated()
]
]
]);
- $this->boolean($result)->isTrue();
+ $this->assertTrue($result);
$result = $change->update([
'id' => $changes_id,
@@ -272,7 +271,7 @@ public function testAddAdditionalActorsDuplicated()
]
]
]);
- $this->boolean($result)->isTrue();
+ $this->assertTrue($result);
}
public function testInitialStatus()
@@ -285,9 +284,9 @@ public function testInitialStatus()
'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true),
'_users_id_assign' => getItemByTypeName('User', TU_USER, true),
]);
- $this->integer($changes_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $changes_id);
// Even when automatically assigning a user, the initial status should be set to New
- $this->integer($change->fields['status'])->isIdenticalTo(\CommonITILObject::INCOMING);
+ $this->assertSame(\CommonITILObject::INCOMING, $change->fields['status']);
}
public function testStatusWhenSolutionIsRefused()
@@ -301,7 +300,7 @@ public function testStatusWhenSolutionIsRefused()
'_users_id_assign' => getItemByTypeName('User', TU_USER, true),
'status' => \CommonITILObject::SOLVED,
]);
- $this->integer($changes_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $changes_id);
$followup = new \ITILFollowup();
$followup_id = $followup->add([
@@ -314,9 +313,9 @@ public function testStatusWhenSolutionIsRefused()
'timeline_position' => \CommonITILObject::TIMELINE_LEFT,
'add_reopen' => ''
]);
- $this->integer($followup_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $followup_id);
$item = $change->getById($changes_id);
- $this->integer($item->fields['status'])->isIdenticalTo(\CommonITILObject::INCOMING);
+ $this->assertSame(\CommonITILObject::INCOMING, $item->fields['status']);
}
}
diff --git a/tests/functional/ITILTemplate.php b/phpunit/functional/ITILTemplateTest.php
similarity index 79%
rename from tests/functional/ITILTemplate.php
rename to phpunit/functional/ITILTemplateTest.php
index 4a5c767a486..2406ee812f8 100644
--- a/tests/functional/ITILTemplate.php
+++ b/phpunit/functional/ITILTemplateTest.php
@@ -38,9 +38,9 @@
use DbTestCase;
/* Test for inc/itiltemplate.class.php */
-class ITILTemplate extends DbTestCase
+class ITILTemplateTest extends DbTestCase
{
- protected function itilProvider()
+ public static function itilProvider()
{
return [
['Ticket'],
@@ -56,50 +56,54 @@ public function testTemplateUsage($itiltype)
{
$this->login();
- //create template
+ //create template
$tpl_class = '\\' . $itiltype . 'Template';
$tpl = new $tpl_class();
$tpl_id = (int)$tpl->add([
'name' => 'Template for ' . $itiltype
]);
- $this->integer($tpl_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $tpl_id);
- //add a mandatory field
+ //add a mandatory field
$mandat_class = '\\' . $itiltype . 'TemplateMandatoryField';
$mandat = new $mandat_class();
- $this->integer(
+ $this->assertGreaterThan(
+ 0,
(int)$mandat->add([
$mandat::$items_id => $tpl_id,
'num' => $mandat->getFieldNum($tpl, 'Title')
])
- )->isGreaterThan(0);
+ );
if ($itiltype === \Ticket::getType()) {
- $this->integer(
+ $this->assertGreaterThan(
+ 0,
(int)$mandat->add([
$mandat::$items_id => $tpl_id,
'num' => $mandat->getFieldNum($tpl, 'Location')
])
- )->isGreaterThan(0);
+ );
}
- $this->integer(
+ $this->assertGreaterThan(
+ 0,
(int)$mandat->add([
$mandat::$items_id => $tpl_id,
'num' => $mandat->getFieldNum($tpl, 'Description')
])
- )->isGreaterThan(0);
+ );
//add a predefined field
$predef_class = '\\' . $itiltype . 'TemplatePredefinedField';
$predef = new $predef_class();
- $this->integer(
+ $this->assertGreaterThan(
+ 0,
(int)$predef->add([
$mandat::$items_id => $tpl_id,
'num' => $predef->getFieldNum($tpl, 'Description'), //Description
'value' => 'Description from template'
])
- )->isGreaterThan(0);
+ );
$category = new \ITILCategory();
$cat_field = strtolower($itiltype) . 'templates_id';
@@ -110,7 +114,7 @@ public function testTemplateUsage($itiltype)
'name' => 'Category for a template',
$cat_field => $tpl_id
]);
- $this->integer($cat_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $cat_id);
$object = new $itiltype();
$tpl_key = $object->getTemplateFormFieldName();
@@ -126,7 +130,7 @@ public function testTemplateUsage($itiltype)
$content['type'] = \Ticket::INCIDENT_TYPE;
}
$tid = (int)$object->add($content);
- $this->integer($tid)->isIdenticalTo(0);
+ $this->assertSame(0, $tid);
$err_msg = 'Mandatory fields are not filled. Please correct: Title' .
($itiltype === \Ticket::getType() ? ', Location' : '') . ', Description';
@@ -137,7 +141,7 @@ public function testTemplateUsage($itiltype)
$content['locations_id'] = getItemByTypeName('Location', '_location01', true);
$tid = (int)$object->add($content);
- $this->integer($tid)->isIdenticalTo(0);
+ $this->assertSame(0, $tid);
$this->hasSessionMessages(
ERROR,
@@ -149,7 +153,7 @@ public function testTemplateUsage($itiltype)
$content['content'] = 'A content for our ' . $itiltype;
$tid = (int)$object->add($content);
- $this->integer($tid)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $tid);
}
/**
@@ -183,9 +187,10 @@ private function checkField($itiltype, $field)
global $DB;
if (!str_starts_with($field, '_') && 'items_id' != $field) {
- $this->boolean(
- $DB->fieldExists($itiltype::getTable(), $field)
- )->isTrue("$field in $itiltype");
+ $this->assertTrue(
+ $DB->fieldExists($itiltype::getTable(), $field),
+ "$field in $itiltype"
+ );
} else {
//howto test dynamic fields (those wich names begin with a "_")?
//howto test items_id (from Ticket at least)?
@@ -193,7 +198,7 @@ private function checkField($itiltype, $field)
}
}
- protected function fieldsProvider()
+ public static function fieldsProvider()
{
return [
[
@@ -303,7 +308,7 @@ public function testGetMandatoryFields($itemtype, $fields)
$class = $tpl_class . 'MandatoryField';
$tpl_field = new $class();
$result = $tpl_field->getAllFields($tpl);
- $this->array($result)->isIdenticalTo($fields);
+ $this->assertSame($fields, $result);
}
/**
@@ -329,7 +334,7 @@ public function testGetTabNameForItem($itiltype)
];
break;
}
- $this->array($tpl->getTabNameForItem($tpl))->isIdenticalTo($expected);
+ $this->assertSame($expected, $tpl->getTabNameForItem($tpl));
}
/**
@@ -349,7 +354,7 @@ public function testTasks($itiltype)
$tpl_id = (int)$tpl->add([
'name' => 'Template for ' . $itiltype
]);
- $this->integer($tpl_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $tpl_id);
$task_tpl = new \TaskTemplate();
$tid1 = (int)$task_tpl->add([
@@ -357,17 +362,17 @@ public function testTasks($itiltype)
'content' => 'First task content',
'is_recursive' => 1
]);
- $this->integer($tid1)->isGreaterThan(0);
- $this->boolean($task_tpl->getFromDB($tid1))->isTrue();
+ $this->assertGreaterThan(0, $tid1);
+ $this->assertTrue($task_tpl->getFromDB($tid1));
$tid2 = (int)$task_tpl->add([
'name' => 'Second task template',
'content' => 'Second task content',
'is_recursive' => 1
]);
- $this->integer($tid1)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $tid1);
- //add predefined tasks
+ //add predefined tasks
$predef_class = '\\' . $itiltype . 'TemplatePredefinedField';
$predef = new $predef_class();
$puid = (int)$predef->add([
@@ -376,8 +381,8 @@ public function testTasks($itiltype)
'value' => $tid1,
'is_recursive' => 1
]);
- $this->integer($puid)->isGreaterThan(0);
- $this->boolean($predef->getFromDB($puid))->isTrue();
+ $this->assertGreaterThan(0, $puid);
+ $this->assertTrue($predef->getFromDB($puid));
$puid = (int)$predef->add([
$mandat::$items_id => $tpl_id,
@@ -385,8 +390,8 @@ public function testTasks($itiltype)
'value' => $tid2,
'is_recursive' => 1
]);
- $this->integer($puid)->isGreaterThan(0);
- $this->boolean($predef->getFromDB($puid))->isTrue();
+ $this->assertGreaterThan(0, $puid);
+ $this->assertTrue($predef->getFromDB($puid));
$category = new \ITILCategory();
$cat_field = strtolower($itiltype) . 'templates_id';
@@ -397,7 +402,7 @@ public function testTasks($itiltype)
'name' => 'Category for a template',
$cat_field => $tpl_id
]);
- $this->integer($cat_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $cat_id);
$object = new $itiltype();
$tpl_key = $object->getTemplateFormFieldName();
@@ -417,7 +422,7 @@ public function testTasks($itiltype)
}
$tid = (int)$object->add($content);
- $this->integer($tid)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $tid);
global $DB;
$task_class = $itiltype . 'Task';
@@ -427,7 +432,7 @@ public function testTasks($itiltype)
$object->getForeignKeyField() => $tid
]
]);
- $this->integer(count($iterator))->isIdenticalTo(2);
+ $this->assertCount(2, $iterator);
}
/**
@@ -438,12 +443,12 @@ public function testGetITILTemplateToUse($itiltype)
$this->login('tech', 'tech');
$itilobject = new $itiltype();
- //1- per default, no template is assigned
+ //1- per default, no template is assigned
$tt = $itilobject->getITILTemplateToUse();
- $this->boolean($tt->isNewItem())->isTrue('Not an empty template');
+ $this->assertTrue($tt->isNewItem(), 'Not an empty template');
- //2- create a category with an new template for it,
- // and check the correct template is returned
+ //2- create a category with a new template for it,
+ // and check the correct template is returned
$category_tpl_id = $this->createTemplate($itiltype);
$category = new \ITILCategory();
@@ -456,72 +461,84 @@ public function testGetITILTemplateToUse($itiltype)
'name' => 'Category for a ' . $itiltype . ' template',
$cat_field => $category_tpl_id
]);
- $this->integer($cat_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $cat_id);
$type = ($itiltype == 'Ticket' ? \Ticket::DEMAND_TYPE : null);
$tt = $itilobject->getITILTemplateToUse(0, $type, $cat_id);
- $this->boolean($tt->isNewItem())
- ->isFalse('Not template expected from category assignment');
- $this->integer((int)$tt->fields['id'])->isIdenticalTo($category_tpl_id);
+ $this->assertFalse(
+ $tt->isNewItem(),
+ 'Not template expected from category assignment'
+ );
+ $this->assertSame($category_tpl_id, (int)$tt->fields['id']);
- //3- edit existing entity with new template as default
- // and check the correct template is returned
- // check if category has precedence
+ //3- edit existing entity with new template as default
+ // and check the correct template is returned
+ // check if category has precedence
$entity_tpl_id = $this->createTemplate($itiltype);
- //login as admin to change entity conf
+ //login as admin to change entity conf
$this->login();
$entity = getItemByTypeName('Entity', '_test_child_1');
- $this->boolean($entity->update(['id' => $entity->fields['id'], $field => $entity_tpl_id]))->isTrue();
+ $this->assertTrue($entity->update(['id' => $entity->fields['id'], $field => $entity_tpl_id]));
- //login back as tech
+ //login back as tech
$this->login('tech', 'tech');
$tt = $itilobject->getITILTemplateToUse(0, $type, 0, $entity->fields['id']);
- $this->boolean($tt->isNewItem())
- ->isFalse('Not template expected from entity assignment');
- $this->integer((int)$tt->fields['id'])->isIdenticalTo($entity_tpl_id);
+ $this->assertFalse(
+ $tt->isNewItem(),
+ 'Not template expected from entity assignment'
+ );
+ $this->assertSame($entity_tpl_id, (int)$tt->fields['id']);
$tt = $itilobject->getITILTemplateToUse(0, $type, $cat_id, $entity->fields['id']);
- $this->boolean($tt->isNewItem())
- ->isFalse('Not template expected from entity assignment overrided with category');
- $this->integer((int)$tt->fields['id'])->isIdenticalTo($category_tpl_id);
-
- //4- set default to a new template fo tech profile
- // check the correct template is returned
- // check if profile has precedence on entity
- // check if category has precedence
+ $this->assertFalse(
+ $tt->isNewItem(),
+ 'Not template expected from entity assignment overrided with category'
+ );
+ $this->assertSame($category_tpl_id, (int)$tt->fields['id']);
+
+ //4- set default to a new template fo tech profile
+ // check the correct template is returned
+ // check if profile has precedence on entity
+ // check if category has precedence
$profile_tpl_id = $this->createTemplate($itiltype);
$profile = getItemByTypeName('Profile', 'Technician');
- $this->boolean($profile->update(['id' => $profile->fields['id'], $field => $profile_tpl_id]))->isTrue();
+ $this->assertTrue($profile->update(['id' => $profile->fields['id'], $field => $profile_tpl_id]));
- //login again to refresh profile
+ //login again to refresh profile
$this->login('tech', 'tech');
$tt = $itilobject->getITILTemplateToUse(0, $type, 0);
- $this->boolean($tt->isNewItem())
- ->isFalse('Not template expected from profile assignment');
- $this->integer((int)$tt->fields['id'])->isIdenticalTo($profile_tpl_id);
+ $this->assertFalse(
+ $tt->isNewItem(),
+ 'Not template expected from profile assignment'
+ );
+ $this->assertSame($profile_tpl_id, (int)$tt->fields['id']);
$tt = $itilobject->getITILTemplateToUse(0, $type, 0, $entity->fields['id']);
- $this->boolean($tt->isNewItem())
- ->isFalse('Not template expected from entity assignment overrided by profile');
- $this->integer((int)$tt->fields['id'])->isIdenticalTo($profile_tpl_id);
+ $this->assertFalse(
+ $tt->isNewItem(),
+ 'Not template expected from entity assignment overrided by profile'
+ );
+ $this->assertSame($profile_tpl_id, (int)$tt->fields['id']);
$tt = $itilobject->getITILTemplateToUse(0, $type, $cat_id, $entity->fields['id']);
- $this->boolean($tt->isNewItem())
- ->isFalse('Not template expected');
- $this->integer((int)$tt->fields['id'])->isIdenticalTo($category_tpl_id);
+ $this->assertFalse(
+ $tt->isNewItem(),
+ 'Not template expected'
+ );
+ $this->assertSame($category_tpl_id, (int)$tt->fields['id']);
}
private function createTemplate($itiltype)
{
- //create template
+ //create template
$tpl_class = '\\' . $itiltype . 'Template';
$tpl = new $tpl_class();
$tpl_id = (int)$tpl->add([
'name' => 'Template for ' . $itiltype
]);
- $this->integer($tpl_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $tpl_id);
return $tpl_id;
}
}
diff --git a/phpunit/functional/InfocomTest.php b/phpunit/functional/InfocomTest.php
index 11e92c4a6b3..913f0cdd00b 100644
--- a/phpunit/functional/InfocomTest.php
+++ b/phpunit/functional/InfocomTest.php
@@ -39,7 +39,7 @@
class InfocomTest extends \GLPITestCase
{
- public function dataLinearAmortise()
+ public static function dataLinearAmortise()
{
return [
[
diff --git a/tests/functional/Itil_Project.php b/phpunit/functional/Itil_ProjectTest.php
similarity index 70%
rename from tests/functional/Itil_Project.php
rename to phpunit/functional/Itil_ProjectTest.php
index bb4f1da5431..d8b6c278543 100644
--- a/tests/functional/Itil_Project.php
+++ b/phpunit/functional/Itil_ProjectTest.php
@@ -39,7 +39,7 @@
/* Test for inc/itil_project.class.php */
-class Itil_Project extends DbTestCase
+class Itil_ProjectTest extends DbTestCase
{
/**
* Test ability to link ITIL items to a project.
@@ -54,83 +54,96 @@ public function testLink()
$project = new \Project();
$itil_project = new \Itil_Project();
- $this->integer(
+ $this->assertGreaterThan(
+ 0,
(int)$project->add([
'name' => 'Some project',
])
- )->isGreaterThan(0);
+ );
$baseProjectId = $project->fields['id'];
$items = [];
foreach ([\Change::class, \Problem::class, \Ticket::class] as $itemtype) {
$item = new $itemtype();
- $this->integer(
+ $this->assertGreaterThan(
+ 0,
(int)$item->add([
'name' => 'ITIL item ' . $itemtype,
'content' => 'ITIL item ' . $itemtype,
])
- )->isGreaterThan(0);
+ );
$items[] = $item;
- // Item should be linkable to a project
- $this->integer(
+ // Item should be linkable to a project
+ $this->assertGreaterThan(
+ 0,
(int)$itil_project->add([
'itemtype' => $itemtype,
'items_id' => $item->fields['id'],
'projects_id' => $baseProjectId,
])
- )->isGreaterThan(0);
+ );
- // Count displayed in tab name should be equal to count of ITIL items linked to project
- $this->integer(
+ // Count displayed in tab name should be equal to count of ITIL items linked to project
+ $this->assertEquals(
+ count($items),
(int)preg_replace('/[^\d]*(\d+)[^\d]*/', '$1', $itil_project->getTabNameForItem($project))
- )->isEqualTo(count($items));
+ );
}
- //add a task
+ //add a task
$ptask = new \ProjectTask();
$ptid = (int)$ptask->add([
'name' => 'Task for test project Clone',
'projects_id' => $baseProjectId
]);
- $this->integer($ptid)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $ptid);
- // Clone project should clone its links to ITIL items and task
+ // Clone project should clone its links to ITIL items and task
$cloneProjectId = (int)$project->add([
'name' => 'Some project clone',
'_oldID' => $baseProjectId,
]);
- $this->integer($cloneProjectId)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $cloneProjectId);
- $this->integer($cloneProjectId)->isNotEqualTo($baseProjectId, 'Project has not been cloned (same id)!');
+ $this->assertNotEmpty(
+ $baseProjectId,
+ $cloneProjectId,
+ 'Project has not been cloned (same id)!'
+ );
- $this->integer(
+ $this->assertEquals(
+ 1,
countElementsInTable($ptask::getTable(), ['projects_id' => $baseProjectId])
- )->isEqualTo(1);
+ );
- $this->integer(
+ $this->assertEquals(
+ 1,
countElementsInTable($ptask::getTable(), ['projects_id' => $cloneProjectId])
- )->isEqualTo(1);
+ );
- $this->integer(
+ $this->assertSame(
+ count($items),
countElementsInTable($itil_project::getTable(), ['projects_id' => $cloneProjectId])
- )->isEqualTo(count($items));
+ );
- // Deletion of project should delete links with ITIL items
- $this->boolean($project->delete(['id' => $baseProjectId], true))->isTrue();
+ // Deletion of project should delete links with ITIL items
+ $this->assertTrue($project->delete(['id' => $baseProjectId], true));
- $this->integer(
+ $this->assertEquals(
+ 0,
countElementsInTable($itil_project::getTable(), ['projects_id' => $baseProjectId])
- )->isEqualTo(0);
+ );
- // Deletion of ITIL items should delete links with project
+ // Deletion of ITIL items should delete links with project
foreach ($items as $item) {
$itemtype = $item->getType();
$items_id = $item->fields['id'];
- $this->boolean((new $itemtype())->delete(['id' => $items_id], true))->isTrue();
+ $this->assertTrue((new $itemtype())->delete(['id' => $items_id], true));
- $this->integer(
+ $this->assertEquals(
+ 0,
countElementsInTable(
$itil_project::getTable(),
[
@@ -138,7 +151,7 @@ public function testLink()
'items_id' => $items_id,
]
)
- )->isEqualTo(0);
+ );
}
}
}
diff --git a/phpunit/functional/KnowbaseItemTest.php b/phpunit/functional/KnowbaseItemTest.php
index 03318e10a36..53c1b40dc66 100644
--- a/phpunit/functional/KnowbaseItemTest.php
+++ b/phpunit/functional/KnowbaseItemTest.php
@@ -808,7 +808,7 @@ public function testGetAnswerAnchors(): void
// Check category id
$data = array_pop($linked_categories);
- $this->integer($data['knowbaseitemcategories_id'])->isEqualTo($category->getID());
+ $this->assertEquals($category->getID(), $data['knowbaseitemcategories_id']);
}*/
public function testCreateWithCategories()
diff --git a/tests/functional/MassiveAction.php b/phpunit/functional/MassiveActionTest.php
similarity index 70%
rename from tests/functional/MassiveAction.php
rename to phpunit/functional/MassiveActionTest.php
index c8a827e1bbe..43e9a634ee1 100644
--- a/tests/functional/MassiveAction.php
+++ b/phpunit/functional/MassiveActionTest.php
@@ -45,9 +45,9 @@
/* Test for inc/massiveaction.class.php */
-class MassiveAction extends DbTestCase
+class MassiveActionTest extends DbTestCase
{
- protected function actionsProvider()
+ public static function actionsProvider()
{
return [
[
@@ -118,11 +118,10 @@ public function testGetAllMassiveActions($itemtype, $items_id, $allcount, $singl
'initial'
);
$input = $mact->getInput();
- $this->array($input)
- ->hasKey('action_filter')
- ->hasKey('actions');
- $this->array($input['action_filter'])->hasSize($allcount);
- $this->array($input['actions'])->hasSize($allcount);
+ $this->assertArrayHasKey('action_filter', $input);
+ $this->assertArrayHasKey('actions', $input);
+ $this->assertCount($allcount, $input['action_filter']);
+ $this->assertCount($allcount, $input['actions']);
$mact = new \MassiveAction(
[
@@ -137,11 +136,10 @@ public function testGetAllMassiveActions($itemtype, $items_id, $allcount, $singl
$items_id
);
$input = $mact->getInput();
- $this->array($input)
- ->hasKey('action_filter')
- ->hasKey('actions');
- $this->array($input['action_filter'])->hasSize($singlecount);
- $this->array($input['actions'])->hasSize($singlecount);
+ $this->assertArrayHasKey('action_filter', $input);
+ $this->assertArrayHasKey('actions', $input);
+ $this->assertCount($singlecount, $input['action_filter']);
+ $this->assertCount($singlecount, $input['actions']);
}
protected function processMassiveActionsForOneItemtype(
@@ -153,37 +151,38 @@ protected function processMassiveActionsForOneItemtype(
int $ko,
string $action_class = \MassiveAction::class
) {
-
$ma_ok = 0;
$ma_ko = 0;
- // Create mock
- $this->mockGenerator->orphanize('__construct');
- $ma = new \mock\MassiveAction([], [], '');
-
- // Mock needed methods
- $ma->getMockController()->getAction = $action_code;
- $ma->getMockController()->addMessage = function () {
- };
- $ma->getMockController()->getInput = $input;
- $ma->getMockController()->itemDone =
+ // Create mock
+ $ma = $this->getMockBuilder(\MassiveAction::class)
+ ->disableOriginalConstructor()
+ ->onlyMethods(['getAction', 'addMessage', 'getInput', 'itemDone'])
+ ->getMock();
+
+ // Mock needed methods
+ $ma->method('getAction')->willReturn($action_code);
+ $ma->method('addMessage')->willReturn(null);
+ $ma->method('getInput')->willReturn($input);
+ $ma->method('itemDone')->willReturnCallback(
function ($item, $id, $res) use (&$ma_ok, &$ma_ko) {
if ($res == \MassiveAction::ACTION_OK) {
$ma_ok++;
} else {
$ma_ko++;
}
- };
+ }
+ );
- // Execute method
+ // Execute method
$action_class::processMassiveActionsForOneItemtype($ma, $item, $ids);
- // Check expected number of success and failures
- $this->integer($ma_ok)->isIdenticalTo($ok);
- $this->integer($ma_ko)->isIdenticalTo($ko);
+ // Check expected number of success and failures
+ $this->assertSame($ok, $ma_ok);
+ $this->assertSame($ko, $ma_ko);
}
- protected function amendCommentProvider()
+ public static function amendCommentProvider()
{
return [
[
@@ -216,39 +215,39 @@ public function testProcessMassiveActionsForOneItemtype_AmendComment(
$amendment = "test amendment";
$old_session = $_SESSION['glpiactiveentities'] ?? [];
- // Set rights if needed
+ // Set rights if needed
if ($has_right) {
$_SESSION['glpiactiveentities'] = [
$item->getEntityID()
];
}
- // Check supplied params match the data
+ // Check supplied params match the data
$comment_exist = array_key_exists('comment', $item->fields);
- $this->boolean($comment_exist)->isIdenticalTo($itemtype_is_compatible);
- $this->boolean($item->canUpdateItem())->isIdenticalTo($has_right);
+ $this->assertSame($itemtype_is_compatible, $comment_exist);
+ $this->assertSame($has_right, $item->canUpdateItem());
if ($itemtype_is_compatible && $has_right) {
$expected_ok = 1;
$expected_ko = 0;
- // If we expect the test to work, set the comment to $base_comment
+ // If we expect the test to work, set the comment to $base_comment
$update = $item->update([
'id' => $item->fields['id'],
'comment' => $base_comment,
]);
- $this->boolean($update)->isTrue();
+ $this->assertTrue($update);
} else if (!$itemtype_is_compatible) {
- // Itemtype incompatible, the action wont run on any items
+ // Itemtype incompatible, the action won't run on any items
$expected_ok = 0;
$expected_ko = 0;
} else {
- // No update right, the action will run and fail
+ // No update right, the action will run and fail
$expected_ok = 0;
$expected_ko = 1;
}
- // Execute action
+ // Execute action
$this->processMassiveActionsForOneItemtype(
"amend_comment",
$item,
@@ -258,19 +257,20 @@ public function testProcessMassiveActionsForOneItemtype_AmendComment(
$expected_ko
);
- // If the item was modified, check the new comment value
+ // If the item was modified, check the new comment value
if ($itemtype_is_compatible && $has_right) {
// Refresh data
- $this->boolean($item->getFromDB($item->fields['id']))->isTrue();
- $this
- ->string($item->fields['comment'])
- ->isIdenticalTo("$base_comment\n\n$amendment");
+ $this->assertTrue($item->getFromDB($item->fields['id']));
+ $this->assertSame(
+ "$base_comment\n\n$amendment",
+ $item->fields['comment']
+ );
}
$_SESSION['glpiactiveentities'] = $old_session;
}
- protected function addNoteProvider()
+ public static function addNoteProvider()
{
return [
[
@@ -291,10 +291,9 @@ public function testProcessMassiveActionsForOneItemtype_AddNote(
CommonDBTM $item,
bool $has_right
) {
-
$this->login(); // must be logged as MassiveAction uses Session::getLoginUserID()
- // Init vars
+ // Init vars
$new_note_content = "Test add note";
$old_session = $_SESSION['glpiactiveprofile'][$item::$rightname] ?? 0;
$note_search = [
@@ -307,24 +306,25 @@ public function testProcessMassiveActionsForOneItemtype_AddNote(
$_SESSION['glpiactiveprofile'][$item::$rightname] = UPDATENOTE;
}
- // Check expected rights
- $this
- ->boolean(boolval(Session::haveRight($item::$rightname, UPDATENOTE)))
- ->isIdenticalTo($has_right);
+ // Check expected rights
+ $this->assertSame(
+ $has_right,
+ (bool)Session::haveRight($item::$rightname, UPDATENOTE)
+ );
if ($has_right) {
$expected_ok = 1;
$expected_ko = 0;
- // Keep track of the number of existing notes for this item
+ // Keep track of the number of existing notes for this item
$count_notes = countElementsInTable(Notepad::getTable(), $note_search);
} else {
- // No rights, the action wont run on any items
+ // No rights, the action won't run on any items
$expected_ok = 0;
$expected_ko = 0;
}
- // Execute action
+ // Execute action
$this->processMassiveActionsForOneItemtype(
"add_note",
$item,
@@ -334,16 +334,16 @@ public function testProcessMassiveActionsForOneItemtype_AddNote(
$expected_ko
);
- // If the note was added, check it's value in the DB
+ // If the note was added, check it's value in the DB
if ($has_right) {
$new_count = countElementsInTable(Notepad::getTable(), $note_search);
- $this->integer($new_count)->isIdenticalTo($count_notes + 1);
+ $this->assertSame($count_notes + 1, $new_count);
}
$_SESSION['glpiactiveprofile'][$item::$rightname] = $old_session;
}
- protected function linkToProblemProvider()
+ public static function linkToProblemProvider()
{
return [
[
@@ -387,22 +387,23 @@ public function testProcessMassiveActionsForOneItemtype_linkToProblem(
array $input,
bool $has_right
) {
- // Set up session rights
+ // Set up session rights
$old_session = $_SESSION['glpiactiveprofile'][Problem::$rightname] ?? 0;
if ($has_right) {
$_SESSION['glpiactiveprofile'][Problem::$rightname] = UPDATE;
}
- // Default expectation: can't run
+ // Default expectation: can't run
$expected_ok = 0;
$expected_ko = 0;
- // Check rights set up was successful
- $this
- ->boolean(boolval(Session::haveRight(Problem::$rightname, UPDATE)))
- ->isIdenticalTo($has_right);
+ // Check rights set up was successful
+ $this->assertSame(
+ $has_right,
+ (bool)Session::haveRight(Problem::$rightname, UPDATE)
+ );
- // If input is valid, make sure we have a matching problem
+ // If input is valid, make sure we have a matching problem
$problems_id = $input['problems_id'] ?? -1;
if ($problems_id > 0) {
$problem = new Problem();
@@ -410,13 +411,13 @@ public function testProcessMassiveActionsForOneItemtype_linkToProblem(
'name' => "tmp",
'content' => "tmp",
]);
- $this->integer($input['problems_id']);
+ $this->assertGreaterThan(0, $input['problems_id']);
- // Update expectation: this item should be OK
+ // Update expectation: this item should be OK
$expected_ok = 1;
}
- // Execute action
+ // Execute action
$this->processMassiveActionsForOneItemtype(
"link_to_problem",
$item,
@@ -427,7 +428,7 @@ public function testProcessMassiveActionsForOneItemtype_linkToProblem(
Ticket::class
);
- // Reset rights
+ // Reset rights
$_SESSION['glpiactiveprofile'][Problem::$rightname] = $old_session;
}
@@ -475,53 +476,55 @@ protected function resolveTicketsProvider()
];
}
- /**
- * @dataProvider resolveTicketsProvider
- */
- public function testProcessMassiveActionsForOneItemtype_resolveTickets(
- CommonDBTM $item,
- array $input,
- bool $has_right,
- bool $should_work
- ) {
-
+ public function testProcessMassiveActionsForOneItemtype_resolveTickets()
+ {
$this->login(); // must be logged as ITILSolution uses Session::getLoginUserID()
- // Set up session rights
- $old_session = $_SESSION['glpiactiveprofile'][Ticket::$rightname] ?? 0;
- if ($has_right) {
- $_SESSION['glpiactiveprofile'][Ticket::$rightname] = UPDATE;
- } else {
- $_SESSION['glpiactiveprofile'][Ticket::$rightname] = 0;
- }
-
- // Default expectation: can't run
- $expected_ok = 0;
- $expected_ko = 0;
+ $provider = $this->resolveTicketsProvider();
+ foreach ($provider as $row) {
+ $item = $row['item'];
+ $input = $row['input'];
+ $has_right = $row['has_right'];
+ $should_work = $row['should_work'];
- // Check rights set up was successful
- $this
- ->boolean(boolval(Session::haveRight(Ticket::$rightname, UPDATE)))
- ->isIdenticalTo($has_right);
- // Update expectation: this item should be OK
- if ($should_work) {
- $expected_ok = 1;
- }
+ // Set up session rights
+ $old_session = $_SESSION['glpiactiveprofile'][Ticket::$rightname] ?? 0;
+ if ($has_right) {
+ $_SESSION['glpiactiveprofile'][Ticket::$rightname] = UPDATE;
+ } else {
+ $_SESSION['glpiactiveprofile'][Ticket::$rightname] = 0;
+ }
- // Execute action
- $this->processMassiveActionsForOneItemtype(
- "resolve_tickets",
- $item,
- [$item->fields['id']],
- $input,
- $expected_ok,
- $expected_ko,
- Ticket::class
- );
+ // Default expectation: can't run
+ $expected_ok = 0;
+ $expected_ko = 0;
- // Reset rights
- $_SESSION['glpiactiveprofile'][Ticket::$rightname] = $old_session;
+ // Check rights set up was successful
+ $this->assertSame(
+ $has_right,
+ (bool)Session::haveRight(Ticket::$rightname, UPDATE)
+ );
+
+ // Update expectation: this item should be OK
+ if ($should_work) {
+ $expected_ok = 1;
+ }
+
+ // Execute action
+ $this->processMassiveActionsForOneItemtype(
+ "resolve_tickets",
+ $item,
+ [$item->fields['id']],
+ $input,
+ $expected_ok,
+ $expected_ko,
+ Ticket::class
+ );
+
+ // Reset rights
+ $_SESSION['glpiactiveprofile'][Ticket::$rightname] = $old_session;
+ }
}
protected function addContractProvider()
@@ -532,14 +535,14 @@ protected function addContractProvider()
'content' => 'test',
]);
$ticket->getFromDB($id);
- $this->integer($id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $id);
$contract = new Contract();
$contract_id = $contract->add([
'name' => 'test',
'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true),
]);
- $this->integer($contract_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $contract_id);
return [
[
@@ -575,47 +578,50 @@ protected function addContractProvider()
];
}
- /**
- * @dataProvider addContractProvider
- */
- public function testProcessMassiveActionsForOneItemtype_addContract(
- CommonDBTM $item,
- array $input,
- bool $has_right,
- bool $should_work
- ) {
+ public function testProcessMassiveActionsForOneItemtype_addContract()
+ {
$this->login();
- // Set up session rights
- if ($has_right) {
- $this->login('tech', 'tech');
- } else {
- $this->login('post-only', 'postonly');
- }
+ $provider = $this->addContractProvider();
+ foreach ($provider as $row) {
+ $item = $row['item'];
+ $input = $row['input'];
+ $has_right = $row['has_right'];
+ $should_work = $row['should_work'];
- // Default expectation: can't run
- $expected_ok = 0;
- $expected_ko = 0;
- // Check rights set up was successful
- $this
- ->boolean(boolval(Session::haveRight(Ticket::$rightname, UPDATE)))
- ->isIdenticalTo($has_right);
+ // Set up session rights
+ if ($has_right) {
+ $this->login('tech', 'tech');
+ } else {
+ $this->login('post-only', 'postonly');
+ }
- // Update expectation: this item should be OK
- if ($should_work) {
- $expected_ok = 1;
- }
+ // Default expectation: can't run
+ $expected_ok = 0;
+ $expected_ko = 0;
- // Execute action
- $this->processMassiveActionsForOneItemtype(
- "add_contract",
- $item,
- [$item->fields['id']],
- $input,
- $expected_ok,
- $expected_ko,
- Ticket::class
- );
+ // Check rights set up was successful
+ $this->assertSame(
+ $has_right,
+ (bool)Session::haveRight(Ticket::$rightname, UPDATE)
+ );
+
+ // Update expectation: this item should be OK
+ if ($should_work) {
+ $expected_ok = 1;
+ }
+
+ // Execute action
+ $this->processMassiveActionsForOneItemtype(
+ "add_contract",
+ $item,
+ [$item->fields['id']],
+ $input,
+ $expected_ok,
+ $expected_ko,
+ Ticket::class
+ );
+ }
}
}
diff --git a/tests/functional/NotificationAjaxSetting.php b/phpunit/functional/NotificationAjaxSettingTest.php
similarity index 56%
rename from tests/functional/NotificationAjaxSetting.php
rename to phpunit/functional/NotificationAjaxSettingTest.php
index a817373628b..014471352db 100644
--- a/tests/functional/NotificationAjaxSetting.php
+++ b/phpunit/functional/NotificationAjaxSettingTest.php
@@ -39,79 +39,76 @@
/* Test for inc/notificationajaxsetting.class.php .class.php */
-class NotificationAjaxSetting extends DbTestCase
+class NotificationAjaxSettingTest extends DbTestCase
{
public function testGetTable()
{
- $this->string(\NotificationAjaxSetting::getTable())->isIdenticalTo('glpi_configs');
+ $this->assertSame('glpi_configs', \NotificationAjaxSetting::getTable());
}
public function testGetTypeName()
{
- $this->string(\NotificationAjaxSetting::getTypeName())->isIdenticalTo('Browser followups configuration');
- $this->string(\NotificationAjaxSetting::getTypeName(10))->isIdenticalTo('Browser followups configuration');
+ $this->assertSame('Browser followups configuration', \NotificationAjaxSetting::getTypeName());
+ $this->assertSame('Browser followups configuration', \NotificationAjaxSetting::getTypeName(10));
}
public function testDefineTabs()
{
$instance = new \NotificationAjaxSetting();
$tabs = $instance->defineTabs();
- $this->array($tabs)
- ->hasSize(1)
- ->isIdenticalTo(['NotificationAjaxSetting$1' => 'Setup']);
+ $this->assertSame(['NotificationAjaxSetting$1' => 'Setup'], $tabs);
}
public function testGetTabNameForItem()
{
$instance = new \NotificationAjaxSetting();
- $this->array($instance->getTabNameForItem($instance))->isIdenticalTo(['1' => 'Setup']);
+ $this->assertSame(['1' => 'Setup'], $instance->getTabNameForItem($instance));
}
public function testDisplayTabContentForItem()
{
- $this->output(
- function () {
- $instance = new \NotificationAjaxSetting();
- $instance->displayTabContentForItem($instance);
- }
- )->hasLengthGreaterThan(100);
+ ob_start();
+ $instance = new \NotificationAjaxSetting();
+ $instance->displayTabContentForItem($instance);
+ $content = ob_get_clean();
+ $this->assertGreaterThan(100, strlen($content));
}
public function testGetEnableLabel()
{
$settings = new \NotificationAjaxSetting();
- $this->string($settings->getEnableLabel())->isIdenticalTo('Enable followups from browser');
+ $this->assertSame('Enable followups from browser', $settings->getEnableLabel());
}
public function testGetMode()
{
- $this->string(\NotificationAjaxSetting::getMode())
- ->isIdenticalTo(\Notification_NotificationTemplate::MODE_AJAX);
+ $this->assertSame(
+ \Notification_NotificationTemplate::MODE_AJAX,
+ \NotificationAjaxSetting::getMode()
+ );
}
public function testShowFormConfig()
{
global $CFG_GLPI;
- $this->variable($CFG_GLPI['notifications_ajax'])->isEqualTo(0);
+ $this->assertEquals(0, $CFG_GLPI['notifications_ajax']);
- $this->output(
- function () {
- $instance = new \NotificationAjaxSetting();
- $instance->showFormConfig();
- }
- )->contains('Notifications are disabled.');
+ ob_start();
+ $instance = new \NotificationAjaxSetting();
+ $instance->showFormConfig();
+ $content = ob_get_clean();
+ $this->assertStringContainsString('Notifications are disabled.', $content);
$CFG_GLPI['notifications_ajax'] = 1;
- $this->output(
- function () {
- $instance = new \NotificationAjaxSetting();
- $instance->showFormConfig();
- }
- )->notContains('Notifications are disabled.');
+ ob_start();
+ $instance = new \NotificationAjaxSetting();
+ $instance->showFormConfig();
+ $content = ob_get_clean();
+ $this->assertStringNotContainsString('Notifications are enabled.', $content);
- //rest to defaults
+ //reset to defaults
$CFG_GLPI['notifications_ajax'] = 0;
}
}
diff --git a/tests/functional/NotificationAjax.php b/phpunit/functional/NotificationAjaxTest.php
similarity index 72%
rename from tests/functional/NotificationAjax.php
rename to phpunit/functional/NotificationAjaxTest.php
index eeace7ba8e2..f3f9e54b0f4 100644
--- a/tests/functional/NotificationAjax.php
+++ b/phpunit/functional/NotificationAjaxTest.php
@@ -39,34 +39,34 @@
/* Test for inc/notificationajax.class.php .class.php */
-class NotificationAjax extends DbTestCase
+class NotificationAjaxTest extends DbTestCase
{
public function testCheck()
{
$instance = new \NotificationAjax();
$uid = getItemByTypeName('User', TU_USER, true);
- $this->boolean($instance->check($uid))->isTrue();
- $this->boolean($instance->check(0))->isFalse();
- $this->boolean($instance->check('abc'))->isFalse;
+ $this->assertTrue($instance->check($uid));
+ $this->assertFalse($instance->check(0));
+ $this->assertFalse($instance->check('abc'));
}
public function testSendNotification()
{
- $this->boolean(\NotificationAjax::testNotification())->isTrue();
+ $this->assertTrue(\NotificationAjax::testNotification());
}
public function testGetMyNotifications()
{
global $CFG_GLPI;
- //setup
+ //setup
$this->login();
- $this->boolean(\NotificationAjax::testNotification())->isTrue();
- //another one
- $this->boolean(\NotificationAjax::testNotification())->isTrue();
+ $this->assertTrue(\NotificationAjax::testNotification());
+ //another one
+ $this->assertTrue(\NotificationAjax::testNotification());
- //also add a mailing notification to make sure we get only ajax ons back #2997
+ //also add a mailing notification to make sure we get only ajax ons back #2997
$instance = new \NotificationMailing();
$res = $instance->sendNotification([
'_itemtype' => 'NotificationMailing',
@@ -81,43 +81,45 @@ public function testGetMyNotifications()
'toname' => '',
'event' => 'test_notification'
]);
- $this->boolean($res)->isTrue();
+ $this->assertTrue($res);
- //ajax notifications disabled: gets nothing.
+ //ajax notifications disabled: gets nothing.
$notifs = \NotificationAjax::getMyNotifications();
- $this->boolean($notifs)->isFalse();
+ $this->assertFalse($notifs);
$CFG_GLPI['notifications_ajax'] = 1;
$notifs = \NotificationAjax::getMyNotifications();
- $this->array($notifs)->hasSize(2);
+ $this->assertCount(2, $notifs);
foreach ($notifs as $notif) {
unset($notif['id']);
- $this->array($notif)->isIdenticalTo([
- 'title' => 'Test notification',
- 'body' => 'Hello, this is a test notification.',
- 'url' => null
- ]);
+ $this->assertSame(
+ [
+ 'title' => 'Test notification',
+ 'body' => 'Hello, this is a test notification.',
+ 'url' => null
+ ],
+ $notif
+ );
}
- //while not deleted, still 2 notifs available
+ //while not deleted, still 2 notifs available
$notifs = \NotificationAjax::getMyNotifications();
- $this->array($notifs)->hasSize(2);
+ $this->assertCount(2, $notifs);
- //void method
+ //void method
\NotificationAjax::raisedNotification($notifs[1]['id']);
$expected = $notifs[0];
$notifs = \NotificationAjax::getMyNotifications();
- $this->array($notifs)
- ->hasSize(1);
- $this->array($notifs[0])->isIdenticalTo($expected);
+ $this->assertCount(1, $notifs);
+ $this->assertSame($expected, $notifs[0]);
- //void method
+ //void method
\NotificationAjax::raisedNotification($notifs[0]['id']);
$notifs = \NotificationAjax::getMyNotifications();
- $this->boolean($notifs)->isFalse();
+ $this->assertFalse($notifs);
$computer = getItemByTypeName('Computer', '_test_pc01');
$instance = new \NotificationAjax();
@@ -132,14 +134,16 @@ public function testGetMyNotifications()
'to' => \Session::getLoginUserID(),
'event' => 'test_notification',
]);
- $this->boolean($res)->isTrue();
+ $this->assertTrue($res);
$notifs = \NotificationAjax::getMyNotifications();
- $this->array($notifs)->hasSize(1);
- $this->string($notifs[0]['url'])
- ->isIdenticalTo($computer->getFormURLWithID($computer->fields['id'], true));
+ $this->assertCount(1, $notifs);
+ $this->assertSame(
+ $computer->getFormURLWithID($computer->fields['id'], true),
+ $notifs[0]['url']
+ );
- //reset
+ //reset
$CFG_GLPI['notifications_ajax'] = 0;
}
}
diff --git a/tests/functional/NotificationEventAjax.php b/phpunit/functional/NotificationEventAjaxTest.php
similarity index 80%
rename from tests/functional/NotificationEventAjax.php
rename to phpunit/functional/NotificationEventAjaxTest.php
index ee830719f0c..2f18524ee79 100644
--- a/tests/functional/NotificationEventAjax.php
+++ b/phpunit/functional/NotificationEventAjaxTest.php
@@ -36,51 +36,49 @@
namespace tests\units;
use DbTestCase;
+use Monolog\Logger;
/* Test for inc/notificationeventajax.class.php */
-class NotificationEventAjax extends DbTestCase
+class NotificationEventAjaxTest extends DbTestCase
{
public function testGetTargetField()
{
$data = [];
- $this->string(\NotificationEventAjax::getTargetField($data))->isIdenticalTo('users_id');
+ $this->assertSame('users_id', \NotificationEventAjax::getTargetField($data));
$expected = ['users_id' => null];
- $this->array($data)->isIdenticalTo($expected);
+ $this->assertSame($expected, $data);
$data = ['users_id' => '121'];
- $this->string(\NotificationEventAjax::getTargetField($data))->isIdenticalTo('users_id');
+ $this->assertSame('users_id', \NotificationEventAjax::getTargetField($data));
$expected = ['users_id' => '121'];
- $this->array($data)->isIdenticalTo($expected);
+ $this->assertSame($expected, $data);
}
public function testCanCron()
{
- $this->boolean(\NotificationEventAjax::canCron())->isFalse();
+ $this->assertFalse(\NotificationEventAjax::canCron());
}
public function testGetAdminData()
{
- $this->array(\NotificationEventAjax::getAdminData())->isIdenticalTo([]);
+ $this->assertSame([], \NotificationEventAjax::getAdminData());
}
public function testGetEntityAdminsData()
{
- $this->array(\NotificationEventAjax::getEntityAdminsData(0))->isIdenticalTo([]);
+ $this->assertSame([], \NotificationEventAjax::getEntityAdminsData(0));
}
public function testSend()
{
- $this->when(
- function () {
- $this->boolean(\NotificationEventAjax::send([]))->isFalse();
- }
- )->error
- ->withType(E_USER_WARNING)
- ->withMessage('NotificationEventAjax::send should not be called!')
- ->exists();
+ $this->assertFalse(\NotificationEventAjax::send([]));
+ $this->hasPhpLogRecordThatContains(
+ 'NotificationEventAjax::send should not be called!',
+ Logger::WARNING
+ );
}
public function testRaise()
@@ -95,20 +93,21 @@ public function testRaise()
$ticket = new \Ticket();
$uid = getItemByTypeName('User', TU_USER, true);
- $this->integer(
+ $this->assertGreaterThan(
+ 0,
(int)$ticket->add([
'name' => '',
'description' => 'My ticket to be notified.',
'_users_id_requester' => $uid,
'content' => ''
])
- )->isGreaterThan(0);
+ );
//event has been raised; it is in the queue!
$queue = getAllDataFromTable('glpi_queuednotifications');
//no ajax notification configured per default
- $this->array($queue)->hasSize(0);
+ $this->assertCount(0, $queue);
//add an ajax notification on tickets creation
$iterator = $DB->request([
@@ -118,7 +117,7 @@ public function testRaise()
'event' => 'new'
]
]);
- $this->integer($iterator->numRows())->isIdenticalTo(1);
+ $this->assertSame(1, $iterator->numRows());
$row = $iterator->current();
$notif_id = $row['id'];
@@ -129,27 +128,28 @@ public function testRaise()
'mode' => \Notification_NotificationTemplate::MODE_MAIL
]
]);
- $this->integer($iterator->numRows())->isIdenticalTo(1);
+ $this->assertSame(1, $iterator->numRows());
$row = $iterator->current();
unset($row['id']);
$row['mode'] = \Notification_NotificationTemplate::MODE_AJAX;
$notiftpltpl = new \Notification_NotificationTemplate();
- $this->integer($notiftpltpl->add($row))->isGreaterThan(0);
+ $this->assertGreaterThan(0, $notiftpltpl->add($row));
- $this->integer(
+ $this->assertGreaterThan(
+ 0,
(int)$ticket->add([
'name' => '',
'description' => 'My ticket to be notified.',
'_users_id_requester' => $uid,
'content' => ''
])
- )->isGreaterThan(0);
+ );
//event has been raised; it is in the queue!
$queue = getAllDataFromTable('glpi_queuednotifications');
//no ajax notification configured per default
- $this->array($queue)->hasSize(1);
+ $this->assertCount(1, $queue);
$GLPI_URI = GLPI_URI;
@@ -220,7 +220,7 @@ public function testRaise()
'mode' => 'ajax',
'event' => 'new',
];
- $this->array($data)->isIdenticalTo($expected);
+ $this->assertSame($expected, $data);
//reset
$CFG_GLPI['use_notifications'] = 0;
diff --git a/tests/functional/NotificationEventMailing.php b/phpunit/functional/NotificationEventMailingTest.php
similarity index 58%
rename from tests/functional/NotificationEventMailing.php
rename to phpunit/functional/NotificationEventMailingTest.php
index 3d036b66ada..7a4126dcf24 100644
--- a/tests/functional/NotificationEventMailing.php
+++ b/phpunit/functional/NotificationEventMailingTest.php
@@ -36,68 +36,68 @@
namespace tests\units;
use DbTestCase;
+use Monolog\Logger;
/* Test for inc/notificationeventajax.class.php */
-class NotificationEventMailing extends DbTestCase
+class NotificationEventMailingTest extends DbTestCase
{
public function testGetTargetField()
{
$data = [];
- $this->string(\NotificationEventMailing::getTargetField($data))->isIdenticalTo('email');
+ $this->assertSame('email', \NotificationEventMailing::getTargetField($data));
$expected = ['email' => null];
- $this->array($data)->isIdenticalTo($expected);
+ $this->assertSame($expected, $data);
$data = ['email' => 'user'];
- $this->string(\NotificationEventMailing::getTargetField($data))->isIdenticalTo('email');
+ $this->assertSame('email', \NotificationEventMailing::getTargetField($data));
$expected = ['email' => null];
- $this->array($data)->isIdenticalTo($expected);
+ $this->assertSame($expected, $data);
$data = ['email' => 'user@localhost'];
- $this->string(\NotificationEventMailing::getTargetField($data))->isIdenticalTo('email');
+ $this->assertSame('email', \NotificationEventMailing::getTargetField($data));
$expected = ['email' => 'user@localhost'];
- $this->array($data)->isIdenticalTo($expected);
+ $this->assertSame($expected, $data);
$uid = getItemByTypeName('User', TU_USER, true);
$data = ['users_id' => $uid];
- $this->string(\NotificationEventMailing::getTargetField($data))->isIdenticalTo('email');
+ $this->assertSame('email', \NotificationEventMailing::getTargetField($data));
$expected = [
'users_id' => $uid,
'email' => TU_USER . '@glpi.com'
];
- $this->array($data)->isIdenticalTo($expected);
+ $this->assertSame($expected, $data);
}
public function testCanCron()
{
- $this->boolean(\NotificationEventMailing::canCron())->isTrue();
+ $this->assertTrue(\NotificationEventMailing::canCron());
}
public function testGetAdminData()
{
global $CFG_GLPI;
- $this->array(\NotificationEventMailing::getAdminData())
- ->isIdenticalTo([
- 'email' => $CFG_GLPI['admin_email'],
- 'name' => $CFG_GLPI['admin_email_name'],
- 'language' => $CFG_GLPI['language']
- ]);
+ $this->assertSame(
+ [
+ 'email' => $CFG_GLPI['admin_email'],
+ 'name' => $CFG_GLPI['admin_email_name'],
+ 'language' => $CFG_GLPI['language']
+ ],
+ \NotificationEventMailing::getAdminData()
+ );
$CFG_GLPI['admin_email'] = 'adminlocalhost';
- $this->when(
- function () {
- $this->array(\NotificationEventMailing::getAdminData())->isIdenticalTo([]);
- }
- )->error
- ->withType(E_USER_WARNING)
- ->withMessage('Invalid email address "adminlocalhost" configured in "admin_email".')
- ->exists();
+ $this->assertSame([], \NotificationEventMailing::getAdminData());
+ $this->hasPhpLogRecordThatContains(
+ 'Invalid email address "adminlocalhost" configured in "admin_email".',
+ Logger::WARNING
+ );
}
public function testGetEntityAdminsData()
@@ -105,24 +105,24 @@ public function testGetEntityAdminsData()
$this->login();
$entity1 = getItemByTypeName('Entity', '_test_child_1');
- $this->boolean(
+ $this->assertTrue(
$entity1->update([
'id' => $entity1->getId(),
'admin_email' => 'entadmin@localhost',
'admin_email_name' => 'Entity admin ONE'
])
- )->isTrue();
+ );
$sub_entity1 = $this->createItem(\Entity::class, ['name' => 'sub entity', 'entities_id' => $entity1->getId()]);
$entity2 = getItemByTypeName('Entity', '_test_child_2');
- $this->boolean(
+ $this->assertTrue(
$entity2->update([
'id' => $entity2->getId(),
'admin_email' => 'entadmin2localhost',
'admin_email_name' => 'Entity admin TWO'
])
- )->isTrue();
+ );
$entity0_result = [
[
@@ -131,7 +131,7 @@ public function testGetEntityAdminsData()
'language' => 'en_GB',
]
];
- $this->array(\NotificationEventMailing::getEntityAdminsData(0))->isEqualTo($entity0_result);
+ $this->assertEquals($entity0_result, \NotificationEventMailing::getEntityAdminsData(0));
$entity1_result = [
[
'name' => 'Entity admin ONE',
@@ -139,16 +139,13 @@ public function testGetEntityAdminsData()
'language' => 'en_GB',
]
];
- $this->array(\NotificationEventMailing::getEntityAdminsData($entity1->getID()))->isEqualTo($entity1_result);
- $this->array(\NotificationEventMailing::getEntityAdminsData($sub_entity1->getID()))->isEqualTo($entity1_result);
-
- $this->when(
- function () use ($entity2, $entity0_result) {
- $this->array(\NotificationEventMailing::getEntityAdminsData($entity2->getID()))->isEqualTo($entity0_result);
- }
- )->error
- ->withType(E_USER_WARNING)
- ->withMessage('Invalid email address "entadmin2localhost" configured for entity "' . $entity2->getID() . '". Default administrator email will be used.')
- ->exists();
+ $this->assertEquals($entity1_result, \NotificationEventMailing::getEntityAdminsData($entity1->getID()));
+ $this->assertEquals($entity1_result, \NotificationEventMailing::getEntityAdminsData($sub_entity1->getID()));
+
+ $this->assertEquals($entity0_result, \NotificationEventMailing::getEntityAdminsData($entity2->getID()));
+ $this->hasPhpLogRecordThatContains(
+ 'Invalid email address "entadmin2localhost" configured for entity "' . $entity2->getID() . '". Default administrator email will be used.',
+ Logger::WARNING
+ );
}
}
diff --git a/tests/functional/NotificationMailingSetting.php b/phpunit/functional/NotificationMailingSettingTest.php
similarity index 56%
rename from tests/functional/NotificationMailingSetting.php
rename to phpunit/functional/NotificationMailingSettingTest.php
index 86c29e0c891..8b2738cb9be 100644
--- a/tests/functional/NotificationMailingSetting.php
+++ b/phpunit/functional/NotificationMailingSettingTest.php
@@ -39,80 +39,82 @@
/* Test for inc/notificationmailingsetting.class.php .class.php */
-class NotificationMailingSetting extends DbTestCase
+class NotificationMailingSettingTest extends DbTestCase
{
public function testGetTable()
{
- $this->string(\NotificationMailingSetting::getTable())->isIdenticalTo('glpi_configs');
+ $this->assertSame('glpi_configs', \NotificationMailingSetting::getTable());
}
public function testGetTypeName()
{
- $this->string(\NotificationMailingSetting::getTypeName())->isIdenticalTo('Email followups configuration');
- $this->string(\NotificationMailingSetting::getTypeName(10))->isIdenticalTo('Email followups configuration');
+ $this->assertSame('Email followups configuration', \NotificationMailingSetting::getTypeName());
+ $this->assertSame('Email followups configuration', \NotificationMailingSetting::getTypeName(10));
}
public function testDefineTabs()
{
$instance = new \NotificationMailingSetting();
$tabs = $instance->defineTabs();
- $this->array($tabs)
- ->hasSize(1)
- ->isIdenticalTo(['NotificationMailingSetting$1' => 'Setup']);
+ $this->assertSame(
+ ['NotificationMailingSetting$1' => 'Setup'],
+ $tabs
+ );
}
public function testGetTabNameForItem()
{
$instance = new \NotificationMailingSetting();
- $this->array($instance->getTabNameForItem($instance))->isIdenticalTo(['1' => 'Setup']);
+ $this->assertSame(
+ ['1' => 'Setup'],
+ $instance->getTabNameForItem($instance)
+ );
}
public function testDisplayTabContentForItem()
{
-
- $this->output(
- function () {
- $instance = new \NotificationMailingSetting();
- $instance->displayTabContentForItem($instance);
- }
- )->hasLengthGreaterThan(100);
+ ob_start();
+ $instance = new \NotificationMailingSetting();
+ $instance->displayTabContentForItem($instance);
+ $content = ob_get_clean();
+ $this->assertGreaterThan(100, strlen($content));
}
public function testGetEnableLabel()
{
$settings = new \NotificationMailingSetting();
- $this->string($settings->getEnableLabel())->isIdenticalTo('Enable followups via email');
+ $this->assertSame('Enable followups via email', $settings->getEnableLabel());
}
public function testGetMode()
{
- $this->string(\NotificationMailingSetting::getMode())
- ->isIdenticalTo(\Notification_NotificationTemplate::MODE_MAIL);
+ $this->assertSame(
+ \Notification_NotificationTemplate::MODE_MAIL,
+ \NotificationMailingSetting::getMode()
+ );
}
public function testShowFormConfig()
{
global $CFG_GLPI;
- $this->variable($CFG_GLPI['notifications_mailing'])->isEqualTo(0);
+ $this->assertEquals(0, $CFG_GLPI['notifications_mailing']);
- $this->output(
- function () {
- $instance = new \NotificationMailingSetting();
- $instance->showFormConfig();
- }
- )->contains('Notifications are disabled.');
+ ob_start();
+ $instance = new \NotificationMailingSetting();
+ $instance->showFormConfig();
+ $content = ob_get_clean();
+ $this->assertStringContainsString('Notifications are disabled.', $content);
$CFG_GLPI['notifications_mailing'] = 1;
- $this->output(
- function () {
- $instance = new \NotificationMailingSetting();
- $instance->showFormConfig();
- }
- )->notContains('Notifications are disabled.');
+ ob_start();
+ $instance = new \NotificationMailingSetting();
+ $instance->showFormConfig();
+ $content = ob_get_clean();
+ $this->assertStringNotContainsString('Notifications are disabled.', $content);
- //rest to defaults
+ //reset to defaults
$CFG_GLPI['notifications_mailing'] = 0;
}
}
diff --git a/tests/functional/NotificationMailing.php b/phpunit/functional/NotificationMailingTest.php
similarity index 58%
rename from tests/functional/NotificationMailing.php
rename to phpunit/functional/NotificationMailingTest.php
index 892c3c3607a..162b6f277bf 100644
--- a/tests/functional/NotificationMailing.php
+++ b/phpunit/functional/NotificationMailingTest.php
@@ -39,7 +39,7 @@
/* Test for inc/notificationmailing.class.php .class.php */
-class NotificationMailing extends DbTestCase
+class NotificationMailingTest extends DbTestCase
{
/**
* @ignore
@@ -49,18 +49,18 @@ public function testCheck()
{
$instance = new \NotificationMailing();
- $this->boolean($instance->check('user'))->isFalse();
- $this->boolean($instance->check('user@localhost'))->isTrue();
- $this->boolean($instance->check('user@localhost.dot'))->isTrue();
+ $this->assertFalse($instance->check('user'));
+ $this->assertTrue($instance->check('user@localhost'));
+ $this->assertTrue($instance->check('user@localhost.dot'));
if (!getenv('GLPI_SKIP_ONLINE')) {
- $this->boolean($instance->check('user@localhost.dot', ['checkdns' => true]))->isFalse();
- $this->boolean($instance->check('user@glpi-project.org', ['checkdns' => true]))->isTrue();
+ $this->assertFalse($instance->check('user@localhost.dot', ['checkdns' => true]));
+ $this->assertTrue($instance->check('user@glpi-project.org', ['checkdns' => true]));
}
}
public function testSendNotification()
{
- //setup
+ //setup
$this->login();
$instance = new \NotificationMailing();
@@ -77,39 +77,41 @@ public function testSendNotification()
'toname' => '',
'event' => 'test_notification'
]);
- $this->boolean($res)->isTrue();
+ $this->assertTrue($res);
$data = getAllDataFromTable('glpi_queuednotifications');
- $this->array($data)->hasSize(1);
+ $this->assertCount(1, $data);
$row = array_pop($data);
unset($row['id']);
unset($row['create_time']);
unset($row['send_time']);
- $this->array($row)
- ->isIdenticalTo([
- 'itemtype' => 'NotificationMailing',
- 'items_id' => 1,
- 'notificationtemplates_id' => 0,
- 'entities_id' => 0,
- 'is_deleted' => 0,
- 'sent_try' => 0,
- 'sent_time' => null,
- 'name' => 'Test notification',
- 'sender' => 'glpi@tests',
- 'sendername' => 'TEST',
- 'recipient' => '7',
- 'recipientname' => '',
- 'replyto' => null,
- 'replytoname' => null,
- 'headers' => '{"Auto-Submitted":"auto-generated","X-Auto-Response-Suppress":"OOF, DR, NDR, RN, NRN"}',
- 'body_html' => null,
- 'body_text' => 'Hello, this is a test notification.',
- 'messageid' => null,
- 'documents' => '',
- 'mode' => 'mailing',
- 'event' => 'test_notification'
- ]);
+ $this->assertSame(
+ [
+ 'itemtype' => 'NotificationMailing',
+ 'items_id' => 1,
+ 'notificationtemplates_id' => 0,
+ 'entities_id' => 0,
+ 'is_deleted' => 0,
+ 'sent_try' => 0,
+ 'sent_time' => null,
+ 'name' => 'Test notification',
+ 'sender' => 'glpi@tests',
+ 'sendername' => 'TEST',
+ 'recipient' => '7',
+ 'recipientname' => '',
+ 'replyto' => null,
+ 'replytoname' => null,
+ 'headers' => '{"Auto-Submitted":"auto-generated","X-Auto-Response-Suppress":"OOF, DR, NDR, RN, NRN"}',
+ 'body_html' => null,
+ 'body_text' => 'Hello, this is a test notification.',
+ 'messageid' => null,
+ 'documents' => '',
+ 'mode' => 'mailing',
+ 'event' => 'test_notification'
+ ],
+ $row
+ );
}
}
diff --git a/tests/functional/NotificationSettingConfig.php b/phpunit/functional/NotificationSettingConfigTest.php
similarity index 50%
rename from tests/functional/NotificationSettingConfig.php
rename to phpunit/functional/NotificationSettingConfigTest.php
index 8f778183ab2..60cf01c83cb 100644
--- a/tests/functional/NotificationSettingConfig.php
+++ b/phpunit/functional/NotificationSettingConfigTest.php
@@ -39,15 +39,15 @@
/* Test for inc/notificationsettingconfig.class.php */
-class NotificationSettingConfig extends DbTestCase
+class NotificationSettingConfigTest extends DbTestCase
{
public function testUpdate()
{
$current_config = \Config::getConfigurationValues('core');
- $this->variable($current_config['use_notifications'])->isEqualTo(0);
- $this->variable($current_config['notifications_mailing'])->isEqualTo(0);
- $this->variable($current_config['notifications_ajax'])->isEqualTo(0);
+ $this->assertEquals(0, $current_config['use_notifications']);
+ $this->assertEquals(0, $current_config['notifications_mailing']);
+ $this->assertEquals(0, $current_config['notifications_ajax']);
$settingconfig = new \NotificationSettingConfig();
$settingconfig->update([
@@ -56,9 +56,9 @@ public function testUpdate()
$current_config = \Config::getConfigurationValues('core');
- $this->variable($current_config['use_notifications'])->isEqualTo(1);
- $this->variable($current_config['notifications_mailing'])->isEqualTo(0);
- $this->variable($current_config['notifications_ajax'])->isEqualTo(0);
+ $this->assertEquals(1, $current_config['use_notifications']);
+ $this->assertEquals(0, $current_config['notifications_mailing']);
+ $this->assertEquals(0, $current_config['notifications_ajax']);
$settingconfig->update([
'notifications_mailing' => 1
@@ -66,9 +66,9 @@ public function testUpdate()
$current_config = \Config::getConfigurationValues('core');
- $this->variable($current_config['use_notifications'])->isEqualTo(1);
- $this->variable($current_config['notifications_mailing'])->isEqualTo(1);
- $this->variable($current_config['notifications_ajax'])->isEqualTo(0);
+ $this->assertEquals(1, $current_config['use_notifications']);
+ $this->assertEquals(1, $current_config['notifications_mailing']);
+ $this->assertEquals(0, $current_config['notifications_ajax']);
$settingconfig->update([
'use_notifications' => 0
@@ -76,9 +76,9 @@ public function testUpdate()
$current_config = \Config::getConfigurationValues('core');
- $this->variable($current_config['use_notifications'])->isEqualTo(0);
- $this->variable($current_config['notifications_mailing'])->isEqualTo(0);
- $this->variable($current_config['notifications_ajax'])->isEqualTo(0);
+ $this->assertEquals(0, $current_config['use_notifications']);
+ $this->assertEquals(0, $current_config['notifications_mailing']);
+ $this->assertEquals(0, $current_config['notifications_ajax']);
}
public function testShowForm()
@@ -89,53 +89,45 @@ public function testShowForm()
$options = ['display' => false];
$output = $settingconfig->showConfigForm($options);
- $this->string(trim($output))->isEmpty(); // Only whitespaces, no real content
+ $this->assertEmpty(trim($output)); // Only whitespaces, no real content
$this->login();
- $this->output(
- function () use ($settingconfig) {
- $settingconfig->showConfigForm();
- }
- )
- ->contains('Notifications configuration')
- ->notContains('Notification templates');
+ ob_start();
+ $settingconfig->showConfigForm();
+ $content = ob_get_clean();
+ $this->assertStringContainsString('Notifications configuration', $content);
+ $this->assertStringNotContainsString('Notification templates', $content);
$CFG_GLPI['use_notifications'] = 1;
- $this->output(
- function () use ($settingconfig) {
- $settingconfig->showConfigForm();
- }
- )
- ->contains('Notifications configuration')
- ->notContains('Notification templates');
+ ob_start();
+ $settingconfig->showConfigForm();
+ $content = ob_get_clean();
+ $this->assertStringContainsString('Notifications configuration', $content);
+ $this->assertStringNotContainsString('Notification templates', $content);
$CFG_GLPI['notifications_ajax'] = 1;
- $this->output(
- function () use ($settingconfig) {
- $settingconfig->showConfigForm();
- }
- )
- ->contains('Notifications configuration')
- ->contains('Notification templates')
- ->contains('Browser followups configuration')
- ->notContains('Email followups configuration');
+ ob_start();
+ $settingconfig->showConfigForm();
+ $content = ob_get_clean();
+ $this->assertStringContainsString('Notifications configuration', $content);
+ $this->assertStringContainsString('Notification templates', $content);
+ $this->assertStringContainsString('Browser followups configuration', $content);
+ $this->assertStringNotContainsString('Email followups configuration', $content);
$CFG_GLPI['notifications_mailing'] = 1;
- $this->output(
- function () use ($settingconfig) {
- $settingconfig->showConfigForm();
- }
- )
- ->contains('Notifications configuration')
- ->contains('Notification templates')
- ->contains('Browser followups configuration')
- ->contains('Email followups configuration');
-
- //reset
+ ob_start();
+ $settingconfig->showConfigForm();
+ $content = ob_get_clean();
+ $this->assertStringContainsString('Notifications configuration', $content);
+ $this->assertStringContainsString('Notification templates', $content);
+ $this->assertStringContainsString('Browser followups configuration', $content);
+ $this->assertStringContainsString('Email followups configuration', $content);
+
+ //reset
$CFG_GLPI['use_notifications'] = 0;
$CFG_GLPI['notifications_mailing'] = 0;
$CFG_GLPI['notifications_ajax'] = 0;
diff --git a/tests/functional/NotificationSettingInstance.php b/phpunit/functional/NotificationSettingInstanceTest.php
similarity index 65%
rename from tests/functional/NotificationSettingInstance.php
rename to phpunit/functional/NotificationSettingInstanceTest.php
index 29b6adc87ac..f984ae47aff 100644
--- a/tests/functional/NotificationSettingInstance.php
+++ b/phpunit/functional/NotificationSettingInstanceTest.php
@@ -41,37 +41,32 @@
/* Test for inc/notificationmailingsetting.class.php */
-class NotificationSettingInstance extends DbTestCase
+class NotificationSettingInstancetest extends DbTestCase
{
public function testGetTable()
{
- $this->string(\NotificationSetting::getTable())->isIdenticalTo('glpi_configs');
+ $this->assertSame('glpi_configs', \NotificationSetting::getTable());
}
public function testGetTypeName()
{
- $this->exception(
- function () {
- \NotificationSetting::getTypeName();
- }
- )
- ->isInstanceOf('RuntimeException')
- ->hasMessage('getTypeName must be implemented');
+ $this->expectExceptionMessage('getTypeName must be implemented');
+ \NotificationSetting::getTypeName();
}
public function testDisplayTabContentForItem()
{
- $instance = new \mock\NotificationMailingSetting();
- $this->boolean(\NotificationSetting::displayTabContentForItem($instance))->isTrue();
+ $instance = new \NotificationMailingSetting();
+ $this->assertTrue(\NotificationSetting::displayTabContentForItem($instance));
}
public function testDisableAll()
{
global $CFG_GLPI;
- $this->variable($CFG_GLPI['use_notifications'])->isEqualTo(0);
- $this->variable($CFG_GLPI['notifications_mailing'])->isEqualTo(0);
- $this->array($CFG_GLPI)->notHasKey('notifications_xyz');
+ $this->assertEquals(0, $CFG_GLPI['use_notifications']);
+ $this->assertEquals(0, $CFG_GLPI['notifications_mailing']);
+ $this->assertArrayNotHasKey('notifications_xyz', $CFG_GLPI);
$CFG_GLPI['use_notifications'] = 1;
$CFG_GLPI['notifications_mailing'] = 1;
@@ -79,8 +74,8 @@ public function testDisableAll()
\NotificationSetting::disableAll();
- $this->variable($CFG_GLPI['use_notifications'])->isEqualTo(0);
- $this->variable($CFG_GLPI['notifications_mailing'])->isEqualTo(0);
- $this->variable($CFG_GLPI['notifications_xyz'])->isEqualTo(0);
+ $this->assertEquals(0, $CFG_GLPI['use_notifications']);
+ $this->assertEquals(0, $CFG_GLPI['notifications_mailing']);
+ $this->assertEquals(0, $CFG_GLPI['notifications_xyz']);
}
}
diff --git a/tests/functional/NotificationTargetSavedSearch_Alert.php b/phpunit/functional/NotificationTargetSavedSearch_AlertTest.php
similarity index 90%
rename from tests/functional/NotificationTargetSavedSearch_Alert.php
rename to phpunit/functional/NotificationTargetSavedSearch_AlertTest.php
index decbbb8b36c..393c6bb64f4 100644
--- a/tests/functional/NotificationTargetSavedSearch_Alert.php
+++ b/phpunit/functional/NotificationTargetSavedSearch_AlertTest.php
@@ -39,7 +39,7 @@
/* Test for inc/notificationtargetuser.class.php */
-class NotificationTargetSavedSearch_Alert extends DbTestCase
+class NotificationTargetSavedSearch_AlertTest extends DbTestCase
{
public function testAddDataForTemplate()
{
@@ -54,7 +54,7 @@ public function testAddDataForTemplate()
'itemtype' => 'Computer',
'url' => 'http://glpi.localhost/front/computer.php?is_deleted=0&as_map=0&browse=0&criteria%5B0%5D%5Blink%5D=AND&criteria%5B0%5D%5Bfield%5D=view&criteria%5B0%5D%5Bsearchtype%5D=contains&criteria%5B0%5D%5Bvalue%5D=test&itemtype=Computer&start=0&_glpi_csrf_token=735e344f1f47545e5bea56aa4e75c15ca45d3628307937c3bf185e0a3bca39db&sort%5B%5D=1&order%5B%5D=ASC'
]);
- $this->integer($saved_searches_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $saved_searches_id);
// Create saved search alert
$saved_search_alert = new \SavedSearch_Alert();
@@ -66,7 +66,7 @@ public function testAddDataForTemplate()
'value' => '5',
'frequency' => DAY_TIMESTAMP,
]);
- $this->integer($saved_search_alerts_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $saved_search_alerts_id);
// Create a notification target
$target = new \NotificationTargetSavedSearch_Alert(
@@ -89,7 +89,9 @@ public function testAddDataForTemplate()
// Host may change so only check the end of the URL
global $CFG_GLPI;
$expected_redirect = '%2Ffront%2Fsavedsearch.php%3Faction%3Dload%26id%3D' . $saved_searches_id;
- $this->string($target->data['##savedsearch.url##'])
- ->isEqualTo($CFG_GLPI['url_base'] . '/index.php?redirect=' . $expected_redirect);
+ $this->assertEquals(
+ $CFG_GLPI['url_base'] . '/index.php?redirect=' . $expected_redirect,
+ $target->data['##savedsearch.url##']
+ );
}
}
diff --git a/tests/functional/NotificationTarget.php b/phpunit/functional/NotificationTargetTest.php
similarity index 76%
rename from tests/functional/NotificationTarget.php
rename to phpunit/functional/NotificationTargetTest.php
index 76b71565bd8..55f01bb6db2 100644
--- a/tests/functional/NotificationTarget.php
+++ b/phpunit/functional/NotificationTargetTest.php
@@ -38,11 +38,12 @@
use DbTestCase;
use Entity;
use Generator;
+use Monolog\Logger;
use Session;
/* Test for inc/notificationtarget.class.php */
-class NotificationTarget extends DbTestCase
+class NotificationTargetTest extends DbTestCase
{
public function testGetSubjectPrefix()
{
@@ -57,52 +58,50 @@ public function testGetSubjectPrefix()
$ntarget_child_1 = new \NotificationTarget($child_1);
$ntarget_child_2 = new \NotificationTarget($child_2);
- $this->string($ntarget_parent->getSubjectPrefix())->isEqualTo("[GLPI] ");
- $this->string($ntarget_child_1->getSubjectPrefix())->isEqualTo("[GLPI] ");
- $this->string($ntarget_child_2->getSubjectPrefix())->isEqualTo("[GLPI] ");
+ $this->assertEquals("[GLPI] ", $ntarget_parent->getSubjectPrefix());
+ $this->assertEquals("[GLPI] ", $ntarget_child_1->getSubjectPrefix());
+ $this->assertEquals("[GLPI] ", $ntarget_child_2->getSubjectPrefix());
$entity = new \Entity();
- $this->boolean($entity->update([
+ $this->assertTrue($entity->update([
'id' => $root,
'notification_subject_tag' => "prefix_root",
- ]))->isTrue();
+ ]));
- $this->string($ntarget_parent->getSubjectPrefix())->isEqualTo("[prefix_root] ");
- $this->string($ntarget_child_1->getSubjectPrefix())->isEqualTo("[prefix_root] ");
- $this->string($ntarget_child_2->getSubjectPrefix())->isEqualTo("[prefix_root] ");
+ $this->assertEquals("[prefix_root] ", $ntarget_parent->getSubjectPrefix());
+ $this->assertEquals("[prefix_root] ", $ntarget_child_1->getSubjectPrefix());
+ $this->assertEquals("[prefix_root] ", $ntarget_child_2->getSubjectPrefix());
- $this->boolean($entity->update([
+ $this->assertTrue($entity->update([
'id' => $parent,
'notification_subject_tag' => "prefix_parent",
- ]))->isTrue();
+ ]));
- $this->string($ntarget_parent->getSubjectPrefix())->isEqualTo("[prefix_parent] ");
- $this->string($ntarget_child_1->getSubjectPrefix())->isEqualTo("[prefix_parent] ");
- $this->string($ntarget_child_2->getSubjectPrefix())->isEqualTo("[prefix_parent] ");
+ $this->assertEquals("[prefix_parent] ", $ntarget_parent->getSubjectPrefix());
+ $this->assertEquals("[prefix_parent] ", $ntarget_child_1->getSubjectPrefix());
+ $this->assertEquals("[prefix_parent] ", $ntarget_child_2->getSubjectPrefix());
- $this->boolean($entity->update([
+ $this->assertTrue($entity->update([
'id' => $child_1,
'notification_subject_tag' => "prefix_child_1",
- ]))->isTrue();
+ ]));
- $this->string($ntarget_parent->getSubjectPrefix())->isEqualTo("[prefix_parent] ");
- $this->string($ntarget_child_1->getSubjectPrefix())->isEqualTo("[prefix_child_1] ");
- $this->string($ntarget_child_2->getSubjectPrefix())->isEqualTo("[prefix_parent] ");
+ $this->assertEquals("[prefix_parent] ", $ntarget_parent->getSubjectPrefix());
+ $this->assertEquals("[prefix_child_1] ", $ntarget_child_1->getSubjectPrefix());
+ $this->assertEquals("[prefix_parent] ", $ntarget_child_2->getSubjectPrefix());
- $this->boolean($entity->update([
+ $this->assertTrue($entity->update([
'id' => $child_2,
'notification_subject_tag' => "prefix_child_2",
- ]))->isTrue();
+ ]));
- $this->string($ntarget_parent->getSubjectPrefix())->isEqualTo("[prefix_parent] ");
- $this->string($ntarget_child_1->getSubjectPrefix())->isEqualTo("[prefix_child_1] ");
- $this->string($ntarget_child_2->getSubjectPrefix())->isEqualTo("[prefix_child_2] ");
+ $this->assertEquals("[prefix_parent] ", $ntarget_parent->getSubjectPrefix());
+ $this->assertEquals("[prefix_child_1] ", $ntarget_child_1->getSubjectPrefix());
+ $this->assertEquals("[prefix_child_2] ", $ntarget_child_2->getSubjectPrefix());
}
- protected function getReplyToProvider(): iterable
+ public static function getReplyToProvider(): iterable
{
- $this->login(); // must be logged-in to update entities
-
$root_entity_id = 0;
$parent_entity_id = getItemByTypeName('Entity', '_test_root_entity', true);
$child_1_entity_id = getItemByTypeName('Entity', '_test_child_1', true);
@@ -228,6 +227,8 @@ public function testGetReplyTo(
): void {
global $CFG_GLPI;
+ $this->login(); // must be logged-in to update entities
+
foreach ($global_config as $config_key => $config_value) {
$CFG_GLPI[$config_key] = $config_value;
}
@@ -239,7 +240,7 @@ public function testGetReplyTo(
foreach ($expected_results as $entity_id => $expected_result) {
$target = new \NotificationTarget($entity_id);
$target->setAllowResponse($allow_response);
- $this->array($target->getReplyTo())->isEqualTo($expected_result);
+ $this->assertEquals($expected_result, $target->getReplyTo());
}
}
@@ -291,16 +292,16 @@ protected function getSenderProvider(): Generator
// Case 5: default post install values with specific entity config
$entity = new Entity();
- $this->boolean($entity->update([
+ $this->assertTrue($entity->update([
'id' => Session::getActiveEntity(),
'admin_email' => "specificadmin@localhost",
'admin_email_name' => "Specific admin",
- ]))->isTrue();
- $this->boolean(
+ ]));
+ $this->assertTrue(
$entity->getFromDB(Session::getActiveEntity())
- )->isTrue();
- $this->string($entity->fields['admin_email'])->isEqualTo("specificadmin@localhost");
- $this->string($entity->fields['admin_email_name'])->isEqualTo("Specific admin");
+ );
+ $this->assertEquals("specificadmin@localhost", $entity->fields['admin_email']);
+ $this->assertEquals("Specific admin", $entity->fields['admin_email_name']);
yield [
'allow_response' => true,
@@ -320,45 +321,42 @@ protected function getSenderProvider(): Generator
}
/**
- * Functionals tests for the getSender method
- *
- * @dataProvider getSenderProvider
- *
- * @param bool $allow_response Use reply to or admin email ?
- * @param string|null $email Expected email
- * @param string|null $name Expected name
- * @param string|null $warning Exected warnings (default: none)
+ * Functional tests for the getSender method
*
* @return void
*/
- public function testGetSender(
- bool $allow_response,
- ?string $email,
- ?string $name,
- ?string $warning = null
- ): void {
- $target = new \mock\NotificationTarget();
- $this->calling($target)->allowResponse = $allow_response;
-
- if (is_null($warning)) {
- $this->array($target->getSender())->isEqualTo([
- 'email' => $email,
- 'name' => $name,
- ]);
- } else {
- $this->when(function () use ($target, $email, $name) {
- $this->array($target->getSender())->isEqualTo([
+ public function testGetSender(): void
+ {
+ $provider = $this->getSenderProvider();
+ foreach ($provider as $row) {
+ $allow_response = $row['allow_response'];
+ $email = $row['email'] ?? null;
+ $name = $row['name'] ?? null;
+ $warning = $row['warning'] ?? null;
+
+ $target = $this->getMockBuilder(\NotificationTarget::class)
+ ->onlyMethods(['allowResponse'])
+ ->getMock();
+ $target->method('allowResponse')->willReturn($allow_response);
+
+ $this->assertEquals(
+ [
'email' => $email,
- 'name' => $name,
- ]);
- })->error()
- ->withType(E_USER_WARNING)
- ->withMessage($warning)
- ->exists();
+ 'name' => $name,
+ ],
+ $target->getSender()
+ );
+
+ if (!is_null($warning)) {
+ $this->hasPhpLogRecordThatContains(
+ $warning,
+ Logger::WARNING
+ );
+ }
}
}
- protected function testGetInstanceClassProvider(): Generator
+ public static function testGetInstanceClassProvider(): Generator
{
yield [
'itemtype' => 'Test',
@@ -384,10 +382,10 @@ protected function testGetInstanceClassProvider(): Generator
public function testGetInstanceClass(string $itemtype, string $class): void
{
$output = \NotificationTarget::getInstanceClass($itemtype);
- $this->string($output)->isEqualTo($class);
+ $this->assertEquals($class, $output);
}
- protected function testFormatUrlProvider(): iterable
+ public static function testFormatUrlProvider(): iterable
{
global $CFG_GLPI;
@@ -428,69 +426,63 @@ protected function testFormatUrlProvider(): iterable
*/
public function testFormatUrl(int $usertype, string $redirect, string $expected): void
{
- $this->newTestedInstance();
-
- $this->string($this->testedInstance->formatUrl($usertype, $redirect))->isEqualTo($expected);
+ $instance = new \NotificationTarget();
+ $this->assertEquals($expected, $instance->formatUrl($usertype, $redirect));
}
- protected function messageItemProvider(): iterable
+ public static function messageItemProvider(): iterable
{
- //set UUID
- $uuid = \Toolbox::getRandomString(40);
- \Config::setConfigurationValues('core', ['notification' . '_uuid' => $uuid]);
- $uname = php_uname('n');
-
return [
[
"itemtype" => "Ticket",
"items_id" => 1,
"event" => "new",
- "expected" => "/^GLPI_{$uuid}-Ticket-1\/new@{$uname}$/",
+ "expected" => "/^GLPI_%UUID%-Ticket-1\/new@%UNAME%$/",
],
[
"itemtype" => "Ticket",
"items_id" => 1,
"event" => "update",
- "expected" => "/^GLPI_{$uuid}-Ticket-1\/update\.\d+\.\d+@{$uname}$/",
+ "expected" => "/^GLPI_%UUID%-Ticket-1\/update\.\d+\.\d+@%UNAME%$/",
],
[
"itemtype" => "Certificate",
"items_id" => 1,
"event" => 'alert',
- "expected" => "/^GLPI_{$uuid}-Certificate-1\/alert\.\d+\.\d+@{$uname}$/",
+ "expected" => "/^GLPI_%UUID%-Certificate-1\/alert\.\d+\.\d+@%UNAME%$/",
],
[
"itemtype" => "User",
"items_id" => 7,
"event" => 'new',
- "expected" => "/^GLPI_{$uuid}-User-7\/new@{$uname}$/",
+ "expected" => "/^GLPI_%UUID%-User-7\/new@%UNAME%$/",
],
[
"itemtype" => "User",
"items_id" => 7,
"event" => 'passwordexpires',
- "expected" => "/^GLPI_{$uuid}-User-7\/passwordexpires\.\d+\.\d+@{$uname}$/",
+ "expected" => "/^GLPI_%UUID%-User-7\/passwordexpires\.\d+\.\d+@%UNAME%$/",
],
[
// no item
"itemtype" => null,
"items_id" => null,
"event" => "some_event",
- "expected" => "/^GLPI_{$uuid}\/some_event\.\d+\.\d+@{$uname}$/",
+ "expected" => "/^GLPI_%UUID%\/some_event\.\d+\.\d+@%UNAME%$/",
],
[
// invalid itemtype
"itemtype" => "Other",
"items_id" => 1,
"event" => "update",
- "expected" => "/^GLPI_{$uuid}\/update\.\d+\.\d+@{$uname}$/",
+ "expected" => "/^GLPI_%UUID%\/update\.\d+\.\d+@%UNAME%$/",
],
[
// no event
"itemtype" => null,
"items_id" => null,
"event" => null,
- "expected" => "/^GLPI_{$uuid}\/none\.\d+\.\d+@{$uname}$/",
+ "expected" => "/^GLPI_%UUID%\/none\.\d+\.\d+@%UNAME%$/",
],
];
}
@@ -500,7 +492,27 @@ protected function messageItemProvider(): iterable
*/
public function testGetMessageIdForEvent(?string $itemtype, ?int $items_id, ?string $event, string $expected)
{
- $messageid = $this->newTestedInstance()->getMessageIdForEvent($itemtype, $items_id, $event);
- $this->string($messageid)->matches($expected);
+ //set UUID
+ $uuid = \Toolbox::getRandomString(40);
+ \Config::setConfigurationValues('core', ['notification_uuid' => $uuid]);
+
+ $uuid = \Config::getConfigurationValue('core', 'notification_uuid');
+ $uname = php_uname('n');
+
+ $expected = str_replace(
+ [
+ '%UUID%',
+ '%UNAME%',
+ ],
+ [
+ $uuid,
+ $uname,
+ ],
+ $expected
+ );
+
+ $instance = new \NotificationTarget();
+ $messageid = $instance->getMessageIdForEvent($itemtype, $items_id, $event);
+ $this->assertMatchesRegularExpression($expected, $messageid);
}
}
diff --git a/tests/functional/NotificationTargetTicket.php b/phpunit/functional/NotificationTargetTicketTest.php
similarity index 88%
rename from tests/functional/NotificationTargetTicket.php
rename to phpunit/functional/NotificationTargetTicketTest.php
index e24f66f1be7..e6848056bb3 100644
--- a/tests/functional/NotificationTargetTicket.php
+++ b/phpunit/functional/NotificationTargetTicketTest.php
@@ -41,7 +41,7 @@
/* Test for inc/notificationtargetticket.class.php */
-class NotificationTargetTicket extends DbTestCase
+class NotificationTargetTicketTest extends DbTestCase
{
public function testgetDataForObject()
{
@@ -51,7 +51,7 @@ public function testgetDataForObject()
$notiftargetticket = new \NotificationTargetTicket(getItemByTypeName('Entity', '_test_root_entity', true), 'new', $tkt);
$notiftargetticket->getTags();
- // basic test for ##task.categorycomment## tag
+ // basic test for ##task.categorycomment## tag
$expected = [
'tag' => 'task.categorycomment',
'value' => true,
@@ -62,12 +62,10 @@ public function testgetDataForObject()
'allowed_values' => [],
];
- $this->array($notiftargetticket->tag_descriptions['lang']['##lang.task.categorycomment##'])
- ->isIdenticalTo($expected);
- $this->array($notiftargetticket->tag_descriptions['tag']['##task.categorycomment##'])
- ->isIdenticalTo($expected);
+ $this->assertSame($expected, $notiftargetticket->tag_descriptions['lang']['##lang.task.categorycomment##']);
+ $this->assertSame($expected, $notiftargetticket->tag_descriptions['tag']['##task.categorycomment##']);
- // basic test for ##task.categorid## tag
+ // basic test for ##task.categorid## tag
$expected = [
'tag' => 'task.categoryid',
'value' => true,
@@ -77,13 +75,11 @@ public function testgetDataForObject()
'lang' => true,
'allowed_values' => [],
];
- $this->array($notiftargetticket->tag_descriptions['lang']['##lang.task.categoryid##'])
- ->isIdenticalTo($expected);
- $this->array($notiftargetticket->tag_descriptions['tag']['##task.categoryid##'])
- ->isIdenticalTo($expected);
+ $this->assertSame($expected, $notiftargetticket->tag_descriptions['lang']['##lang.task.categoryid##']);
+ $this->assertSame($expected, $notiftargetticket->tag_descriptions['tag']['##task.categoryid##']);
- // advanced test for ##task.categorycomment## and ##task.categoryid## tags
- // test of the getDataForObject for default language en_GB
+ // advanced test for ##task.categorycomment## and ##task.categoryid## tags
+ // test of the getDataForObject for default language en_GB
$taskcat = getItemByTypeName('TaskCategory', '_subcat_1');
$encoded_sep = Sanitizer::sanitize('>');
$expected = [
@@ -112,9 +108,9 @@ public function testgetDataForObject()
];
$ret = $notiftargetticket->getDataForObject($tkt, $basic_options);
- $this->array($ret['tasks'])->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret['tasks']);
- // test of the getDataForObject for default language fr_FR
+ // test of the getDataForObject for default language fr_FR
$CFG_GLPI['translate_dropdowns'] = 1;
// Force generation of completename that was not done on dataset bootstrap
// because `translate_dropdowns` is false by default.
@@ -147,19 +143,18 @@ public function testgetDataForObject()
]
];
- $this->array($ret['tasks'])->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret['tasks']);
- // switch back to default language
+ // switch back to default language
$_SESSION["glpilanguage"] = \Session::loadLanguage('en_GB');
}
public function testTimelineTag()
{
-
$entity = getItemByTypeName("Entity", "_test_root_entity");
global $DB;
- // Build test ticket
+ // Build test ticket
$this->login('tech', 'tech');
$ticket = new \Ticket();
$tickets_id = $ticket->add($input = [
@@ -172,16 +167,16 @@ public function testTimelineTag()
'users_id_lastupdater' => getItemByTypeName('User', 'tech', true),
'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);
- // Add followup from tech
+ // Add followup from tech
$fup_tech = new \ITILFollowup();
$fup1_id = $fup_tech->add([
'content' => 'test followup',
@@ -192,9 +187,9 @@ public function testTimelineTag()
'items_id' => $tickets_id,
'date_creation' => date('Y-m-d H:i:s', strtotime($_SESSION['glpi_currenttime']) + 1),
]);
- $this->integer($fup1_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $fup1_id);
- // Add followup from post_only
+ // Add followup from post_only
$fup_post_only = new \ITILFollowup();
$fup2_id = $fup_post_only->add([
'content' => 'test post_only',
@@ -205,9 +200,9 @@ public function testTimelineTag()
'items_id' => $tickets_id,
'date_creation' => date('Y-m-d H:i:s', strtotime($_SESSION['glpi_currenttime']) + 2),
]);
- $this->integer($fup2_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $fup2_id);
- // Add private followup to tech
+ // Add private followup to tech
$fup_private_tech = new \ITILFollowup();
$fup3_id = $fup_private_tech->add([
'content' => 'test private followup',
@@ -218,9 +213,9 @@ public function testTimelineTag()
'items_id' => $tickets_id,
'date_creation' => date('Y-m-d H:i:s', strtotime($_SESSION['glpi_currenttime']) + 3),
]);
- $this->integer($fup3_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $fup3_id);
- //add private task from tech
+ //add private task from tech
$task_private = new \TicketTask();
$task1_id = $task_private->add([
'state' => \Planning::TODO,
@@ -233,9 +228,9 @@ public function testTimelineTag()
'users_id_tech' => getItemByTypeName('User', 'tech', true),
'date_creation' => date('Y-m-d H:i:s', strtotime($_SESSION['glpi_currenttime']) + 4),
]);
- $this->integer($task1_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $task1_id);
- //add task from tech
+ //add task from tech
$task_tech = new \TicketTask();
$task2_id = $task_tech->add([
'state' => \Planning::TODO,
@@ -243,14 +238,14 @@ public function testTimelineTag()
'tasktemplates_id' => '0',
'taskcategories_id' => '0',
'is_private' => 0,
- 'actiontime' => "172800", //1hours
+ 'actiontime' => "172800", //1hour
'content' => "Task",
'users_id_tech' => getItemByTypeName('User', 'tech', true),
'date_creation' => date('Y-m-d H:i:s', strtotime($_SESSION['glpi_currenttime']) + 5),
]);
- $this->integer($task2_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $task2_id);
- // Add solution to test ticket
+ // Add solution to test ticket
$solution = new \ITILSolution();
$solutions_id = $solution->add([
'content' => 'test',
@@ -260,7 +255,7 @@ public function testTimelineTag()
'items_id' => $tickets_id,
'date_creation' => date('Y-m-d H:i:s', strtotime($_SESSION['glpi_currenttime']) + 6),
]);
- $this->integer($solutions_id)->isGreaterThan(0);
+ $this->assertGreaterThan(0, $solutions_id);
// Must be logged out to ensure session rights are not checked.
$this->resetSession();
@@ -276,7 +271,7 @@ public function testTimelineTag()
$notiftargetticket = new \NotificationTargetTicket(getItemByTypeName('Entity', '_test_root_entity', true), 'new', $ticket);
$ret = $notiftargetticket->getDataForObject($ticket, $basic_options);
- //get all task / solution / followup (because is tech)
+ //get all task / solution / followup (because is tech)
$expected = [
[
"##timelineitems.type##" => "ITILSolution",
@@ -323,9 +318,9 @@ public function testTimelineTag()
]
];
- $this->array($ret['timelineitems'])->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret['timelineitems']);
- $this->boolean((bool)$this->login('post-only', 'postonly', true))->isTrue();
+ $this->assertTrue((bool)$this->login('post-only', 'postonly', true));
$basic_options = [
'additionnaloption' => [
@@ -337,7 +332,7 @@ public function testTimelineTag()
$ret = $notiftargetticket->getDataForObject($ticket, $basic_options);
- //get only public task / followup / Solution (because is post_only)
+ //get only public task / followup / Solution (because is post_only)
$expected = [
[
"##timelineitems.type##" => "ITILSolution",
@@ -415,6 +410,6 @@ public function testTimelineTag()
]
];
- $this->array($ret['timelineitems'])->isIdenticalTo($expected);
+ $this->assertSame($expected, $ret['timelineitems']);
}
}
diff --git a/tests/functional/NotificationTargetUser.php b/phpunit/functional/NotificationTargetUserTest.php
similarity index 92%
rename from tests/functional/NotificationTargetUser.php
rename to phpunit/functional/NotificationTargetUserTest.php
index f922f780aa0..225cf64e5b8 100644
--- a/tests/functional/NotificationTargetUser.php
+++ b/phpunit/functional/NotificationTargetUserTest.php
@@ -39,9 +39,9 @@
/* Test for inc/notificationtargetuser.class.php */
-class NotificationTargetUser extends DbTestCase
+class NotificationTargetUserTest extends DbTestCase
{
- protected function addDataForPasswordExpiresTemplateProvider()
+ public static function addDataForPasswordExpiresTemplateProvider()
{
global $CFG_GLPI;
@@ -104,8 +104,10 @@ public function testAddDataForPasswordExpiresTemplate(int $expiration_time, int
{
global $CFG_GLPI;
- $user = new \mock\User();
- $this->calling($user)->getPasswordExpirationTime = $expiration_time;
+ $user = $this->getMockBuilder(\User::class)
+ ->onlyMethods(['getPasswordExpirationTime'])
+ ->getMock();
+ $user->method('getPasswordExpirationTime')->willReturn($expiration_time);
$cfg_backup = $CFG_GLPI;
$CFG_GLPI['password_expiration_lock_delay'] = $lock_delay;$target = new \NotificationTargetUser(
@@ -121,9 +123,8 @@ public function testAddDataForPasswordExpiresTemplate(int $expiration_time, int
private function checkTemplateData(array $data, array $expected)
{
- $this->array($data)->hasKeys(array_keys($expected));
foreach ($expected as $key => $value) {
- $this->variable($data[$key])->isIdenticalTo($value);
+ $this->assertSame($value, $data[$key]);
}
}
}
diff --git a/tests/functional/NotificationTemplate.php b/phpunit/functional/NotificationTemplateTest.php
similarity index 90%
rename from tests/functional/NotificationTemplate.php
rename to phpunit/functional/NotificationTemplateTest.php
index b6d7c776ed4..69397cda356 100644
--- a/tests/functional/NotificationTemplate.php
+++ b/phpunit/functional/NotificationTemplateTest.php
@@ -39,7 +39,7 @@
/* Test for inc/notificationtemplate.class.php */
-class NotificationTemplate extends DbTestCase
+class NotificationTemplateTest extends DbTestCase
{
public function testClone()
{
@@ -55,10 +55,10 @@ public function testClone()
$template = new \NotificationTemplate();
$template->getFromDB($data['notificationtemplates_id']);
$added = $template->clone();
- $this->integer((int)$added)->isGreaterThan(0);
+ $this->assertGreaterThan(0, (int)$added);
$clonedTemplate = new \NotificationTemplate();
- $this->boolean($clonedTemplate->getFromDB($added))->isTrue();
+ $this->assertTrue($clonedTemplate->getFromDB($added));
unset($template->fields['id']);
unset($template->fields['name']);
@@ -70,10 +70,10 @@ public function testClone()
unset($clonedTemplate->fields['date_creation']);
unset($clonedTemplate->fields['date_mod']);
- $this->array($template->fields)->isIdenticalTo($clonedTemplate->fields);
+ $this->assertSame($clonedTemplate->fields, $template->fields);
}
- protected function linksProvider(): iterable
+ public static function linksProvider(): iterable
{
$base_url = GLPI_URI;
@@ -130,8 +130,8 @@ public function testConvertRelativeGlpiLinksToAbsolute(
string $content,
string $expected
): void {
- $instance = $this->newTestedInstance();
+ $instance = new \NotificationTemplate();
$result = $this->callPrivateMethod($instance, 'convertRelativeGlpiLinksToAbsolute', $content);
- $this->string($result)->isEqualTo($expected);
+ $this->assertEquals($expected, $result);
}
}
diff --git a/tests/functional/NotificationTemplateTranslation.php b/phpunit/functional/NotificationTemplateTranslationTest.php
similarity index 88%
rename from tests/functional/NotificationTemplateTranslation.php
rename to phpunit/functional/NotificationTemplateTranslationTest.php
index d511c85e0a5..df19f4ed5b6 100644
--- a/tests/functional/NotificationTemplateTranslation.php
+++ b/phpunit/functional/NotificationTemplateTranslationTest.php
@@ -39,7 +39,7 @@
/* Test for inc/notificationtemplatetranslation.class.php */
-class NotificationTemplateTranslation extends DbTestCase
+class NotificationTemplateTranslationTest extends DbTestCase
{
public function testClone()
{
@@ -55,15 +55,15 @@ public function testClone()
$translation = new \NotificationTemplateTranslation();
$translation->getFromDB($data['id']);
$added = $translation->clone();
- $this->integer((int)$added)->isGreaterThan(0);
+ $this->assertGreaterThan(0, (int)$added);
$clonedTranslation = new \NotificationTemplateTranslation();
- $this->boolean($clonedTranslation->getFromDB($added))->isTrue();
+ $this->assertTrue($clonedTranslation->getFromDB($added));
unset($translation->fields['id']);
unset($clonedTranslation->fields['id']);
- $this->array($translation->fields)->isIdenticalTo($clonedTranslation->fields);
+ $this->assertSame($clonedTranslation->fields, $translation->fields);
}
public function testCloneFromTemplate()
@@ -94,6 +94,6 @@ public function testCloneFromTemplate()
'WHERE' => ['notificationtemplates_id' => $added]
]);
- $this->integer(count($translations))->isIdenticalTo(count($clonedTranslations));
+ $this->assertCount(count($clonedTranslations), $translations);
}
}
diff --git a/tests/functional/Notification.php b/phpunit/functional/NotificationTest.php
similarity index 62%
rename from tests/functional/Notification.php
rename to phpunit/functional/NotificationTest.php
index 928a409d1e0..5fcd4101f78 100644
--- a/tests/functional/Notification.php
+++ b/phpunit/functional/NotificationTest.php
@@ -47,7 +47,7 @@
/* Test for inc/notification.class.php */
-class Notification extends DbTestCase
+class NotificationTest extends DbTestCase
{
public function testGetMailingSignature()
{
@@ -62,46 +62,46 @@ public function testGetMailingSignature()
$CFG_GLPI['mailing_signature'] = 'global_signature';
- $this->string(\Notification::getMailingSignature($parent))->isEqualTo("global_signature");
- $this->string(\Notification::getMailingSignature($child_1))->isEqualTo("global_signature");
- $this->string(\Notification::getMailingSignature($child_2))->isEqualTo("global_signature");
+ $this->assertEquals("global_signature", \Notification::getMailingSignature($parent));
+ $this->assertEquals("global_signature", \Notification::getMailingSignature($child_1));
+ $this->assertEquals("global_signature", \Notification::getMailingSignature($child_2));
$entity = new \Entity();
- $this->boolean($entity->update([
+ $this->assertTrue($entity->update([
'id' => $root,
'mailing_signature' => "signature_root",
- ]))->isTrue();
+ ]));
- $this->string(\Notification::getMailingSignature($parent))->isEqualTo("signature_root");
- $this->string(\Notification::getMailingSignature($child_1))->isEqualTo("signature_root");
- $this->string(\Notification::getMailingSignature($child_2))->isEqualTo("signature_root");
+ $this->assertEquals("signature_root", \Notification::getMailingSignature($parent));
+ $this->assertEquals("signature_root", \Notification::getMailingSignature($child_1));
+ $this->assertEquals("signature_root", \Notification::getMailingSignature($child_2));
- $this->boolean($entity->update([
+ $this->assertTrue($entity->update([
'id' => $parent,
'mailing_signature' => "signature_parent",
- ]))->isTrue();
+ ]));
- $this->string(\Notification::getMailingSignature($parent))->isEqualTo("signature_parent");
- $this->string(\Notification::getMailingSignature($child_1))->isEqualTo("signature_parent");
- $this->string(\Notification::getMailingSignature($child_2))->isEqualTo("signature_parent");
+ $this->assertEquals("signature_parent", \Notification::getMailingSignature($parent));
+ $this->assertEquals("signature_parent", \Notification::getMailingSignature($child_1));
+ $this->assertEquals("signature_parent", \Notification::getMailingSignature($child_2));
- $this->boolean($entity->update([
+ $this->assertTrue($entity->update([
'id' => $child_1,
'mailing_signature' => "signature_child_1",
- ]))->isTrue();
+ ]));
- $this->string(\Notification::getMailingSignature($parent))->isEqualTo("signature_parent");
- $this->string(\Notification::getMailingSignature($child_1))->isEqualTo("signature_child_1");
- $this->string(\Notification::getMailingSignature($child_2))->isEqualTo("signature_parent");
+ $this->assertEquals("signature_parent", \Notification::getMailingSignature($parent));
+ $this->assertEquals("signature_child_1", \Notification::getMailingSignature($child_1));
+ $this->assertEquals("signature_parent", \Notification::getMailingSignature($child_2));
- $this->boolean($entity->update([
+ $this->assertTrue($entity->update([
'id' => $child_2,
'mailing_signature' => "signature_child_2",
- ]))->isTrue();
+ ]));
- $this->string(\Notification::getMailingSignature($parent))->isEqualTo("signature_parent");
- $this->string(\Notification::getMailingSignature($child_1))->isEqualTo("signature_child_1");
- $this->string(\Notification::getMailingSignature($child_2))->isEqualTo("signature_child_2");
+ $this->assertEquals("signature_parent", \Notification::getMailingSignature($parent));
+ $this->assertEquals("signature_child_1", \Notification::getMailingSignature($child_1));
+ $this->assertEquals("signature_child_2", \Notification::getMailingSignature($child_2));
}
/**
@@ -113,8 +113,6 @@ protected function testEntityRestrictionProvider(): iterable
{
global $DB, $CFG_GLPI;
- $this->login();
-
// Test users
list($user_root, $user_sub) = $this->createItems(User::class, [
[
@@ -152,7 +150,7 @@ protected function testEntityRestrictionProvider(): iterable
// Set up notifications
$DB->update(\Notification::getTable(), ['is_active' => 0], [1]);
$active_notification = countElementsInTable(\Notification::getTable(), ['is_active' => 1]);
- $this->integer($active_notification)->isEqualTo(0);
+ $this->assertEquals(0, $active_notification);
// Enable notification
$CFG_GLPI['notifications_mailing'] = true;
@@ -193,45 +191,46 @@ protected function testEntityRestrictionProvider(): iterable
* Test that entity restriction are applied correctly for notifications (a
* user should only receive notification on items he is allowed to see)
*
- * @dataProvider testEntityRestrictionProvider
- *
- * @param Contract $contract Test subject on which the notification will be fired
- * @param string[] $expected_queue Array of expected emails
- *
* @return void
*/
- public function testEntityRestriction(Contract $contract, array $expected_queue): void
+ public function testEntityRestriction(): void
{
global $DB;
+ $this->login();
- // Clear notification queue
- $DB->delete(QueuedNotification::getTable(), [1]);
- $queue_size = countElementsInTable(QueuedNotification::getTable());
- $this->integer($queue_size)->isEqualTo(0);
-
- // Raise fake notification
- NotificationEvent::raiseEvent('end', $contract, [
- 'entities_id' => $this->getTestRootEntity(true),
- 'items' => [
- [
- 'id' => $contract->getID(),
- 'name' => $contract->fields['name'],
- 'num' => $contract->fields['num'],
- 'comment' => $contract->fields['comment'],
- 'accounting_number' => $contract->fields['accounting_number'],
- 'contracttypes_id' => $contract->fields['contracttypes_id'],
- 'states_id' => $contract->fields['states_id'],
- 'begin_date' => $contract->fields['begin_date'],
- 'duration' => $contract->fields['duration'],
- ]
- ],
- ]);
-
- // Validate notification queue size
- $queue = (new QueuedNotification())->find();
- $emails = array_column($queue, 'recipient');
- sort($emails);
- sort($expected_queue);
- $this->array($emails)->isEqualTo($expected_queue);
+ $provider = $this->testEntityRestrictionProvider();
+ foreach ($provider as $row) {
+ list($contract, $expected_queue) = $row;
+
+ // Clear notification queue
+ $DB->delete(QueuedNotification::getTable(), [1]);
+ $queue_size = countElementsInTable(QueuedNotification::getTable());
+ $this->assertEquals(0, $queue_size);
+
+ // Raise fake notification
+ NotificationEvent::raiseEvent('end', $contract, [
+ 'entities_id' => $this->getTestRootEntity(true),
+ 'items' => [
+ [
+ 'id' => $contract->getID(),
+ 'name' => $contract->fields['name'],
+ 'num' => $contract->fields['num'],
+ 'comment' => $contract->fields['comment'],
+ 'accounting_number' => $contract->fields['accounting_number'],
+ 'contracttypes_id' => $contract->fields['contracttypes_id'],
+ 'states_id' => $contract->fields['states_id'],
+ 'begin_date' => $contract->fields['begin_date'],
+ 'duration' => $contract->fields['duration'],
+ ]
+ ],
+ ]);
+
+ // Validate notification queue size
+ $queue = (new QueuedNotification())->find();
+ $emails = array_column($queue, 'recipient');
+ sort($emails);
+ sort($expected_queue);
+ $this->assertEquals($expected_queue, $emails);
+ }
}
}
diff --git a/tests/functional/Notification_NotificationTemplate.php b/phpunit/functional/Notification_NotificationTemplateTest.php
similarity index 59%
rename from tests/functional/Notification_NotificationTemplate.php
rename to phpunit/functional/Notification_NotificationTemplateTest.php
index 38fc5b0b915..2997dd466e6 100644
--- a/tests/functional/Notification_NotificationTemplate.php
+++ b/phpunit/functional/Notification_NotificationTemplateTest.php
@@ -39,97 +39,95 @@
/* Test for inc/notification_notificationtemplate.class.php */
-class Notification_NotificationTemplate extends DbTestCase
+class Notification_NotificationTemplateTest extends DbTestCase
{
public function testGetTypeName()
{
- $this->string(\Notification_NotificationTemplate::getTypeName(0))->isIdenticalTo('Templates');
- $this->string(\Notification_NotificationTemplate::getTypeName(1))->isIdenticalTo('Template');
- $this->string(\Notification_NotificationTemplate::getTypeName(2))->isIdenticalTo('Templates');
- $this->string(\Notification_NotificationTemplate::getTypeName(10))->isIdenticalTo('Templates');
+ $this->assertSame('Templates', \Notification_NotificationTemplate::getTypeName(0));
+ $this->assertSame('Template', \Notification_NotificationTemplate::getTypeName(1));
+ $this->assertSame('Templates', \Notification_NotificationTemplate::getTypeName(2));
+ $this->assertSame('Templates', \Notification_NotificationTemplate::getTypeName(10));
}
public function testGetTabNameForItem()
{
$n_nt = new \Notification_NotificationTemplate();
- $this->boolean($n_nt->getFromDB(1))->isTrue();
+ $this->assertTrue($n_nt->getFromDB(1));
$notif = new \Notification();
- $this->boolean($notif->getFromDB($n_nt->getField('notifications_id')))->isTrue();
+ $this->assertTrue($notif->getFromDB($n_nt->getField('notifications_id')));
$_SESSION['glpishow_count_on_tabs'] = 1;
- //not logged => no ACLs
+ //not logged => no ACLs
$name = $n_nt->getTabNameForItem($notif);
- $this->string($name)->isIdenticalTo('');
+ $this->assertSame('', $name);
$this->login();
$name = $n_nt->getTabNameForItem($notif);
- $this->string($name)->isIdenticalTo('Templates 1');
+ $this->assertSame('Templates 1', $name);
$_SESSION['glpishow_count_on_tabs'] = 0;
$name = $n_nt->getTabNameForItem($notif);
- $this->string($name)->isIdenticalTo('Templates');
+ $this->assertSame('Templates', $name);
$toadd = $n_nt->fields;
unset($toadd['id']);
$toadd['mode'] = \Notification_NotificationTemplate::MODE_XMPP;
- $this->integer((int)$n_nt->add($toadd))->isGreaterThan(0);
+ $this->assertGreaterThan(0, (int)$n_nt->add($toadd));
$_SESSION['glpishow_count_on_tabs'] = 1;
$name = $n_nt->getTabNameForItem($notif);
- $this->string($name)->isIdenticalTo('Templates 2');
+ $this->assertSame('Templates 2', $name);
}
public function testShowForNotification()
{
$notif = new \Notification();
- $this->boolean($notif->getFromDB(1))->isTrue();
+ $this->assertTrue($notif->getFromDB(1));
- //not logged, no ACLs
- $this->output(
- function () use ($notif) {
- \Notification_NotificationTemplate::showForNotification($notif);
- }
- )->isEmpty();
+ //not logged, no ACLs
+ ob_start();
+ \Notification_NotificationTemplate::showForNotification($notif);
+ $output = ob_get_clean();
+ $this->assertEmpty($output);
$this->login();
- $this->output(
- function () use ($notif) {
- \Notification_NotificationTemplate::showForNotification($notif);
- }
- )->isIdenticalTo("
");
+ ob_start();
+ \Notification_NotificationTemplate::showForNotification($notif);
+ $output = ob_get_clean();
+ $this->assertSame(
+ "",
+ $output
+ );
}
public function testGetName()
{
$n_nt = new \Notification_NotificationTemplate();
- $this->boolean($n_nt->getFromDB(1))->isTrue();
- $this->integer($n_nt->getName())->isIdenticalTo(1);
+ $this->assertTrue($n_nt->getFromDB(1));
+ $this->assertSame(1, $n_nt->getName());
}
public function testShowForFormNotLogged()
{
- //not logged, no ACLs
- $this->output(
- function () {
- $n_nt = new \Notification_NotificationTemplate();
- $n_nt->showForm(1);
- }
- )->isEmpty();
+ //not logged, no ACLs
+ ob_start();
+ $n_nt = new \Notification_NotificationTemplate();
+ $n_nt->showForm(1);
+ $output = ob_get_clean();
+ $this->assertEmpty($output);
}
public function testShowForForm()
{
-
$this->login();
- $this->output(
- function () {
- $n_nt = new \Notification_NotificationTemplate();
- $n_nt->showForm(1);
- }
- )->matches('/_glpi_csrf/');
+ ob_start();
+ $n_nt = new \Notification_NotificationTemplate();
+ $n_nt->showForm(1);
+ $output = ob_get_clean();
+ $this->assertMatchesRegularExpression('/_glpi_csrf/', $output);
}
public function testGetMode()
@@ -139,10 +137,10 @@ public function testGetMode()
'label' => 'Email',
'from' => 'core'
];
- $this->array($mode)->isIdenticalTo($expected);
+ $this->assertSame($expected, $mode);
$mode = \Notification_NotificationTemplate::getMode('not_a_mode');
- $this->string($mode)->isIdenticalTo(NOT_AVAILABLE);
+ $this->assertSame(NOT_AVAILABLE, $mode);
}
public function testGetModes()
@@ -158,9 +156,9 @@ public function testGetModes()
'from' => 'core'
]
];
- $this->array($modes)->isIdenticalTo($expected);
+ $this->assertSame($expected, $modes);
- //register new mode
+ //register new mode
\Notification_NotificationTemplate::registerMode(
'test_mode',
'A test label',
@@ -171,45 +169,46 @@ public function testGetModes()
'label' => 'A test label',
'from' => 'anyplugin'
];
- $this->array($modes)->isIdenticalTo($expected);
+ $this->assertSame($expected, $modes);
}
public function testGetSpecificValueToDisplay()
{
$n_nt = new \Notification_NotificationTemplate();
$display = $n_nt->getSpecificValueToDisplay('id', 1);
- $this->string($display)->isEmpty();
+ $this->assertEmpty($display);
$display = $n_nt->getSpecificValueToDisplay('mode', \Notification_NotificationTemplate::MODE_AJAX);
- $this->string($display)->isIdenticalTo('Browser');
+ $this->assertSame('Browser', $display);
$display = $n_nt->getSpecificValueToDisplay('mode', 'not_a_mode');
- $this->string($display)->isIdenticalTo('not_a_mode (N/A)');
+ $this->assertSame('not_a_mode (N/A)', $display);
}
public function testGetSpecificValueToSelect()
{
$n_nt = new \Notification_NotificationTemplate();
$select = $n_nt->getSpecificValueToSelect('id', 1);
- $this->string($select)->isEmpty();
+ $this->assertEmpty($select);
$select = $n_nt->getSpecificValueToSelect('mode', 'a_name', \Notification_NotificationTemplate::MODE_AJAX);
- //FIXME: why @selected?
- $this->string($select)->matches(
- "/