repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Host/Domain/Model/SmallHostTest.php | centreon/tests/php/Core/Host/Domain/Model/SmallHostTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Host\Domain\Model;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Host\Domain\Model\SmallHost;
beforeEach(function (): void {
$this->parameters = [
'id' => 1,
'name' => new TrimmedString('name'),
'alias' => new TrimmedString('alias'),
'ipAddress' => new TrimmedString('127.0.0.1'),
'normalCheckInterval' => 1,
'retryCheckInterval' => 2,
'isActivated' => true,
'monitoringServer' => new SimpleEntity(1, new TrimmedString('Central'), 'host'),
'checkTimePeriod' => new SimpleEntity(1, new TrimmedString('24x7'), 'host'),
'notificationTimePeriod' => new SimpleEntity(1, new TrimmedString('24x7'), 'host'),
'severity' => new SimpleEntity(1, new TrimmedString('severity_name'), 'host'),
];
});
it('should throw an exception when the id property is not a positive number', function (): void {
$this->parameters['id'] = 0;
new SmallHost(...$this->parameters);
})->expectException(\Assert\AssertionFailedException::class);
it('should throw an exception when the name property is empty', function (): void {
$this->parameters['name'] = new TrimmedString('');
new SmallHost(...$this->parameters);
})->expectException(\Assert\AssertionFailedException::class);
it('should throw an exception when the ipAddress property is empty', function (): void {
$this->parameters['ipAddress'] = new TrimmedString('');
new SmallHost(...$this->parameters);
})->expectException(\Assert\AssertionFailedException::class);
it('should throw an exception when the normalCheckInterval property is not a positive number', function (): void {
$this->parameters['normalCheckInterval'] = -1;
new SmallHost(...$this->parameters);
})->expectException(\Assert\AssertionFailedException::class);
it('should throw an exception when the retryCheckInterval property is not a positive number greater than 1', function (): void {
$this->parameters['retryCheckInterval'] = 0;
new SmallHost(...$this->parameters);
})->expectException(\Assert\AssertionFailedException::class);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Host/Domain/Model/HostTest.php | centreon/tests/php/Core/Host/Domain/Model/HostTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Host\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Common\Domain\YesNoDefault;
use Core\Domain\Common\GeoCoords;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\SnmpVersion;
beforeEach(function (): void {
$this->createHost = static fn (array $fields = []): Host => new Host(
...[
'id' => 1,
'monitoringServerId' => 1,
'name' => 'host-name',
'address' => '127.0.0.1',
'snmpVersion' => SnmpVersion::Two,
'geoCoordinates' => GeoCoords::fromString('48.51,2.20'),
'alias' => 'host-alias',
'snmpCommunity' => 'snmpCommunity-value',
'noteUrl' => 'noteUrl-value',
'note' => 'note-value',
'actionUrl' => 'actionUrl-value',
'iconAlternative' => 'iconAlternative-value',
'comment' => 'comment-value',
'checkCommandArgs' => ['arg1', 'arg2'],
'eventHandlerCommandArgs' => ['arg3', 'arg4'],
'notificationOptions' => [HostEvent::Down, HostEvent::Unreachable],
'timezoneId' => 1,
'severityId' => 1,
'checkCommandId' => 1,
'checkTimeperiodId' => 1,
'notificationTimeperiodId' => 1,
'eventHandlerCommandId' => 1,
'iconId' => 1,
'maxCheckAttempts' => 5,
'normalCheckInterval' => 5,
'retryCheckInterval' => 5,
'notificationInterval' => 5,
'firstNotificationDelay' => 5,
'recoveryNotificationDelay' => 5,
'acknowledgementTimeout' => 5,
'freshnessThreshold' => 5,
'lowFlapThreshold' => 5,
'highFlapThreshold' => 5,
'activeCheckEnabled' => YesNoDefault::Yes,
'passiveCheckEnabled' => YesNoDefault::Yes,
'notificationEnabled' => YesNoDefault::Yes,
'freshnessChecked' => YesNoDefault::Yes,
'flapDetectionEnabled' => YesNoDefault::Yes,
'eventHandlerEnabled' => YesNoDefault::Yes,
'addInheritedContactGroup' => true,
'addInheritedContact' => true,
'isActivated' => false,
...$fields,
]
);
});
it('should return properly set host instance (all properties)', function (): void {
$host = ($this->createHost)();
expect($host->getId())->toBe(1)
->and($host->getMonitoringServerId())->toBe(1)
->and($host->getName())->toBe('host-name')
->and($host->getAddress())->toBe('127.0.0.1')
->and($host->getAlias())->toBe('host-alias')
->and($host->getSnmpVersion())->toBe(SnmpVersion::Two)
->and($host->getSnmpCommunity())->toBe('snmpCommunity-value')
->and($host->getNoteUrl())->toBe('noteUrl-value')
->and($host->getNote())->toBe('note-value')
->and($host->getActionUrl())->toBe('actionUrl-value')
->and($host->getIconAlternative())->toBe('iconAlternative-value')
->and($host->getComment())->toBe('comment-value')
->and($host->getGeoCoordinates()?->__toString())->toBe('48.51,2.20')
->and($host->getCheckCommandArgs())->toBe(['arg1', 'arg2'])
->and($host->getEventHandlerCommandArgs())->toBe(['arg3', 'arg4'])
->and($host->getNotificationOptions())->toBe([HostEvent::Down, HostEvent::Unreachable])
->and($host->getTimezoneId())->toBe(1)
->and($host->getSeverityId())->toBe(1)
->and($host->getCheckCommandId())->toBe(1)
->and($host->getCheckTimeperiodId())->toBe(1)
->and($host->getNotificationTimeperiodId())->toBe(1)
->and($host->getEventHandlerCommandId())->toBe(1)
->and($host->getIconId())->toBe(1)
->and($host->getMaxCheckAttempts())->toBe(5)
->and($host->getNormalCheckInterval())->toBe(5)
->and($host->getRetryCheckInterval())->toBe(5)
->and($host->getNotificationInterval())->toBe(5)
->and($host->getFirstNotificationDelay())->toBe(5)
->and($host->getRecoveryNotificationDelay())->toBe(5)
->and($host->getAcknowledgementTimeout())->toBe(5)
->and($host->getFreshnessThreshold())->toBe(5)
->and($host->getLowFlapThreshold())->toBe(5)
->and($host->getHighFlapThreshold())->toBe(5)
->and($host->getActiveCheckEnabled())->toBe(YesNoDefault::Yes)
->and($host->getPassiveCheckEnabled())->toBe(YesNoDefault::Yes)
->and($host->getNotificationEnabled())->toBe(YesNoDefault::Yes)
->and($host->getFreshnessChecked())->toBe(YesNoDefault::Yes)
->and($host->getFlapDetectionEnabled())->toBe(YesNoDefault::Yes)
->and($host->getEventHandlerEnabled())->toBe(YesNoDefault::Yes)
->and($host->addInheritedContactGroup())->toBe(true)
->and($host->addInheritedContact())->toBe(true)
->and($host->isActivated())->toBe(false);
});
it('should return properly set host instance (mandatory properties only)', function (): void {
$host = new Host(
id: 1,
monitoringServerId: 1,
name: 'host-name',
address: '127.0.0.1'
);
expect($host->getId())->toBe(1)
->and($host->getMonitoringServerId())->toBe(1)
->and($host->getName())->toBe('host-name')
->and($host->getAddress())->toBe('127.0.0.1')
->and($host->getGeoCoordinates())->toBe(null)
->and($host->getSnmpVersion())->toBe(null)
->and($host->getSnmpCommunity())->toBe('')
->and($host->getAlias())->toBe('')
->and($host->getNoteUrl())->toBe('')
->and($host->getNote())->toBe('')
->and($host->getActionUrl())->toBe('')
->and($host->getIconAlternative())->toBe('')
->and($host->getComment())->toBe('')
->and($host->getCheckCommandArgs())->toBe([])
->and($host->getEventHandlerCommandArgs())->toBe([])
->and($host->getNotificationOptions())->toBe([])
->and($host->getTimezoneId())->toBe(null)
->and($host->getSeverityId())->toBe(null)
->and($host->getCheckCommandId())->toBe(null)
->and($host->getCheckTimeperiodId())->toBe(null)
->and($host->getNotificationTimeperiodId())->toBe(null)
->and($host->getEventHandlerCommandId())->toBe(null)
->and($host->getIconId())->toBe(null)
->and($host->getMaxCheckAttempts())->toBe(null)
->and($host->getNormalCheckInterval())->toBe(null)
->and($host->getRetryCheckInterval())->toBe(null)
->and($host->getNotificationInterval())->toBe(null)
->and($host->getFirstNotificationDelay())->toBe(null)
->and($host->getRecoveryNotificationDelay())->toBe(null)
->and($host->getAcknowledgementTimeout())->toBe(null)
->and($host->getFreshnessThreshold())->toBe(null)
->and($host->getLowFlapThreshold())->toBe(null)
->and($host->getHighFlapThreshold())->toBe(null)
->and($host->getActiveCheckEnabled())->toBe(YesNoDefault::Default)
->and($host->getPassiveCheckEnabled())->toBe(YesNoDefault::Default)
->and($host->getNotificationEnabled())->toBe(YesNoDefault::Default)
->and($host->getFreshnessChecked())->toBe(YesNoDefault::Default)
->and($host->getFlapDetectionEnabled())->toBe(YesNoDefault::Default)
->and($host->getEventHandlerEnabled())->toBe(YesNoDefault::Default)
->and($host->addInheritedContactGroup())->toBe(false)
->and($host->addInheritedContact())->toBe(false)
->and($host->isActivated())->toBe(true);
});
// mandatory fields
it(
'should throw an exception when host name is an empty string',
fn () => ($this->createHost)(['name' => ' '])
)->throws(
InvalidArgumentException::class,
AssertionException::notEmptyString('Host::name')->getMessage()
);
it(
'should throw an exception when host name is set to an empty string',
function (): void {
$host = ($this->createHost)();
$host->setName(' ');
}
)->throws(
InvalidArgumentException::class,
AssertionException::notEmptyString('Host::name')->getMessage()
);
it(
'should throw an exception when host address does not respect format',
fn () => ($this->createHost)(['address' => 'hello world'])
)->throws(
InvalidArgumentException::class,
AssertionException::ipOrDomain('hello world', 'Host::address')->getMessage()
);
it(
'should throw an exception when host address does not respect format in setter',
function (): void {
$host = ($this->createHost)();
$host->setAddress('hello world');
}
)->throws(
InvalidArgumentException::class,
AssertionException::ipOrDomain('hello world', 'Host::address')->getMessage()
);
// name and conmmands args should be formated
it('should return trimmed and formatted field name after construct', function (): void {
$host = ($this->createHost)(['name' => ' host name ']);
expect($host->getName())->toBe('host_name');
});
it('should trim and format field name when set', function (): void {
$host = ($this->createHost)();
$host->setName(' some new name ');
expect($host->getName())->toBe('some_new_name');
});
foreach (
[
'checkCommandArgs',
'eventHandlerCommandArgs',
] as $field
) {
it(
"should return a trimmed field {$field}",
function () use ($field): void {
$host = ($this->createHost)([$field => [' arg1 ', ' arg2 ']]);
$valueFromGetter = $host->{'get' . $field}();
expect($valueFromGetter)->toBe(['arg1', 'arg2']);
}
);
}
foreach (
[
'checkCommandArgs',
'eventHandlerCommandArgs',
] as $field
) {
it(
"should set a trimmed field {$field}",
function () use ($field): void {
$host = ($this->createHost)();
$host->{'set' . $field}([' arg1 ', ' arg2 ']);
expect($host->{'get' . $field}())->toBe(['arg1', 'arg2']);
}
);
}
// string field trimmed
foreach (
[
'alias',
'snmpCommunity',
'noteUrl',
'note',
'actionUrl',
'iconAlternative',
'comment',
] as $field
) {
it(
"should return trimmed field {$field} after construct",
function () use ($field): void {
$host = ($this->createHost)([$field => ' abcd ']);
$valueFromGetter = $host->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
foreach (
[
'alias',
'snmpCommunity',
'noteUrl',
'note',
'actionUrl',
'iconAlternative',
'comment',
] as $field
) {
it(
"should set a trimmed field {$field}",
function () use ($field): void {
$host = ($this->createHost)();
$host->{'set' . $field}(' abcd ');
expect($host->{'get' . $field}())->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => Host::MAX_NAME_LENGTH,
'alias' => Host::MAX_ALIAS_LENGTH,
'snmpCommunity' => Host::MAX_SNMP_COMMUNITY_LENGTH,
'noteUrl' => Host::MAX_NOTE_URL_LENGTH,
'note' => Host::MAX_NOTE_LENGTH,
'actionUrl' => Host::MAX_ACTION_URL_LENGTH,
'iconAlternative' => Host::MAX_ICON_ALT_LENGTH,
'comment' => Host::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when host {$field} is too long",
fn () => ($this->createHost)([$field => $tooLong])
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "Host::{$field}")->getMessage()
);
}
foreach (
[
'name' => Host::MAX_NAME_LENGTH,
'alias' => Host::MAX_ALIAS_LENGTH,
'snmpCommunity' => Host::MAX_SNMP_COMMUNITY_LENGTH,
'noteUrl' => Host::MAX_NOTE_URL_LENGTH,
'note' => Host::MAX_NOTE_LENGTH,
'actionUrl' => Host::MAX_ACTION_URL_LENGTH,
'iconAlternative' => Host::MAX_ICON_ALT_LENGTH,
'comment' => Host::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLongStr = str_repeat('a', $length + 1);
it(
"should throw an exception when host {$field} is set too long",
function () use ($field, $tooLongStr): void {
$host = ($this->createHost)();
$host->{'set' . $field}($tooLongStr);
}
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLongStr, $length + 1, $length, "Host::{$field}")->getMessage()
);
}
// foreign keys fields
foreach (
[
'monitoringServerId',
'timezoneId',
'severityId',
'checkCommandId',
'checkTimeperiodId',
'notificationTimeperiodId',
'eventHandlerCommandId',
'iconId',
] as $field
) {
it(
"should throw an exception when host {$field} is not > 0",
fn () => ($this->createHost)([$field => 0])
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(0, "Host::{$field}")->getMessage()
);
}
foreach (
[
'monitoringServerId',
'timezoneId',
'severityId',
'checkCommandId',
'checkTimeperiodId',
'notificationTimeperiodId',
'eventHandlerCommandId',
'iconId',
] as $field
) {
it(
"should throw an exception when host {$field} set value is not > 0",
function () use ($field): void {
$host = ($this->createHost)();
$host->{'set' . $field}(0);
}
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(0, "Host::{$field}")->getMessage()
);
}
// integer >= 0 field
foreach (
[
'maxCheckAttempts',
'normalCheckInterval',
'retryCheckInterval',
'notificationInterval',
'firstNotificationDelay',
'recoveryNotificationDelay',
'acknowledgementTimeout',
'freshnessThreshold',
'lowFlapThreshold',
'highFlapThreshold',
] as $field
) {
it(
"should throw an exception when host {$field} is not >= 0",
fn () => ($this->createHost)([$field => -1])
)->throws(
InvalidArgumentException::class,
AssertionException::min(-1, 0, "Host::{$field}")->getMessage()
);
}
foreach (
[
'maxCheckAttempts',
'normalCheckInterval',
'retryCheckInterval',
'notificationInterval',
'firstNotificationDelay',
'recoveryNotificationDelay',
'acknowledgementTimeout',
'freshnessThreshold',
'lowFlapThreshold',
'highFlapThreshold',
] as $field
) {
it(
"should throw an exception when host {$field} set value is not >= 0",
function () use ($field): void {
$host = ($this->createHost)();
$host->{'set' . $field}(-1);
}
)->throws(
InvalidArgumentException::class,
AssertionException::min(-1, 0, "Host::{$field}")->getMessage()
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Host/Domain/Model/NewHostTest.php | centreon/tests/php/Core/Host/Domain/Model/NewHostTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Host\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Common\Domain\YesNoDefault;
use Core\Domain\Common\GeoCoords;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\NewHost;
use Core\Host\Domain\Model\SnmpVersion;
beforeEach(function (): void {
$this->createHost = static fn (array $fields = []): NewHost => new NewHost(
...[
'monitoringServerId' => 1,
'name' => 'host-name',
'address' => '127.0.0.1',
'alias' => 'host-alias',
'snmpVersion' => SnmpVersion::Two,
'snmpCommunity' => 'snmpCommunity-value',
'noteUrl' => 'noteUrl-value',
'note' => 'note-value',
'actionUrl' => 'actionUrl-value',
'iconAlternative' => 'iconAlternative-value',
'comment' => 'comment-value',
'geoCoordinates' => GeoCoords::fromString('48.51,2.20'),
'checkCommandArgs' => ['arg1', 'arg2'],
'eventHandlerCommandArgs' => ['arg3', 'arg4'],
'notificationOptions' => [HostEvent::Down, HostEvent::Unreachable],
'timezoneId' => 1,
'severityId' => 1,
'checkCommandId' => 1,
'checkTimeperiodId' => 1,
'notificationTimeperiodId' => 1,
'eventHandlerCommandId' => 1,
'iconId' => 1,
'maxCheckAttempts' => 5,
'normalCheckInterval' => 5,
'retryCheckInterval' => 5,
'notificationInterval' => 5,
'firstNotificationDelay' => 5,
'recoveryNotificationDelay' => 5,
'acknowledgementTimeout' => 5,
'freshnessThreshold' => 5,
'lowFlapThreshold' => 5,
'highFlapThreshold' => 5,
'activeCheckEnabled' => YesNoDefault::Yes,
'passiveCheckEnabled' => YesNoDefault::Yes,
'notificationEnabled' => YesNoDefault::Yes,
'freshnessChecked' => YesNoDefault::Yes,
'flapDetectionEnabled' => YesNoDefault::Yes,
'eventHandlerEnabled' => YesNoDefault::Yes,
'addInheritedContactGroup' => true,
'addInheritedContact' => true,
'isActivated' => false,
...$fields,
]
);
});
it('should return properly set host instance (all properties)', function (): void {
$host = ($this->createHost)();
expect($host->getMonitoringServerId())->toBe(1)
->and($host->getName())->toBe('host-name')
->and($host->getAddress())->toBe('127.0.0.1')
->and($host->getAlias())->toBe('host-alias')
->and($host->getSnmpVersion())->toBe(SnmpVersion::Two)
->and($host->getSnmpCommunity())->toBe('snmpCommunity-value')
->and($host->getNoteUrl())->toBe('noteUrl-value')
->and($host->getNote())->toBe('note-value')
->and($host->getActionUrl())->toBe('actionUrl-value')
->and($host->getIconAlternative())->toBe('iconAlternative-value')
->and($host->getComment())->toBe('comment-value')
->and($host->getGeoCoordinates()?->__toString())->toBe('48.51,2.20')
->and($host->getCheckCommandArgs())->toBe(['arg1', 'arg2'])
->and($host->getEventHandlerCommandArgs())->toBe(['arg3', 'arg4'])
->and($host->getNotificationOptions())->toBe([HostEvent::Down, HostEvent::Unreachable])
->and($host->getTimezoneId())->toBe(1)
->and($host->getSeverityId())->toBe(1)
->and($host->getCheckCommandId())->toBe(1)
->and($host->getCheckTimeperiodId())->toBe(1)
->and($host->getNotificationTimeperiodId())->toBe(1)
->and($host->getEventHandlerCommandId())->toBe(1)
->and($host->getIconId())->toBe(1)
->and($host->getMaxCheckAttempts())->toBe(5)
->and($host->getNormalCheckInterval())->toBe(5)
->and($host->getRetryCheckInterval())->toBe(5)
->and($host->getNotificationInterval())->toBe(5)
->and($host->getFirstNotificationDelay())->toBe(5)
->and($host->getRecoveryNotificationDelay())->toBe(5)
->and($host->getAcknowledgementTimeout())->toBe(5)
->and($host->getFreshnessThreshold())->toBe(5)
->and($host->getLowFlapThreshold())->toBe(5)
->and($host->getHighFlapThreshold())->toBe(5)
->and($host->getActiveCheckEnabled())->toBe(YesNoDefault::Yes)
->and($host->getPassiveCheckEnabled())->toBe(YesNoDefault::Yes)
->and($host->getNotificationEnabled())->toBe(YesNoDefault::Yes)
->and($host->getFreshnessChecked())->toBe(YesNoDefault::Yes)
->and($host->getFlapDetectionEnabled())->toBe(YesNoDefault::Yes)
->and($host->getEventHandlerEnabled())->toBe(YesNoDefault::Yes)
->and($host->addInheritedContactGroup())->toBe(true)
->and($host->addInheritedContact())->toBe(true)
->and($host->isActivated())->toBe(false);
});
it('should return properly set host instance (mandatory properties only)', function (): void {
$host = new NewHost(
monitoringServerId: 1,
name: 'host-name',
address: '127.0.0.1'
);
expect($host->getMonitoringServerId())->toBe(1)
->and($host->getName())->toBe('host-name')
->and($host->getAddress())->toBe('127.0.0.1')
->and($host->getGeoCoordinates())->toBe(null)
->and($host->getSnmpVersion())->toBe(null)
->and($host->getSnmpCommunity())->toBe('')
->and($host->getAlias())->toBe('')
->and($host->getNoteUrl())->toBe('')
->and($host->getNote())->toBe('')
->and($host->getActionUrl())->toBe('')
->and($host->getIconAlternative())->toBe('')
->and($host->getComment())->toBe('')
->and($host->getCheckCommandArgs())->toBe([])
->and($host->getEventHandlerCommandArgs())->toBe([])
->and($host->getNotificationOptions())->toBe([])
->and($host->getTimezoneId())->toBe(null)
->and($host->getSeverityId())->toBe(null)
->and($host->getCheckCommandId())->toBe(null)
->and($host->getCheckTimeperiodId())->toBe(null)
->and($host->getNotificationTimeperiodId())->toBe(null)
->and($host->getEventHandlerCommandId())->toBe(null)
->and($host->getIconId())->toBe(null)
->and($host->getMaxCheckAttempts())->toBe(null)
->and($host->getNormalCheckInterval())->toBe(null)
->and($host->getRetryCheckInterval())->toBe(null)
->and($host->getNotificationInterval())->toBe(null)
->and($host->getFirstNotificationDelay())->toBe(null)
->and($host->getRecoveryNotificationDelay())->toBe(null)
->and($host->getAcknowledgementTimeout())->toBe(null)
->and($host->getFreshnessThreshold())->toBe(null)
->and($host->getLowFlapThreshold())->toBe(null)
->and($host->getHighFlapThreshold())->toBe(null)
->and($host->getActiveCheckEnabled())->toBe(YesNoDefault::Default)
->and($host->getPassiveCheckEnabled())->toBe(YesNoDefault::Default)
->and($host->getNotificationEnabled())->toBe(YesNoDefault::Default)
->and($host->getFreshnessChecked())->toBe(YesNoDefault::Default)
->and($host->getFlapDetectionEnabled())->toBe(YesNoDefault::Default)
->and($host->getEventHandlerEnabled())->toBe(YesNoDefault::Default)
->and($host->addInheritedContactGroup())->toBe(false)
->and($host->addInheritedContact())->toBe(false)
->and($host->isActivated())->toBe(true);
});
// mandatory fields
it(
'should throw an exception when host name is an empty string',
fn () => ($this->createHost)(['name' => ' '])
)->throws(
InvalidArgumentException::class,
AssertionException::notEmptyString('NewHost::name')->getMessage()
);
it(
'should throw an exception when host address does not respect format',
fn () => ($this->createHost)(['address' => 'hello world'])
)->throws(
InvalidArgumentException::class,
AssertionException::ipOrDomain('hello world', 'NewHost::address')->getMessage()
);
// name and conmmands args should be formated
it('should return trimmed and formatted name field after construct', function (): void {
$host = ($this->createHost)(['name' => ' host name ']);
expect($host->getName())->toBe('host_name');
});
foreach (
[
'checkCommandArgs',
'eventHandlerCommandArgs',
] as $field
) {
it(
"should return a trimmed field {$field}",
function () use ($field): void {
$host = ($this->createHost)([$field => [' arg1 ', ' arg2 ']]);
$valueFromGetter = $host->{'get' . $field}();
expect($valueFromGetter)->toBe(['arg1', 'arg2']);
}
);
}
foreach (
[
'name',
'alias',
'snmpCommunity',
'noteUrl',
'note',
'actionUrl',
'iconAlternative',
'comment',
] as $field
) {
it(
"should return trimmed field {$field} after construct",
function () use ($field): void {
$host = ($this->createHost)([$field => ' abc ']);
$valueFromGetter = $host->{'get' . $field}();
expect($valueFromGetter)->toBe('abc');
}
);
}
// too long fields
foreach (
[
'name' => NewHost::MAX_NAME_LENGTH,
'address' => NewHost::MAX_ADDRESS_LENGTH,
'alias' => NewHost::MAX_ALIAS_LENGTH,
'snmpCommunity' => NewHost::MAX_SNMP_COMMUNITY_LENGTH,
'noteUrl' => NewHost::MAX_NOTE_URL_LENGTH,
'note' => NewHost::MAX_NOTE_LENGTH,
'actionUrl' => NewHost::MAX_ACTION_URL_LENGTH,
'iconAlternative' => NewHost::MAX_ICON_ALT_LENGTH,
'comment' => NewHost::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when host {$field} is too long",
fn () => ($this->createHost)([$field => $tooLong])
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "NewHost::{$field}")->getMessage()
);
}
// foreign keys fields
foreach (
[
'monitoringServerId',
'timezoneId',
'severityId',
'checkCommandId',
'checkTimeperiodId',
'notificationTimeperiodId',
'eventHandlerCommandId',
'iconId',
] as $field
) {
it(
"should throw an exception when host {$field} is not > 0",
fn () => ($this->createHost)([$field => 0])
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(0, "NewHost::{$field}")->getMessage()
);
}
// integer >= 0 field
foreach (
[
'maxCheckAttempts',
'normalCheckInterval',
'retryCheckInterval',
'notificationInterval',
'firstNotificationDelay',
'recoveryNotificationDelay',
'acknowledgementTimeout',
'freshnessThreshold',
'lowFlapThreshold',
'highFlapThreshold',
] as $field
) {
it(
"should throw an exception when host {$field} is not >= 0",
fn () => ($this->createHost)([$field => -1])
)->throws(
InvalidArgumentException::class,
AssertionException::min(-1, 0, "NewHost::{$field}")->getMessage()
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Host/Infrastructure/API/AddHost/AddHostPresenterStub.php | centreon/tests/php/Core/Host/Infrastructure/API/AddHost/AddHostPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Host\Infrastructure\API\AddHost;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Host\Application\UseCase\AddHost\AddHostPresenterInterface;
use Core\Host\Application\UseCase\AddHost\AddHostResponse;
class AddHostPresenterStub extends AbstractPresenter implements AddHostPresenterInterface
{
public ResponseStatusInterface|AddHostResponse $response;
public function presentResponse(ResponseStatusInterface|AddHostResponse $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Host/Infrastructure/API/DeleteHost/DeleteHostPresenterStub.php | centreon/tests/php/Core/Host/Infrastructure/API/DeleteHost/DeleteHostPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Host\Infrastructure\API\DeleteHost;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
class DeleteHostPresenterStub extends AbstractPresenter
{
public ?ResponseStatusInterface $response = null;
public function setResponseStatus(?ResponseStatusInterface $responseStatus): void
{
$this->response = $responseStatus;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Host/Infrastructure/API/FindHosts/FindHostsPresenterStub.php | centreon/tests/php/Core/Host/Infrastructure/API/FindHosts/FindHostsPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Host\Infrastructure\API\FindHosts;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Host\Application\UseCase\FindHosts\FindHostsPresenterInterface;
use Core\Host\Application\UseCase\FindHosts\FindHostsResponse;
class FindHostsPresenterStub extends AbstractPresenter implements FindHostsPresenterInterface
{
public FindHostsResponse|ResponseStatusInterface $response;
public function presentResponse(FindHostsResponse|ResponseStatusInterface $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Host/Infrastructure/API/PartialUpdateHost/PartialUpdateHostPresenterStub.php | centreon/tests/php/Core/Host/Infrastructure/API/PartialUpdateHost/PartialUpdateHostPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Host\Infrastructure\API\PartialUpdateHost;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
class PartialUpdateHostPresenterStub extends AbstractPresenter
{
public ?ResponseStatusInterface $response = null;
public function setResponseStatus(?ResponseStatusInterface $responseStatus): void
{
$this->response = $responseStatus;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/FindNotification/FindNotificationTest.php | centreon/tests/php/Core/Notification/Application/UseCase/FindNotification/FindNotificationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\FindNotification;
use Centreon\Domain\Contact\Contact;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\Converter\NotificationHostEventConverter;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\FindNotification\FindNotification;
use Core\Notification\Application\UseCase\FindNotification\FindNotificationResponse;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\ConfigurationResource;
use Core\Notification\Domain\Model\Contact as NotificationContact;
use Core\Notification\Domain\Model\HostEvent;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Notification\Domain\Model\TimePeriod;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Tests\Core\Notification\Infrastructure\API\FindNotification\FindNotificationPresenterStub;
beforeEach(function (): void {
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new FindNotificationPresenterStub($this->presenterFormatter);
$this->notificationRepository = $this->createMock(ReadNotificationRepositoryInterface::class);
$this->repositoryProvider = $this->createMock(NotificationResourceRepositoryProviderInterface::class);
$this->resourceRepository = $this->createMock(NotificationResourceRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->adminResolver = $this->createMock(AdminResolver::class);
});
it('should present an error response when the user is not admin and doesn\'t have sufficient ACLs', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1);
(new FindNotification(
$this->notificationRepository,
$contact,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->adminResolver,
))(1, $this->presenter);
expect($this->presenter->responseStatus)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->responseStatus?->getMessage())
->toBe(NotificationException::listOneNotAllowed()->getMessage());
});
it('should present a not found response when the notification does not exist', function (): void {
$contact = (new Contact())->setAdmin(true)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$this->notificationRepository
->expects($this->once())
->method('findById')
->willReturn(null);
(new FindNotification(
$this->notificationRepository,
$contact,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->adminResolver,
))(1, $this->presenter);
expect($this->presenter->responseStatus)
->toBeInstanceOf(NotFoundResponse::class);
});
it('should present an error response when something unhandled occurs', function (): void {
$contact = (new Contact())->setAdmin(true)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$this->notificationRepository
->expects($this->once())
->method('findById')
->willThrowException(new \Exception());
(new FindNotification(
$this->notificationRepository,
$contact,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->adminResolver,
))(1, $this->presenter);
expect($this->presenter->responseStatus)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->responseStatus?->getMessage())
->toBe(NotificationException::errorWhileRetrievingObject()->getMessage());
});
it('should get the resources with ACL calculation when the user is not admin', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$notification = new Notification(1, 'notification', new TimePeriod(1, '24x7'), false);
$notificationMessage = new Message(
Channel::from('Slack'),
'Message subject',
'Message content',
'<p>Message content</p>'
);
$notificationUser = new NotificationContact(
3,
'test-user',
'email-user',
'test-alias',
);
$this->notificationRepository
->expects($this->once())
->method('findById')
->willReturn($notification);
$this->notificationRepository
->expects($this->once())
->method('findMessagesByNotificationId')
->willReturn([$notificationMessage]);
$this->readAccessGroupRepository
->expects($this->atLeastOnce())
->method('findByContact');
$this->notificationRepository
->expects($this->once())
->method('findUsersByNotificationIdUserAndAccessGroups')
->willReturn([$notificationUser]);
$this->notificationRepository
->expects($this->once())
->method('findContactGroupsByNotificationIdAndAccessGroups')
->willReturn([]);
$this->repositoryProvider
->expects($this->once())
->method('getRepositories')
->willReturn(
[$this->resourceRepository]
);
$this->resourceRepository
->expects($this->once())
->method('findByNotificationIdAndAccessGroups');
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->with($contact)
->willReturn(false);
(new FindNotification(
$this->notificationRepository,
$contact,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->adminResolver,
))(1, $this->presenter);
});
it('should present a FindNotificationResponse when everything is OK', function (): void {
$contact = (new Contact())->setAdmin(true)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$contactGroups = [
new ContactGroup(1, 'contactgroup_1', 'contactgroup_1'),
new ContactGroup(2, 'contactgroup_2', 'contactgroup_2'),
];
$notification = new Notification(1, 'notification', new TimePeriod(1, '24x7'), false);
$notificationMessage = new Message(
Channel::from('Slack'),
'Message subject',
'Message content',
'<p>Message content</p>'
);
$notificationUser = new NotificationContact(
3,
'test-user',
'email-user',
'test-alias'
);
$notificationResource = new NotificationResource(
NotificationResource::TYPE_HOST_GROUP,
HostEvent::class,
[new ConfigurationResource(1, 'hostgroup-resource')],
NotificationHostEventConverter::fromBitFlags(4)
);
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->with($contact)
->willReturn(true);
$this->notificationRepository
->expects($this->once())
->method('findById')
->willReturn($notification);
$this->notificationRepository
->expects($this->once())
->method('findMessagesByNotificationId')
->willReturn([$notificationMessage]);
$this->notificationRepository
->expects($this->once())
->method('findUsersByNotificationId')
->willReturn([$notificationUser]);
$this->notificationRepository
->expects($this->once())
->method('findContactGroupsByNotificationId')
->willReturn($contactGroups);
$this->repositoryProvider
->expects($this->once())
->method('getRepositories')
->willReturn(
[$this->resourceRepository]
);
$this->resourceRepository
->expects($this->once())
->method('findByNotificationId')
->willReturn($notificationResource);
(new FindNotification(
$this->notificationRepository,
$contact,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->adminResolver,
))(1, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindNotificationResponse::class)
->and($this->presenter->response->id)->toBe(1)
->and($this->presenter->response->name)->toBe('notification')
->and($this->presenter->response->timeperiodId)->toBe(1)
->and($this->presenter->response->timeperiodName)->toBe('24x7')
->and($this->presenter->response->isActivated)->toBe(false)
->and($this->presenter->response->messages)->toBeArray()
->and($this->presenter->response->messages[0]['channel'])->toBe('Slack')
->and($this->presenter->response->messages[0]['subject'])->toBe('Message subject')
->and($this->presenter->response->messages[0]['message'])->toBe('Message content')
->and($this->presenter->response->users)->toBeArray()
->and($this->presenter->response->users[0]['id'])->toBe(3)
->and($this->presenter->response->users[0]['alias'])->toBe('test-alias')
->and($this->presenter->response->contactGroups[0]['id'])->toBe(1)
->and($this->presenter->response->contactGroups[0]['name'])->toBe('contactgroup_1')
->and($this->presenter->response->contactGroups[1]['id'])->toBe(2)
->and($this->presenter->response->contactGroups[1]['name'])->toBe('contactgroup_2')
->and($this->presenter->response->resources)->toBeArray()
->and($this->presenter->response->resources[0]['type'])->toBe(NotificationResource::TYPE_HOST_GROUP)
->and($this->presenter->response->resources[0]['events'])->toBe([HostEvent::Unreachable])
->and($this->presenter->response->resources[0]['ids'][0]['id'])->toBe(1)
->and($this->presenter->response->resources[0]['ids'][0]['name'])->toBe('hostgroup-resource');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/DeleteNotification/DeleteNotificationPresenterStub.php | centreon/tests/php/Core/Notification/Application/UseCase/DeleteNotification/DeleteNotificationPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\DeleteNotification;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Notification\Application\UseCase\DeleteNotification\DeleteNotificationPresenterInterface;
class DeleteNotificationPresenterStub implements DeleteNotificationPresenterInterface
{
/** @var ResponseStatusInterface|NoContentResponse */
public ResponseStatusInterface|NoContentResponse $data;
/**
* @param NoContentResponse|ResponseStatusInterface $data
*/
public function presentResponse(NoContentResponse|ResponseStatusInterface $data): void
{
$this->data = $data;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/DeleteNotification/DeleteNotificationTest.php | centreon/tests/php/Core/Notification/Application/UseCase/DeleteNotification/DeleteNotificationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\DeleteNotification;
use Centreon\Domain\Contact\Contact;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\DeleteNotification\DeleteNotification;
beforeEach(function (): void {
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DeleteNotificationPresenterStub();
$this->writeRepository = $this->createMock(WriteNotificationRepositoryInterface::class);
});
it('should present a ForbiddenResponse when the user doesn\'t have access to endpoint', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1);
(new DeleteNotification($contact, $this->writeRepository))(1, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(NotificationException::deleteNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the notification to delete is not found', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$this->writeRepository
->expects($this->once())
->method('deleteNotification')
->willReturn(0);
(new DeleteNotification($contact, $this->writeRepository))(1, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->data->getMessage())
->toBe('Notification not found');
});
it('should present an ErrorResponse when an unhandled error occurs', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$this->writeRepository
->expects($this->once())
->method('deleteNotification')
->willThrowException(new \Exception());
(new DeleteNotification($contact, $this->writeRepository))(1, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(NotificationException::errorWhileDeletingObject()->getMessage());
});
it('should present a NoContentResponse when a notification is deleted', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$this->writeRepository
->expects($this->once())
->method('deleteNotification')
->willReturn(1);
(new DeleteNotification($contact, $this->writeRepository))(1, $this->presenter);
expect($this->presenter->data)->toBeInstanceOf(NoContentResponse::class);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRuleTest.php | centreon/tests/php/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRuleTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\FindNotifiableRule;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\FindNotifiableRule\FindNotifiableRule;
use Core\Notification\Application\UseCase\FindNotifiableRule\FindNotifiableRuleResponse;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\Contact as NotificationContact;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\TimePeriod;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->presenter = new FindNotifiableRulePresenterStub();
$this->useCase = new FindNotifiableRule(
$this->notificationRepository = $this->createMock(ReadNotificationRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->contact = $this->createMock(ContactInterface::class),
$this->adminResolver = $this->createMock(AdminResolver::class),
);
});
it(
'should present an error response when the user is not admin and doesn\'t have sufficient ACLs',
function (): void {
$this->contact->expects($this->atLeastOnce())
->method('getId')->willReturn(1);
$this->contact->expects($this->atLeastOnce())
->method('hasTopologyRole')
->willReturnMap(
[[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE, false]]
);
($this->useCase)(1, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data?->getMessage())
->toBe(NotificationException::listOneNotAllowed()->getMessage());
}
);
it(
'should present a not found response when the notification does not exist',
function (): void {
$this->contact->expects($this->atLeastOnce())
->method('hasTopologyRole')
->willReturnMap(
[[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE, true]]
);
$this->notificationRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)(1, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should present an error response when something unhandled occurs',
function (): void {
$this->contact->expects($this->atLeastOnce())
->method('hasTopologyRole')
->willReturnMap(
[[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE, true]]
);
$this->notificationRepository
->expects($this->once())
->method('findById')
->willThrowException(new \Exception());
($this->useCase)(1, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data?->getMessage())
->toBe(NotificationException::errorWhileRetrievingObject()->getMessage());
}
);
it(
'should get the rule with ACL calculation when the user is not admin',
function (): void {
$this->contact->expects($this->atLeastOnce())
->method('hasTopologyRole')
->willReturnMap(
[[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE, true]]
);
$notification = new Notification(
1,
'notification',
new TimePeriod(1, '24x7'),
false
);
$notificationMessage = new Message(
Channel::from('Slack'),
'Message subject',
'Message content',
'<p>Message content</p>'
);
$notificationUser = new NotificationContact(
3,
'test-user',
'test-email',
'test-alias'
);
$this->notificationRepository
->expects($this->once())
->method('findById')
->willReturn($notification);
$this->notificationRepository
->expects($this->once())
->method('findMessagesByNotificationId')
->willReturn([$notificationMessage]);
$this->adminResolver
->expects($this->atLeastOnce())
->method('isAdmin')
->with($this->contact)
->willReturn(false);
$this->notificationRepository
->expects($this->once())
->method('findUsersByNotificationIdUserAndAccessGroups')
->willReturn([$notificationUser]);
$this->notificationRepository
->expects($this->once())
->method('findContactGroupsByNotificationIdAndAccessGroups')
->willReturn([]);
($this->useCase)(1, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(FindNotifiableRuleResponse::class);
}
);
it(
'should present a FindNotifiableRuleResponse when everything is OK',
function (): void {
$this->adminResolver
->expects($this->atLeastOnce())
->method('isAdmin')
->with($this->contact)
->willReturn(true);
$this->contact->expects($this->atLeastOnce())
->method('hasTopologyRole')
->willReturnMap(
[[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE, true]]
);
$contactGroups = [
new ContactGroup(1, 'contactgroup_1', 'contactgroup_1'),
new ContactGroup(2, 'contactgroup_2', 'contactgroup_2'),
];
$notification = new Notification(1, 'notification', new TimePeriod(1, '24x7'), false);
$notificationMessage = new Message(
Channel::from('Email'),
'Message subject',
'Message content',
'<p>Message content</p>'
);
$notificationUser = new NotificationContact(
3,
'test-user',
'test-email',
'test-alias'
);
$this->notificationRepository
->expects($this->once())
->method('findById')
->willReturn($notification);
$this->notificationRepository
->expects($this->once())
->method('findMessagesByNotificationId')
->willReturn([$notificationMessage]);
$this->notificationRepository
->expects($this->once())
->method('findUsersByNotificationId')
->willReturn([$notificationUser]);
$this->notificationRepository
->expects($this->once())
->method('findContactGroupsByNotificationId')
->willReturn($contactGroups);
($this->useCase)(1, $this->presenter);
expect($this->presenter->data)->toBeInstanceOf(FindNotifiableRuleResponse::class)
->and($this->presenter->data->notificationId)->toBe(1)
->and($this->presenter->data->channels->slack)->toBe(null)
->and($this->presenter->data->channels->sms)->toBe(null)
->and($this->presenter->data->channels->email?->subject)->toBe('Message subject')
->and($this->presenter->data->channels->email?->formattedMessage)->toBe('<p>Message content</p>')
->and($this->presenter->data->channels->email?->contacts[0]->fullName)->toBe('test-user')
->and($this->presenter->data->channels->email?->contacts[0]->emailAddress)->toBe('test-email');
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRulePresenterStub.php | centreon/tests/php/Core/Notification/Application/UseCase/FindNotifiableRule/FindNotifiableRulePresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\FindNotifiableRule;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Notification\Application\UseCase\FindNotifiableRule\FindNotifiableRulePresenterInterface;
use Core\Notification\Application\UseCase\FindNotifiableRule\FindNotifiableRuleResponse;
class FindNotifiableRulePresenterStub implements FindNotifiableRulePresenterInterface
{
public FindNotifiableRuleResponse|ResponseStatusInterface $data;
public function presentResponse(FindNotifiableRuleResponse|ResponseStatusInterface $data): void
{
$this->data = $data;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/FindNotifiableResources/FindNotifiableResourcesTest.php | centreon/tests/php/Core/Notification/Application/UseCase/FindNotifiableResources/FindNotifiableResourcesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Notification\Application\UseCase\FindNotifiableResources;
use Centreon\Domain\Contact\Contact;
use Core\Application\Common\UseCase\{ErrorResponse, ForbiddenResponse, NotModifiedResponse};
use Core\Contact\Domain\AdminResolver;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\ReadNotifiableResourceRepositoryInterface;
use Core\Notification\Application\UseCase\FindNotifiableResources\{
FindNotifiableResources,
FindNotifiableResourcesResponse,
NotifiableHostDto,
NotifiableResourceDto
};
use Core\Notification\Domain\Model\{NotifiableHost, NotifiableResource, NotifiableService, ServiceEvent};
use Tests\Core\Notification\Infrastructure\API\FindNotifiableResources\FindNotifiableResourcesPresenterStub;
beforeEach(function (): void {
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new FindNotifiableResourcesPresenterStub($this->presenterFormatter);
$this->readRepository = $this->createMock(ReadNotifiableResourceRepositoryInterface::class);
$this->adminResolver = $this->createMock(AdminResolver::class);
});
it('should present a Forbidden Response when user doesn\'t have access to endpoint.', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1);
$requestUid = '';
$useCase = new FindNotifiableResources($contact, $this->readRepository, $this->adminResolver);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->with($contact)
->willReturn(false);
$useCase($this->presenter, $requestUid);
expect($this->presenter->responseStatus)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->responseStatus->getMessage())
->toBe(NotificationException::listResourcesNotAllowed()->getMessage());
});
it('should present an Error Response when an unhandled error occurs.', function (): void {
$contact = (new Contact())->setAdmin(true)->setId(1);
$requestUid = '';
$useCase = new FindNotifiableResources($contact, $this->readRepository, $this->adminResolver);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->with($contact)
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findAllForActivatedNotifications')
->willThrowException(new \Exception());
$useCase($this->presenter, $requestUid);
expect($this->presenter->responseStatus)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->responseStatus->getMessage())
->toBe(NotificationException::errorWhileListingResources()->getMessage());
});
it(
'should present a Not Modified Response when request UID header is equal to MD5 hash of database query',
function (iterable $notifiableResources): void {
$contact = (new Contact())->setAdmin(true)->setId(1);
$requestUid = '40f7bc75fcc26954c7190dc743d0a9a6';
$useCase = new FindNotifiableResources($contact, $this->readRepository, $this->adminResolver);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->with($contact)
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findAllForActivatedNotifications')
->willReturn($notifiableResources);
$useCase($this->presenter, $requestUid);
expect($this->presenter->responseStatus)
->toBeInstanceOf(NotModifiedResponse::class);
}
)->with([
[
[
new NotifiableResource(
1,
[
new NotifiableHost(
24,
'myHost',
'mytHost',
[],
[new NotifiableService(13, 'Ping', null, [ServiceEvent::Ok])]
),
]
),
],
],
]);
it(
'should present a FindNotifiableResourcesResponse if request UID header isn\'t equal to MD5 hash of database query',
function (iterable $resources): void {
$contact = (new Contact())->setAdmin(true)->setId(1);
$requestUid = '';
$useCase = new FindNotifiableResources($contact, $this->readRepository, $this->adminResolver);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->with($contact)
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findAllForActivatedNotifications')
->willReturn($resources);
$useCase($this->presenter, $requestUid);
expect($this->presenter->response)
->toBeInstanceOf(FindNotifiableResourcesResponse::class)
->and($this->presenter->response->uid)
->toBe('40f7bc75fcc26954c7190dc743d0a9a6')
->and($this->presenter->response->notifiableResources)
->toBeArray()
->and($this->presenter->response->notifiableResources[0])
->toBeInstanceOf(NotifiableResourceDto::class)
->and($this->presenter->response->notifiableResources[0]->notificationId)
->toBe($resources[0]->getNotificationId())
->and($this->presenter->response->notifiableResources[0]->hosts)
->toBeArray()
->and($this->presenter->response->notifiableResources[0]->hosts[0])
->toBeInstanceOf(NotifiableHostDto::class)
->and($this->presenter->response->notifiableResources[0]->hosts[0]->id)
->toBe($resources[0]->getHosts()[0]->getId())
->and($this->presenter->response->notifiableResources[0]->hosts[0]->name)
->toBe($resources[0]->getHosts()[0]->getName())
->and($this->presenter->response->notifiableResources[0]->hosts[0]->alias)
->toBe($resources[0]->getHosts()[0]->getAlias())
->and($this->presenter->response->notifiableResources[0]->hosts[0]->events)
->toBe(0)
->and($this->presenter->response->notifiableResources[0]->hosts[0]->services)
->toBeArray()
->and($this->presenter->response->notifiableResources[0]->hosts[0]->services[0]->id)
->toBe($resources[0]->getHosts()[0]->getServices()[0]->getId())
->and($this->presenter->response->notifiableResources[0]->hosts[0]->services[0]->name)
->toBe($resources[0]->getHosts()[0]->getServices()[0]->getName())
->and($this->presenter->response->notifiableResources[0]->hosts[0]->services[0]->alias)
->toBeNull()
->and($this->presenter->response->notifiableResources[0]->hosts[0]->services[0]->events)
->toBe(1);
}
)->with([
[
[
new NotifiableResource(
1,
[
new NotifiableHost(
24,
'myHost',
'mytHost',
[],
[new NotifiableService(13, 'Ping', null, [ServiceEvent::Ok])]
),
]
),
],
],
]);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/AddNotification/AddNotificationTest.php | centreon/tests/php/Core/Notification/Application/UseCase/AddNotification/AddNotificationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\AddNotification;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\Converter\NotificationHostEventConverter;
use Core\Notification\Application\Converter\NotificationServiceEventConverter;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\AddNotification\AddNotification;
use Core\Notification\Application\UseCase\AddNotification\AddNotificationRequest;
use Core\Notification\Application\UseCase\AddNotification\Factory\NewNotificationFactory;
use Core\Notification\Application\UseCase\AddNotification\Factory\NotificationResourceFactory;
use Core\Notification\Application\UseCase\AddNotification\Validator\NotificationValidator;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\ConfigurationResource;
use Core\Notification\Domain\Model\Contact;
use Core\Notification\Domain\Model\HostEvent;
use Core\Notification\Domain\Model\Message;
use Core\Notification\Domain\Model\NewNotification;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Notification\Domain\Model\TimePeriod;
use Core\Notification\Infrastructure\API\AddNotification\AddNotificationPresenter;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new AddNotificationPresenter($this->presenterFormatter);
$this->request = new AddNotificationRequest();
$this->request->name = 'notification-name';
$this->request->timePeriodId = 2;
$this->request->users = [20, 21];
$this->request->contactGroups = [5, 6];
$this->request->resources = [
['type' => 'hostgroup', 'ids' => [12, 25], 'events' => 5, 'includeServiceEvents' => 1],
];
$this->request->messages = [
[
'channel' => 'Slack',
'subject' => 'some subject',
'message' => 'some message',
'formatted_message' => '<h1> A Test Message </h1>',
],
];
$this->request->isActivated = true;
$this->useCase = new AddNotification(
$this->readNotificationRepository = $this->createMock(ReadNotificationRepositoryInterface::class),
$this->writeNotificationRepository = $this->createMock(WriteNotificationRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->resourceRepositoryProvider = $this->createMock(NotificationResourceRepositoryProviderInterface::class),
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->newNotificationFactory = $this->createMock(NewNotificationFactory::class),
$this->notificationResourceFactory = $this->createMock(NotificationResourceFactory::class),
$this->notificationValidator = $this->createMock(NotificationValidator::class),
$this->user = $this->createMock(ContactInterface::class),
$this->adminResolver = $this->createMock(AdminResolver::class),
);
$this->resourceRepository = $this->createMock(NotificationResourceRepositoryInterface::class);
$this->notification = new Notification(
1,
$this->request->name,
$this->timeperiodLight = new TimePeriod($this->request->timePeriodId, 'timeperiod-name'),
$this->request->isActivated
);
$this->messages = [
new Message(
Channel::from($this->request->messages[0]['channel']),
$this->request->messages[0]['subject'],
$this->request->messages[0]['message'],
$this->request->messages[0]['formatted_message'],
),
];
$this->resources = [
$this->hostgroupResource = new NotificationResource(
'hostgroup',
HostEvent::class,
array_map(
(fn ($resourceId) => new ConfigurationResource($resourceId, "resource-name-{$resourceId}")),
$this->request->resources[0]['ids']
),
NotificationHostEventConverter::fromBitFlags($this->request->resources[0]['events']),
NotificationServiceEventConverter::fromBitFlags($this->request->resources[0]['includeServiceEvents']),
),
];
$this->users = array_map(
(fn ($userId) => new Contact(
$userId,
"user_name_{$userId}",
"email_{$userId}@centreon.com",
"alias_{$userId}"
)),
$this->request->users
);
$this->contactGroups = array_map(
(fn ($contactGroupIds) => new ContactGroup($contactGroupIds, "user_name_{$contactGroupIds}", "alias_{$contactGroupIds}")),
$this->request->contactGroups
);
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->newNotificationFactory
->expects($this->once())
->method('create')
->willThrowException(new \Exception());
$this->notificationValidator
->expects($this->once())
->method('validateUsersAndContactGroups');
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(NotificationException::addNotification()->getMessage());
});
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(NotificationException::addNotAllowed()->getMessage());
});
it('should present an InvalidArgumentResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->newNotificationFactory
->expects($this->once())
->method('create')
->willThrowException(NotificationException::nameAlreadyExists());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(NotificationException::nameAlreadyExists()->getMessage());
});
it('should present an InvalidArgumentResponse if an error is generated when creating a notification resource.', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$newNotification = new NewNotification(
$this->request->name,
new TimePeriod(1, ''),
$this->request->isActivated
);
$this->newNotificationFactory
->method('create')
->willReturn($newNotification);
$this->notificationResourceFactory
->expects($this->once())
->method('createNotificationResources')
->willThrowException(NotificationException::invalidId('resource.ids'));
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(NotificationException::invalidId('resource.ids')->getMessage());
});
it('should throw an InvalidArgumentResponse if at least one of the user IDs does not exist', function (): void {
$this->request->users = [10, 12];
$this->notificationValidator
->expects($this->once())
->method('validateUsersAndContactGroups')
->willThrowException(NotificationException::invalidId('users'));
$this->user
->expects($this->never())
->method('isAdmin')
->willReturn(true);
$this->resourceRepositoryProvider
->expects($this->never())
->method('getRepository')
->willReturn($this->resourceRepository);
$this->resourceRepository
->expects($this->never())
->method('eventEnum')
->willReturn(HostEvent::class);
$this->resourceRepository
->expects($this->never())
->method('eventEnumConverter')
->willReturn(NotificationHostEventConverter::class);
$this->resourceRepository
->expects($this->never())
->method('resourceType')
->willReturn('hostgroup');
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readNotificationRepository
->expects($this->never())
->method('existsByName')
->willReturn(false);
$this->resourceRepository
->expects($this->never())
->method('exist')
->willReturn($this->request->resources[0]['ids']);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(NotificationException::invalidId('users')->getMessage());
});
it('should throw an InvalidArgumentResponse if at least one of the user IDs is not provided', function (): void {
$this->notificationValidator
->expects($this->once())
->method('validateUsersAndContactGroups')
->willThrowException(NotificationException::invalidId('users'));
$this->user
->expects($this->never())
->method('isAdmin')
->willReturn(true);
$this->resourceRepositoryProvider
->expects($this->never())
->method('getRepository')
->willReturn($this->resourceRepository);
$this->resourceRepository
->expects($this->never())
->method('eventEnum')
->willReturn(HostEvent::class);
$this->resourceRepository
->expects($this->never())
->method('eventEnumConverter')
->willReturn(NotificationHostEventConverter::class);
$this->resourceRepository
->expects($this->never())
->method('resourceType')
->willReturn('hostgroup');
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readNotificationRepository
->expects($this->never())
->method('existsByName')
->willReturn(false);
$this->resourceRepository
->expects($this->never())
->method('exist')
->willReturn($this->request->resources[0]['ids']);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(NotificationException::invalidId('users')->getMessage());
});
it('should present an ErrorResponse if the newly created service severity cannot be retrieved', function (): void {
$this->notificationValidator
->expects($this->once())
->method('validateUsersAndContactGroups');
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->newNotificationFactory
->expects($this->once())
->method('create');
$this->notificationResourceFactory
->expects($this->once())
->method('createNotificationResources');
$this->dataStorageEngine
->expects($this->once())
->method('startTransaction');
$this->writeNotificationRepository
->expects($this->once())
->method('addNewNotification');
$this->writeNotificationRepository
->expects($this->once())
->method('addMessagesToNotification');
$this->writeNotificationRepository
->expects($this->once())
->method('addUsersToNotification');
$this->writeNotificationRepository
->expects($this->once())
->method('addContactGroupsToNotification');
$this->dataStorageEngine
->expects($this->once())
->method('commitTransaction');
$this->readNotificationRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(NotificationException::errorWhileRetrievingObject()->getMessage());
});
it('should return created object on success', function (): void {
$this->notificationValidator
->expects($this->once())
->method('validateUsersAndContactGroups');
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readNotificationRepository
->expects($this->once())
->method('findById')
->willReturn($this->notification);
$this->readNotificationRepository
->expects($this->once())
->method('findMessagesByNotificationId')
->willReturn($this->messages);
$this->readNotificationRepository
->expects($this->once())
->method('findUsersByNotificationId')
->willReturn($this->users);
$this->readNotificationRepository
->expects($this->once())
->method('findContactGroupsByNotificationId')
->willReturn($this->contactGroups);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->with($this->user)
->willReturn(true);
$this->resourceRepositoryProvider
->expects($this->once())
->method('getRepositories')
->willReturn([$this->resourceRepository]);
$this->resourceRepository
->expects($this->once(1))
->method('findByNotificationId')
->willReturn(
$this->hostgroupResource
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getPresentedData())->toBeInstanceOf(CreatedResponse::class);
expect($this->presenter->getPresentedData()->getResourceId())->toBe($this->notification->getId());
$payload = $this->presenter->getPresentedData()->getPayload();
expect($payload['name'])
->toBe($this->notification->getName())
->and($payload['timeperiod'])
->toBe([
'id' => $this->notification->getTimePeriod()->getId(),
'name' => $this->notification->getTimePeriod()->getName(),
])
->and($payload['is_activated'])
->toBe($this->notification->isActivated())
->and($payload['users'])
->toBe(array_map(
(fn ($user) => [
'id' => $user->getId(),
'name' => $user->getName(),
]),
$this->users
))
->and($payload['contactgroups'])
->toBe(array_map(
(fn ($contactgroup) => [
'id' => $contactgroup->getId(),
'name' => $contactgroup->getName(),
]),
$this->contactGroups
))
->and($payload['messages'])
->toBe(array_map(
(fn ($message) => [
'channel' => $message->getChannel()->value,
'subject' => $message->getSubject(),
'message' => $message->getRawMessage(),
'formatted_message' => $message->getFormattedMessage(),
]),
$this->messages
))
->and($payload['resources'])
->toBe(array_map(
(fn ($resource) => [
'type' => $resource->getType(),
'events' => NotificationHostEventConverter::toBitFlags($resource->getEvents()),
'ids' => array_map(
(fn ($resourceDetail) => [
'id' => $resourceDetail->getId(),
'name' => $resourceDetail->getName(),
]),
$resource->getResources()
),
'extra' => [
'event_services' => NotificationServiceEventConverter::toBitFlags($resource->getServiceEvents()),
],
]),
$this->resources
));
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/AddNotification/Validator/NotificationValidatorTest.php | centreon/tests/php/Core/Notification/Application/UseCase/AddNotification/Validator/NotificationValidatorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\AddNotification\Validator;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Contact\Domain\AdminResolver;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\UseCase\AddNotification\Validator\NotificationValidator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
beforeEach(function (): void {
$this->user = $this->createMock(ContactInterface::class);
$this->contactRepository = $this->createMock(ReadContactRepositoryInterface::class);
$this->contactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->readTimePeriodRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class);
$this->adminResolver = $this->createMock(AdminResolver::class);
$this->validator = new NotificationValidator(
$this->contactRepository,
$this->contactGroupRepository,
$this->accessGroupRepository,
$this->readTimePeriodRepository,
$this->adminResolver,
);
});
it('should throw a NotificationException if users and contact groups are empty', function (): void {
$this->validator->validateUsersAndContactGroups([], [], $this->user);
})->throws(NotificationException::class)
->expectExceptionMessage(NotificationException::emptyArrayNotAllowed('users, contact groups')->getMessage());
it('should throw a NotificationException if at least one of the user IDs does not exist', function (): void {
$requestUsers = [20, 21];
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->with($this->user)
->willReturn(true);
$this->contactRepository
->expects($this->once())
->method('retrieveExistingContactIds')
->willReturn([$requestUsers[0]]);
$this->validator->validateUsersAndContactGroups($requestUsers, [], $this->user);
})->throws(NotificationException::class)
->expectExceptionMessage(NotificationException::invalidId('users')->getMessage());
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/AddNotification/Factory/NewNotificationFactoryTest.php | centreon/tests/php/Core/Notification/Application/UseCase/AddNotification/Factory/NewNotificationFactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\AddNotification\Factory;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\AddNotification\Factory\NewNotificationFactory;
beforeEach(function (): void {
$this->notificationRepository = $this->createMock(ReadNotificationRepositoryInterface::class);
$this->factory = new NewNotificationFactory($this->notificationRepository);
});
it('should throw an InvalidArgumentResponse when a field assert fails', function (): void {
$this->notificationRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->factory->create('', true, 1);
})->throws(AssertionException::class)
->expectExceptionMessage(AssertionException::notEmptyString('NewNotification::name')->getMessage());
it('should present an InvalidArgumentResponse when name is already used', function (): void {
$this->notificationRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->factory->create('name', true, 1);
})->throws(NotificationException::class)
->expectExceptionMessage(NotificationException::nameAlreadyExists()->getMessage());
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/AddNotification/Factory/NotificationResourceFactoryTest.php | centreon/tests/php/Core/Notification/Application/UseCase/AddNotification/Factory/NotificationResourceFactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\AddNotification\Factory;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Contact\Domain\AdminResolver;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Application\UseCase\AddNotification\Factory\NotificationResourceFactory;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->notificationResourceRepositoryProvider = $this->createMock(NotificationResourceRepositoryProviderInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->adminResolver = $this->createMock(AdminResolver::class);
$this->notificationResouceFactory = new NotificationResourceFactory(
$this->notificationResourceRepositoryProvider,
$this->readAccessGroupRepository,
$this->user,
$this->adminResolver,
);
$this->resourceRepository = $this->createMock(NotificationResourceRepositoryInterface::class);
$this->requestResources = [
['type' => 'hostgroup', 'ids' => [12, 25], 'events' => 5, 'includeServiceEvents' => 1],
];
});
it('should throw a NotificationException if at least one of the resource IDs does not exist', function (): void {
$this->notificationResourceRepositoryProvider
->method('getRepository')
->willReturn($this->resourceRepository);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->with($this->user)
->willReturn(true);
$this->resourceRepository
->expects($this->atMost(2))
->method('exist')
->willReturn([$this->requestResources[0]['ids'][0]]);
$this->notificationResouceFactory->createNotificationResources($this->requestResources);
})->expectException(NotificationException::class)
->expectExceptionMessage(NotificationException::invalidId('resource.ids')->getMessage());
it('should throw a NotificationException if at least one resource ID is not provided', function (): void {
$this->notificationResourceRepositoryProvider
->method('getRepository')
->willReturn($this->resourceRepository);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->with($this->user)
->willReturn(true);
$this->notificationResouceFactory->createNotificationResources($this->requestResources);
})->expectException(NotificationException::class)
->expectExceptionMessage(NotificationException::invalidId('resource.ids')->getMessage());
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsTest.php | centreon/tests/php/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\DeleteNotifications;
use Centreon\Domain\Contact\Contact;
use Core\Application\Common\UseCase\{ForbiddenResponse, MultiStatusResponse};
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\DeleteNotifications\{DeleteNotifications, DeleteNotificationsRequest};
beforeEach(function (): void {
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DeleteNotificationsPresenterStub($this->presenterFormatter);
$this->writeRepository = $this->createMock(WriteNotificationRepositoryInterface::class);
});
it('should present a ForbiddenResponse when the user doesn\'t have access to endpoint', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1);
$request = new DeleteNotificationsRequest();
$request->ids = [1, 2];
(new DeleteNotifications($contact, $this->writeRepository)) ($request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(NotificationException::deleteNotAllowed()->getMessage());
});
it('should present a Multi-Status Response when a bulk delete action is executed', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$request = new DeleteNotificationsRequest();
$request->ids = [1, 2, 3];
$this->writeRepository
->expects($this->exactly(3))
->method('deleteNotification')
->will($this->onConsecutiveCalls(1, 0, $this->throwException(new \Exception())));
(new DeleteNotifications($contact, $this->writeRepository)) ($request, $this->presenter);
$expectedResult = [
'results' => [
[
'href' => 'centreon/api/latest/configuration/notifications/1',
'status' => 204,
'message' => null,
],
[
'href' => 'centreon/api/latest/configuration/notifications/2',
'status' => 404,
'message' => 'Notification not found',
],
[
'href' => 'centreon/api/latest/configuration/notifications/3',
'status' => 500,
'message' => 'Error while deleting a notification configuration',
],
],
];
expect($this->presenter->response)
->toBeInstanceOf(MultiStatusResponse::class)
->and($this->presenter->response->getPayload())
->toBeArray()
->and($this->presenter->response->getPayload())
->toBe($expectedResult);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsPresenterStub.php | centreon/tests/php/Core/Notification/Application/UseCase/DeleteNotifications/DeleteNotificationsPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\DeleteNotifications;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\MultiStatusResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Notification\Application\UseCase\DeleteNotifications\DeleteNotificationsPresenterInterface;
use Core\Notification\Application\UseCase\DeleteNotifications\DeleteNotificationsResponse;
use Core\Notification\Application\UseCase\DeleteNotifications\DeleteNotificationsStatusResponse;
use Core\Notification\Domain\Model\ResponseCode;
use Symfony\Component\HttpFoundation\Response;
class DeleteNotificationsPresenterStub extends AbstractPresenter implements DeleteNotificationsPresenterInterface
{
private const HREF = 'centreon/api/latest/configuration/notifications/';
/** @var ResponseStatusInterface */
public ResponseStatusInterface $response;
public function presentResponse(DeleteNotificationsResponse|ResponseStatusInterface $response): void
{
if ($response instanceof DeleteNotificationsResponse) {
$multiStatusResponse = [
'results' => array_map(fn (DeleteNotificationsStatusResponse $notificationDto) => [
'href' => self::HREF . $notificationDto->id,
'status' => $this->enumToIntConverter($notificationDto->status),
'message' => $notificationDto->message,
], $response->results),
];
$this->response = new MultiStatusResponse($multiStatusResponse);
} else {
$this->response = $response;
}
}
/**
* @param ResponseCode $code
*
* @return int
*/
private function enumToIntConverter(ResponseCode $code): int
{
return match ($code) {
ResponseCode::OK => Response::HTTP_NO_CONTENT,
ResponseCode::NotFound => Response::HTTP_NOT_FOUND,
ResponseCode::Error => Response::HTTP_INTERNAL_SERVER_ERROR,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotificationTest.php | centreon/tests/php/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotificationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\PartialUpdateNotification;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\{ErrorResponse, ForbiddenResponse, NoContentResponse, NotFoundResponse};
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\{
ReadNotificationRepositoryInterface,
WriteNotificationRepositoryInterface
};
use Core\Notification\Application\UseCase\PartialUpdateNotification\{
PartialUpdateNotification,
PartialUpdateNotificationRequest
};
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\TimePeriod;
beforeEach(function (): void {
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new PartialUpdateNotificationPresenterStub($this->presenterFormatter);
$this->dataStorage = $this->createMock(DataStorageEngineInterface::class);
$this->readRepository = $this->createMock(ReadNotificationRepositoryInterface::class);
$this->writeRepository = $this->createMock(WriteNotificationRepositoryInterface::class);
$this->notificationId = 1;
});
it('should present a Forbidden Response when user doesn\'t have access to endpoint', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1);
$request = new PartialUpdateNotificationRequest();
$request->isActivated = true;
$useCase = (new PartialUpdateNotification(
$contact,
$this->readRepository,
$this->writeRepository,
$this->dataStorage
));
$useCase($request, $this->presenter, $this->notificationId);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(NotificationException::partialUpdateNotAllowed()->getMessage());
});
it('should present a Not Found Response when notification ID doesn\'t exist', function (): void {
$contact = (new Contact())
->setAdmin(false)
->setTopologyRules([Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]);
$request = new PartialUpdateNotificationRequest();
$request->isActivated = true;
$this->readRepository
->expects($this->once())
->method('findById')
->with($this->notificationId)
->willReturn(null);
$useCase = (new PartialUpdateNotification(
$contact,
$this->readRepository,
$this->writeRepository,
$this->dataStorage
));
$useCase($request, $this->presenter, $this->notificationId);
expect($this->presenter->response)
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->response->getMessage())
->toBe('Notification not found');
});
it('should present an Error Response when an unhandled error occurs', function (): void {
$contact = (new Contact())
->setAdmin(false)
->setTopologyRules([Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]);
$request = new PartialUpdateNotificationRequest();
$request->isActivated = false;
$this->readRepository
->expects($this->once())
->method('findById')
->with($this->notificationId)
->willThrowException(new \Exception());
$useCase = (new PartialUpdateNotification(
$contact,
$this->readRepository,
$this->writeRepository,
$this->dataStorage
));
$useCase($request, $this->presenter, $this->notificationId);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(NotificationException::errorWhilePartiallyUpdatingObject()->getMessage());
});
it('should present a No Content Response when a notification definition has been partially updated', function (): void {
$contact = (new Contact())
->setAdmin(false)
->setTopologyRules([Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]);
$request = new PartialUpdateNotificationRequest();
$request->isActivated = false;
$notification = new Notification(1, 'myNotification', new TimePeriod(1, '24x7'), true);
$this->readRepository
->expects($this->once())
->method('findById')
->with($this->notificationId)
->willReturn($notification);
$useCase = (new PartialUpdateNotification(
$contact,
$this->readRepository,
$this->writeRepository,
$this->dataStorage
));
$useCase($request, $this->presenter, $this->notificationId);
expect($this->presenter->response)->toBeInstanceOf(NoContentResponse::class);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotificationPresenterStub.php | centreon/tests/php/Core/Notification/Application/UseCase/PartialUpdateNotification/PartialUpdateNotificationPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\PartialUpdateNotification;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Notification\Application\UseCase\PartialUpdateNotification\{
PartialUpdateNotificationPresenterInterface as PresenterInterface
};
class PartialUpdateNotificationPresenterStub extends AbstractPresenter implements PresenterInterface
{
/** @var ResponseStatusInterface */
public ResponseStatusInterface $response;
/**
* @inheritDoc
*/
public function presentResponse(ResponseStatusInterface $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/FindNotifications/FindNotificationsTest.php | centreon/tests/php/Core/Notification/Application/UseCase/FindNotifications/FindNotificationsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\FindNotifications;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryInterface;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\FindNotifications\FindNotifications;
use Core\Notification\Application\UseCase\FindNotifications\FindNotificationsResponse;
use Core\Notification\Application\UseCase\FindNotifications\NotificationDto;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\NotificationResource;
use Core\Notification\Domain\Model\TimePeriod;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Tests\Core\Notification\Infrastructure\API\FindNotifications\FindNotificationsPresenterStub;
beforeEach(function (): void {
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new FindNotificationsPresenterStub($this->presenterFormatter);
$this->notificationRepository = $this->createMock(ReadNotificationRepositoryInterface::class);
$this->repositoryProvider = $this->createMock(NotificationResourceRepositoryProviderInterface::class);
$this->hgResourceRepository = $this->createMock(NotificationResourceRepositoryInterface::class);
$this->sgResourceRepository = $this->createMock(NotificationResourceRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->adminResolver = $this->createMock(AdminResolver::class);
});
it('should present an error response when the user is not admin and doesn\'t have sufficient ACLs', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1);
(new FindNotifications(
$contact,
$this->notificationRepository,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->requestParameters,
$this->adminResolver
))($this->presenter);
expect($this->presenter->responseStatus)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->responseStatus?->getMessage())
->toBe(NotificationException::listNotAllowed()->getMessage());
});
it('should present an empty response when no notifications are configured', function (): void {
$contact = (new Contact())->setAdmin(true)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$this->notificationRepository
->expects($this->once())
->method('findAll')
->willReturn([]);
(new FindNotifications(
$contact,
$this->notificationRepository,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->requestParameters,
$this->adminResolver
))($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindNotificationsResponse::class)
->and($this->presenter->response->notifications)
->toBeArray()
->toBeEmpty();
});
it('should get the resources count with ACL calculation when the user is not admin', function (): void {
$contact = (new Contact())->setAdmin(false)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$notificationOne = new Notification(1, 'notification-one', new TimePeriod(1, '24x7'), true);
$notificationTwo = new Notification(2, 'notification-two', new TimePeriod(1, '24x7'), true);
$notificationThree = new Notification(3, 'notification-three', new TimePeriod(1, '24x7'), true);
$this->notificationRepository
->expects($this->once())
->method('findAll')
->willReturn([
$notificationOne,
$notificationTwo,
$notificationThree,
]);
$this->notificationRepository
->expects($this->once())
->method('countContactsByNotificationIdsAndAccessGroup')
->willReturn([
1 => 4,
2 => 3,
]);
$accessGroups = [
new AccessGroup(1, 'acl-name', 'acl-alias'),
new AccessGroup(2, 'acl-name-two', 'acl-alias-two'),
];
$repositories = [$this->hgResourceRepository, $this->sgResourceRepository];
$this->repositoryProvider
->expects($this->any())
->method('getRepositories')
->willReturn($repositories);
$this->readAccessGroupRepository
->expects($this->atLeastOnce())
->method('findByContact')
->with($contact)
->willReturn($accessGroups);
foreach ($repositories as $repository) {
$repository
->expects($this->any())
->method('countResourcesByNotificationIdsAndAccessGroups');
}
(new FindNotifications(
$contact,
$this->notificationRepository,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->requestParameters,
$this->adminResolver
))($this->presenter);
});
it('should get the resources count without ACL calculation when the user is admin', function (): void {
$contact = (new Contact())->setAdmin(true)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$notificationOne = new Notification(1, 'notification-one', new TimePeriod(1, '24x7'), true);
$notificationTwo = new Notification(2, 'notification-two', new TimePeriod(1, '24x7'), true);
$notificationThree = new Notification(3, 'notification-three', new TimePeriod(1, '24x7'), true);
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->with($contact)
->willReturn(true);
$this->notificationRepository
->expects($this->once())
->method('findAll')
->willReturn([
$notificationOne,
$notificationTwo,
$notificationThree,
]);
$this->notificationRepository
->expects($this->once())
->method('countContactsByNotificationIds')
->willReturn([
1 => 4,
2 => 3,
]);
$repositories = [$this->hgResourceRepository, $this->sgResourceRepository];
$this->repositoryProvider
->expects($this->any())
->method('getRepositories')
->willReturn($repositories);
foreach ($repositories as $repository) {
$repository
->expects($this->any())
->method('countResourcesByNotificationIdsAndAccessGroups');
}
(new FindNotifications(
$contact,
$this->notificationRepository,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->requestParameters,
$this->adminResolver
))($this->presenter);
});
it('should present a FindNotificationsResponse when the use case is executed correctly', function (): void {
$contact = (new Contact())->setAdmin(true)->setId(1)->setTopologyRules(
[Contact::ROLE_CONFIGURATION_NOTIFICATIONS_READ_WRITE]
);
$notificationOne = new Notification(1, 'notification-one', new TimePeriod(1, '24x7'), true);
$notificationTwo = new Notification(2, 'notification-two', new TimePeriod(1, '24x7'), true);
$notificationThree = new Notification(3, 'notification-three', new TimePeriod(1, '24x7'), true);
$this->notificationRepository
->expects($this->once())
->method('findAll')
->willReturn([
$notificationOne,
$notificationTwo,
$notificationThree,
]);
$notificationChannelsByNotifications = [
1 => [Channel::from('Slack')],
2 => [Channel::from('Slack'), Channel::from('Sms')],
3 => [
Channel::from('Slack'),
Channel::from('Sms'),
Channel::from('Email'),
],
];
$this->notificationRepository
->expects($this->once())
->method('findNotificationChannelsByNotificationIds')
->willReturn($notificationChannelsByNotifications);
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->with($contact)
->willReturn(true);
$usersCount = [
1 => 4,
2 => 4,
3 => 2,
];
$this->notificationRepository
->expects($this->once())
->method('countContactsByNotificationIds')
->willReturn($usersCount);
$this->hgResourceRepository
->expects($this->any())
->method('resourceType')
->willReturn('hostgroup');
$this->sgResourceRepository
->expects($this->any())
->method('resourceType')
->willReturn('servicegroup');
$repositories = [$this->hgResourceRepository, $this->sgResourceRepository];
$this->repositoryProvider
->expects($this->any())
->method('getRepositories')
->willReturn($repositories);
$hostgroupResourcesCount = [1 => 10, 2 => 5, 3 => 6];
$servicegroupResourcesCount = [1 => 8, 2 => 12, 3 => 3];
$resourcesCount = [$hostgroupResourcesCount, $servicegroupResourcesCount];
$index = 0;
foreach ($repositories as $repository) {
$repository
->expects($this->any())
->method('countResourcesByNotificationIds')
->willReturn($resourcesCount[$index]);
$index++;
}
(new FindNotifications(
$contact,
$this->notificationRepository,
$this->repositoryProvider,
$this->readAccessGroupRepository,
$this->requestParameters,
$this->adminResolver
))($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindNotificationsResponse::class)
->and($this->presenter->response->notifications)
->toBeArray();
$firstNotification = $this->presenter->response->notifications[0];
$secondNotification = $this->presenter->response->notifications[1];
$thirdNotification = $this->presenter->response->notifications[2];
expect($firstNotification)
->toBeInstanceOf(NotificationDto::class)
->and($firstNotification->id)->toBe($notificationOne->getId())
->and($firstNotification->name)->toBe($notificationOne->getName())
->and($firstNotification->usersCount)->toBe($usersCount[$notificationOne->getId()])
->and($firstNotification->isActivated)->toBeTrue()
->and($firstNotification->notificationChannels)
->toBe($notificationChannelsByNotifications[$notificationOne->getId()])
->and($firstNotification->resources)->toBe(
[
[
'type' => NotificationResource::TYPE_HOST_GROUP,
'count' => $hostgroupResourcesCount[$notificationOne->getId()],
],
[
'type' => NotificationResource::TYPE_SERVICE_GROUP,
'count' => $servicegroupResourcesCount[$notificationOne->getId()],
],
]
)
->and($firstNotification->timeperiodId)->toBe(1)
->and($firstNotification->timeperiodName)->toBe('24x7');
expect($secondNotification)
->toBeInstanceOf(NotificationDto::class)
->and($secondNotification->id)->toBe($notificationTwo->getId())
->and($secondNotification->name)->toBe($notificationTwo->getName())
->and($secondNotification->usersCount)->toBe($usersCount[$notificationTwo->getId()])
->and($secondNotification->isActivated)->toBeTrue()
->and($secondNotification->notificationChannels)
->toBe($notificationChannelsByNotifications[$notificationTwo->getId()])
->and($secondNotification->resources)->toBe(
[
[
'type' => NotificationResource::TYPE_HOST_GROUP,
'count' => $hostgroupResourcesCount[$notificationTwo->getId()],
],
[
'type' => NotificationResource::TYPE_SERVICE_GROUP,
'count' => $servicegroupResourcesCount[$notificationTwo->getId()],
],
]
)
->and($secondNotification->timeperiodId)->toBe(1)
->and($secondNotification->timeperiodName)->toBe('24x7');
expect($thirdNotification)
->toBeInstanceOf(NotificationDto::class)
->and($thirdNotification->id)->toBe($notificationThree->getId())
->and($thirdNotification->name)->toBe($notificationThree->getName())
->and($thirdNotification->usersCount)->toBe($usersCount[$notificationThree->getId()])
->and($thirdNotification->isActivated)->toBeTrue()
->and($thirdNotification->notificationChannels)
->toBe($notificationChannelsByNotifications[$notificationThree->getId()])
->and($thirdNotification->resources)->toBe(
[
[
'type' => NotificationResource::TYPE_HOST_GROUP,
'count' => $hostgroupResourcesCount[$notificationThree->getId()],
],
[
'type' => NotificationResource::TYPE_SERVICE_GROUP,
'count' => $servicegroupResourcesCount[$notificationThree->getId()],
],
]
)
->and($thirdNotification->timeperiodId)->toBe(1)
->and($thirdNotification->timeperiodName)->toBe('24x7');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/UpdateNotification/UpdateNotificationTest.php | centreon/tests/php/Core/Notification/Application/UseCase/UpdateNotification/UpdateNotificationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\UpdateNotification;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\NotificationResourceRepositoryProviderInterface;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\UpdateNotification\Factory\NotificationFactory;
use Core\Notification\Application\UseCase\UpdateNotification\Factory\NotificationResourceFactory;
use Core\Notification\Application\UseCase\UpdateNotification\UpdateNotification;
use Core\Notification\Application\UseCase\UpdateNotification\UpdateNotificationRequest;
use Core\Notification\Application\UseCase\UpdateNotification\Validator\NotificationValidator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Tests\Core\Notification\Infrastructure\API\UpdateNotification\UpdateNotificationPresenterStub;
beforeEach(function (): void {
$this->readNotificationRepository = $this->createMock(ReadNotificationRepositoryInterface::class);
$this->writeNotificationRepository = $this->createMock(WriteNotificationRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->resourceRepositoryProvider = $this->createMock(NotificationResourceRepositoryProviderInterface::class);
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class);
$this->notificationValidator = $this->createMock(NotificationValidator::class);
$this->notificationFactory = $this->createMock(NotificationFactory::class);
$this->notificationResourceFactory = $this->createMock(NotificationResourceFactory::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->adminResolver = $this->createMock(AdminResolver::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new UpdateNotificationPresenterStub($this->presenterFormatter);
$this->useCase = new UpdateNotification(
$this->readNotificationRepository,
$this->writeNotificationRepository,
$this->readAccessGroupRepository,
$this->resourceRepositoryProvider,
$this->dataStorageEngine,
$this->notificationValidator,
$this->notificationFactory,
$this->notificationResourceFactory,
$this->contact,
$this->adminResolver,
);
});
it('should present a forbidden response when the user is not admin and does not have sufficient ACLs', function (): void {
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
$request = new UpdateNotificationRequest();
$this->useCase->__invoke($request, $this->presenter);
expect($this->presenter->responseStatus)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->responseStatus?->getMessage())
->toBe(NotificationException::updateNotAllowed()->getMessage());
});
it('should present a not found response when the notification does not exist', function (): void {
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$request = new UpdateNotificationRequest();
$request->id = 2;
$this->readNotificationRepository
->expects($this->once())
->method('exists')
->with($request->id)
->willReturn(false);
$this->useCase->__invoke($request, $this->presenter);
expect($this->presenter->responseStatus)->toBeInstanceOf(NotFoundResponse::class);
});
it('should present a no content response when everything is ok', function (): void {
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$request = new UpdateNotificationRequest();
$request->id = 1;
$request->name = 'notification';
$request->messages = [
[
'channel' => 'Email',
'subject' => 'Subject',
'message' => 'This is my message',
'formatted_message' => '<h1>This is my message</h1>',
],
];
$request->resources = [
[
'type' => 'hostgroup',
'events' => 3,
'ids' => [1, 2, 3],
'includeServiceEvents' => 0,
],
];
$request->users = [1];
$this->readNotificationRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->useCase->__invoke($request, $this->presenter);
expect($this->presenter->responseStatus)->toBeInstanceOf(NoContentResponse::class);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationMessageFactoryTest.php | centreon/tests/php/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationMessageFactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\UpdateNotification\Factory;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Notification\Application\UseCase\UpdateNotification\Factory\NotificationMessageFactory;
it('should throw an AssertionException when a message has an empty subject', function (): void {
$messages = [
[
'channel' => 'Email',
'subject' => '',
'message' => 'This is my message',
'formatted_message' => '<h1>This is my message</h1>',
],
];
NotificationMessageFactory::createMultipleMessage($messages);
})->throws(AssertionException::class);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationFactoryTest.php | centreon/tests/php/Core/Notification/Application/UseCase/UpdateNotification/Factory/NotificationFactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Application\UseCase\UpdateNotification\Factory;
use Core\Notification\Application\Exception\NotificationException;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\UseCase\UpdateNotification\Factory\NotificationFactory;
use Core\Notification\Application\UseCase\UpdateNotification\UpdateNotificationRequest;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\TimePeriod;
beforeEach(function (): void {
$this->repository = $this->createMock(ReadNotificationRepositoryInterface::class);
$this->factory = new NotificationFactory($this->repository);
});
it('should throw a NotificationException when a different notification with the same name exists', function (): void {
$request = new UpdateNotificationRequest();
$request->id = 1;
$request->name = 'notification';
$existingNotification = new Notification(
2,
'notification',
new TimePeriod(1, TimePeriod::ALL_TIME_PERIOD)
);
$this->repository
->expects($this->once())
->method('findByName')
->with($request->name)
->willReturn($existingNotification);
$this->factory->create($request);
})->throws(NotificationException::class)
->expectExceptionMessage(NotificationException::nameAlreadyExists()->getMessage());
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Domain/Model/NotificationTest.php | centreon/tests/php/Core/Notification/Domain/Model/NotificationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Notification\Domain\Model\Notification;
use Core\Notification\Domain\Model\TimePeriod;
beforeEach(function (): void {
$this->name = 'notification-name';
$this->timePeriod = new TimePeriod(1, '');
$this->isActivated = false;
});
it('should return properly set notification instance', function (): void {
$notification = new Notification(
1,
$this->name,
$this->timePeriod,
$this->isActivated
);
expect($notification->getName())->toBe($this->name)
->and($notification->getTimePeriod())->toBe($this->timePeriod)
->and($notification->isActivated())->toBe(false);
});
it('should trim the "name" field', function (): void {
$notification = new Notification(
1,
$nameWithSpaces = ' my-name ',
$this->timePeriod,
$this->isActivated
);
expect($notification->getName())->toBe(trim($nameWithSpaces));
});
it('should throw an exception when notification name is empty', function (): void {
new Notification(
1,
'',
$this->timePeriod,
$this->isActivated
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Notification::name')
->getMessage()
);
it('should throw an exception when notification name is too long', function (): void {
new Notification(
1,
str_repeat('a', Notification::MAX_NAME_LENGTH + 1),
$this->timePeriod,
$this->isActivated
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Notification::MAX_NAME_LENGTH + 1),
Notification::MAX_NAME_LENGTH + 1,
Notification::MAX_NAME_LENGTH,
'Notification::name'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Domain/Model/NewNotificationTest.php | centreon/tests/php/Core/Notification/Domain/Model/NewNotificationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Notification\Domain\Model\NewNotification;
use Core\Notification\Domain\Model\TimePeriod;
beforeEach(function (): void {
$this->name = 'notification-name';
$this->timePeriod = new TimePeriod(1, '');
$this->isActivated = false;
});
it('should return properly set notification instance', function (): void {
$notification = new NewNotification($this->name, $this->timePeriod, $this->isActivated);
expect($notification->getName())->toBe($this->name)
->and($notification->getTimePeriod())->toBe($this->timePeriod)
->and($notification->isActivated())->toBe(false);
});
it('should trim the "name" field', function (): void {
$notification = new NewNotification(
$nameWithSpaces = ' my-name ',
$this->timePeriod,
$this->isActivated
);
expect($notification->getName())->toBe(trim($nameWithSpaces));
});
it('should throw an exception when notification name is empty', function (): void {
new NewNotification(
'',
$this->timePeriod,
$this->isActivated
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewNotification::name')
->getMessage()
);
it('should throw an exception when notification name is too long', function (): void {
new NewNotification(
str_repeat('a', NewNotification::MAX_NAME_LENGTH + 1),
$this->timePeriod,
$this->isActivated
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewNotification::MAX_NAME_LENGTH + 1),
NewNotification::MAX_NAME_LENGTH + 1,
NewNotification::MAX_NAME_LENGTH,
'NewNotification::name'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Domain/Model/MessageTest.php | centreon/tests/php/Core/Notification/Domain/Model/MessageTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Notification\Domain\Model\Channel;
use Core\Notification\Domain\Model\Message;
beforeEach(function (): void {
$this->channel = Channel::Slack;
$this->subject = 'some subject';
$this->message = 'some message';
$this->formattedMessage = '<p>some message</p>';
});
it('should return properly set notification message instance', function (): void {
$message = new Message(
$this->channel,
$this->subject,
$this->message,
$this->formattedMessage
);
expect($message->getChannel())->toBe(Channel::Slack)
->and($message->getSubject())->toBe($this->subject)
->and($message->getRawMessage())->toBe($this->message)
->and($message->getFormattedMessage())->toBe($this->formattedMessage);
});
it('should trim the "subject" and "message" fields', function (): void {
$message = new Message(
$this->channel,
$subjectWithSpaces = ' my-subject ',
$messageWithSpaces = ' my-message ',
$formattedMessageWithSpaces = ' <p>my-message</p> ',
);
expect($message->getSubject())->toBe(trim($subjectWithSpaces))
->and($message->getRawMessage())->toBe(trim($messageWithSpaces))
->and($message->getFormattedMessage())->toBe(trim($formattedMessageWithSpaces));
});
it('should throw an exception when notification message subject is too long', function (): void {
new Message(
$this->channel,
str_repeat('a', Message::MAX_SUBJECT_LENGTH + 1),
$this->message
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Message::MAX_SUBJECT_LENGTH + 1),
Message::MAX_SUBJECT_LENGTH + 1,
Message::MAX_SUBJECT_LENGTH,
'Message::subject'
)->getMessage()
);
it('should throw an exception when notification message content is too long', function (): void {
new Message(
$this->channel,
$this->subject,
str_repeat('a', Message::MAX_MESSAGE_LENGTH + 1),
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Message::MAX_MESSAGE_LENGTH + 1),
Message::MAX_MESSAGE_LENGTH + 1,
Message::MAX_MESSAGE_LENGTH,
'Message::message'
)->getMessage()
);
it('should throw an exception when notification formatted message content is too long', function (): void {
new Message(
$this->channel,
$this->subject,
$this->message,
str_repeat('a', Message::MAX_MESSAGE_LENGTH + 1),
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Message::MAX_MESSAGE_LENGTH + 1),
Message::MAX_MESSAGE_LENGTH + 1,
Message::MAX_MESSAGE_LENGTH,
'Message::formattedMessage'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Infrastructure/Repository/DbNotifiableResourceFactoryTest.php | centreon/tests/php/Core/Notification/Infrastructure/Repository/DbNotifiableResourceFactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Infrastructure\Repository;
use Core\Notification\Domain\Model\{HostEvent, NotifiableHost, NotifiableResource, NotifiableService, ServiceEvent};
use Core\Notification\Infrastructure\Repository\DbNotifiableResourceFactory;
dataset('$records', [
[
[
[
'notification_id' => 1,
'host_id' => 16,
'host_name' => 'myHost',
'host_alias' => 'myHost',
'host_events' => 0,
'service_id' => 27,
'service_name' => 'Ping',
'service_alias' => null,
'service_events' => 1,
'included_service_events' => 0,
],
[
'notification_id' => 2,
'host_id' => 17,
'host_name' => 'myHost2',
'host_alias' => 'myHost2',
'host_events' => 6,
'service_id' => 34,
'service_name' => 'Ping',
'service_alias' => null,
'service_events' => 0,
'included_service_events' => 6,
],
[
'notification_id' => 2,
'host_id' => 17,
'host_name' => 'myHost2',
'host_alias' => 'myHost2',
'host_events' => 6,
'service_id' => 35,
'service_name' => 'Disk-/',
'service_alias' => null,
'service_events' => 0,
'included_service_events' => 6,
],
[
'notification_id' => 3,
'host_id' => 18,
'host_name' => 'myHost3',
'host_alias' => 'myHost3',
'host_events' => 4,
'service_id' => 36,
'service_name' => 'Ping',
'service_alias' => null,
'service_events' => 0,
'included_service_events' => 0,
],
],
],
]);
it('can create an array of notifiable resources from an array of records', function (array $records): void {
$notifiableResources = DbNotifiableResourceFactory::createFromRecords($records);
foreach ($notifiableResources as $notifiableResource) {
expect($notifiableResource)->toBeInstanceOf(NotifiableResource::class);
expect($notifiableResource->getHosts())->toBeArray();
foreach ($notifiableResource->getHosts() as $host) {
expect($host)->toBeInstanceOf(NotifiableHost::class);
expect($host->getEvents())->toBeArray();
foreach ($host->getEvents() as $hostEvent) {
expect($hostEvent)->toBeInstanceOf(HostEvent::class);
}
expect($host->getServices())->toBeArray();
foreach ($host->getServices() as $service) {
expect($service)->toBeInstanceOf(NotifiableService::class);
expect($service->getEvents())->toBeArray();
foreach ($service->getEvents() as $serviceEvent) {
expect($serviceEvent)->toBeInstanceOf(ServiceEvent::class);
}
}
}
}
})->with('$records');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Infrastructure/API/FindNotification/FindNotificationPresenterStub.php | centreon/tests/php/Core/Notification/Infrastructure/API/FindNotification/FindNotificationPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Infrastructure\API\FindNotification;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\UseCase\FindNotification\FindNotificationPresenterInterface;
use Core\Notification\Application\UseCase\FindNotification\FindNotificationResponse;
class FindNotificationPresenterStub extends AbstractPresenter implements FindNotificationPresenterInterface
{
public ?FindNotificationResponse $response = null;
public ?ResponseStatusInterface $responseStatus = null;
public function __construct(protected PresenterFormatterInterface $presenterFormatter)
{
parent::__construct($presenterFormatter);
}
/**
* @param FindNotificationResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindNotificationResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->responseStatus = $response;
} else {
$this->response = $response;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Infrastructure/API/FindNotifiableResources/FindNotifiableResourcesPresenterStub.php | centreon/tests/php/Core/Notification/Infrastructure/API/FindNotifiableResources/FindNotifiableResourcesPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Infrastructure\API\FindNotifiableResources;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\UseCase\FindNotifiableResources\{
FindNotifiableResourcesPresenterInterface as PresenterInterface,
FindNotifiableResourcesResponse
};
class FindNotifiableResourcesPresenterStub extends AbstractPresenter implements PresenterInterface
{
/** @var FindNotifiableResourcesResponse|null */
public ?FindNotifiableResourcesResponse $response = null;
/** @var ResponseStatusInterface|null */
public ?ResponseStatusInterface $responseStatus = null;
public function __construct(protected PresenterFormatterInterface $presenterFormatter)
{
parent::__construct($presenterFormatter);
}
/**
* @inheritDoc
*/
public function presentResponse(FindNotifiableResourcesResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->responseStatus = $response;
} else {
$this->response = $response;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Infrastructure/API/FindNotifications/FindNotificationsPresenterStub.php | centreon/tests/php/Core/Notification/Infrastructure/API/FindNotifications/FindNotificationsPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Infrastructure\API\FindNotifications;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\UseCase\FindNotifications\FindNotificationsPresenterInterface;
use Core\Notification\Application\UseCase\FindNotifications\FindNotificationsResponse;
class FindNotificationsPresenterStub extends AbstractPresenter implements FindNotificationsPresenterInterface
{
public ?FindNotificationsResponse $response = null;
public ?ResponseStatusInterface $responseStatus = null;
public function __construct(protected PresenterFormatterInterface $presenterFormatter)
{
parent::__construct($presenterFormatter);
}
/**
* @param FindNotificationsResponse|ResponseStatusInterface $response
*/
public function presentResponse(FindNotificationsResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->responseStatus = $response;
} else {
$this->response = $response;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Notification/Infrastructure/API/UpdateNotification/UpdateNotificationPresenterStub.php | centreon/tests/php/Core/Notification/Infrastructure/API/UpdateNotification/UpdateNotificationPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Notification\Infrastructure\API\UpdateNotification;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Notification\Application\UseCase\UpdateNotification\UpdateNotificationPresenterInterface;
class UpdateNotificationPresenterStub extends AbstractPresenter implements UpdateNotificationPresenterInterface
{
public ?ResponseStatusInterface $responseStatus = null;
public function __construct(protected PresenterFormatterInterface $presenterFormatter)
{
parent::__construct($presenterFormatter);
}
/**
* @param NoContentResponse|ResponseStatusInterface $response
*/
public function presentResponse(NoContentResponse|ResponseStatusInterface $response): void
{
$this->responseStatus = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Timezone/Domain/Model/TimezoneTest.php | centreon/tests/php/Core/Timezone/Domain/Model/TimezoneTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Timezone\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Timezone\Domain\Model\Timezone;
beforeEach(function (): void {
$this->name = 'host-name';
$this->offset = '+05:00';
$this->dayligthSavingTimeOffset = '+06:00';
});
it('should return properly set timezone instance', function (): void {
$timezone = new Timezone(1, $this->name, $this->offset, $this->dayligthSavingTimeOffset);
expect($timezone->getId())->toBe(1)
->and($timezone->getName())->toBe($this->name)
->and($timezone->getOffset())->toBe($this->offset)
->and($timezone->getDaylightSavingTimeOffset())->toBe($this->dayligthSavingTimeOffset);
});
it('should throw an exception when timezone name is empty', function (): void {
new Timezone(1, '', $this->offset, $this->dayligthSavingTimeOffset);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Timezone::name')->getMessage()
);
it('should throw an exception when timezone offset format is not respected', function (): void {
new Timezone(1, $this->name, 'aaa', $this->dayligthSavingTimeOffset);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::matchRegex('aaa', '/^[-+][0-9]{2}:[0-9]{2}$/', 'Timezone::offset')->getMessage()
);
it('should throw an exception when timezone daylightSavingTimeOffset format is not respected', function (): void {
new Timezone(1, $this->name, $this->offset, 'aaa');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::matchRegex('aaa', '/^[-+][0-9]{2}:[0-9]{2}$/', 'Timezone::daylightSavingTimeOffset')->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Tag/RealTime/Infrastructure/Repository/DbTagFactoryTest.php | centreon/tests/php/Core/Tag/RealTime/Infrastructure/Repository/DbTagFactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Category\RealTime\Infrastructure\Repository;
use Core\Tag\RealTime\Domain\Model\Tag;
use Core\Tag\RealTime\Infrastructure\Repository\Tag\DbTagFactory;
it('DbTagFactory creation test', function (): void {
$record = [
'id' => 1,
'name' => 'Name of the tag',
'type' => Tag::SERVICE_CATEGORY_TYPE_ID,
];
$category = DbTagFactory::createFromRecord($record);
expect($category->getId())->toBe((int) $record['id']);
expect($category->getName())->toBe($record['name']);
expect($category->getType())->toBe($record['type']);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Metric/Application/UseCase/FindMetricsByService/FindMetricsByServiceTest.php | centreon/tests/php/Core/Metric/Application/UseCase/FindMetricsByService/FindMetricsByServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Metric\Application\UseCase\FindMetricsByService;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Metric\Application\UseCase\FindMetricsByService\FindMetricsByService;
use Core\Metric\Application\UseCase\FindMetricsByService\FindMetricsByServiceResponse;
use Core\Metric\Domain\Model\Metric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->metricRepository = $this->createMock(ReadMetricRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->adminUser = (new Contact())->setAdmin(true)->setId(1);
$this->nonAdminUser = (new Contact())->setAdmin(false)->setId(1);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->hostId = 1;
$this->serviceId = 2;
$this->metrics = [
(new Metric(1, 'mymetric'))
->setUnit('ms')
->setCurrentValue(1.5)
->setWarningHighThreshold(100)
->setWarningLowThreshold(50)
->setCriticalHighThreshold(300)
->setCriticalLowThreshold(100),
(new Metric(2, 'anothermetric'))
->setUnit('%')
->setCurrentValue(10)
->setWarningHighThreshold(50)
->setWarningLowThreshold(0)
->setCriticalHighThreshold(100)
->setCriticalLowThreshold(50),
];
});
it('should present a NotFoundResponse when no metrics could be found as admin', function (): void {
$this->metricRepository
->expects($this->once())
->method('findByHostIdAndServiceId')
->willReturn([]);
$useCase = new FindMetricsByService(
$this->adminUser,
$this->metricRepository,
$this->accessGroupRepository,
$this->requestParameters
);
$presenter = new FindMetricsByServicePresenterStub();
$useCase($this->hostId, $this->serviceId, $presenter);
expect($presenter->data)->toBeInstanceOf(NotFoundResponse::class)->and($presenter->data->getMessage())->toBe('metrics not found');
});
it('should present a NotFoundResponse when no metrics could be found as non-admin', function (): void {
$this->metricRepository
->expects($this->once())
->method('findByHostIdAndServiceIdAndAccessGroups')
->willReturn([]);
$useCase = new FindMetricsByService(
$this->nonAdminUser,
$this->metricRepository,
$this->accessGroupRepository,
$this->requestParameters
);
$presenter = new FindMetricsByServicePresenterStub();
$useCase($this->hostId, $this->serviceId, $presenter);
expect($presenter->data)->toBeInstanceOf(NotFoundResponse::class)->and($presenter->data->getMessage())->toBe('metrics not found');
});
it('should present an ErrorResponse when an error occured as admin', function (): void {
$this->metricRepository
->expects($this->once())
->method('findByHostIdAndServiceId')
->willThrowException(new \Exception());
$useCase = new FindMetricsByService(
$this->adminUser,
$this->metricRepository,
$this->accessGroupRepository,
$this->requestParameters
);
$presenter = new FindMetricsByServicePresenterStub();
$useCase($this->hostId, $this->serviceId, $presenter);
expect($presenter->data)->toBeInstanceOf(ErrorResponse::class)->and($presenter->data->getMessage())->toBe('An error occured while finding metrics');
});
it('should present an ErrorResponse when an error occured as non-admin', function (): void {
$this->metricRepository
->expects($this->once())
->method('findByHostIdAndServiceIdAndAccessGroups')
->willThrowException(new \Exception());
$useCase = new FindMetricsByService(
$this->nonAdminUser,
$this->metricRepository,
$this->accessGroupRepository,
$this->requestParameters
);
$presenter = new FindMetricsByServicePresenterStub();
$useCase($this->hostId, $this->serviceId, $presenter);
expect($presenter->data)->toBeInstanceOf(ErrorResponse::class)->and($presenter->data->getMessage())->toBe('An error occured while finding metrics');
});
it('should present an FindMetricsByServiceResponse when metrics are correctly found as admin', function (): void {
$this->metricRepository
->expects($this->once())
->method('findByHostIdAndServiceId')
->willReturn($this->metrics);
$useCase = new FindMetricsByService(
$this->adminUser,
$this->metricRepository,
$this->accessGroupRepository,
$this->requestParameters
);
$presenter = new FindMetricsByServicePresenterStub();
$useCase($this->hostId, $this->serviceId, $presenter);
expect($presenter->data)->toBeInstanceOf(FindMetricsByServiceResponse::class)
->and($presenter->data->metricsDto[0]->id)->toBe(1)
->and($presenter->data->metricsDto[0]->name)->toBe('mymetric')
->and($presenter->data->metricsDto[0]->unit)->toBe('ms')
->and($presenter->data->metricsDto[0]->currentValue)->toBe(1.5)
->and($presenter->data->metricsDto[0]->warningHighThreshold)->toBe(100.0)
->and($presenter->data->metricsDto[0]->warningLowThreshold)->toBe(50.0)
->and($presenter->data->metricsDto[0]->criticalHighThreshold)->toBe(300.0)
->and($presenter->data->metricsDto[0]->criticalLowThreshold)->toBe(100.0)
->and($presenter->data->metricsDto[1]->id)->toBe(2)
->and($presenter->data->metricsDto[1]->name)->toBe('anothermetric')
->and($presenter->data->metricsDto[1]->unit)->toBe('%')
->and($presenter->data->metricsDto[1]->currentValue)->toBe(10.0)
->and($presenter->data->metricsDto[1]->warningHighThreshold)->toBe(50.0)
->and($presenter->data->metricsDto[1]->warningLowThreshold)->toBe(0.0)
->and($presenter->data->metricsDto[1]->criticalHighThreshold)->toBe(100.0)
->and($presenter->data->metricsDto[1]->criticalLowThreshold)->toBe(50.0);
});
it('should present an FindMetricsByServiceResponse when metrics are correctly found as non-admin', function (): void {
$this->metricRepository
->expects($this->once())
->method('findByHostIdAndServiceIdAndAccessGroups')
->willReturn($this->metrics);
$useCase = new FindMetricsByService(
$this->nonAdminUser,
$this->metricRepository,
$this->accessGroupRepository,
$this->requestParameters
);
$presenter = new FindMetricsByServicePresenterStub();
$useCase($this->hostId, $this->serviceId, $presenter);
expect($presenter->data)->toBeInstanceOf(FindMetricsByServiceResponse::class)
->and($presenter->data->metricsDto[0]->id)->toBe(1)
->and($presenter->data->metricsDto[0]->name)->toBe('mymetric')
->and($presenter->data->metricsDto[0]->unit)->toBe('ms')
->and($presenter->data->metricsDto[0]->currentValue)->toBe(1.5)
->and($presenter->data->metricsDto[0]->warningHighThreshold)->toBe(100.0)
->and($presenter->data->metricsDto[0]->warningLowThreshold)->toBe(50.0)
->and($presenter->data->metricsDto[0]->criticalHighThreshold)->toBe(300.0)
->and($presenter->data->metricsDto[0]->criticalLowThreshold)->toBe(100.0)
->and($presenter->data->metricsDto[1]->id)->toBe(2)
->and($presenter->data->metricsDto[1]->name)->toBe('anothermetric')
->and($presenter->data->metricsDto[1]->unit)->toBe('%')
->and($presenter->data->metricsDto[1]->currentValue)->toBe(10.0)
->and($presenter->data->metricsDto[1]->warningHighThreshold)->toBe(50.0)
->and($presenter->data->metricsDto[1]->warningLowThreshold)->toBe(0.0)
->and($presenter->data->metricsDto[1]->criticalHighThreshold)->toBe(100.0)
->and($presenter->data->metricsDto[1]->criticalLowThreshold)->toBe(50.0);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Metric/Application/UseCase/FindMetricsByService/FindMetricsByServicePresenterStub.php | centreon/tests/php/Core/Metric/Application/UseCase/FindMetricsByService/FindMetricsByServicePresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Metric\Application\UseCase\FindMetricsByService;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Metric\Application\UseCase\FindMetricsByService\FindMetricsByServicePresenterInterface;
use Core\Metric\Application\UseCase\FindMetricsByService\FindMetricsByServiceResponse;
class FindMetricsByServicePresenterStub implements FindMetricsByServicePresenterInterface
{
public ResponseStatusInterface|FindMetricsByServiceResponse $data;
public function presentResponse(FindMetricsByServiceResponse|ResponseStatusInterface $data): void
{
$this->data = $data;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricsTest.php | centreon/tests/php/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Metric\Application\UseCase\DownloadPerformanceMetrics;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\RealTime\Repository\ReadIndexDataRepositoryInterface;
use Core\Application\RealTime\Repository\ReadPerformanceDataRepositoryInterface;
use Core\Domain\RealTime\Model\IndexData;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetricPresenterInterface;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetricRequest;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetricResponse;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetrics;
use Core\Metric\Domain\Model\MetricValue;
use Core\Metric\Domain\Model\PerformanceMetric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use DateTimeImmutable;
use Tests\Core\Metric\Infrastructure\API\DownloadPerformanceMetrics\DownloadPerformanceMetricsPresenterStub;
beforeEach(function (): void {
$this->hostId = 1;
$this->serviceId = 2;
$this->indexId = 15;
});
it('returns an error response if the user does not have access to the correct topology', function (): void {
$indexDataRepository = $this->createMock(ReadIndexDataRepositoryInterface::class);
$metricRepository = $this->createMock(ReadMetricRepositoryInterface::class);
$performanceDataRepository = $this->createMock(ReadPerformanceDataRepositoryInterface::class);
$readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class);
$contact = $this->createMock(ContactInterface::class);
$contact->expects($this->any())
->method('hasTopologyRole')
->willReturn(false);
$useCase = new DownloadPerformanceMetrics(
$indexDataRepository,
$metricRepository,
$performanceDataRepository,
$readAccessGroupRepository,
$readServiceRepository,
$contact,
);
$performanceMetricRequest = new DownloadPerformanceMetricRequest(
$this->hostId,
$this->serviceId,
new DateTimeImmutable('2022-01-01'),
new DateTimeImmutable('2023-01-01')
);
$presenter = new DownloadPerformanceMetricsPresenterStub($this->createMock(PresenterFormatterInterface::class));
$useCase($performanceMetricRequest, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class);
});
it(
'download file name is properly generated',
function (string $hostName, string $serviceDescription, string $expectedFileName): void {
$indexData = new IndexData($hostName, $serviceDescription);
$indexDataRepository = $this->createMock(ReadIndexDataRepositoryInterface::class);
$indexDataRepository
->expects($this->once())
->method('findIndexByHostIdAndServiceId')
->with(
$this->equalTo($this->hostId),
$this->equalTo($this->serviceId),
)
->willReturn($this->indexId);
$indexDataRepository
->expects($this->once())
->method('findHostNameAndServiceDescriptionByIndex')
->willReturn($indexData);
$metricRepository = $this->createMock(ReadMetricRepositoryInterface::class);
$performanceDataRepository = $this->createMock(ReadPerformanceDataRepositoryInterface::class);
$presenter = $this->createMock(DownloadPerformanceMetricPresenterInterface::class);
$readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class);
$contact = $this->createMock(ContactInterface::class);
$contact->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$performanceMetricRequest = new DownloadPerformanceMetricRequest(
$this->hostId,
$this->serviceId,
new DateTimeImmutable('2022-01-01'),
new DateTimeImmutable('2023-01-01')
);
$useCase = new DownloadPerformanceMetrics(
$indexDataRepository,
$metricRepository,
$performanceDataRepository,
$readAccessGroupRepository,
$readServiceRepository,
$contact,
);
$useCase($performanceMetricRequest, $presenter);
}
)->with(
[
['Centreon-Server', 'Ping', 'Centreon-Server_Ping'],
['', 'Ping', '15'],
['Centreon-Server', '', '15'],
['', '', '15'],
]
);
it(
'validate presenter response',
function (iterable $performanceData, DownloadPerformanceMetricResponse $expectedResponse): void {
$indexDataRepository = $this->createMock(ReadIndexDataRepositoryInterface::class);
$indexDataRepository
->expects($this->once())
->method('findIndexByHostIdAndServiceId')
->with(
$this->equalTo($this->hostId),
$this->equalTo($this->serviceId),
)
->willReturn($this->indexId);
$indexDataRepository
->expects($this->once())
->method('findHostNameAndServiceDescriptionByIndex')
->willReturn(null);
$metricRepository = $this->createMock(ReadMetricRepositoryInterface::class);
$performanceDataRepository = $this->createMock(ReadPerformanceDataRepositoryInterface::class);
$performanceDataRepository
->expects($this->once())
->method('findDataByMetricsAndDates')
->willReturn($performanceData);
$presenter = $this->createMock(DownloadPerformanceMetricPresenterInterface::class);
$readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class);
$contact = $this->createMock(ContactInterface::class);
$contact->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$presenter
->expects($this->once())
->method('present')
->with($this->equalTo($expectedResponse));
$performanceMetricRequest = new DownloadPerformanceMetricRequest(
$this->hostId,
$this->serviceId,
new DateTimeImmutable('2022-02-01'),
new DateTimeImmutable('2023-01-01')
);
$useCase = new DownloadPerformanceMetrics(
$indexDataRepository,
$metricRepository,
$performanceDataRepository,
$readAccessGroupRepository,
$readServiceRepository,
$contact,
);
$useCase($performanceMetricRequest, $presenter);
}
)->with([
[
[['rta' => 0.01]],
new DownloadPerformanceMetricResponse(
[
new PerformanceMetric(
new DateTimeImmutable(),
[new MetricValue('rta', 0.001)]
),
],
'15'
),
],
[
[['rta' => 0.01], ['pl' => 0.02]],
new DownloadPerformanceMetricResponse(
[
new PerformanceMetric(
new DateTimeImmutable(),
[
new MetricValue('rta', 0.001),
new MetricValue('pl', 0.002),
]
),
],
'15'
),
],
]);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricResponseTest.php | centreon/tests/php/Core/Metric/Application/UseCase/DownloadPerformanceMetrics/DownloadPerformanceMetricResponseTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Metric\Application\UseCase\DownloadPerformanceMetrics;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetricResponse;
use Core\Metric\Domain\Model\MetricValue;
use Core\Metric\Domain\Model\PerformanceMetric;
use DateTimeImmutable;
function createPerformanceMetric(
string $date,
float $rta,
float $packetLoss,
float $rtmax,
float $rtmin,
): PerformanceMetric {
$metricValues = [];
$metrics = ['rta' => $rta, 'pl' => $packetLoss, 'rtmax' => $rtmax, 'rtmin' => $rtmin];
foreach ($metrics as $columnName => $columnValue) {
$metricValues[] = new MetricValue($columnName, $columnValue);
}
return new PerformanceMetric(new DateTimeImmutable($date), $metricValues);
}
/**
* @return array<string, int|string>
*/
function generateExpectedResponseData(string $date, float $rta, float $packetLoss, float $rtmax, float $rtmin): array
{
$dateTime = new DateTimeImmutable($date);
return [
'time' => $dateTime->getTimestamp(),
'humantime' => $dateTime->format('Y-m-d H:i:s'),
'rta' => sprintf('%f', $rta),
'pl' => sprintf('%f', $packetLoss),
'rtmax' => sprintf('%f', $rtmax),
'rtmin' => sprintf('%f', $rtmin),
];
}
it(
'response contains properly formatted performanceMetrics',
function (iterable $performanceMetrics, array $expectedResponseData, string $filename): void {
$response = new DownloadPerformanceMetricResponse($performanceMetrics, $filename);
$this->assertTrue(property_exists($response, 'performanceMetrics'));
$this->assertInstanceOf(\Generator::class, $response->performanceMetrics);
$actualResponseData = [...$response->performanceMetrics];
$this->assertSame($expectedResponseData, $actualResponseData);
}
)->with([
[
[], [], 'filename',
],
[
[
createPerformanceMetric('2022-01-01', 0.039, 0, 0.108, 0.0049),
],
[
generateExpectedResponseData('2022-01-01', 0.039, 0, 0.108, 0.0049),
],
'filename',
],
[
[
createPerformanceMetric('2022-01-01', 0.039, 0, 0.108, 0.0049),
createPerformanceMetric('2022-01-01 11:00:05', 0.04, 0.1, 0.10, 0.006),
],
[
generateExpectedResponseData('2022-01-01', 0.039, 0, 0.108, 0.0049),
generateExpectedResponseData('2022-01-01 11:00:05', 0.04, 0.1, 0.10, 0.006),
],
'filename',
],
]);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Metric/Infrastructure/API/DownloadPerformanceMetrics/DownloadPerformanceMetricsPresenterStub.php | centreon/tests/php/Core/Metric/Infrastructure/API/DownloadPerformanceMetrics/DownloadPerformanceMetricsPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Metric\Infrastructure\API\DownloadPerformanceMetrics;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Metric\Application\UseCase\DownloadPerformanceMetrics\DownloadPerformanceMetricPresenterInterface;
use Core\Service\Application\UseCase\AddService\AddServiceResponse;
class DownloadPerformanceMetricsPresenterStub extends AbstractPresenter implements DownloadPerformanceMetricPresenterInterface
{
public ResponseStatusInterface|AddServiceResponse $response;
public function presentResponse(ResponseStatusInterface|AddServiceResponse $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceGroup/Application/FindServiceGroups/FindServiceGroupsTest.php | centreon/tests/php/Core/ServiceGroup/Application/FindServiceGroups/FindServiceGroupsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceGroup\Application\UseCase\FindServiceGroups;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Domain\Common\GeoCoords;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceGroup\Application\Exception\ServiceGroupException;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\UseCase\FindServiceGroups\FindServiceGroups;
use Core\ServiceGroup\Application\UseCase\FindServiceGroups\FindServiceGroupsResponse;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
beforeEach(function (): void {
$this->presenter = new DefaultPresenter($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new FindServiceGroups(
readServiceGroupRepository: $this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
requestParameters: $this->createMock(RequestParametersInterface::class),
contact: $this->contact = $this->createMock(ContactInterface::class),
isCloudPlatform: false
);
$this->testedServiceGroup = new ServiceGroup(
1,
'sg-name',
'sg-alias',
GeoCoords::fromString('-2,100'),
'',
true
);
$this->testedServiceGroupArray = [
'id' => 1,
'name' => 'sg-name',
'alias' => 'sg-alias',
'geoCoords' => '-2,100',
'comment' => '',
'isActivated' => true,
];
});
it(
'should present an ErrorResponse when an exception is thrown',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('findAll')
->willThrowException(new \Exception());
($this->useCase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceGroupException::errorWhileSearching()->getMessage());
}
);
it(
'should present a ForbiddenResponse when the user does not have the correct role',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, false],
]
);
($this->useCase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceGroupException::accessNotAllowed()->getMessage());
}
);
it(
'should present a FindServiceGroupsResponse as admin',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('findAll')
->willReturn(new \ArrayIterator([$this->testedServiceGroup]));
($this->useCase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindServiceGroupsResponse::class)
->and($this->presenter->getPresentedData()->servicegroups[0])
->toBe($this->testedServiceGroupArray);
}
);
it(
'should present a FindServiceGroupsResponse as allowed READ user',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ, true],
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, false],
]
);
$this->readAccessGroupRepository
->expects($this->any())
->method('findByContact')
->willReturn([new AccessGroup(id: 1, name: 'TestName', alias: 'TestAlias')]);
$this->readServiceGroupRepository
->expects($this->once())
->method('hasAccessToAllServiceGroups')
->willReturn(false);
$this->readServiceGroupRepository
->expects($this->once())
->method('findAllByAccessGroupIds')
->willReturn(new \ArrayIterator([$this->testedServiceGroup]));
($this->useCase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindServiceGroupsResponse::class)
->and($this->presenter->getPresentedData()->servicegroups[0])
->toBe($this->testedServiceGroupArray);
}
);
it(
'should present a FindServiceGroupsResponse as allowed READ_WRITE user',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, true],
]
);
$this->readAccessGroupRepository
->expects($this->any())
->method('findByContact')
->willReturn([new AccessGroup(id: 1, name: 'TestName', alias: 'TestAlias')]);
$this->readServiceGroupRepository
->expects($this->once())
->method('hasAccessToAllServiceGroups')
->willReturn(false);
$this->readServiceGroupRepository
->expects($this->once())
->method('findAllByAccessGroupIds')
->willReturn(new \ArrayIterator([$this->testedServiceGroup]));
($this->useCase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindServiceGroupsResponse::class)
->and($this->presenter->getPresentedData()->servicegroups[0])
->toBe($this->testedServiceGroupArray);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceGroup/Application/AddServiceGroup/AddServiceGroupTest.php | centreon/tests/php/Core/ServiceGroup/Application/AddServiceGroup/AddServiceGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceGroup\Application\UseCase\AddServiceGroup;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Domain\Common\GeoCoords;
use Core\Domain\Exception\InvalidGeoCoordException;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\WriteAccessGroupRepositoryInterface;
use Core\ServiceGroup\Application\Exception\ServiceGroupException;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\UseCase\AddServiceGroup\AddServiceGroup;
use Core\ServiceGroup\Application\UseCase\AddServiceGroup\AddServiceGroupRequest;
use Core\ServiceGroup\Application\UseCase\AddServiceGroup\AddServiceGroupResponse;
use Core\ServiceGroup\Domain\Model\NewServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
beforeEach(function (): void {
$this->presenter = new DefaultPresenter($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new AddServiceGroup(
$this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class),
$this->writeServiceGroupRepository = $this->createMock(WriteServiceGroupRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->writeAccessGroupRepository = $this->createMock(WriteAccessGroupRepositoryInterface::class),
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->contact = $this->createMock(ContactInterface::class)
);
$this->testedAddServiceGroupRequest = new AddServiceGroupRequest();
$this->testedAddServiceGroupRequest->name = 'added-servicegroup';
$this->testedServiceGroup = new ServiceGroup(
66,
'sg-name',
'sg-alias',
GeoCoords::fromString('-2,100'),
'',
true
);
});
it(
'should present an ErrorResponse when a generic exception is thrown',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('nameAlreadyExists')
->willThrowException(new \Exception());
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceGroupException::errorWhileAdding()->getMessage());
}
);
it(
'should present an ErrorResponse with a custom message when a ServiceGroupException is thrown',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('nameAlreadyExists')
->willThrowException(new ServiceGroupException($msg = uniqid('fake message ', true)));
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe($msg);
}
);
it(
'should present a ConflictResponse if the name already exists',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('nameAlreadyExists')
->willReturn(true);
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceGroupException::nameAlreadyExists($this->testedAddServiceGroupRequest->name)->getMessage());
}
);
it(
'should present an InvalidArgumentResponse when a model field value is not valid',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('nameAlreadyExists')
->willReturn(false);
$this->testedAddServiceGroupRequest->name = '';
$expectedException = AssertionException::minLength(
$this->testedAddServiceGroupRequest->name,
mb_strlen($this->testedAddServiceGroupRequest->name),
NewServiceGroup::MIN_NAME_LENGTH,
'NewServiceGroup::name'
);
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe($expectedException->getMessage());
}
);
it(
'should present an InvalidArgumentResponse when the "geoCoords" field value is not valid',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('nameAlreadyExists')
->willReturn(false);
$this->testedAddServiceGroupRequest->geoCoords = 'this,is,wrong';
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(InvalidGeoCoordException::invalidFormat()->getMessage());
}
);
it(
'should present an ErrorResponse if the newly created service group cannot be retrieved',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('nameAlreadyExists')
->willReturn(false);
$this->writeServiceGroupRepository
->expects($this->once())
->method('add')
->willReturn($this->testedServiceGroup->getId());
$this->readServiceGroupRepository
->expects($this->once())
->method('findOne')
->willReturn(null); // the failure
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceGroupException::errorWhileRetrievingJustCreated()->getMessage());
}
);
it(
'should present a ForbiddenResponse when the user does not have the correct role',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, false],
]
);
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceGroupException::accessNotAllowedForWriting()->getMessage());
}
);
it(
'should present a CreatedResponse<AddServiceGroupResponse> as admin',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('nameAlreadyExists')
->willReturn(false);
$this->writeServiceGroupRepository
->expects($this->once())
->method('add')
->willReturn($this->testedServiceGroup->getId());
$this->readServiceGroupRepository
->expects($this->once())
->method('findOne')
->willReturn($this->testedServiceGroup);
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
/** @var CreatedResponse<int, AddServiceGroupResponse> $presentedData */
$presentedData = $this->presenter->getPresentedData();
expect($presentedData)->toBeInstanceOf(CreatedResponse::class)
->and($presentedData->getPayload())->toBeInstanceOf(AddServiceGroupResponse::class);
}
);
it(
'should present a ForbiddenResponse as allowed READ user',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ, true],
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, false],
]
);
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(ForbiddenResponse::class);
}
);
it(
'should present a CreatedResponse<AddServiceGroupResponse> as allowed READ_WRITE user',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, true],
]
);
$this->readServiceGroupRepository
->expects($this->once())
->method('nameAlreadyExists')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([]);
$this->writeServiceGroupRepository
->expects($this->once())
->method('add')
->willReturn($this->testedServiceGroup->getId());
$this->writeAccessGroupRepository
->expects($this->once())
->method('addLinksBetweenServiceGroupAndAccessGroups');
$this->readServiceGroupRepository
->expects($this->once())
->method('findOneByAccessGroups')
->willReturn($this->testedServiceGroup);
($this->useCase)($this->testedAddServiceGroupRequest, $this->presenter);
/** @var CreatedResponse<int, AddServiceGroupResponse> $presentedData */
$presentedData = $this->presenter->getPresentedData();
expect($presentedData)->toBeInstanceOf(CreatedResponse::class)
->and($presentedData->getPayload())->toBeInstanceOf(AddServiceGroupResponse::class);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceGroup/Application/DeleteServiceGroup/DeleteServiceGroupTest.php | centreon/tests/php/Core/ServiceGroup/Application/DeleteServiceGroup/DeleteServiceGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceGroup\Application\UseCase\DeleteServiceGroup;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Domain\Common\GeoCoords;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceGroup\Application\Exception\ServiceGroupException;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\UseCase\DeleteServiceGroup\DeleteServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
beforeEach(function (): void {
$this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class);
$this->writeServiceGroupRepository = $this->createMock(WriteServiceGroupRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->presenter = new DefaultPresenter($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new DeleteServiceGroup(
$this->readServiceGroupRepository,
$this->writeServiceGroupRepository,
$this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->contact
);
$this->testedServiceGroup = new ServiceGroup(
$this->servicegroupId = 1,
'sg-name',
'sg-alias',
GeoCoords::fromString('-2,100'),
'',
true
);
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('existsOne')
->willThrowException(new \Exception());
($this->useCase)($this->servicegroupId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceGroupException::errorWhileDeleting()->getMessage());
});
it('should present a ForbiddenResponse when the user does not have the correct role', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, false],
]
);
($this->useCase)($this->servicegroupId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceGroupException::accessNotAllowedForWriting()->getMessage());
});
it('should present a NoContentResponse as admin', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
($this->useCase)($this->servicegroupId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NoContentResponse::class);
});
it('should present a ForbiddenResponse as allowed READ user', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ, true],
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, false],
]
);
$this->readServiceGroupRepository
->expects($this->never())
->method('findOneByAccessGroups');
($this->useCase)($this->servicegroupId, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(ForbiddenResponse::class);
});
it('should present a NoContentResponse as allowed READ_WRITE user', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_SERVICE_GROUPS_READ_WRITE, true],
]
);
$this->readServiceGroupRepository
->expects($this->once())
->method('existsOneByAccessGroups')
->willReturn(true);
($this->useCase)($this->servicegroupId, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceGroup/Domain/Model/ServiceGroupTest.php | centreon/tests/php/Core/ServiceGroup/Domain/Model/ServiceGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceGroup\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\Common\GeoCoords;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
beforeEach(function (): void {
$this->createServiceGroup = static fn (array $fields = []): ServiceGroup => new ServiceGroup(
...[
'id' => 1,
'name' => 'service-name',
'alias' => 'service-alias',
'geoCoords' => GeoCoords::fromString('-90.0,180.0'),
'comment' => '',
'isActivated' => true,
...$fields,
]
);
});
it('should return properly set service group instance', function (): void {
$serviceGroup = ($this->createServiceGroup)();
expect($serviceGroup->getId())->toBe(1)
->and((string) $serviceGroup->getGeoCoords())->toBe('-90.0,180.0')
->and($serviceGroup->getName())->toBe('service-name')
->and($serviceGroup->getAlias())->toBe('service-alias');
});
// mandatory fields
it(
'should throw an exception when service group name is an empty string',
fn () => ($this->createServiceGroup)(['name' => ''])
)->throws(
InvalidArgumentException::class,
AssertionException::minLength('', 0, ServiceGroup::MIN_NAME_LENGTH, 'ServiceGroup::name')->getMessage()
);
// string field trimmed
foreach (
[
'name',
'alias',
'comment',
] as $field
) {
it(
"should return trim the field {$field} after construct",
function () use ($field): void {
$serviceGroup = ($this->createServiceGroup)([$field => ' abcd ']);
$valueFromGetter = $serviceGroup->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => ServiceGroup::MAX_NAME_LENGTH,
'alias' => ServiceGroup::MAX_ALIAS_LENGTH,
// We have skipped the comment max size test because it costs ~1 second
// to run it, so more than 10 times the time of all the other tests.
// At this moment, I didn't find any explanation, and considering
// this is a non-critical field ... I prefer skipping it.
// 'comment' => ServiceGroup::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when service group {$field} is too long",
fn () => ($this->createServiceGroup)([$field => $tooLong])
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "ServiceGroup::{$field}")->getMessage()
);
}
// geoCoords field
it(
'should return a valid service group if the "geoCoords" field is valid',
function (): void {
$serviceGroup = ($this->createServiceGroup)();
expect($serviceGroup->getGeoCoords())->toBeInstanceOf(GeoCoords::class);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceGroup/Domain/Model/NewServiceGroupTest.php | centreon/tests/php/Core/ServiceGroup/Domain/Model/NewServiceGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceGroup\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\Common\GeoCoords;
use Core\ServiceGroup\Domain\Model\NewServiceGroup;
beforeEach(function (): void {
$this->createServiceGroup = static fn (array $fields = []): NewServiceGroup => new NewServiceGroup(
...[
'name' => 'service-name',
'alias' => 'service-alias',
'geoCoords' => GeoCoords::fromString('-90.0,180.0'),
'comment' => '',
'isActivated' => true,
...$fields,
]
);
});
it('should return properly set service group instance', function (): void {
$serviceGroup = ($this->createServiceGroup)();
expect((string) $serviceGroup->getGeoCoords())->toBe('-90.0,180.0')
->and($serviceGroup->getName())->toBe('service-name')
->and($serviceGroup->getAlias())->toBe('service-alias');
});
// mandatory fields
it(
'should throw an exception when service group name is an empty string',
fn () => ($this->createServiceGroup)(['name' => ''])
)->throws(
InvalidArgumentException::class,
AssertionException::minLength('', 0, NewServiceGroup::MIN_NAME_LENGTH, 'NewServiceGroup::name')->getMessage()
);
// string field trimmed
foreach (
[
'name',
'alias',
'comment',
] as $field
) {
it(
"should return trim the field {$field} after construct",
function () use ($field): void {
$serviceGroup = ($this->createServiceGroup)([$field => ' abcd ']);
$valueFromGetter = $serviceGroup->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => NewServiceGroup::MAX_NAME_LENGTH,
'alias' => NewServiceGroup::MAX_ALIAS_LENGTH,
// We have skipped the comment max size test because it costs ~1 second
// to run it, so more than 10 times the time of all the other tests.
// At this moment, I didn't find any explanation, and considering
// this is a non-critical field ... I prefer skipping it.
// 'comment' => NewServiceGroup::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when service group {$field} is too long",
fn () => ($this->createServiceGroup)([$field => $tooLong])
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "NewServiceGroup::{$field}")->getMessage()
);
}
// geoCoords field
it(
'should return a valid service group if the "geoCoords" field is valid',
function (): void {
$serviceGroup = ($this->createServiceGroup)();
expect($serviceGroup->getGeoCoords())->toBeInstanceOf(GeoCoords::class);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Connector/Application/UseCase/FindConnectors/FindConnectorsTest.php | centreon/tests/php/Core/Connector/Application/UseCase/FindConnectors/FindConnectorsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Connector\Application\UseCase\FindConnectors;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\CommandType;
use Core\Connector\Application\Exception\ConnectorException;
use Core\Connector\Application\Repository\ReadConnectorRepositoryInterface;
use Core\Connector\Application\UseCase\FindConnectors\FindConnectors;
use Core\Connector\Application\UseCase\FindConnectors\FindConnectorsResponse;
use Core\Connector\Domain\Model\Connector;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Tests\Core\Connector\Infrastructure\API\FindConnectors\FindConnectorsPresenterStub;
beforeEach(closure: function (): void {
$this->presenter = new FindConnectorsPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new FindConnectors(
$this->createMock(RequestParametersInterface::class),
$this->readConnectorRepository = $this->createMock(ReadConnectorRepositoryInterface::class),
$this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class),
$this->contact = $this->createMock(ContactInterface::class),
);
});
it('should present a ForbiddenResponse when the user has insufficient rights', function (): void {
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(ConnectorException::accessNotAllowed()->getMessage());
});
it(
'should present an ErrorResponse when an exception of type RequestParametersTranslatorException is thrown',
function (): void {
$this->contact
->expects($this->atMost(5))
->method('hasTopologyRole')
->willReturn(true);
$exception = new RequestParametersTranslatorException('Error');
$this->readConnectorRepository
->expects($this->once())
->method('findByRequestParametersAndCommandTypes')
->willThrowException($exception);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe($exception->getMessage());
}
);
it(
'should present an ErrorResponse when an exception of type Exception is thrown',
function (): void {
$this->contact
->expects($this->atMost(5))
->method('hasTopologyRole')
->willReturn(true);
$exception = new \Exception('Error');
$this->readConnectorRepository
->expects($this->once())
->method('findByRequestParametersAndCommandTypes')
->willThrowException($exception);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(ConnectorException::errorWhileSearching($exception)->getMessage());
}
);
it(
'should present a FindConnectorsResponse when everything has gone well',
function (): void {
$this->contact
->expects($this->atMost(5))
->method('hasTopologyRole')
->willReturn(true);
$connector = new Connector(
id: 1,
name: 'fake',
commandLine: 'line',
description: 'some-description',
isActivated: true,
commandIds: [12]
);
$this->readConnectorRepository
->expects($this->once())
->method('findByRequestParametersAndCommandTypes')
->willReturn([$connector]);
$command = new Command(
id: 12,
name: 'fake',
commandLine: 'line',
type: CommandType::Check
);
$this->readCommandRepository
->expects($this->once())
->method('findByIds')
->willReturn([$command->getId() => $command]);
($this->useCase)($this->presenter);
$connectorsResponse = $this->presenter->response;
expect($connectorsResponse)->toBeInstanceOf(FindConnectorsResponse::class);
expect($connectorsResponse->connectors[0]->id)->toBe($connector->getId());
expect($connectorsResponse->connectors[0]->name)->toBe($connector->getName());
expect($connectorsResponse->connectors[0]->commandLine)->toBe($command->getCommandLine());
expect($connectorsResponse->connectors[0]->description)->toBe($connector->getDescription());
expect($connectorsResponse->connectors[0]->isActivated)->toBe($connector->isActivated());
expect($connectorsResponse->connectors[0]->commands[0]['id'])->toBe($command->getId());
expect($connectorsResponse->connectors[0]->commands[0]['name'])->toBe($command->getName());
expect($connectorsResponse->connectors[0]->commands[0]['type'])->toBe($command->getType());
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Connector/Domain/Model/ConnectorTest.php | centreon/tests/php/Core/Connector/Domain/Model/ConnectorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Connector\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Connector\Domain\Model\Connector;
it('should return properly set instance', function (): void {
$connector = new Connector(
id: 1,
name: 'connector-name',
commandLine: 'commandline',
description: 'some-description',
isActivated: false,
commandIds: [12, 23, 45],
);
expect($connector->getId())->toBe(1)
->and($connector->getName())->toBe('connector-name')
->and($connector->getCommandLine())->toBe('commandline')
->and($connector->isActivated())->toBe(false)
->and($connector->getDescription())->toBe('some-description')
->and($connector->getCommandIds())->toBe([12, 23, 45]);
});
it('should throw an exception when ID is < 0', function (): void {
new Connector(
id: 0,
name: 'connector-name',
commandLine: 'commandline'
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::positiveInt(0, 'Connector::id')->getMessage()
);
it('should throw an exception when name is empty', function (): void {
new Connector(
id: 1,
name: '',
commandLine: 'commandline',
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Connector::name')->getMessage()
);
it('should throw an exception when name is too long', function (): void {
new Connector(
id: 1,
name: str_repeat('a', Connector::NAME_MAX_LENGTH + 1),
commandLine: 'commandline',
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Connector::NAME_MAX_LENGTH + 1),
Connector::NAME_MAX_LENGTH + 1,
Connector::NAME_MAX_LENGTH,
'Connector::name'
)->getMessage()
);
it('should throw an exception when command line is empty', function (): void {
new Connector(
id: 1,
name: 'connector-line',
commandLine: '',
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Connector::commandLine')->getMessage()
);
it('should throw an exception when command line is too long', function (): void {
new Connector(
id: 1,
name: 'connector-name',
commandLine: str_repeat('a', Connector::COMMAND_MAX_LENGTH + 1),
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Connector::COMMAND_MAX_LENGTH + 1),
Connector::COMMAND_MAX_LENGTH + 1,
Connector::COMMAND_MAX_LENGTH,
'Connector::commandLine'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Connector/Infrastructure/API/FindConnectors/FindConnectorsPresenterStub.php | centreon/tests/php/Core/Connector/Infrastructure/API/FindConnectors/FindConnectorsPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Connector\Infrastructure\API\FindConnectors;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Connector\Application\UseCase\FindConnectors\FindConnectorsPresenterInterface;
use Core\Connector\Application\UseCase\FindConnectors\FindConnectorsResponse;
class FindConnectorsPresenterStub extends AbstractPresenter implements FindConnectorsPresenterInterface
{
public FindConnectorsResponse|ResponseStatusInterface $response;
public function presentResponse(ResponseStatusInterface|FindConnectorsResponse $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Domain/GeoCoordsTest.php | centreon/tests/php/Core/Domain/GeoCoordsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Domain;
use Core\Domain\Common\GeoCoords;
use Core\Domain\Exception\InvalidGeoCoordException;
beforeEach(function (): void {
});
it(
'should return a valid geographic coordinates object for valid latitudes',
fn () => expect((new GeoCoords($lat = '0', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '0.0', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '+0.0', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '-0.0', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '1', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '11', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '89.999', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '-89.999', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '90.000', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '+90.000', '0'))->latitude)->toBe($lat)
->and((new GeoCoords($lat = '-90.000', '0'))->latitude)->toBe($lat)
);
it(
'should return a valid geographic coordinates object for valid longitudes',
fn () => expect((new GeoCoords('0', $lng = '0'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '0.0'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '+0.0'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '-0.0'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '1'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '11'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '111'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '179.999'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '-179.999'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '180.000'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '+180.000'))->longitude)->toBe($lng)
->and((new GeoCoords('0', $lng = '-180.000'))->longitude)->toBe($lng)
);
it(
'should not return a valid geographic coordinates object for invalid latitudes',
function (): void {
$factory = static fn (string $lat, string $lng) => static fn () => new GeoCoords($lat, $lng);
expect($factory('', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('90.00001', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('-90.00001', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('1.2.3', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('1-2', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('1+2', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('--1.2', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('++1.2', '0'))->toThrow(InvalidGeoCoordException::class);
}
);
it(
'should not return a valid geographic coordinates object for invalid longitudes',
function (): void {
$factory = static fn (string $lat, string $lng) => static fn (): GeoCoords => new GeoCoords($lat, $lng);
expect($factory('0', ''))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '180.00001'))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '-180.00001'))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '1.2.3'))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '1-2'))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '1+2'))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '--1.2'))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '++1.2'))->toThrow(InvalidGeoCoordException::class);
}
);
it(
'should throw an exception when the geographic coordinates object has too few coordinates',
fn () => GeoCoords::fromString('')
)->throws(
InvalidGeoCoordException::class,
InvalidGeoCoordException::invalidFormat()->getMessage()
);
it(
'should throw an exception when the geographic coordinates object has too many coordinates',
fn () => GeoCoords::fromString('1,2,3')
)->throws(
InvalidGeoCoordException::class,
InvalidGeoCoordException::invalidFormat()->getMessage()
);
it(
'should throw an exception when the geographic coordinates object has wrong values but a valid format',
fn () => GeoCoords::fromString(',')
)->throws(
InvalidGeoCoordException::class,
InvalidGeoCoordException::invalidValues()->getMessage()
);
it(
'should throw an exception when the geographic coordinates object has wrong latitude',
fn () => GeoCoords::fromString('-91.0,100')
)->throws(
InvalidGeoCoordException::class,
InvalidGeoCoordException::invalidValues()->getMessage()
);
it(
'should throw an exception when the geographic coordinates object has wrong longitude',
fn () => GeoCoords::fromString('-90.0,200')
)->throws(
InvalidGeoCoordException::class,
InvalidGeoCoordException::invalidValues()->getMessage()
);
it(
'should handle whitespace after comma in string format',
function (): void {
$coords = GeoCoords::fromString('45.123, -123.789');
expect($coords->latitude)->toBe('45.123')
->and($coords->longitude)->toBe('-123.789');
$coords = GeoCoords::fromString('0, 0');
expect($coords->latitude)->toBe('0')
->and($coords->longitude)->toBe('0');
}
);
it(
'should convert coordinates to string format using toString method',
function (): void {
$coords = new GeoCoords('45.123456', '-123.789012');
expect((string) $coords)->toBe('45.123456,-123.789012');
$coords = new GeoCoords('0', '0');
expect($coords->__toString())->toBe('0,0');
$coords = new GeoCoords('-90.000000', '180.000000');
expect((string) $coords)->toBe('-90.000000,180.000000');
}
);
it(
'should truncate decimal places to maximum of 6 digits',
function (): void {
$coords = GeoCoords::fromString('45.1234567890,-123.9876543210');
expect($coords->latitude)->toBe('45.123456')
->and($coords->longitude)->toBe('-123.987654');
$coords = GeoCoords::fromString('45.1000000000,-123.0000000000');
expect($coords->latitude)->toBe('45.100000')
->and($coords->longitude)->toBe('-123.000000');
$coords = GeoCoords::fromString('45.0000000000,-123.0000000000');
expect($coords->latitude)->toBe('45.000000')
->and($coords->longitude)->toBe('-123.000000');
}
);
it(
'should handle coordinates without decimal places',
function (): void {
$coords = GeoCoords::fromString('45,-123');
expect($coords->latitude)->toBe('45')
->and($coords->longitude)->toBe('-123');
$coords = GeoCoords::fromString('0,0');
expect($coords->latitude)->toBe('0')
->and($coords->longitude)->toBe('0');
}
);
it(
'should handle edge case boundary values',
function (): void {
$coords = GeoCoords::fromString('89.9999999999999,179.99999999999999');
expect($coords->latitude)->toBe('89.999999')
->and($coords->longitude)->toBe('179.999999');
$coords = GeoCoords::fromString('-89.9999999999999,-179.9999999999999');
expect($coords->latitude)->toBe('-89.999999')
->and($coords->longitude)->toBe('-179.999999');
$coords = GeoCoords::fromString('90.0000000000000,180.0000000000000');
expect($coords->latitude)->toBe('90.000000')
->and($coords->longitude)->toBe('180.000000');
}
);
it(
'should handle positive sign prefix',
function (): void {
$coords = GeoCoords::fromString('+45.123,+123.789');
expect($coords->latitude)->toBe('+45.123')
->and($coords->longitude)->toBe('+123.789');
$coords = GeoCoords::fromString('+0,+0');
expect($coords->latitude)->toBe('+0')
->and($coords->longitude)->toBe('+0');
}
);
it(
'should handle numeric validation for fromString method',
function (): void {
expect(fn () => GeoCoords::fromString('abc,123'))
->toThrow(InvalidGeoCoordException::class, InvalidGeoCoordException::invalidValues()->getMessage());
expect(fn () => GeoCoords::fromString('123,abc'))
->toThrow(InvalidGeoCoordException::class, InvalidGeoCoordException::invalidValues()->getMessage());
expect(fn () => GeoCoords::fromString('abc,abc'))
->toThrow(InvalidGeoCoordException::class, InvalidGeoCoordException::invalidValues()->getMessage());
}
);
it(
'should validate coordinates through constructor with complex invalid formats',
function (): void {
$factory = static fn (string $lat, string $lng) => static fn () => new GeoCoords($lat, $lng);
expect($factory('91', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('-91', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '181'))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '-181'))->toThrow(InvalidGeoCoordException::class)
->and($factory('90.1', '0'))->toThrow(InvalidGeoCoordException::class)
->and($factory('0', '180.1'))->toThrow(InvalidGeoCoordException::class);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Domain/RealTime/Model/HostTest.php | centreon/tests/php/Core/Domain/RealTime/Model/HostTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Domain\RealTime\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\RealTime\Model\Host;
use Core\Domain\RealTime\Model\HostStatus;
use Core\Domain\RealTime\Model\Icon;
use PHPUnit\Framework\TestCase;
class HostTest extends TestCase
{
/**
* test Name too long exception
*/
public function testNameTooLongException(): void
{
$hostName = str_repeat('.', Host::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$hostName,
mb_strlen($hostName),
Host::MAX_NAME_LENGTH,
'Host::name'
)->getMessage()
);
new Host(1, $hostName, 'localhost', 'central', new HostStatus('UP', 0, 0));
}
/**
* test Name empty exception
*/
public function testNameEmptyException(): void
{
$hostName = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::notEmpty(
'Host::name'
)->getMessage()
);
new Host(1, $hostName, 'localhost', 'central', new HostStatus('UP', 0, 0));
}
/**
* test address too long exception
*/
public function testAddressTooLongException(): void
{
$address = str_repeat('.', Host::MAX_ADDRESS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$address,
mb_strlen($address),
Host::MAX_ADDRESS_LENGTH,
'Host::address'
)->getMessage()
);
new Host(1, 'Central-Server', $address, 'central', new HostStatus('UP', 0, 0));
}
/**
* test address empty exception
*/
public function testAddressEmptyException(): void
{
$address = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::notEmpty(
'Host::address'
)->getMessage()
);
new Host(1, 'Central-Server', $address, 'central', new HostStatus('UP', 0, 0));
}
/**
* @return Host
*/
public static function createHostModel(): Host
{
$status = (new HostStatus('UP', 0, 1))
->setOrder(HostStatus::STATUS_ORDER_OK);
$icon = (new Icon())
->setName('dog')
->setUrl('/dog.png');
return (new Host(1, 'Centreon-Central', 'localhost', 'Central', $status))
->setAlias('Central')
->setIcon($icon)
->setCommandLine('/usr/lib64/nagios/plugins/check_icmp -H 127.0.0.1 -n 3 -w 200,20% -c 400,50%')
->setTimeZone(':Europe/Paris')
->setIsFlapping(false)
->setIsInDowntime(false)
->setIsAcknowledged(false)
->setActiveChecks(true)
->setPassiveChecks(false)
->setLastStatusChange(new \DateTime('1991-09-10'))
->setLastNotification(new \DateTime('1991-09-10'))
->setLastTimeUp(new \DateTime('1991-09-10'))
->setLastCheck(new \DateTime('1991-09-10'))
->setNextCheck(new \DateTime('1991-09-10'))
->setOutput('Host check output')
->setPerformanceData('rta=0.342ms;200.000;400.000;0; pl=0%;20;50;0;100 rtmax=0.439ms;;;; rtmin=0.260ms;;;;')
->setExecutionTime(0.1)
->setLatency(0.214)
->setMaxCheckAttempts(5)
->setCheckAttempts(2);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Domain/RealTime/Model/ServiceTest.php | centreon/tests/php/Core/Domain/RealTime/Model/ServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Domain\RealTime\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\RealTime\Model\Icon;
use Core\Domain\RealTime\Model\Service;
use Core\Domain\RealTime\Model\ServiceStatus;
use PHPUnit\Framework\TestCase;
class ServiceTest extends TestCase
{
/**
* test name too long exception
*/
public function testNameTooLongException(): void
{
$name = str_repeat('.', Service::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
mb_strlen($name),
Service::MAX_NAME_LENGTH,
'Service::name'
)->getMessage()
);
new Service(10, 1, $name, new ServiceStatus('OK', 0, 0));
}
/**
* test name empty exception
*/
public function testNameEmptyException(): void
{
$name = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::notEmpty(
'Service::name'
)->getMessage()
);
new Service(10, 1, $name, new ServiceStatus('OK', 0, 0));
}
/**
* @return Service
*/
public static function createServiceModel(): Service
{
$status = (new ServiceStatus('OK', 0, 0))
->setOrder(ServiceStatus::STATUS_ORDER_OK);
$icon = (new Icon())
->setName('dog')
->setUrl('/dog.png');
return (new Service(10, 1, 'Ping', $status))
->setIcon($icon)
->setCommandLine('/usr/lib64/nagios/plugins/check_icmp -H 127.0.0.1 -n 3 -w 200,20% -c 400,50%')
->setIsFlapping(false)
->setIsInDowntime(false)
->setIsAcknowledged(false)
->setActiveChecks(true)
->setPassiveChecks(false)
->setLastStatusChange(new \DateTime('1991-09-10'))
->setLastNotification(new \DateTime('1991-09-10'))
->setLastTimeOk(new \DateTime('1991-09-10'))
->setLastCheck(new \DateTime('1991-09-10'))
->setNextCheck(new \DateTime('1991-09-10'))
->setOutput('Ping check output')
->setPerformanceData('rta=0.342ms;200.000;400.000;0; pl=0%;20;50;0;100 rtmax=0.439ms;;;; rtmin=0.260ms;;;;')
->setExecutionTime(0.1)
->setLatency(0.214)
->setMaxCheckAttempts(5)
->setCheckAttempts(2);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Domain/RealTime/Model/MetaServiceTest.php | centreon/tests/php/Core/Domain/RealTime/Model/MetaServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Domain\RealTime\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\RealTime\Model\MetaService;
use Core\Domain\RealTime\Model\ServiceStatus;
use PHPUnit\Framework\TestCase;
class MetaServiceTest extends TestCase
{
/**
* test name too long exception
*/
public function testNameTooLongException(): void
{
$name = str_repeat('.', MetaService::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
mb_strlen($name),
MetaService::MAX_NAME_LENGTH,
'MetaService::name'
)->getMessage()
);
new MetaService(1, 10, 1, $name, 'Central', new ServiceStatus('OK', 0, 0));
}
/**
* test name empty exception
*/
public function testNameEmptyException(): void
{
$name = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::notEmpty(
'MetaService::name'
)->getMessage()
);
new MetaService(1, 10, 1, $name, 'Central', new ServiceStatus('OK', 0, 0));
}
/**
* @return MetaService
*/
public static function createMetaServiceModel(): MetaService
{
$status = (new ServiceStatus('OK', 0, 0))
->setOrder(ServiceStatus::STATUS_ORDER_OK);
return (new MetaService(1, 10, 20, 'Meta test', 'Central', $status))
->setCommandLine('/usr/lib/centreon/plugins/centreon_centreon_central.pl --mode=metaservice --meta-id 1')
->setIsFlapping(false)
->setIsInDowntime(false)
->setIsAcknowledged(false)
->setActiveChecks(true)
->setPassiveChecks(false)
->setLastStatusChange(new \DateTime('1991-09-10'))
->setLastNotification(new \DateTime('1991-09-10'))
->setLastTimeOk(new \DateTime('1991-09-10'))
->setLastCheck(new \DateTime('1991-09-10'))
->setNextCheck(new \DateTime('1991-09-10'))
->setOutput('Meta output: 0.49')
->setPerformanceData('\'g[value]\'=0.49;;;;')
->setExecutionTime(0.1)
->setLatency(0.214)
->setMaxCheckAttempts(5)
->setCheckAttempts(2);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Domain/Configuration/MetaServiceTest.php | centreon/tests/php/Core/Domain/Configuration/MetaServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Domain\Configuration;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\Configuration\Model\MetaService;
use PHPUnit\Framework\TestCase;
class MetaServiceTest extends TestCase
{
/**
* test name empty exception
*/
public function testNameEmptyException(): void
{
$name = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::notEmpty(
'MetaService::name'
)->getMessage()
);
new MetaService(1, $name, 'average', 1, 'gauge');
}
public function testNameTooLongException(): void
{
$name = str_repeat('.', MetaService::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
mb_strlen($name),
MetaService::MAX_NAME_LENGTH,
'MetaService::name'
)->getMessage()
);
new MetaService(1, $name, 'average', 1, 'gauge');
}
/**
* test wrong data source type provided
*/
public function testUnknownDataSourceType(): void
{
$dataSourceType = 'not-handled';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::inArray(
$dataSourceType,
MetaService::AVAILABLE_DATA_SOURCE_TYPES,
'MetaService::dataSourceType'
)->getMessage()
);
new MetaService(1, 'Meta 1', 'average', 1, $dataSourceType);
}
/**
* test wrong calculation type provided
*/
public function testUnknownCalculationType(): void
{
$calculationType = 'not-handled';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::inArray(
$calculationType,
MetaService::AVAILABLE_CALCULATION_TYPES,
'MetaService::calculationType'
)->getMessage()
);
new MetaService(1, 'Meta 1', $calculationType, 1, 'gauge');
}
/**
* @return MetaService
*/
public static function createMetaServiceModel(): MetaService
{
return (new MetaService(1, 'Meta 1', 'average', 1, 'gauge'))
->setCriticalThreshold(80)
->setWarningThreshold(70)
->setMetric('rta')
->setActivated(true)
->setregexpSearchServices('Ping')
->setOutput('Meta output: %s');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Domain/Configuration/User/Model/UserTest.php | centreon/tests/php/Core/Domain/Configuration/User/Model/UserTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Domain\Configuration\User\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\Configuration\User\Model\User;
use PHPUnit\Framework\TestCase;
class UserTest extends TestCase
{
/**
* Test user creation with empty alias
*/
public function testAliasEmpty(): void
{
$alias = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$alias,
mb_strlen($alias),
User::MIN_ALIAS_LENGTH,
'User::alias'
)->getMessage()
);
new User(
1,
$alias,
'name',
'email',
false,
'light',
'compact',
true
);
}
/**
* Test user creation with too long alias
*/
public function testAliasTooLong(): void
{
$alias = str_repeat('a', 256);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$alias,
mb_strlen($alias),
User::MAX_ALIAS_LENGTH,
'User::alias'
)->getMessage()
);
new User(
1,
$alias,
'name',
'email',
false,
'light',
'compact',
true
);
}
/**
* Test user creation with empty name
*/
public function testNameEmpty(): void
{
$name = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$name,
mb_strlen($name),
User::MIN_NAME_LENGTH,
'User::name'
)->getMessage()
);
new User(
1,
'alias',
$name,
'email',
false,
'light',
'compact',
true
);
}
/**
* Test user creation with too long name
*/
public function testNameTooLong(): void
{
$name = str_repeat('a', 256);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
mb_strlen($name),
User::MAX_NAME_LENGTH,
'User::name'
)->getMessage()
);
new User(
1,
'alias',
$name,
'email',
false,
'light',
'compact',
true
);
}
/**
* Test user creation with empty email
*/
public function testEmailEmpty(): void
{
$email = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$email,
mb_strlen($email),
User::MIN_EMAIL_LENGTH,
'User::email'
)->getMessage()
);
new User(
1,
'alias',
'name',
$email,
false,
'light',
'compact',
true
);
}
/**
* Test user creation with too long email
*/
public function testEmailTooLong(): void
{
$email = str_repeat('a', 256) . '@centreon.com';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$email,
mb_strlen($email),
User::MAX_EMAIL_LENGTH,
'User::email'
)->getMessage()
);
new User(
1,
'alias',
'name',
$email,
false,
'light',
'compact',
true
);
}
/**
* Test user creation with too long userInterfaceViewMode
*/
public function testUserInterfaceViewModeTooLong(): void
{
$userInterfaceViewMode = str_repeat('a', 256);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$userInterfaceViewMode,
mb_strlen($userInterfaceViewMode),
User::MAX_USER_INTERFACE_DENSITY_LENGTH,
'User::userInterfaceViewMode'
)->getMessage()
);
new User(
1,
'alias',
'name',
'hellotest@centreon.com',
false,
'light',
$userInterfaceViewMode,
true
);
}
/**
* Test user creation with empty userInterfaceViewMode
*/
public function testUserInterfaceViewModeEmpty(): void
{
$userInterfaceViewMode = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::notEmptyString(
'User::userInterfaceViewMode'
)->getMessage()
);
new User(
1,
'alias',
'name',
'hellotest@centreon.com',
false,
'light',
$userInterfaceViewMode,
true
);
}
/**
* Test user creation with userInterfaceViewMode not handled
*/
public function testUserInterfaceViewModeNotHandled(): void
{
$userInterfaceViewMode = 'random-ui';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('User interface view mode provided not handled');
new User(
1,
'alias',
'name',
'hellotest@centreon.com',
false,
'light',
$userInterfaceViewMode,
true
);
}
/**
* Test user creation
*/
public function testUserCreation(): void
{
$id = 1;
$alias = 'alias';
$name = 'name';
$email = 'root@localhost';
$isAdmin = true;
$theme = 'light';
$userInterfaceViewMode = 'compact';
$user = new User(
$id,
$alias,
$name,
$email,
$isAdmin,
'light',
'compact',
true
);
$this->assertEquals($id, $user->getId());
$this->assertEquals($alias, $user->getAlias());
$this->assertEquals($name, $user->getName());
$this->assertEquals($email, $user->getEmail());
$this->assertEquals($isAdmin, $user->isAdmin());
$this->assertEquals($theme, $user->getTheme());
$this->assertEquals($userInterfaceViewMode, $user->getUserInterfaceDensity());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Domain/Configuration/UserGroup/Model/UserGroupTest.php | centreon/tests/php/Core/Domain/Configuration/UserGroup/Model/UserGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Domain\Configuration\UserGroup\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\Configuration\UserGroup\Model\UserGroup;
use PHPUnit\Framework\TestCase;
class UserGroupTest extends TestCase
{
/**
* test name empty exception
*/
public function testNameEmpty(): void
{
$name = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::notEmpty(
'UserGroup::name'
)->getMessage()
);
new UserGroup(1, $name, 'userGroupAlias');
}
/**
* test name too long exception
*/
public function testNameTooLong(): void
{
$name = str_repeat('.', UserGroup::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
mb_strlen($name),
UserGroup::MAX_NAME_LENGTH,
'UserGroup::name'
)->getMessage()
);
new UserGroup(1, $name, 'userGroupAlias');
}
/**
* test alias empty exception
*/
public function testAliasEmpty(): void
{
$alias = '';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::notEmpty(
'UserGroup::alias'
)->getMessage()
);
new UserGroup(1, 'userGroupName', $alias);
}
/**
* test alias too long exception
*/
public function testAliasTooLong(): void
{
$alias = str_repeat('.', UserGroup::MAX_ALIAS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$alias,
mb_strlen($alias),
UserGroup::MAX_ALIAS_LENGTH,
'UserGroup::alias'
)->getMessage()
);
new UserGroup(1, 'userGroupName', $alias);
}
/**
* @return UserGroup
*/
public static function createUserGroupModel(): UserGroup
{
return new UserGroup(10, 'userGroupName', 'userGroupAlias');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Broker/Application/UseCase/AddBrokerInputOutput/BrokerInputOutputValidatorTest.php | centreon/tests/php/Core/Broker/Application/UseCase/AddBrokerInputOutput/BrokerInputOutputValidatorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Broker\Application\UseCase\AddBrokerInputOutput;
use Core\Broker\Application\Exception\BrokerException;
use Core\Broker\Application\Repository\ReadBrokerRepositoryInterface;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\BrokerInputOutputValidator;
use Core\Broker\Domain\Model\BrokerInputOutputField;
beforeEach(function (): void {
$this->validator = new BrokerInputOutputValidator(
$this->readBrokerRepository = $this->createMock(ReadBrokerRepositoryInterface::class),
);
$this->outputFields = [
'mandatory-field' => new BrokerInputOutputField(1, 'mandatory-field', 'text', null, null, true, false, null, []),
'optional-field' => new BrokerInputOutputField(2, 'optional-field', 'text', null, null, false, false, null, []),
'integer-field' => new BrokerInputOutputField(3, 'integer-field', 'int', null, null, false, false, null, []),
'password-field' => new BrokerInputOutputField(4, 'password-field', 'password', null, null, false, false, null, []),
'select-field' => new BrokerInputOutputField(5, 'select-field', 'select', null, null, false, false, 'a', ['a', 'b', 'c']),
'radio-field' => new BrokerInputOutputField(6, 'radio-field', 'radio', null, null, false, false, 'A', ['A', 'B', 'C']),
'multiselect-field' => [
'subfield' => new BrokerInputOutputField(3, 'subfield', 'multiselect', null, null, false, false, null, ['X', 'Y', 'Z']),
],
'group-field' => [
'field-A' => new BrokerInputOutputField(3, 'field-A', 'text', null, null, false, false, null, []),
'field-B' => new BrokerInputOutputField(3, 'field-B', 'text', null, null, false, false, null, []),
],
];
$this->outputValues = [
'mandatory-field' => 'mandatory-test',
'optional-field' => 'optional-test',
'integer-field' => 12,
'password-field' => 'password-test',
'select-field' => 'a',
'radio-field' => 'B',
'multiselect-field_subfield' => ['X', 'Z'],
'group-field' => [
[
'field-A' => 'value-A1',
'field-B' => 'value B1',
],
[
'field-A' => 'value-A2',
'field-B' => 'value-B2',
],
],
];
});
it('throws an exception when broker ID is invalid', function (): void {
$this->readBrokerRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validator->brokerIsValidOrFail(1);
})->throws(
BrokerException::class,
BrokerException::notFound(1)->getMessage()
);
it('throws an exception when mandatory field is missing', function (): void {
$this->validator->validateParameters($this->outputFields, []);
})->throws(
BrokerException::class,
BrokerException::missingParameter('mandatory-field')->getMessage()
);
it('throws an exception when mandatory field is empty', function (): void {
$this->validator->validateParameters($this->outputFields, ['mandatory-field' => '']);
})->throws(
BrokerException::class,
BrokerException::missingParameter('mandatory-field')->getMessage()
);
it('throws an exception when mandatory field is null', function (): void {
$this->validator->validateParameters($this->outputFields, ['mandatory-field' => null]);
})->throws(
BrokerException::class,
BrokerException::missingParameter('mandatory-field')->getMessage()
);
it('throws an exception when optional field is missing', function (): void {
$this->validator->validateParameters(
fields: ['optional-field' => $this->outputFields['optional-field']],
values: []
);
})->throws(
BrokerException::class,
BrokerException::missingParameter('optional-field')->getMessage()
);
it('throws an exception when select field value is not in the allowed values', function (): void {
$this->validator->validateParameters(
fields: ['select-field' => $this->outputFields['select-field']],
values: ['select-field' => 'invalid-value']
);
})->throws(
BrokerException::class,
BrokerException::invalidParameter('select-field', 'invalid-value')->getMessage()
);
it('throws an exception when radio field value is not in the allowed values', function (): void {
$this->validator->validateParameters(
fields: ['radio-field' => $this->outputFields['radio-field']],
values: ['radio-field' => 'invalid-value']
);
})->throws(
BrokerException::class,
BrokerException::invalidParameter('radio-field', 'invalid-value')->getMessage()
);
it('throws an exception when multiselect field value is not an array', function (): void {
$this->validator->validateParameters(
fields: ['multiselect-field' => $this->outputFields['multiselect-field']],
values: ['multiselect-field_subfield' => 'invalid-test']
);
})->throws(
BrokerException::class,
BrokerException::invalidParameterType('multiselect-field_subfield', 'invalid-test')->getMessage()
);
it('throws an exception when multiselect field value is not in the allowed values', function (): void {
$this->validator->validateParameters(
fields: ['multiselect-field' => $this->outputFields['multiselect-field']],
values: ['multiselect-field_subfield' => ['invalid-test']]
);
})->throws(
BrokerException::class,
BrokerException::invalidParameter('multiselect-field_subfield', 'invalid-test')->getMessage()
);
it('throws an exception when group field does not contain expected subfield', function (): void {
$this->validator->validateParameters(
fields: ['group-field' => $this->outputFields['group-field']],
values: ['group-field' => [['unknownField' => 'azerty']]]
);
})->throws(
BrokerException::class,
BrokerException::missingParameter('group-field[].field-A')->getMessage()
);
it('does not throw an exception when optional field is empty', function (): void {
$this->validator->validateParameters(
fields: ['optional-field' => $this->outputFields['optional-field']],
values: ['optional-field' => '']
);
expect(true)->toBe(true);
});
it('does not throw an exception when optional field is null', function (): void {
$this->validator->validateParameters(
fields: ['optional-field' => $this->outputFields['optional-field']],
values: ['optional-field' => null]
);
expect(true)->toBe(true);
});
it('does not throw an exception when a multiselect field has expected format', function (): void {
$this->validator->validateParameters(
fields: ['multiselect-field' => $this->outputFields['multiselect-field']],
values: ['multiselect-field_subfield' => $this->outputValues['multiselect-field_subfield']]
);
expect(true)->toBe(true);
});
it('does not throw an exception when a group field has expected format', function (): void {
$this->validator->validateParameters(
fields: ['group-field' => $this->outputFields['group-field']],
values: ['group-field' => $this->outputValues['group-field']]
);
expect(true)->toBe(true);
});
it('does not throw an exception when a group field is empty', function (): void {
$this->validator->validateParameters(
fields: ['group-field' => $this->outputFields['group-field']],
values: ['group-field' => []]
);
expect(true)->toBe(true);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutputTest.php | centreon/tests/php/Core/Broker/Application/UseCase/AddBrokerInputOutput/AddBrokerInputOutputTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Application\UseCase\AddHostCategory;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Broker\Application\Exception\BrokerException;
use Core\Broker\Application\Repository\ReadBrokerInputOutputRepositoryInterface;
use Core\Broker\Application\Repository\WriteBrokerInputOutputRepositoryInterface;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\AddBrokerInputOutput;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\AddBrokerInputOutputRequest;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\AddBrokerInputOutputResponse;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\BrokerInputOutputValidator;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Broker\Domain\Model\BrokerInputOutputField;
use Core\Broker\Domain\Model\Type;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Infrastructure\FeatureFlags;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Tests\Core\Broker\Infrastructure\API\AddBrokerInputOutput\AddBrokerInputOutputPresenterStub;
beforeEach(function (): void {
$this->request = new AddBrokerInputOutputRequest();
$this->request->brokerId = 1;
$this->request->name = 'my-output-test';
$this->request->type = 33;
$this->request->parameters = [
'path' => 'some/path/file',
];
$this->type = new Type(33, 'lua');
$this->output = new BrokerInputOutput(
id: 1,
tag: 'output',
type: $this->type,
name: $this->request->name,
parameters: $this->request->parameters
);
$this->outputFields = [
$this->field = new BrokerInputOutputField(
1,
'path',
'text',
null,
null,
true,
false,
null,
[]
),
];
$this->presenter = new AddBrokerInputOutputPresenterStub(
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class)
);
$this->useCase = new AddBrokerInputOutput(
$this->writeOutputRepository = $this->createMock(WriteBrokerInputOutputRepositoryInterface::class),
$this->readOutputRepository = $this->createMock(ReadBrokerInputOutputRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
$this->validator = $this->createMock(BrokerInputOutputValidator::class),
$this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class),
$this->flags = new FeatureFlags(false, ''),
);
});
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(BrokerException::editNotAllowed()->getMessage());
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('brokerIsValidOrFail')
->willThrowException(BrokerException::notFound($this->request->brokerId));
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(BrokerException::notFound($this->request->brokerId)->getMessage());
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('brokerIsValidOrFail');
$this->readOutputRepository
->expects($this->once())
->method('findType')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(BrokerException::addBrokerInputOutput()->getMessage());
});
it('should present an ErrorResponse if the newly created output cannot be retrieved', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('brokerIsValidOrFail');
$this->readOutputRepository
->expects($this->once())
->method('findType')
->willReturn($this->type);
$this->readOutputRepository
->expects($this->once())
->method('findParametersByType')
->willReturn($this->outputFields);
$this->validator
->expects($this->once())
->method('validateParameters');
$this->writeOutputRepository
->expects($this->once())
->method('add')
->willReturn($this->output->getId());
$this->readOutputRepository
->expects($this->once())
->method('findByIdAndBrokerId')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(BrokerException::inputOutputNotFound($this->request->brokerId, $this->output->getId())->getMessage());
});
it('should return created object on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('brokerIsValidOrFail');
$this->readOutputRepository
->expects($this->once())
->method('findType')
->willReturn($this->type);
$this->readOutputRepository
->expects($this->once())
->method('findParametersByType')
->willReturn($this->outputFields);
$this->validator
->expects($this->once())
->method('validateParameters');
$this->writeOutputRepository
->expects($this->once())
->method('add')
->willReturn($this->output->getId());
$this->readOutputRepository
->expects($this->once())
->method('findByIdAndBrokerId')
->willReturn($this->output);
($this->useCase)($this->request, $this->presenter);
$response = $this->presenter->response;
expect($this->presenter->response)->toBeInstanceOf(AddBrokerInputOutputResponse::class)
->and($response->name)
->toBe($this->output->getName())
->and($response->type->name)
->toBe(($this->output->getType())->name)
->and($response->parameters)
->toBe($this->output->getParameters());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFileTest.php | centreon/tests/php/Core/Broker/Application/UseCase/UpdateStreamConnectorFile/UpdateStreamConnectorFileTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Application\UseCase\AddHostCategory;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Broker\Application\Exception\BrokerException;
use Core\Broker\Application\Repository\ReadBrokerInputOutputRepositoryInterface;
use Core\Broker\Application\Repository\WriteBrokerInputOutputRepositoryInterface;
use Core\Broker\Application\Repository\WriteBrokerRepositoryInterface;
use Core\Broker\Application\UseCase\UpdateStreamConnectorFile\UpdateStreamConnectorFile;
use Core\Broker\Application\UseCase\UpdateStreamConnectorFile\UpdateStreamConnectorFileRequest;
use Core\Broker\Application\UseCase\UpdateStreamConnectorFile\UpdateStreamConnectorFileResponse;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Broker\Domain\Model\BrokerInputOutputField;
use Core\Broker\Domain\Model\Type;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Tests\Core\Broker\Infrastructure\API\UpdateStreamConnectorFile\UpdateStreamConnectorFilePresenterStub;
beforeEach(function (): void {
$this->request = new UpdateStreamConnectorFileRequest();
$this->request->brokerId = 1;
$this->request->outputId = 2;
$this->request->fileContent = '{"test": "hello world"}';
$this->type = new Type(33, 'lua');
$this->output = new BrokerInputOutput(
id: 1,
tag: 'output',
type: $this->type,
name: 'my-output-test',
parameters: ['path' => 'some/fake/path.json'],
);
$this->outputFields = [
$this->field = new BrokerInputOutputField(
1,
'path',
'text',
null,
null,
true,
false,
null,
[]
),
];
$this->presenter = new UpdateStreamConnectorFilePresenterStub(
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class)
);
$this->useCase = new UpdateStreamConnectorFile(
$this->writeOutputRepository = $this->createMock(WriteBrokerInputOutputRepositoryInterface::class),
$this->readOutputRepository = $this->createMock(ReadBrokerInputOutputRepositoryInterface::class),
$this->fileRepository = $this->createMock(WriteBrokerRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
);
});
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(BrokerException::editNotAllowed()->getMessage());
});
it('should present an ErrorResponse when the output is invalid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readOutputRepository
->expects($this->once())
->method('findByIdAndBrokerId')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(BrokerException::inputOutputNotFound($this->request->brokerId, $this->request->outputId)->getMessage());
});
it('should present an ErrorResponse if the file content is invalid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readOutputRepository
->expects($this->once())
->method('findByIdAndBrokerId')
->willReturn($this->output);
$this->request->fileContent = '';
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response?->getMessage())
->toBe(BrokerException::invalidJsonContent()->getMessage());
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readOutputRepository
->expects($this->once())
->method('findByIdAndBrokerId')
->willReturn($this->output);
$this->fileRepository
->expects($this->once())
->method('create');
$this->fileRepository
->expects($this->once())
->method('delete');
$this->readOutputRepository
->expects($this->once())
->method('findParametersByType')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(BrokerException::updateBrokerInputOutput()->getMessage());
});
it('should return created file path on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readOutputRepository
->expects($this->once())
->method('findByIdAndBrokerId')
->willReturn($this->output);
$this->fileRepository
->expects($this->once())
->method('create');
$this->fileRepository
->expects($this->once())
->method('delete');
$this->readOutputRepository
->expects($this->once())
->method('findParametersByType')
->willReturn($this->outputFields);
$this->writeOutputRepository
->expects($this->once())
->method('update');
($this->useCase)($this->request, $this->presenter);
$response = $this->presenter->response;
expect($this->presenter->response)->toBeInstanceOf(UpdateStreamConnectorFileResponse::class)
->and($response->path)
->toBeString();
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Broker/Domain/Model/BrokerInputOutputTest.php | centreon/tests/php/Core/Broker/Domain/Model/BrokerInputOutputTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Broker\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Broker\Domain\Model\Type;
beforeEach(function (): void {
$this->name = 'my-output-test';
$this->type = new Type(33, 'lua');
$this->parameters = [
'path' => 'some/path/file',
];
});
it('should return properly set broker output instance', function (): void {
$output = new BrokerInputOutput(1, 'output', $this->type, $this->name, $this->parameters);
expect($output->getId())->toBe(1)
->and($output->getName())->toBe($this->name)
->and($output->getType()->name)->toBe($this->type->name)
->and($output->getParameters())->toBe($this->parameters);
});
it('should throw an exception when broker output ID is invalid', function (): void {
new BrokerInputOutput(-1, 'output', $this->type, $this->name, $this->parameters);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::min(-1, 0, 'BrokerInputOutput::id')->getMessage()
);
it('should throw an exception when broker output name is empty', function (): void {
new BrokerInputOutput(1, 'output', $this->type, '', $this->parameters);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('BrokerInputOutput::name')->getMessage()
);
it('should throw an exception when broker output name is too long', function (): void {
new BrokerInputOutput(
1,
'output',
$this->type,
str_repeat('a', BrokerInputOutput::NAME_MAX_LENGTH + 1),
$this->parameters
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', BrokerInputOutput::NAME_MAX_LENGTH + 1),
BrokerInputOutput::NAME_MAX_LENGTH + 1,
BrokerInputOutput::NAME_MAX_LENGTH,
'BrokerInputOutput::name'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Broker/Domain/Model/NewBrokerInputOutputTest.php | centreon/tests/php/Core/Broker/Domain/Model/NewBrokerInputOutputTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Broker\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Broker\Domain\Model\NewBrokerInputOutput;
use Core\Broker\Domain\Model\Type;
beforeEach(function (): void {
$this->name = 'my-output-test';
$this->type = new Type(33, 'lua');
$this->parameters = [
'path' => 'some/path/file',
];
});
it('should return properly set broker output instance', function (): void {
$output = new NewBrokerInputOutput('output', $this->type, $this->name, $this->parameters);
expect($output->getName())->toBe($this->name)
->and($output->getType()->name)->toBe($this->type->name)
->and($output->getParameters())->toBe($this->parameters);
});
it('should throw an exception when broker output name is empty', function (): void {
new NewBrokerInputOutput('output', $this->type, '', $this->parameters);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewBrokerInputOutput::name')->getMessage()
);
it('should throw an exception when broker output name is too long', function (): void {
new NewBrokerInputOutput('output', $this->type, str_repeat('a', BrokerInputOutput::NAME_MAX_LENGTH + 1), $this->parameters);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', BrokerInputOutput::NAME_MAX_LENGTH + 1),
BrokerInputOutput::NAME_MAX_LENGTH + 1,
BrokerInputOutput::NAME_MAX_LENGTH,
'NewBrokerInputOutput::name'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Broker/Infrastructure/API/AddBrokerInputOutput/AddBrokerInputOutputPresenterStub.php | centreon/tests/php/Core/Broker/Infrastructure/API/AddBrokerInputOutput/AddBrokerInputOutputPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Broker\Infrastructure\API\AddBrokerInputOutput;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\AddBrokerInputOutputPresenterInterface;
use Core\Broker\Application\UseCase\AddBrokerInputOutput\AddBrokerInputOutputResponse;
class AddBrokerInputOutputPresenterStub extends AbstractPresenter implements AddBrokerInputOutputPresenterInterface
{
public ResponseStatusInterface|AddBrokerInputOutputResponse $response;
public function presentResponse(ResponseStatusInterface|AddBrokerInputOutputResponse $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Broker/Infrastructure/API/UpdateStreamConnectorFile/UpdateStreamConnectorFilePresenterStub.php | centreon/tests/php/Core/Broker/Infrastructure/API/UpdateStreamConnectorFile/UpdateStreamConnectorFilePresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Broker\Infrastructure\API\UpdateStreamConnectorFile;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Broker\Application\UseCase\UpdateStreamConnectorFile\UpdateStreamConnectorFilePresenterInterface;
use Core\Broker\Application\UseCase\UpdateStreamConnectorFile\UpdateStreamConnectorFileResponse;
class UpdateStreamConnectorFilePresenterStub extends AbstractPresenter implements UpdateStreamConnectorFilePresenterInterface
{
public ResponseStatusInterface|UpdateStreamConnectorFileResponse $response;
public function presentResponse(ResponseStatusInterface|UpdateStreamConnectorFileResponse $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/ParametersValidationTest.php | centreon/tests/php/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/ParametersValidationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\PerformanceGraph\Application\Repository\ReadPerformanceGraphRepositoryInterface;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\ParametersValidation;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\ServiceGroupDto;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(closure: function (): void {
$this->readServiceTemplateRepository = $this->createMock(ReadServiceTemplateRepositoryInterface::class);
$this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class);
$this->timePeriodRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class);
$this->serviceSeverityRepository = $this->createMock(ReadServiceSeverityRepositoryInterface::class);
$this->performanceGraphRepository = $this->createMock(ReadPerformanceGraphRepositoryInterface::class);
$this->imageRepository = $this->createMock(ReadViewImgRepositoryInterface::class);
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class);
$this->readServiceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class);
$this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->parametersValidation = new ParametersValidation(
$this->readServiceTemplateRepository,
$this->readCommandRepository,
$this->timePeriodRepository,
$this->serviceSeverityRepository,
$this->performanceGraphRepository,
$this->imageRepository,
$this->readHostTemplateRepository,
$this->readServiceCategoryRepository,
$this->readServiceGroupRepository
);
});
it('should raise an exception when the new name already exist', function (): void {
$this->readServiceTemplateRepository
->expects($this->once())
->method('existsByName')
->with('new_name')
->willReturn(true);
$this->parametersValidation->assertIsValidName('old_name', 'new_name');
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::nameAlreadyExists('new_name')->getMessage()
);
it('should raise an exception when the service template ID does not exist', function (): void {
$this->readServiceTemplateRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->parametersValidation->assertIsValidServiceTemplate(1, 2);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('service_template_id', 2)->getMessage()
);
it('should raise an exception when the service template is its own parent', function (): void {
$this->parametersValidation->assertIsValidServiceTemplate(1, 1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::circularTemplateInheritance()->getMessage()
);
it('should raise an exception when the service template has circular inheritance', function (): void {
$this->readServiceTemplateRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readServiceTemplateRepository
->expects($this->once())
->method('findParents')
->willReturn([new ServiceTemplateInheritance(1, 2)]);
$this->parametersValidation->assertIsValidServiceTemplate(1, 2);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::circularTemplateInheritance()->getMessage()
);
it('should raise an exception when the command ID does not exist', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('existsByIdAndCommandType')
->with(1, CommandType::Check)
->willReturn(false);
$this->parametersValidation->assertIsValidCommand(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('check_command_id', 1)->getMessage()
);
it('should raise an exception when the event handler ID does not exist', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('exists')
->with(1)
->willReturn(false);
$this->parametersValidation->assertIsValidEventHandler(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('event_handler_command_id', 1)->getMessage()
);
it('should raise an exception when the time period ID does not exist', function (): void {
$this->timePeriodRepository
->expects($this->once())
->method('exists')
->with(1)
->willReturn(false);
$this->parametersValidation->assertIsValidTimePeriod(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('check_timeperiod_id', 1)->getMessage()
);
it('should raise an exception when the severity ID does not exist', function (): void {
$this->serviceSeverityRepository
->expects($this->once())
->method('exists')
->with(1)
->willReturn(false);
$this->parametersValidation->assertIsValidSeverity(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('severity_id', 1)->getMessage()
);
it('should raise an exception when the notification time period ID does not exist', function (): void {
$this->timePeriodRepository
->expects($this->once())
->method('exists')
->with(1)
->willReturn(false);
$this->parametersValidation->assertIsValidNotificationTimePeriod(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('notification_timeperiod_id', 1)->getMessage()
);
it('should raise an exception when the icon ID does not exist', function (): void {
$this->imageRepository
->expects($this->once())
->method('existsOne')
->with(1)
->willReturn(false);
$this->parametersValidation->assertIsValidIcon(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('icon_id', 1)->getMessage()
);
it('should raise an exception when the host templates IDs does not exist', function (): void {
$this->readHostTemplateRepository
->expects($this->once())
->method('findAllExistingIds')
->with([1, 2])
->willReturn([2]);
$this->parametersValidation->assertHostTemplateIds([1, 2]);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('host_templates', [1])->getMessage()
);
it('should raise an exception when the service category IDs do not exist, as an administrator', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceCategoryRepository
->expects($this->once())
->method('findAllExistingIds')
->with([1, 2])
->willReturn([2]);
$this->parametersValidation->assertServiceCategories([1, 2], $this->contact, []);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('service_categories', [1])->getMessage()
);
it('should raise an exception when the service category IDs do not exist, as a non-administrator', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readServiceCategoryRepository
->expects($this->once())
->method('findAllExistingIdsByAccessGroups')
->with([1, 2], [3])
->willReturn([2]);
$this->parametersValidation->assertServiceCategories([1, 2], $this->contact, [3]);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('service_categories', [1])->getMessage()
);
it('should raise an exception when the service groups IDs do not exist, as an administrator', function (): void {
$serviceTemplateId = 1;
$serviceGroupDtos = [
new ServiceGroupDto(1, 1),
new ServiceGroupDto(2, 2),
new ServiceGroupDto(3, 3),
];
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('exist')
->with([1, 2, 3])
->willReturn([2]);
$this->parametersValidation->assertServiceGroups(
$serviceGroupDtos,
$serviceTemplateId,
$this->contact,
[]
);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('service_groups', [1, 3])->getMessage()
);
it('should raise an exception when the service groups IDs do not exist, as a non-administrator', function (): void {
$serviceTemplateId = 1;
$serviceGroupDtos = [
new ServiceGroupDto(1, 1),
new ServiceGroupDto(2, 2),
new ServiceGroupDto(3, 3),
];
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readServiceGroupRepository
->expects($this->once())
->method('existByAccessGroups')
->willReturn([2]);
$this->parametersValidation->assertServiceGroups(
$serviceGroupDtos,
$serviceTemplateId,
$this->contact,
[]
);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('service_groups', [1, 3])->getMessage()
);
it(
'should raise an exception when the host template IDs are not linked to service template, as a non-administrator',
function (): void {
$serviceTemplateId = 1;
$serviceGroupDtos = [
new ServiceGroupDto(4, 1),
new ServiceGroupDto(5, 1),
new ServiceGroupDto(6, 1),
];
$serviceTemplate = $this->createMock(ServiceTemplate::class);
$serviceTemplate
->expects($this->once())
->method('getHostTemplateIds')
->willReturn([4, 5]);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readServiceGroupRepository
->expects($this->once())
->method('existByAccessGroups')
->willReturn([1]);
$this->readServiceTemplateRepository
->expects($this->once())
->method('findById')
->with($serviceTemplateId)
->willReturn($serviceTemplate);
$this->parametersValidation->assertServiceGroups(
$serviceGroupDtos,
$serviceTemplateId,
$this->contact,
[]
);
}
)->throws(
ServiceTemplateException::class,
ServiceTemplateException::invalidServiceGroupAssociation()->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/PartialUpdateServiceTemplateTest.php | centreon/tests/php/Core/ServiceTemplate/Application/UseCase/PartialUpdateServiceTemplate/PartialUpdateServiceTemplateTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Option\OptionService;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Domain\YesNoDefault;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Domain\Model\ServiceCategory;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\WriteServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\MacroDto;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\ParametersValidation;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\PartialUpdateServiceTemplate;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\PartialUpdateServiceTemplateRequest;
use Core\ServiceTemplate\Application\UseCase\PartialUpdateServiceTemplate\ServiceGroupDto;
use Core\ServiceTemplate\Domain\Model\NotificationType;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
use Core\ServiceTemplate\Infrastructure\Model\NotificationTypeConverter;
use Core\ServiceTemplate\Infrastructure\Model\YesNoDefaultConverter;
use Exception;
beforeEach(closure: function (): void {
$this->presenter = new DefaultPresenter(
$this->createMock(PresenterFormatterInterface::class)
);
$this->useCase = new PartialUpdateServiceTemplate(
$this->writeServiceTemplateRepository = $this->createMock(WriteServiceTemplateRepositoryInterface::class),
$this->readServiceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class),
$this->writeServiceCategoryRepository = $this->createMock(WriteServiceCategoryRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readServiceTemplateRepository = $this->createMock(ReadServiceTemplateRepositoryInterface::class),
$this->readServiceMacroRepository = $this->createMock(ReadServiceMacroRepositoryInterface::class),
$this->writeServiceMacroRepository = $this->createMock(WriteServiceMacroRepositoryInterface::class),
$this->readCommandMacroRepository = $this->createMock(ReadCommandMacroRepositoryInterface::class),
$this->writeServiceGroupRepository = $this->createMock(WriteServiceGroupRepositoryInterface::class),
$this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class),
$this->validation = $this->createMock(ParametersValidation::class),
$this->user = $this->createMock(ContactInterface::class),
$this->storageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->optionService = $this->createMock(OptionService::class),
$this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class),
$this->readVaultRepository = $this->createMock(ReadVaultRepositoryInterface::class),
);
});
it('should present a ForbiddenResponse when the user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, false],
]
);
($this->useCase)(new PartialUpdateServiceTemplateRequest(1), $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceTemplateException::updateNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the service template does not exist', function (): void {
$request = new PartialUpdateServiceTemplateRequest(1);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$accessGroups = [2];
$this->readAccessGroupRepository
->expects($this->any())
->method('findByContact')
->with($this->user)
->willReturn($accessGroups);
$this->readServiceTemplateRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->with($request->id)
->willReturn(null);
($this->useCase)($request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe((new NotFoundResponse('Service template'))->getMessage());
});
it('should present a ConflictResponse when a host template does not exist', function (): void {
$request = new PartialUpdateServiceTemplateRequest(1);
$request->hostTemplates = [1, 8];
$accessGroups = [9, 11];
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->with($this->user)
->willReturn($accessGroups);
$this->readServiceTemplateRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->with($request->id)
->willReturn(new ServiceTemplate(1, 'fake_name', 'fake_alias'));
$exception = ServiceTemplateException::idsDoNotExist('host_templates', [$request->hostTemplates[1]]);
$this->validation
->expects($this->once())
->method('assertHostTemplateIds')
->with($request->hostTemplates)
->willThrowException($exception);
($this->useCase)($request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceTemplateException::idsDoNotExist('host_templates', [$request->hostTemplates[1]])->getMessage());
});
it('should present an ErrorResponse when an error occurs during host templates unlink', function (): void {
$request = new PartialUpdateServiceTemplateRequest(1);
$request->hostTemplates = [1, 8];
$accessGroups = [9, 11];
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->with($this->user)
->willReturn($accessGroups);
$this->readServiceTemplateRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->with($request->id)
->willReturn(new ServiceTemplate(1, 'fake_name', 'fake_alias'));
$this->validation
->expects($this->once())
->method('assertHostTemplateIds')
->with($request->hostTemplates);
$this->writeServiceTemplateRepository
->expects($this->once())
->method('unlinkHosts')
->with($request->id)
->willThrowException(new Exception());
($this->useCase)($request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceTemplateException::errorWhileUpdating()->getMessage());
});
it('should present a ErrorResponse when an error occurs during host templates link', function (): void {
$request = new PartialUpdateServiceTemplateRequest(1);
$request->hostTemplates = [1, 8];
$accessGroups = [9, 11];
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->with($this->user)
->willReturn($accessGroups);
$this->readServiceTemplateRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->with($request->id)
->willReturn(new ServiceTemplate(1, 'fake_name', 'fake_alias'));
$this->validation
->expects($this->once())
->method('assertHostTemplateIds')
->with($request->hostTemplates);
$this->writeServiceTemplateRepository
->expects($this->once())
->method('unlinkHosts')
->with($request->id);
$this->writeServiceTemplateRepository
->expects($this->once())
->method('linkToHosts')
->with($request->id, $request->hostTemplates)
->willThrowException(new Exception());
($this->useCase)($request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceTemplateException::errorWhileUpdating()->getMessage());
});
it('should present a ErrorResponse when an error occurs during service groups link', function (): void {
$request = new PartialUpdateServiceTemplateRequest(1);
$request->serviceGroups = [new ServiceGroupDto(1, 2)];
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$this->readServiceTemplateRepository
->expects($this->once())
->method('findById')
->with($request->id)
->willReturn(new ServiceTemplate(1, 'fake_name', 'fake_alias'));
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('findByService')
->willThrowException(new Exception());
($this->useCase)($request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceTemplateException::errorWhileUpdating()->getMessage());
});
it('should present a NoContentResponse when everything has gone well for an admin user', function (): void {
$request = new PartialUpdateServiceTemplateRequest(20);
$request->name = 'fake_name2';
$request->alias = 'fake_alias2';
$request->commandArguments = ['A'];
$request->eventHandlerArguments = ['B'];
$notificationTypes = [NotificationType::DowntimeScheduled, NotificationType::Flapping];
$request->notificationTypes = NotificationTypeConverter::toBits($notificationTypes);
$request->isContactAdditiveInheritance = true;
$request->isContactGroupAdditiveInheritance = true;
$request->activeChecksEnabled = YesNoDefaultConverter::toInt(YesNoDefault::No);
$request->passiveCheckEnabled = YesNoDefaultConverter::toInt(YesNoDefault::Yes);
$request->volatility = YesNoDefaultConverter::toInt(YesNoDefault::No);
$request->checkFreshness = YesNoDefaultConverter::toInt(YesNoDefault::Yes);
$request->eventHandlerEnabled = YesNoDefaultConverter::toInt(YesNoDefault::No);
$request->flapDetectionEnabled = YesNoDefaultConverter::toInt(YesNoDefault::Yes);
$request->notificationsEnabled = YesNoDefaultConverter::toInt(YesNoDefault::No);
$request->comment = 'new comment';
$request->note = 'new note';
$request->noteUrl = 'new note url';
$request->actionUrl = 'new action url';
$request->iconAlternativeText = 'icon alternative text';
$request->graphTemplateId = 100;
$request->serviceTemplateParentId = 101;
$request->commandId = 102;
$request->eventHandlerId = 103;
$request->notificationTimePeriodId = 104;
$request->checkTimePeriodId = 105;
$request->iconId = 106;
$request->severityId = 107;
$request->maxCheckAttempts = 108;
$request->normalCheckInterval = 109;
$request->retryCheckInterval = 110;
$request->freshnessThreshold = 111;
$request->lowFlapThreshold = 48;
$request->highFlapThreshold = 52;
$request->notificationInterval = 112;
$request->recoveryNotificationDelay = 113;
$request->firstNotificationDelay = 114;
$request->acknowledgementTimeout = 115;
$request->hostTemplates = [1, 8];
$request->serviceCategories = [2, 3];
$request->macros = [
new MacroDto('MACROA', 'A', false, null),
new MacroDto('MACROB', 'B1', false, null),
];
$serviceTemplate = new ServiceTemplate(
id: $request->id,
name: 'fake_name',
alias: 'fake_alias',
commandId: 99,
);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$this->readServiceTemplateRepository
->expects($this->once())
->method('findById')
->with($request->id)
->willReturn($serviceTemplate);
$this->writeServiceTemplateRepository
->expects($this->once())
->method('unlinkHosts')
->with($request->id);
$this->writeServiceTemplateRepository
->expects($this->once())
->method('linkToHosts')
->with($request->id, $request->hostTemplates);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readServiceCategoryRepository
->expects($this->once())
->method('findByService')
->with($request->id)
->willReturn(
array_map(
fn (int $id): ServiceCategory => new ServiceCategory($id, 'name', 'alias'),
$request->serviceCategories
)
);
$this->writeServiceCategoryRepository
->expects($this->once())
->method('unlinkFromService')
->with($request->id, []);
$this->writeServiceCategoryRepository
->expects($this->once())
->method('linkToService')
->with($request->id, []);
$serviceTemplateInheritances = [
new ServiceTemplateInheritance(9, $serviceTemplate->getId()),
new ServiceTemplateInheritance(8, 9),
new ServiceTemplateInheritance(1, 8),
];
$this->readServiceTemplateRepository
->expects($this->once())
->method('findParents')
->willReturn($serviceTemplateInheritances);
$macroA = new Macro(null, $serviceTemplate->getId(), 'MACROA', 'A');
$macroA->setDescription('');
$macroB = new Macro(null, $serviceTemplate->getId(), 'MACROB', 'B');
$macroB->setDescription('');
$this->readServiceMacroRepository
->expects($this->once())
->method('findByServiceIds')
->with($serviceTemplate->getId(), 9, 8, 1)
->willReturn([$macroA, $macroB]);
$this->readCommandMacroRepository
->expects($this->once())
->method('findByCommandIdAndType')
->with($request->commandId, CommandMacroType::Service)
->willReturn([]);
$this->writeServiceMacroRepository
->expects($this->once())
->method('update')
->with(new Macro(null, $serviceTemplate->getId(), 'MACROB', 'B1'));
$this->writeServiceMacroRepository
->expects($this->never())
->method('add');
$this->writeServiceMacroRepository
->expects($this->never())
->method('delete');
$this->validation
->expects($this->once())
->method('assertIsValidName')
->with($serviceTemplate->getName(), $request->name);
$this->validation
->expects($this->once())
->method('assertIsValidPerformanceGraph')
->with($request->graphTemplateId);
$this->validation
->expects($this->once())
->method('assertIsValidServiceTemplate');
$this->validation
->expects($this->once())
->method('assertIsValidCommand')
->with($request->commandId);
$this->validation
->expects($this->once())
->method('assertIsValidEventHandler')
->with($request->eventHandlerId);
$this->validation
->expects($this->once())
->method('assertIsValidNotificationTimePeriod')
->with($request->notificationTimePeriodId);
$this->validation
->expects($this->once())
->method('assertIsValidTimePeriod')
->with($request->checkTimePeriodId);
$this->validation
->expects($this->once())
->method('assertIsValidIcon')
->with($request->iconId);
$this->validation
->expects($this->once())
->method('assertIsValidSeverity')
->with($request->severityId);
$this->validation
->expects($this->once())
->method('assertHostTemplateIds')
->with($request->hostTemplates);
$this->validation
->expects($this->once())
->method('assertServiceCategories')
->with($request->serviceCategories, $this->user, []);
$this->writeServiceTemplateRepository
->expects($this->once())
->method('update');
($this->useCase)($request, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
it('should present a NoContentResponse when everything has gone well for a non-admin user', function (): void {
$request = new PartialUpdateServiceTemplateRequest(1);
$request->hostTemplates = [1, 8];
$request->serviceCategories = [2, 3];
$accessGroups = [9, 11];
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$serviceTemplate = new ServiceTemplate(1, 'fake_name', 'fake_alias');
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->with($this->user)
->willReturn($accessGroups);
$this->readServiceTemplateRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->with($request->id, $accessGroups)
->willReturn($serviceTemplate);
$this->writeServiceTemplateRepository
->expects($this->once())
->method('unlinkHosts')
->with($request->id);
$this->writeServiceTemplateRepository
->expects($this->once())
->method('linkToHosts')
->with($request->id, $request->hostTemplates);
$this->readServiceCategoryRepository
->expects($this->once())
->method('findByServiceAndAccessGroups')
->with($request->id, $accessGroups)
->willReturn(
array_map(
fn (int $id): ServiceCategory => new ServiceCategory($id, 'name', 'alias'),
$request->serviceCategories
)
);
$this->writeServiceCategoryRepository
->expects($this->once())
->method('unlinkFromService')
->with($request->id, []);
$this->writeServiceCategoryRepository
->expects($this->once())
->method('linkToService')
->with($request->id, []);
$this->validation
->expects($this->once())
->method('assertHostTemplateIds')
->with($request->hostTemplates);
$this->validation
->expects($this->once())
->method('assertServiceCategories')
->with($request->serviceCategories, $this->user, $accessGroups);
($this->useCase)($request, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateValidationTest.php | centreon/tests/php/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateValidationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\PerformanceGraph\Application\Repository\ReadPerformanceGraphRepositoryInterface;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplateValidation;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\ServiceGroupDto;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(function (): void {
$this->validation = new AddServiceTemplateValidation(
$this->readServiceTemplateRepository = $this->createMock(ReadServiceTemplateRepositoryInterface::class),
$this->serviceSeverityRepository = $this->createMock(ReadServiceSeverityRepositoryInterface::class),
$this->performanceGraphRepository = $this->createMock(ReadPerformanceGraphRepositoryInterface::class),
$this->commandRepository = $this->createMock(ReadCommandRepositoryInterface::class),
$this->timePeriodRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class),
$this->imageRepository = $this->createMock(ReadViewImgRepositoryInterface::class),
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class),
$this->readServiceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class),
$this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
$this->accessGroups = []
);
$this->serviceGroups = [
new ServiceGroupDto(
serviceGroupId: 1,
hostTemplateId: 3,
),
new ServiceGroupDto(
serviceGroupId: 2,
hostTemplateId: 3,
),
];
});
it('throws an exception when parent template ID does not exist', function (): void {
$this->readServiceTemplateRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidServiceTemplate(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('service_template_id', 1)->getMessage()
);
it('throws an exception when command ID does not exist', function (): void {
$this->commandRepository
->expects($this->once())
->method('existsByIdAndCommandType')
->willReturn(false);
$this->validation->assertIsValidCommand(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('check_command_id', 1)->getMessage()
);
it('throws an exception when event handler ID does not exist', function (): void {
$this->commandRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidEventHandler(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('event_handler_command_id', 1)->getMessage()
);
it('throws an exception when check time period ID does not exist', function (): void {
$this->timePeriodRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidTimePeriod(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('check_timeperiod_id', 1)->getMessage()
);
it('throws an exception when icon ID does not exist', function (): void {
$this->imageRepository
->expects($this->once())
->method('existsOne')
->willReturn(false);
$this->validation->assertIsValidIcon(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('icon_id', 1)->getMessage()
);
it('throws an exception when notification time period ID does not exist', function (): void {
$this->timePeriodRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidNotificationTimePeriod(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('notification_timeperiod_id', 1)->getMessage()
);
it('throws an exception when severity ID does not exist', function (): void {
$this->serviceSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidSeverity(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('severity_id', 1)->getMessage()
);
it('throws an exception when performance graph ID does not exist', function (): void {
$this->performanceGraphRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidPerformanceGraph(1);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idDoesNotExist('graph_template_id', 1)->getMessage()
);
it('throws an exception when host template ID does not exist', function (): void {
$this->readHostTemplateRepository
->expects($this->once())
->method('findAllExistingIds')
->willReturn([]);
$this->validation->assertIsValidHostTemplates([1, 3], 4);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('host_templates', [1, 3])->getMessage()
);
it('throws an exception when category ID does not exist with admin user', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceCategoryRepository
->expects($this->once())
->method('findAllExistingIds')
->willReturn([]);
$this->validation->assertIsValidServiceCategories([1, 3]);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('service_categories', [1, 3])->getMessage()
);
it('throws an exception when category ID does not exist with non-admin user', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readServiceCategoryRepository
->expects($this->once())
->method('findAllExistingIdsByAccessGroups')
->willReturn([]);
$this->validation->assertIsValidServiceCategories([1, 3]);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('service_categories', [1, 3])->getMessage()
);
it('throws an exception when group ID does not exist with admin user', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceGroupRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertIsValidServiceGroups($this->serviceGroups, [3]);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('service_groups', [1, 2])->getMessage()
);
it('throws an exception when group ID does not exist with non-admin user', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readServiceGroupRepository
->expects($this->once())
->method('existByAccessGroups')
->willReturn([]);
$this->validation->assertIsValidServiceGroups($this->serviceGroups, [3]);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::idsDoNotExist('service_groups', [1, 2])->getMessage()
);
it('throws an exception when host template used in service group associations are not linked to service template', function (): void {
$this->validation->assertIsValidServiceGroups($this->serviceGroups, []);
})->throws(
ServiceTemplateException::class,
ServiceTemplateException::invalidServiceGroupAssociation()->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/Mock.php | centreon/tests/php/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/Mock.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Option\OptionService;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface;
use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface;
use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\WriteServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplate;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplateValidation;
use PHPUnit\Framework\TestCase;
use Tests\Core\ServiceTemplate\Infrastructure\API\AddServiceTemplate\AddServiceTemplatePresenterStub;
class Mock extends TestCase
{
public static function create(TestCase $testCase): void
{
$testCase->useCasePresenter = new AddServiceTemplatePresenterStub(
$testCase->createMock(PresenterFormatterInterface::class)
);
$testCase->addUseCase = new AddServiceTemplate(
$testCase->readHostTemplateRepository = $testCase->createMock(ReadHostTemplateRepositoryInterface::class),
$testCase->readServiceTemplateRepository = $testCase->createMock(ReadServiceTemplateRepositoryInterface::class),
$testCase->writeServiceTemplateRepository = $testCase->createMock(WriteServiceTemplateRepositoryInterface::class),
$testCase->readServiceMacroRepository = $testCase->createMock(ReadServiceMacroRepositoryInterface::class),
$testCase->readCommandMacroRepository = $testCase->createMock(ReadCommandMacroRepositoryInterface::class),
$testCase->writeServiceMacroRepository = $testCase->createMock(WriteServiceMacroRepositoryInterface::class),
$testCase->storageEngine = $testCase->createMock(DataStorageEngineInterface::class),
$testCase->readServiceCategoryRepository = $testCase->createMock(ReadServiceCategoryRepositoryInterface::class),
$testCase->writeServiceCategoryRepository = $testCase->createMock(WriteServiceCategoryRepositoryInterface::class),
$testCase->readServiceGroupRepository = $testCase->createMock(ReadServiceGroupRepositoryInterface::class),
$testCase->writeServiceGroupRepository = $testCase->createMock(WriteServiceGroupRepositoryInterface::class),
$testCase->readAccessGroupRepository = $testCase->createMock(ReadAccessGroupRepositoryInterface::class),
$testCase->validation = $testCase->createMock(AddServiceTemplateValidation::class),
$testCase->optionService = $testCase->createMock(OptionService::class),
$testCase->user = $testCase->createMock(ContactInterface::class),
$testCase->writeVaultRepository = $testCase->createMock(WriteVaultRepositoryInterface::class),
$testCase->readVaultRepository = $testCase->createMock(ReadVaultRepositoryInterface::class),
);
}
/**
* @param TestCase $testCase
* @param array<string, array<array{method: string, arguments: mixed, expected: mixed}>> $mockOptions
*/
public static function setMock(TestCase $testCase, array $mockOptions): void
{
foreach ($mockOptions as $mockName => $options) {
foreach ($options as $option) {
switch ($mockName) {
case 'user':
$testCase->user
->expects($testCase->once())
->method('hasTopologyRole')
->willReturnMap($option['expected']);
break;
case 'readServiceTemplateRepository':
$testCase->readServiceTemplateRepository
->expects($testCase->once())
->method($option['method'])
->with($option['arguments'])
->willReturn($option['expected']);
break;
case 'serviceSeverityRepository':
$testCase->serviceSeverityRepository
->expects($testCase->once())
->method('exists')
->with($option['arguments'])
->willReturn($option['expected']);
break;
case 'performanceGraphRepository':
$testCase->performanceGraphRepository
->expects($testCase->once())
->method('exists')
->with($option['arguments'])
->willReturn($option['expected']);
break;
case 'commandRepository':
$testCase->commandRepository
->expects($testCase->once())
->method($option['method'])
->with($option['arguments'])
->willReturn($option['expected']);
break;
case 'timePeriodRepository':
$testCase->timePeriodRepository
->expects($testCase->exactly(count($option['expected'])))
->method('exists')
->will($testCase->returnValueMap($option['expected']));
break;
case 'imageRepository':
$testCase->imageRepository
->expects($testCase->once())
->method('existsOne')
->with($option['arguments'])
->willReturn($option['expected']);
break;
case 'writeServiceTemplateRepository':
$testCase->writeServiceTemplateRepository
->expects($testCase->once())
->method('add')
->willReturn($option['expected']);
break;
case 'readServiceMacroRepository':
$testCase->readServiceMacroRepository
->expects($testCase->exactly(count($option['expected'])))
->method($option['method'])
->will($testCase->returnValueMap($option['expected']));
break;
case 'readCommandMacroRepository':
$testCase->readCommandMacroRepository
->expects($testCase->once())
->method($option['method'])
->with(...$option['arguments'])
->willReturn($option['expected']);
break;
case 'writeServiceMacroRepository':
$testCase->writeServiceMacroRepository
->expects($testCase->exactly(count($option['expected'])))
->method($option['method'])
->will($testCase->returnValueMap($option['expected']));
break;
case 'writeServiceGroupRepository':
$testCase->writeServiceGroupRepository
->expects($testCase->exactly(count($option['expected'])))
->method($option['method'])
->will($testCase->returnValueMap($option['expected']));
break;
case 'readServiceGroupRepository':
$testCase->readServiceGroupRepository
->expects($testCase->exactly(count($option['expected'])))
->method($option['method'])
->will($testCase->returnValueMap($option['expected']));
break;
case 'readHostTemplateRepository':
$testCase->readHostTemplateRepository
->expects($testCase->exactly(count($option['expected'])))
->method($option['method'])
->will($testCase->returnValueMap($option['expected']));
break;
}
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateTest.php | centreon/tests/php/Core/ServiceTemplate/Application/UseCase/AddServiceTemplate/AddServiceTemplateTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Application\UseCase\AddServiceTemplate;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Contact;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Domain\YesNoDefault;
use Core\Macro\Domain\Model\Macro;
use Core\ServiceGroup\Domain\Model\ServiceGroup;
use Core\ServiceGroup\Domain\Model\ServiceGroupRelation;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplateRequest;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplateResponse;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\MacroDto;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\ServiceGroupDto;
use Core\ServiceTemplate\Domain\Model\NotificationType;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
beforeEach(closure: function (): void {
Mock::create($this);
});
function createAddServiceTemplateRequest(): AddServiceTemplateRequest
{
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->alias = 'fake_alias';
$request->comment = null;
$request->note = null;
$request->noteUrl = null;
$request->actionUrl = null;
$request->iconAlternativeText = null;
$request->graphTemplateId = null;
$request->serviceTemplateParentId = null;
$request->commandId = null;
$request->eventHandlerId = null;
$request->notificationTimePeriodId = null;
$request->checkTimePeriodId = null;
$request->iconId = null;
$request->severityId = null;
$request->maxCheckAttempts = null;
$request->normalCheckInterval = null;
$request->retryCheckInterval = null;
$request->freshnessThreshold = null;
$request->lowFlapThreshold = null;
$request->highFlapThreshold = null;
$request->notificationInterval = null;
$request->recoveryNotificationDelay = null;
$request->firstNotificationDelay = null;
$request->acknowledgementTimeout = null;
$request->hostTemplateIds = [];
$request->serviceCategories = [];
$request->serviceGroups = [];
return $request;
}
it('should present a ForbiddenResponse when the user has insufficient rights', function (): void {
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, false]],
]],
]);
($this->addUseCase)(new AddServiceTemplateRequest(), $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(ServiceTemplateException::addNotAllowed()->getMessage());
});
it('should present an ErrorResponse when the service template name already exists', function (): void {
$name = 'fake_name';
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $name,
'expected' => true,
],
],
]);
$this->readServiceTemplateRepository
->expects($this->once())
->method('existsByName')
->with($name)
->willReturn(true);
$request = new AddServiceTemplateRequest();
$request->name = $name;
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(ServiceTemplateException::nameAlreadyExists($name)->getMessage());
});
it('should present a ConflictResponse when the severity ID is not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->severityId = 1;
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidSeverity')
->willThrowException(ServiceTemplateException::idDoesNotExist('severity_id', $request->severityId));
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(ServiceTemplateException::idDoesNotExist('severity_id', $request->severityId)->getMessage());
});
it('should present a ConflictResponse when the performance graph ID is not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->severityId = 1;
$request->graphTemplateId = 1;
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidPerformanceGraph')
->willThrowException(ServiceTemplateException::idDoesNotExist('graph_template_id', $request->severityId));
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(ServiceTemplateException::idDoesNotExist('graph_template_id', $request->severityId)->getMessage());
});
it('should present a ConflictResponse when the service template ID is not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidServiceTemplate')
->willThrowException(ServiceTemplateException::idDoesNotExist('service_template_id', $request->severityId));
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(ServiceTemplateException::idDoesNotExist('service_template_id', $request->severityId)->getMessage());
});
it('should present a ConflictResponse when the command ID is not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidCommand')
->willThrowException(ServiceTemplateException::idDoesNotExist('check_command_id', $request->severityId));
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(ServiceTemplateException::idDoesNotExist('check_command_id', $request->severityId)->getMessage());
});
it('should present a ConflictResponse when the event handler ID is not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
$request->eventHandlerId = 12;
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidCommand')
->willThrowException(
ServiceTemplateException::idDoesNotExist(
'event_handler_command_id',
$request->eventHandlerId
)
);
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(
ServiceTemplateException::idDoesNotExist(
'event_handler_command_id',
$request->eventHandlerId
)->getMessage()
);
});
it('should present a ConflictResponse when the time period ID is not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
$request->eventHandlerId = 12;
$request->checkTimePeriodId = 13;
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidTimePeriod')
->willThrowException(
ServiceTemplateException::idDoesNotExist(
'check_timeperiod_id',
$request->checkTimePeriodId
)
);
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(
ServiceTemplateException::idDoesNotExist(
'check_timeperiod_id',
$request->checkTimePeriodId
)->getMessage()
);
});
it('should present a ConflictResponse when the notification time period ID is not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
$request->eventHandlerId = 12;
$request->checkTimePeriodId = 13;
$request->notificationTimePeriodId = 14;
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidNotificationTimePeriod')
->willThrowException(
ServiceTemplateException::idDoesNotExist(
'notification_timeperiod_id',
$request->notificationTimePeriodId
)
);
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(
ServiceTemplateException::idDoesNotExist(
'notification_timeperiod_id',
$request->notificationTimePeriodId
)->getMessage()
);
});
it('should present a ConflictResponse when the icon ID is not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
$request->eventHandlerId = 12;
$request->checkTimePeriodId = 13;
$request->notificationTimePeriodId = 14;
$request->iconId = 15;
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidIcon')
->willThrowException(
ServiceTemplateException::idDoesNotExist(
'icon_id',
$request->iconId
)
);
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(
ServiceTemplateException::idDoesNotExist(
'icon_id',
$request->iconId
)->getMessage()
);
});
it('should present a ConflictResponse when the host template IDs are not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->alias = 'fake_alias';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
$request->eventHandlerId = 12;
$request->checkTimePeriodId = 13;
$request->notificationTimePeriodId = 14;
$request->iconId = 15;
$request->hostTemplateIds = [2, 3];
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidHostTemplates')
->willThrowException(
ServiceTemplateException::idsDoNotExist(
'host_templates',
[$request->hostTemplateIds[1]]
)
);
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(
ServiceTemplateException::idsDoNotExist(
'host_templates',
[$request->hostTemplateIds[1]]
)->getMessage()
);
});
it('should present a ConflictResponse when the service category IDs are not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->alias = 'fake_alias';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
$request->eventHandlerId = 12;
$request->checkTimePeriodId = 13;
$request->notificationTimePeriodId = 14;
$request->iconId = 15;
$request->serviceCategories = [2, 3];
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidServiceCategories')
->willThrowException(
ServiceTemplateException::idsDoNotExist(
'service_categories',
[$request->serviceCategories[1]]
)
);
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(
ServiceTemplateException::idsDoNotExist(
'service_categories',
[$request->serviceCategories[1]]
)->getMessage()
);
});
it('should present a ConflictResponse when the service group IDs are not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->alias = 'fake_alias';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
$request->eventHandlerId = 12;
$request->checkTimePeriodId = 13;
$request->notificationTimePeriodId = 14;
$request->iconId = 15;
$request->hostTemplateIds = [4];
$request->serviceGroups = [2, 3];
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidServiceGroups')
->willThrowException(
ServiceTemplateException::idsDoNotExist(
'service_groups',
[$request->serviceGroups[1]]
)
);
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(
ServiceTemplateException::idsDoNotExist(
'service_groups',
[$request->serviceGroups[1]]
)->getMessage()
);
});
it('should present a ConflictResponse when trying to set service group IDs without host template IDs', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->alias = 'fake_alias';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
$request->eventHandlerId = 12;
$request->checkTimePeriodId = 13;
$request->notificationTimePeriodId = 14;
$request->iconId = 15;
$request->hostTemplateIds = [];
$request->serviceGroups = [2, 3];
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
$this->validation
->expects($this->once())
->method('assertIsValidServiceGroups')
->willThrowException(ServiceTemplateException::invalidServiceGroupAssociation());
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(
ServiceTemplateException::invalidServiceGroupAssociation()->getMessage()
);
});
it('should present an InvalidArgumentResponse when data are not valid', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 1;
$request->commandId = 1;
$request->eventHandlerId = 12;
$request->checkTimePeriodId = 13;
$request->notificationTimePeriodId = 14;
$request->iconId = 15;
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
],
]);
// An error will be raised because the alias is empty
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(AssertionException::notEmptyString('NewServiceTemplate::alias')->getMessage());
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$request = createAddServiceTemplateRequest();
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$this->writeServiceTemplateRepository
->expects($this->once())
->method('add')
->willThrowException(new \Exception());
($this->addUseCase)($request, $this->useCasePresenter);
expect($this->useCasePresenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->useCasePresenter->response->getMessage())
->toBe(ServiceTemplateException::errorWhileAdding(new \Exception())->getMessage());
});
it('should present an AddServiceTemplateResponse when everything has gone well', function (): void {
$request = new AddServiceTemplateRequest();
$request->name = 'fake_name';
$request->alias = 'fake_alias';
$request->severityId = 1;
$request->graphTemplateId = 1;
$request->serviceTemplateParentId = 10;
$request->commandId = 1;
$request->eventHandlerId = 12;
$request->checkTimePeriodId = 13;
$request->notificationTimePeriodId = 14;
$request->iconId = 15;
$request->macros = [
new MacroDto('MACROA', 'A', false, null),
new MacroDto('MACROB', 'B', false, null),
];
$request->serviceGroups = [
new ServiceGroupDto(2, 1),
];
$newServiceTemplateId = 99;
$serviceTemplateInheritances = [
new ServiceTemplateInheritance(9, 99),
new ServiceTemplateInheritance(8, 9),
new ServiceTemplateInheritance(1, 8),
];
$macroA = new Macro(null, $newServiceTemplateId, 'MACROA', 'A');
$macroA->setDescription('');
$macroB = new Macro(null, $newServiceTemplateId, 'MACROB', 'B');
$macroB->setDescription('');
$serviceGroup = new ServiceGroup(1, 'SG-name', 'SG-alias', null, '', true);
$serviceGroupRelation = new ServiceGroupRelation(
serviceGroupId: $serviceGroup->getId(),
serviceId: $newServiceTemplateId,
hostId: 2
);
$hostTemplateName = 'HostTemplateName';
$this->serviceTemplateFound = new ServiceTemplate(
id: $newServiceTemplateId,
name: $request->name,
alias: $request->alias,
commandArguments: ['a', 'b'],
eventHandlerArguments: ['c', 'd'],
notificationTypes: [NotificationType::Unknown],
hostTemplateIds: [2, 3],
contactAdditiveInheritance: true,
contactGroupAdditiveInheritance: true,
isLocked: true,
activeChecks: YesNoDefault::Yes,
passiveCheck: YesNoDefault::No,
volatility: YesNoDefault::Default,
checkFreshness: YesNoDefault::Yes,
eventHandlerEnabled: YesNoDefault::No,
flapDetectionEnabled: YesNoDefault::Default,
notificationsEnabled: YesNoDefault::Yes,
comment: 'comment',
note: 'note',
noteUrl: 'note_url',
actionUrl: 'action_url',
iconAlternativeText: 'icon_aternative_text',
graphTemplateId: $request->graphTemplateId,
serviceTemplateParentId: $request->serviceTemplateParentId,
commandId: $request->commandId,
eventHandlerId: $request->eventHandlerId,
notificationTimePeriodId: 6,
checkTimePeriodId: $request->checkTimePeriodId,
iconId: $request->iconId,
severityId: $request->severityId,
maxCheckAttempts: 5,
normalCheckInterval: 1,
retryCheckInterval: 3,
freshnessThreshold: 1,
lowFlapThreshold: 10,
highFlapThreshold: 99,
notificationInterval: $request->notificationTimePeriodId,
recoveryNotificationDelay: 0,
firstNotificationDelay: 0,
acknowledgementTimeout: 0,
);
Mock::setMock($this, [
'user' => [[
'expected' => [[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true]],
]],
'readServiceTemplateRepository' => [
[
'method' => 'existsByName',
'arguments' => $request->name,
'expected' => false,
],
[
'method' => 'findById',
'arguments' => $newServiceTemplateId,
'expected' => $this->serviceTemplateFound,
],
[
'method' => 'findParents',
'arguments' => $newServiceTemplateId,
'expected' => $serviceTemplateInheritances,
],
],
'writeServiceTemplateRepository' => [[
'expected' => $newServiceTemplateId,
]],
'readServiceMacroRepository' => [[
'method' => 'findByServiceIds',
'expected' => [
[9, 8, 1, []],
[$newServiceTemplateId, [$macroA, $macroB]],
],
]],
'readCommandMacroRepository' => [[
'method' => 'findByCommandIdAndType',
'arguments' => [$request->commandId, CommandMacroType::Service],
'expected' => [],
]],
'writeServiceMacroRepository' => [[
'method' => 'add',
'expected' => [[$macroA], [$macroB]],
]],
'writeServiceGroupRepository' => [[
'method' => 'link',
'expected' => [$serviceGroupRelation],
]],
'readServiceGroupRepository' => [[
'method' => 'findByService',
'expected' => [
[$newServiceTemplateId, [['relation' => $serviceGroupRelation, 'serviceGroup' => $serviceGroup]]],
],
]],
'readHostTemplateRepository' => [[
'method' => 'findNamesByIds',
'expected' => [
[[$serviceGroupRelation->getHostId()], [$serviceGroupRelation->getHostId() => $hostTemplateName]],
],
]],
]);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
($this->addUseCase)($request, $this->useCasePresenter);
$dto = $this->useCasePresenter->response;
expect($dto)->toBeInstanceOf(AddServiceTemplateResponse::class);
expect($dto->id)->toBe($this->serviceTemplateFound->getId());
expect($dto->name)->toBe($this->serviceTemplateFound->getName());
expect($dto->alias)->toBe($this->serviceTemplateFound->getAlias());
expect($dto->comment)->toBe($this->serviceTemplateFound->getComment());
expect($dto->serviceTemplateId)->toBe($this->serviceTemplateFound->getServiceTemplateParentId());
expect($dto->commandId)->toBe($this->serviceTemplateFound->getCommandId());
expect($dto->commandArguments)->toBe($this->serviceTemplateFound->getCommandArguments());
expect($dto->checkTimePeriodId)->toBe($this->serviceTemplateFound->getCheckTimePeriodId());
expect($dto->maxCheckAttempts)->toBe($this->serviceTemplateFound->getMaxCheckAttempts());
expect($dto->normalCheckInterval)->toBe($this->serviceTemplateFound->getNormalCheckInterval());
expect($dto->retryCheckInterval)->toBe($this->serviceTemplateFound->getRetryCheckInterval());
expect($dto->activeChecks)->toBe($this->serviceTemplateFound->getActiveChecks());
expect($dto->passiveCheck)->toBe($this->serviceTemplateFound->getPassiveCheck());
expect($dto->volatility)->toBe($this->serviceTemplateFound->getVolatility());
expect($dto->notificationsEnabled)->toBe($this->serviceTemplateFound->getNotificationsEnabled());
expect($dto->isContactAdditiveInheritance)->toBe($this->serviceTemplateFound->isContactAdditiveInheritance());
expect($dto->isContactGroupAdditiveInheritance)
->toBe($this->serviceTemplateFound->isContactGroupAdditiveInheritance());
expect($dto->notificationInterval)->toBe($this->serviceTemplateFound->getNotificationInterval());
expect($dto->notificationTimePeriodId)->toBe($this->serviceTemplateFound->getNotificationTimePeriodId());
expect($dto->notificationTypes)->toBe($this->serviceTemplateFound->getNotificationTypes());
expect($dto->firstNotificationDelay)->toBe($this->serviceTemplateFound->getFirstNotificationDelay());
expect($dto->recoveryNotificationDelay)->toBe($this->serviceTemplateFound->getRecoveryNotificationDelay());
expect($dto->acknowledgementTimeout)->toBe($this->serviceTemplateFound->getAcknowledgementTimeout());
expect($dto->checkFreshness)->toBe($this->serviceTemplateFound->getCheckFreshness());
expect($dto->freshnessThreshold)->toBe($this->serviceTemplateFound->getFreshnessThreshold());
expect($dto->flapDetectionEnabled)->toBe($this->serviceTemplateFound->getFlapDetectionEnabled());
expect($dto->lowFlapThreshold)->toBe($this->serviceTemplateFound->getLowFlapThreshold());
expect($dto->highFlapThreshold)->toBe($this->serviceTemplateFound->getHighFlapThreshold());
expect($dto->eventHandlerEnabled)->toBe($this->serviceTemplateFound->getEventHandlerEnabled());
expect($dto->eventHandlerId)->toBe($this->serviceTemplateFound->getEventHandlerId());
expect($dto->eventHandlerArguments)->toBe($this->serviceTemplateFound->getEventHandlerArguments());
expect($dto->graphTemplateId)->toBe($this->serviceTemplateFound->getGraphTemplateId());
expect($dto->note)->toBe($this->serviceTemplateFound->getNote());
expect($dto->noteUrl)->toBe($this->serviceTemplateFound->getNoteUrl());
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Application/UseCase/DeleteServiceTemplate/DeleteServiceTemplateTest.php | centreon/tests/php/Core/ServiceTemplate/Application/UseCase/DeleteServiceTemplate/DeleteServiceTemplateTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Application\UseCase\DeleteServiceTemplate;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\Repository\WriteServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\UseCase\DeleteServiceTemplate\DeleteServiceTemplate;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Tests\Core\ServiceTemplate\Infrastructure\API\DeleteServiceTemplate\DeleteServiceTemplatePresenterStub;
beforeEach(closure: function (): void {
$this->presenter = new DeleteServiceTemplatePresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new DeleteServiceTemplate(
$this->readRepository = $this->createMock(ReadServiceTemplateRepositoryInterface::class),
$this->writeRepository = $this->createMock(WriteServiceTemplateRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
$this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class),
$this->readServiceMacroRepository = $this->createMock(ReadServiceMacroRepositoryInterface::class),
);
$this->serviceTemplateLockedFound = new ServiceTemplate(
1,
'fake_name',
'fake_alias',
...['isLocked' => true]
);
$this->serviceTemplateNotLockedFound = new ServiceTemplate(
1,
'fake_name',
'fake_alias',
...['isLocked' => false]
);
});
it('should present a ForbiddenResponse when the user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, false],
]
);
($this->useCase)(1, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(ServiceTemplateException::deleteNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the service template is not found', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findById')
->with(1)
->willReturn(null);
($this->useCase)(1, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->response->getMessage())
->toBe((new NotFoundResponse('Service template'))->getMessage());
});
it('should present an ErrorResponse when the service template is locked', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findById')
->with($this->serviceTemplateLockedFound->getId())
->willReturn($this->serviceTemplateLockedFound);
($this->useCase)(1, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(ServiceTemplateException::cannotBeDelete($this->serviceTemplateLockedFound->getName())->getMessage());
});
it('should present a NoContentResponse when the service template has been deleted', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findById')
->with($this->serviceTemplateNotLockedFound->getId())
->willReturn($this->serviceTemplateNotLockedFound);
$this->writeRepository
->expects($this->once())
->method('deleteById')
->with($this->serviceTemplateNotLockedFound->getId());
($this->useCase)(1, $this->presenter);
expect($this->presenter->response)->toBeInstanceOf(NoContentResponse::class);
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findById')
->willThrowException(new \Exception());
($this->useCase)(1, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(ServiceTemplateException::errorWhileDeleting(new \Exception())->getMessage());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Application/UseCase/FindServiceTemplates/FindServiceTemplatesTest.php | centreon/tests/php/Core/ServiceTemplate/Application/UseCase/FindServiceTemplates/FindServiceTemplatesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Application\UseCase\FindServiceTemplates;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Common\Domain\YesNoDefault;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceTemplate\Application\Exception\ServiceTemplateException;
use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\FindServiceTemplateResponse;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\FindServiceTemplates;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\ServiceTemplateDto;
use Core\ServiceTemplate\Domain\Model\NotificationType;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
use Tests\Core\ServiceTemplate\Infrastructure\API\FindServiceTemplates\FindServiceTemplatesPresenterStub;
beforeEach(closure: function (): void {
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->repository = $this->createMock(ReadServiceTemplateRepositoryInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->presenter = new FindServiceTemplatesPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new FindServiceTemplates(
$this->readAccessGroupRepository,
$this->repository,
$this->createMock(RequestParametersInterface::class),
$this->user
);
$this->serviceTemplateFound = new ServiceTemplate(
1,
'fake_name',
'fake_alias',
['a', 'b'],
['c', 'd'],
[NotificationType::Unknown],
[2, 3],
true,
true,
true,
YesNoDefault::Yes,
YesNoDefault::No,
YesNoDefault::Default,
YesNoDefault::Yes,
YesNoDefault::No,
YesNoDefault::Default,
YesNoDefault::Yes,
'comment',
'note',
'note_url',
'action_url',
'icon_aternative_text',
2,
3,
4,
5,
6,
7,
8,
9,
5,
1,
3,
1,
10,
99,
5,
0,
0,
0
);
$this->serviceTemplateDto = new ServiceTemplateDto();
$this->serviceTemplateDto->id = $this->serviceTemplateFound->getId();
$this->serviceTemplateDto->name = $this->serviceTemplateFound->getName();
$this->serviceTemplateDto->alias = $this->serviceTemplateFound->getAlias();
$this->serviceTemplateDto->comment = $this->serviceTemplateFound->getComment();
$this->serviceTemplateDto->serviceTemplateId = $this->serviceTemplateFound->getServiceTemplateParentId();
$this->serviceTemplateDto->commandId = $this->serviceTemplateFound->getCommandId();
$this->serviceTemplateDto->commandArguments = $this->serviceTemplateFound->getCommandArguments();
$this->serviceTemplateDto->checkTimePeriodId = $this->serviceTemplateFound->getCheckTimePeriodId();
$this->serviceTemplateDto->maxCheckAttempts = $this->serviceTemplateFound->getMaxCheckAttempts();
$this->serviceTemplateDto->normalCheckInterval = $this->serviceTemplateFound->getNormalCheckInterval();
$this->serviceTemplateDto->retryCheckInterval = $this->serviceTemplateFound->getRetryCheckInterval();
$this->serviceTemplateDto->activeChecks = $this->serviceTemplateFound->getActiveChecks();
$this->serviceTemplateDto->passiveCheck = $this->serviceTemplateFound->getPassiveCheck();
$this->serviceTemplateDto->volatility = $this->serviceTemplateFound->getVolatility();
$this->serviceTemplateDto->notificationsEnabled = $this->serviceTemplateFound->getNotificationsEnabled();
$this->serviceTemplateDto->isContactAdditiveInheritance
= $this->serviceTemplateFound->isContactAdditiveInheritance();
$this->serviceTemplateDto->isContactGroupAdditiveInheritance
= $this->serviceTemplateFound->isContactGroupAdditiveInheritance();
$this->serviceTemplateDto->notificationInterval = $this->serviceTemplateFound->getNotificationInterval();
$this->serviceTemplateDto->notificationTimePeriodId = $this->serviceTemplateFound->getNotificationTimePeriodId();
$this->serviceTemplateDto->notificationTypes = $this->serviceTemplateFound->getNotificationTypes();
$this->serviceTemplateDto->firstNotificationDelay = $this->serviceTemplateFound->getFirstNotificationDelay();
$this->serviceTemplateDto->recoveryNotificationDelay = $this->serviceTemplateFound->getRecoveryNotificationDelay();
$this->serviceTemplateDto->acknowledgementTimeout = $this->serviceTemplateFound->getAcknowledgementTimeout();
$this->serviceTemplateDto->checkFreshness = $this->serviceTemplateFound->getCheckFreshness();
$this->serviceTemplateDto->freshnessThreshold = $this->serviceTemplateFound->getFreshnessThreshold();
$this->serviceTemplateDto->flapDetectionEnabled = $this->serviceTemplateFound->getFlapDetectionEnabled();
$this->serviceTemplateDto->lowFlapThreshold = $this->serviceTemplateFound->getLowFlapThreshold();
$this->serviceTemplateDto->highFlapThreshold = $this->serviceTemplateFound->getHighFlapThreshold();
$this->serviceTemplateDto->eventHandlerEnabled = $this->serviceTemplateFound->getEventHandlerEnabled();
$this->serviceTemplateDto->eventHandlerId = $this->serviceTemplateFound->getEventHandlerId();
$this->serviceTemplateDto->eventHandlerArguments = $this->serviceTemplateFound->getEventHandlerArguments();
$this->serviceTemplateDto->graphTemplateId = $this->serviceTemplateFound->getGraphTemplateId();
$this->serviceTemplateDto->note = $this->serviceTemplateFound->getNote();
$this->serviceTemplateDto->noteUrl = $this->serviceTemplateFound->getNoteUrl();
$this->serviceTemplateDto->actionUrl = $this->serviceTemplateFound->getActionUrl();
$this->serviceTemplateDto->iconId = $this->serviceTemplateFound->getIconId();
$this->serviceTemplateDto->iconAlternativeText = $this->serviceTemplateFound->getIconAlternativeText();
$this->serviceTemplateDto->severityId = $this->serviceTemplateFound->getSeverityId();
$this->serviceTemplateDto->isLocked = $this->serviceTemplateFound->isLocked();
$this->serviceTemplateDto->hostTemplateIds = $this->serviceTemplateFound->getHostTemplateIds();
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->repository
->expects($this->once())
->method('findByRequestParameter')
->willThrowException(new \Exception());
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(ServiceTemplateException::errorWhileSearching(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when the user has insufficient rights', function (): void {
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, false],
]
);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(ServiceTemplateException::accessNotAllowed()->getMessage());
});
it('should present a FindServiceTemplatesResponse when user has read-only rights', closure: function (): void {
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ, true],
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, false],
]
);
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->repository
->expects($this->once())
->method('findByRequestParametersAndAccessGroups')
->willReturn([$this->serviceTemplateFound]);
($this->useCase)($this->presenter);
expect($this->presenter->response)->toBeInstanceOf(FindServiceTemplateResponse::class);
});
it('should present a FindHostTemplatesResponse when user has read-write rights', function (): void {
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->repository
->expects($this->once())
->method('findByRequestParametersAndAccessGroups')
->willReturn([$this->serviceTemplateFound]);
($this->useCase)($this->presenter);
expect($this->presenter->response)->toBeInstanceOf(FindServiceTemplateResponse::class);
});
it('should present a FindHostTemplatesResponse when user has read or write rights', function (): void {
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ, true],
[Contact::ROLE_CONFIGURATION_SERVICES_TEMPLATES_READ_WRITE, true],
]
);
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->repository
->expects($this->once())
->method('findByRequestParametersAndAccessGroups')
->willReturn([$this->serviceTemplateFound]);
($this->useCase)($this->presenter);
expect($this->presenter->response)->toBeInstanceOf(FindServiceTemplateResponse::class);
$dto = $this->presenter->response->serviceTemplates[0];
expect($dto->id)->toBe($this->serviceTemplateFound->getId());
expect($dto->name)->toBe($this->serviceTemplateFound->getName());
expect($dto->alias)->toBe($this->serviceTemplateFound->getAlias());
expect($dto->comment)->toBe($this->serviceTemplateFound->getComment());
expect($dto->serviceTemplateId)->toBe($this->serviceTemplateFound->getServiceTemplateParentId());
expect($dto->commandId)->toBe($this->serviceTemplateFound->getCommandId());
expect($dto->commandArguments)->toBe($this->serviceTemplateFound->getCommandArguments());
expect($dto->checkTimePeriodId)->toBe($this->serviceTemplateFound->getCheckTimePeriodId());
expect($dto->maxCheckAttempts)->toBe($this->serviceTemplateFound->getMaxCheckAttempts());
expect($dto->normalCheckInterval)->toBe($this->serviceTemplateFound->getNormalCheckInterval());
expect($dto->retryCheckInterval)->toBe($this->serviceTemplateFound->getRetryCheckInterval());
expect($dto->activeChecks)->toBe($this->serviceTemplateFound->getActiveChecks());
expect($dto->passiveCheck)->toBe($this->serviceTemplateFound->getPassiveCheck());
expect($dto->volatility)->toBe($this->serviceTemplateFound->getVolatility());
expect($dto->notificationsEnabled)->toBe($this->serviceTemplateFound->getNotificationsEnabled());
expect($dto->isContactAdditiveInheritance)->toBe($this->serviceTemplateFound->isContactAdditiveInheritance());
expect($dto->isContactGroupAdditiveInheritance)
->toBe($this->serviceTemplateFound->isContactGroupAdditiveInheritance());
expect($dto->notificationInterval)->toBe($this->serviceTemplateFound->getNotificationInterval());
expect($dto->notificationTimePeriodId)->toBe($this->serviceTemplateFound->getNotificationTimePeriodId());
expect($dto->notificationTypes)->toBe($this->serviceTemplateFound->getNotificationTypes());
expect($dto->firstNotificationDelay)->toBe($this->serviceTemplateFound->getFirstNotificationDelay());
expect($dto->recoveryNotificationDelay)->toBe($this->serviceTemplateFound->getRecoveryNotificationDelay());
expect($dto->acknowledgementTimeout)->toBe($this->serviceTemplateFound->getAcknowledgementTimeout());
expect($dto->checkFreshness)->toBe($this->serviceTemplateFound->getCheckFreshness());
expect($dto->freshnessThreshold)->toBe($this->serviceTemplateFound->getFreshnessThreshold());
expect($dto->flapDetectionEnabled)->toBe($this->serviceTemplateFound->getFlapDetectionEnabled());
expect($dto->lowFlapThreshold)->toBe($this->serviceTemplateFound->getLowFlapThreshold());
expect($dto->highFlapThreshold)->toBe($this->serviceTemplateFound->getHighFlapThreshold());
expect($dto->eventHandlerEnabled)->toBe($this->serviceTemplateFound->getEventHandlerEnabled());
expect($dto->eventHandlerId)->toBe($this->serviceTemplateFound->getEventHandlerId());
expect($dto->eventHandlerArguments)->toBe($this->serviceTemplateFound->getEventHandlerArguments());
expect($dto->graphTemplateId)->toBe($this->serviceTemplateFound->getGraphTemplateId());
expect($dto->note)->toBe($this->serviceTemplateFound->getNote());
expect($dto->noteUrl)->toBe($this->serviceTemplateFound->getNoteUrl());
expect($dto->actionUrl)->toBe($this->serviceTemplateFound->getActionUrl());
expect($dto->iconId)->toBe($this->serviceTemplateFound->getIconId());
expect($dto->iconAlternativeText)->toBe($this->serviceTemplateFound->getIconAlternativeText());
expect($dto->severityId)->toBe($this->serviceTemplateFound->getSeverityId());
expect($dto->isLocked)->toBe($this->serviceTemplateFound->isLocked());
expect($dto->hostTemplateIds)->toBe($this->serviceTemplateFound->getHostTemplateIds());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Domain/NewServiceTemplateTest.php | centreon/tests/php/Core/ServiceTemplate/Domain/NewServiceTemplateTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\MonitoringServer\Model\MonitoringServer;
use Core\ServiceTemplate\Domain\Model\NewServiceTemplate;
use Core\ServiceTemplate\Domain\Model\NotificationType;
/**
* @throws \Assert\AssertionFailedException
* @return NewServiceTemplate
*/
function createNewServiceTemplate(): NewServiceTemplate
{
return new NewServiceTemplate('name', 'fake_name');
}
foreach (
[
'name' => NewServiceTemplate::MAX_NAME_LENGTH,
'alias' => NewServiceTemplate::MAX_ALIAS_LENGTH,
'comment' => NewServiceTemplate::MAX_COMMENT_LENGTH,
'note' => NewServiceTemplate::MAX_NOTES_LENGTH,
'noteUrl' => NewServiceTemplate::MAX_NOTES_URL_LENGTH,
] as $field => $length
) {
it(
"should throw an exception when service template {$field} is an empty string",
function () use ($field): void {
$template = createNewServiceTemplate();
call_user_func_array([$template, 'set' . ucfirst($field)], ['']);
}
)->throws(
AssertionException::class,
AssertionException::notEmptyString("NewServiceTemplate::{$field}")->getMessage()
);
$tooLongString = str_repeat('a', $length + 1);
it(
"should throw an exception when service template {$field} is too long",
function () use ($field, $tooLongString): void {
$template = createNewServiceTemplate();
call_user_func_array([$template, 'set' . ucfirst($field)], [$tooLongString]);
}
)->throws(
AssertionException::class,
AssertionException::maxLength(
$tooLongString,
$length + 1,
$length,
"NewServiceTemplate::{$field}"
)->getMessage()
);
}
foreach (
[
'maxCheckAttempts',
'normalCheckInterval',
'retryCheckInterval',
'freshnessThreshold',
'notificationInterval',
'recoveryNotificationDelay',
'firstNotificationDelay',
'acknowledgementTimeout',
'lowFlapThreshold',
'highFlapThreshold',
] as $field
) {
it(
"should throw an exception when service template {$field} is less than 0",
function () use ($field): void {
$template = createNewServiceTemplate();
call_user_func_array([$template, 'set' . ucfirst($field)], [-1]);
}
)->throws(
AssertionException::class,
AssertionException::min(
-1,
0,
"NewServiceTemplate::{$field}"
)->getMessage()
);
}
foreach (
[
'serviceTemplateParentId',
'commandId',
'eventHandlerId',
'notificationTimePeriodId',
'checkTimePeriodId',
'iconId',
'graphTemplateId',
'severityId',
] as $field
) {
it(
"should throw an exception when service template {$field} is less than 1",
function () use ($field): void {
$template = createNewServiceTemplate();
call_user_func_array([$template, 'set' . ucfirst($field)], [0]);
}
)->throws(
AssertionException::class,
AssertionException::min(
0,
1,
"NewServiceTemplate::{$field}"
)->getMessage()
);
}
foreach (['commandArgument', 'eventHandlerArgument'] as $field) {
it(
"should retrieve all arguments to the {$field} field that were previously added",
function () use ($field): void {
$arguments = ['1', '2', '3'];
$serviceTemplate = createNewServiceTemplate();
$methodName = 'get' . ucfirst($field) . 's';
foreach ($arguments as $argument) {
call_user_func_array([$serviceTemplate, 'add' . ucfirst($field)], [$argument]);
}
expect($serviceTemplate->{$methodName}())->toBe(['1', '2', '3']);
}
);
}
it(
'should retrieve all notificationTypes that were previously added',
function (): void {
$serviceTemplate = createNewServiceTemplate();
$notificationTypes = [
NotificationType::Unknown,
NotificationType::Warning,
NotificationType::Recovery,
];
foreach ($notificationTypes as $notificationType) {
call_user_func_array([$serviceTemplate, 'addNotificationType'], [$notificationType]);
}
expect($serviceTemplate->getNotificationTypes())->toBe($notificationTypes);
}
);
it(
'should throw an exception when name contains illegal characters',
fn () => (new NewServiceTemplate('fake_name' . MonitoringServer::ILLEGAL_CHARACTERS[0], 'fake_alias'))
)->throws(
AssertionException::class,
AssertionException::unauthorizedCharacters(
'fake_name' . MonitoringServer::ILLEGAL_CHARACTERS[0],
MonitoringServer::ILLEGAL_CHARACTERS[0],
'NewServiceTemplate::name'
)->getMessage()
);
it(
'should throw an exception when alias contains illegal characters',
fn () => (new NewServiceTemplate('fake_name', 'fake_alias' . MonitoringServer::ILLEGAL_CHARACTERS[0]))
)->throws(
AssertionException::class,
AssertionException::unauthorizedCharacters(
'fake_alias' . MonitoringServer::ILLEGAL_CHARACTERS[0],
MonitoringServer::ILLEGAL_CHARACTERS[0],
'NewServiceTemplate::alias'
)->getMessage()
);
it(
'should remove spaces that are too long in the alias',
function (): void {
$serviceTemplate = new NewServiceTemplate('fake_name', ' fake alias ok ');
expect($serviceTemplate->getAlias())->toBe('fake alias ok');
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Domain/ServiceTemplateInheritanceTest.php | centreon/tests/php/Core/ServiceTemplate/Domain/ServiceTemplateInheritanceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Domain;
use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance;
it('return inheritance line in the expected order', function (): void {
$serviceTemplateId = 27;
$parents = [
new ServiceTemplateInheritance(25, 27),
new ServiceTemplateInheritance(12, 13),
new ServiceTemplateInheritance(2, 45),
new ServiceTemplateInheritance(13, 25),
new ServiceTemplateInheritance(45, 10),
new ServiceTemplateInheritance(1, 2),
new ServiceTemplateInheritance(10, 12),
];
$inheritanceLine = ServiceTemplateInheritance::createInheritanceLine($serviceTemplateId, $parents);
expect($inheritanceLine)->toBe([25, 13, 12, 10, 45, 2, 1]);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Domain/ServiceTemplateTest.php | centreon/tests/php/Core/ServiceTemplate/Domain/ServiceTemplateTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\MonitoringServer\Model\MonitoringServer;
use Core\ServiceTemplate\Domain\Model\NotificationType;
use Core\ServiceTemplate\Domain\Model\ServiceTemplate;
/**
* @param $values*
*
* @throws \Assert\AssertionFailedException
*
* @return ServiceTemplate
*/
function createServiceTemplate($values): ServiceTemplate
{
return new ServiceTemplate(...['id' => 1, 'name' => 'fake_name', 'alias' => 'fake_alias', ...$values]);
}
foreach (
[
'name' => ServiceTemplate::MAX_NAME_LENGTH,
'alias' => ServiceTemplate::MAX_ALIAS_LENGTH,
'comment' => ServiceTemplate::MAX_COMMENT_LENGTH,
'note' => ServiceTemplate::MAX_NOTES_LENGTH,
'noteUrl' => ServiceTemplate::MAX_NOTES_URL_LENGTH,
] as $field => $length
) {
it(
"should throw an exception when service template {$field} is an empty string",
fn () => (createServiceTemplate([$field => ' ']))
)->throws(
AssertionException::class,
AssertionException::notEmptyString("ServiceTemplate::{$field}")->getMessage()
);
$tooLongString = str_repeat('a', $length + 1);
it(
"should throw an exception when service template {$field} is too long",
fn () => (
createServiceTemplate([$field => $tooLongString])
)
)->throws(
AssertionException::class,
AssertionException::maxLength(
$tooLongString,
$length + 1,
$length,
"ServiceTemplate::{$field}"
)->getMessage()
);
}
foreach (
[
'maxCheckAttempts',
'normalCheckInterval',
'retryCheckInterval',
'freshnessThreshold',
'notificationInterval',
'recoveryNotificationDelay',
'firstNotificationDelay',
'acknowledgementTimeout',
'lowFlapThreshold',
'highFlapThreshold',
] as $field
) {
it(
"should throw an exception when service template {$field} is less than 0",
fn () => (createServiceTemplate([$field => -1]))
)->throws(
AssertionException::class,
AssertionException::min(
-1,
0,
"ServiceTemplate::{$field}"
)->getMessage()
);
}
foreach (
[
'id',
'serviceTemplateParentId',
'commandId',
'eventHandlerId',
'notificationTimePeriodId',
'checkTimePeriodId',
'iconId',
'graphTemplateId',
'severityId',
] as $field
) {
it(
"should throw an exception when service template {$field} is less than 1",
fn () => (createServiceTemplate([$field => 0]))
)->throws(
AssertionException::class,
AssertionException::min(
0,
1,
"ServiceTemplate::{$field}"
)->getMessage()
);
}
foreach (
[
'hostTemplateIds',
] as $field
) {
it(
"should throw an exception when service template {$field} contains a list of integers less than 1",
fn () => (createServiceTemplate([$field => [0]]))
)->throws(
AssertionException::class,
AssertionException::min(
0,
1,
"ServiceTemplate::{$field}"
)->getMessage()
);
}
foreach (['commandArguments', 'eventHandlerArguments'] as $field) {
it(
"should convert all argument values of the {$field} field to strings only if they are of scalar type",
function () use ($field): void {
$arguments = [1, 2, '3', new \Exception()];
$serviceTemplate = new ServiceTemplate(1, 'fake_name', 'fake_alias', ...[$field => $arguments]);
$methodName = 'get' . ucfirst($field);
expect($serviceTemplate->{$methodName}())->toBe(['1', '2', '3']);
}
);
}
it(
'should throw an exception when one of the arguments in the notification list is not of the correct type',
fn () => (new ServiceTemplate(1, 'fake_name', 'fake_alias', ...['notificationTypes' => ['fake']]))
)->throws(
AssertionException::class,
AssertionException::badInstanceOfObject(
'string',
NotificationType::class,
'ServiceTemplate::notificationTypes'
)->getMessage()
);
it(
'should throw an exception when name contains illegal characters',
fn () => (new ServiceTemplate(1, 'fake_name' . MonitoringServer::ILLEGAL_CHARACTERS[0], 'fake_alias'))
)->throws(
AssertionException::class,
AssertionException::unauthorizedCharacters(
'fake_name' . MonitoringServer::ILLEGAL_CHARACTERS[0],
MonitoringServer::ILLEGAL_CHARACTERS[0],
'ServiceTemplate::name'
)->getMessage()
);
it(
'should throw an exception when alias contains illegal characters',
fn () => (new ServiceTemplate(1, 'fake_name', 'fake_alias' . MonitoringServer::ILLEGAL_CHARACTERS[0]))
)->throws(
AssertionException::class,
AssertionException::unauthorizedCharacters(
'fake_alias' . MonitoringServer::ILLEGAL_CHARACTERS[0],
MonitoringServer::ILLEGAL_CHARACTERS[0],
'ServiceTemplate::alias'
)->getMessage()
);
it(
'should remove spaces that are too long in the alias',
function (): void {
$serviceTemplate = new ServiceTemplate(1, 'fake_name', ' fake alias ok ');
expect($serviceTemplate->getAlias())->toBe('fake alias ok');
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Infrastructure/API/AddServiceTemplate/AddServiceTemplatePresenterStub.php | centreon/tests/php/Core/ServiceTemplate/Infrastructure/API/AddServiceTemplate/AddServiceTemplatePresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Infrastructure\API\AddServiceTemplate;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplatePresenterInterface;
use Core\ServiceTemplate\Application\UseCase\AddServiceTemplate\AddServiceTemplateResponse;
class AddServiceTemplatePresenterStub extends AbstractPresenter implements AddServiceTemplatePresenterInterface
{
public ResponseStatusInterface|AddServiceTemplateResponse|null $response = null;
public function presentResponse(ResponseStatusInterface|AddServiceTemplateResponse $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Infrastructure/API/DeleteServiceTemplate/DeleteServiceTemplatePresenterStub.php | centreon/tests/php/Core/ServiceTemplate/Infrastructure/API/DeleteServiceTemplate/DeleteServiceTemplatePresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Infrastructure\API\DeleteServiceTemplate;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
class DeleteServiceTemplatePresenterStub extends AbstractPresenter
{
public ?ResponseStatusInterface $response = null;
public function setResponseStatus(?ResponseStatusInterface $responseStatus): void
{
$this->response = $responseStatus;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceTemplate/Infrastructure/API/FindServiceTemplates/FindServiceTemplatesPresenterStub.php | centreon/tests/php/Core/ServiceTemplate/Infrastructure/API/FindServiceTemplates/FindServiceTemplatesPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceTemplate\Infrastructure\API\FindServiceTemplates;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\FindServiceTemplateResponse;
use Core\ServiceTemplate\Application\UseCase\FindServiceTemplates\FindServiceTemplatesPresenterInterface;
class FindServiceTemplatesPresenterStub extends AbstractPresenter implements FindServiceTemplatesPresenterInterface
{
public ResponseStatusInterface|FindServiceTemplateResponse $response;
public function presentResponse(ResponseStatusInterface|FindServiceTemplateResponse $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Contact/Application/UseCase/FindContactTemplates/FindContactTemplatesPresenterStub.php | centreon/tests/php/Core/Contact/Application/UseCase/FindContactTemplates/FindContactTemplatesPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Contact\Application\UseCase\FindContactTemplates;
use Core\Application\Common\UseCase\{AbstractPresenter, ResponseStatusInterface};
use Core\Contact\Application\UseCase\FindContactTemplates\FindContactTemplatesPresenterInterface;
use Core\Contact\Application\UseCase\FindContactTemplates\FindContactTemplatesResponse;
class FindContactTemplatesPresenterStub extends AbstractPresenter implements FindContactTemplatesPresenterInterface
{
public FindContactTemplatesResponse|ResponseStatusInterface $data;
public function presentResponse(FindContactTemplatesResponse|ResponseStatusInterface $response): void
{
$this->data = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Contact/Application/UseCase/FindContactTemplates/FindContactTemplatesTest.php | centreon/tests/php/Core/Contact/Application/UseCase/FindContactTemplates/FindContactTemplatesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Contact\Application\UseCase\FindContactTemplates;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Contact\Application\Exception\ContactTemplateException;
use Core\Contact\Application\Repository\ReadContactTemplateRepositoryInterface;
use Core\Contact\Application\UseCase\FindContactTemplates\FindContactTemplates;
use Core\Contact\Application\UseCase\FindContactTemplates\FindContactTemplatesResponse;
use Core\Contact\Domain\Model\ContactTemplate;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
beforeEach(function (): void {
$this->repository = $this->createMock(ReadContactTemplateRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->repositoryException = $this->createMock(RepositoryException::class);
});
it('should present an ErrorResponse when an exception occurred', function (): void {
$useCase = new FindContactTemplates($this->repository, $this->user);
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->repository
->expects($this->once())
->method('findAll')
->willThrowException($this->repositoryException);
$presenter = new FindContactTemplatesPresenterStub($this->presenterFormatter);
$useCase($presenter);
expect($presenter->data)->toBeInstanceOf(ErrorResponse::class)
->and($presenter->data->getMessage())->toBe(
ContactTemplateException::errorWhileSearchingForContactTemplate()->getMessage()
);
});
it('should present a ForbiddenResponse if the user does not have the read menu access to contact templates', function (): void {
$useCase = new FindContactTemplates($this->repository, $this->user);
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(false);
$presenter = new FindContactTemplatesPresenterStub($this->presenterFormatter);
$useCase($presenter);
expect($presenter->data)->toBeInstanceOf(ForbiddenResponse::class)
->and($presenter->data->getMessage())->toBe(
ContactTemplateException::listingNotAllowed()->getMessage()
);
});
it('should present a FindContactTemplatesResponse when no error occured', function (): void {
$useCase = new FindContactTemplates($this->repository, $this->user);
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$contactTemplate = new ContactTemplate(1, 'contact_template');
$this->repository
->expects($this->once())
->method('findAll')
->willReturn([$contactTemplate]);
$presenter = new FindContactTemplatesPresenterStub($this->presenterFormatter);
$useCase($presenter);
expect($presenter->data)->toBeInstanceOf(FindContactTemplatesResponse::class)
->and($presenter->data->contactTemplates[0])->toBe(
[
'id' => 1,
'name' => 'contact_template',
]
);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroupsPresenterStub.php | centreon/tests/php/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroupsPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Contact\Application\UseCase\FindContactGroups;
use Core\Application\Common\UseCase\{
AbstractPresenter
};
use Core\Contact\Application\UseCase\FindContactGroups\FindContactGroupsPresenterInterface;
use Core\Contact\Application\UseCase\FindContactGroups\FindContactGroupsResponse;
use Symfony\Component\HttpFoundation\Response;
class FindContactGroupsPresenterStub extends AbstractPresenter implements FindContactGroupsPresenterInterface
{
/** @var FindContactGroupsResponse */
public $response;
/**
* @param FindContactGroupsResponse $response
*/
public function present(mixed $response): void
{
$this->response = $response;
}
/**
* @return Response
*/
public function show(): Response
{
return new Response();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroupsTest.php | centreon/tests/php/Core/Contact/Application/UseCase/FindContactGroups/FindContactGroupsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Contact\Application\UseCase\FindContactGroups;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Contact\Application\Exception\ContactGroupException;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\UseCase\FindContactGroups\FindContactGroups;
use Core\Contact\Application\UseCase\FindContactGroups\FindContactGroupsResponse;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Contact\Domain\Model\ContactGroupType;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
beforeEach(function (): void {
$this->contactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->requestParameters = new RequestParameters();
$this->useCase = new FindContactGroups(
$this->accessGroupRepository,
$this->contactGroupRepository,
$this->user,
$this->requestParameters,
false,
);
});
it('should present an ErrorResponse when an exception occurs', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->contactGroupRepository
->expects($this->once())
->method('findAll')
->with($this->requestParameters)
->willThrowException(new \Exception());
$presenter = new FindContactGroupsPresenterStub($this->presenterFormatter);
$this->useCase->__invoke($presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($presenter->getResponseStatus()?->getMessage())
->toBe(ContactGroupException::errorWhileSearchingForContactGroups()->getMessage());
});
it('should present a ForbiddenResponse if the user doesn\'t have read menu access to contact group', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturnCallback(fn (string $role): bool => match ($role) {
Contact::ROLE_CONFIGURATION_USERS_CONTACT_GROUPS_READ, Contact::ROLE_CONFIGURATION_USERS_CONTACT_GROUPS_READ_WRITE => false,
default => true,
});
$presenter = new FindContactGroupsPresenterStub($this->presenterFormatter);
$this->useCase->__invoke($presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($presenter->getResponseStatus()?->getMessage())
->toBe(ContactGroupException::notAllowed()->getMessage());
});
it('should call the method findAll if the user is admin', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->contactGroupRepository
->expects($this->once())
->method('findAll')
->with($this->requestParameters);
$presenter = new FindContactGroupsPresenterStub($this->presenterFormatter);
$this->useCase->__invoke($presenter);
});
it('should call the method findByAccessGroups if the user is not admin', function (): void {
$this->user
->expects($this->any())
->method('getId')
->willReturn(1);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->with(Contact::ROLE_CONFIGURATION_USERS_CONTACT_GROUPS_READ)
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$accessGroupsFound = [new AccessGroup(1, 'fake_name', 'fake_alias')];
$this->accessGroupRepository
->expects($this->any())
->method('findByContact')
->willReturn($accessGroupsFound);
$this->contactGroupRepository
->expects($this->once())
->method('findByAccessGroupsAndUserAndRequestParameter')
->with($accessGroupsFound, $this->user, $this->requestParameters)
->willReturn([]);
$presenter = new FindContactGroupsPresenterStub($this->presenterFormatter);
$this->useCase->__invoke($presenter);
});
it('should present a FindContactGroupsResponse when no error occurred', function (): void {
$contactGroup = new ContactGroup(1, 'fake_name', 'fake_alias', 'fake_comments', true, ContactGroupType::Local);
$this->contactGroupRepository
->expects($this->once())
->method('findAll')
->willReturn([$contactGroup]);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$presenter = new FindContactGroupsPresenterStub($this->presenterFormatter);
$this->useCase->__invoke($presenter);
expect($presenter->response)
->toBeInstanceOf(FindContactGroupsResponse::class)
->and($presenter->response->contactGroups[0])
->toBe(
[
'id' => $contactGroup->getId(),
'name' => $contactGroup->getName(),
'alias' => $contactGroup->getAlias(),
'comments' => $contactGroup->getComments(),
'type' => $contactGroup->getType() === ContactGroupType::Local ? 'local' : 'ldap',
'is_activated' => $contactGroup->isActivated(),
]
);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Contact/Domain/Model/ContactGroupTest.php | centreon/tests/php/Core/Contact/Domain/Model/ContactGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Contact\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Contact\Domain\Model\ContactGroup;
it('should raise an exception when the contact group name is empty', function (): void {
new ContactGroup(1, '', '');
})->throws(InvalidArgumentException::class, AssertionException::notEmpty('ContactGroup::name')->getMessage());
it('should raise an exception when the contact group alias is empty', function (): void {
new ContactGroup(1, '', '');
})->throws(InvalidArgumentException::class, AssertionException::notEmpty('ContactGroup::name')->getMessage());
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Contact/Infrastructure/Api/FindContactTemplates/FindContactTemplatesControllerTest.php | centreon/tests/php/Core/Contact/Infrastructure/Api/FindContactTemplates/FindContactTemplatesControllerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Contact\Infrastructure\ProviderConfiguration\WebSSO\Api\FindWebSSOConfiguration;
use Centreon\Domain\Contact\Contact;
use Core\Contact\Application\UseCase\FindContactTemplates\FindContactTemplates;
use Core\Contact\Application\UseCase\FindContactTemplates\FindContactTemplatesPresenterInterface;
use Core\Contact\Infrastructure\Api\FindContactTemplates\FindContactTemplatesController;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
beforeEach(function (): void {
$this->useCase = $this->createMock(FindContactTemplates::class);
$this->presenter = $this->createMock(FindContactTemplatesPresenterInterface::class);
$timezone = new \DateTimeZone('Europe/Paris');
$adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true)
->setTimezone($timezone);
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$authorizationChecker->expects($this->once())
->method('isGranted')
->willReturn(true);
$token = $this->createMock(TokenInterface::class);
$token->expects($this->any())
->method('getUser')
->willReturn($adminContact);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage->expects($this->any())
->method('getToken')
->willReturn($token);
$this->container = $this->createMock(ContainerInterface::class);
$this->container->expects($this->any())
->method('has')
->willReturn(true);
$this->container->expects($this->any())
->method('get')
->willReturnOnConsecutiveCalls(
$authorizationChecker,
new class () {
public function get(): string
{
return __DIR__ . '/../../../../../';
}
}
);
$this->request = $this->createMock(Request::class);
});
it('should call the use case', function (): void {
$controller = new FindContactTemplatesController();
$controller->setContainer($this->container);
$this->useCase
->expects($this->once())
->method('__invoke')
->with(
$this->equalTo($this->presenter)
);
$controller($this->useCase, $this->presenter);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Contact/Infrastructure/Api/FindContactGroups/FindContactGroupsControllerTest.php | centreon/tests/php/Core/Contact/Infrastructure/Api/FindContactGroups/FindContactGroupsControllerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Contact\Infrastructure\Api\FindContactGroups;
use Centreon\Domain\Contact\Contact;
use Core\Contact\Application\UseCase\FindContactGroups\FindContactGroups;
use Core\Contact\Application\UseCase\FindContactGroups\FindContactGroupsPresenterInterface;
use Core\Contact\Infrastructure\Api\FindContactGroups\FindContactGroupsController;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
beforeEach(function (): void {
$this->useCase = $this->createMock(FindContactGroups::class);
$this->presenter = $this->createMock(FindContactGroupsPresenterInterface::class);
$timezone = new \DateTimeZone('Europe/Paris');
$adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true)
->setTimezone($timezone);
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$authorizationChecker->expects($this->once())
->method('isGranted')
->willReturn(true);
$token = $this->createMock(TokenInterface::class);
$token->expects($this->any())
->method('getUser')
->willReturn($adminContact);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage->expects($this->any())
->method('getToken')
->willReturn($token);
$this->container = $this->createMock(ContainerInterface::class);
$this->container->expects($this->any())
->method('has')
->willReturn(true);
$this->container->expects($this->any())
->method('get')
->willReturnOnConsecutiveCalls(
$authorizationChecker,
new class () {
public function get(): string
{
return __DIR__ . '/../../../../../';
}
}
);
$this->request = $this->createMock(Request::class);
});
it('should call the use case', function (): void {
$controller = new FindContactGroupsController();
$controller->setContainer($this->container);
$this->useCase
->expects($this->once())
->method('__invoke')
->with(
$this->equalTo($this->presenter)
);
$controller($this->useCase, $this->presenter);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceCategory/Application/UseCase/FindServiceCategories/FindServiceCategoriesTest.php | centreon/tests/php/Core/ServiceCategory/Application/UseCase/FindServiceCategories/FindServiceCategoriesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceCategory\Application\UseCase\FindServiceCategories;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceCategory\Application\Exception\ServiceCategoryException;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\UseCase\FindServiceCategories\FindServiceCategories;
use Core\ServiceCategory\Application\UseCase\FindServiceCategories\FindServiceCategoriesResponse;
use Core\ServiceCategory\Domain\Model\ServiceCategory;
use Exception;
beforeEach(function (): void {
$this->serviceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->usecase = new FindServiceCategories(
$this->serviceCategoryRepository,
$this->accessGroupRepository,
$this->requestParameters,
$this->user,
false
);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->serviceCategoryName = 'sc-name';
$this->serviceCategoryAlias = 'sc-alias';
$this->serviceCategory = new ServiceCategory(1, $this->serviceCategoryName, $this->serviceCategoryAlias);
$this->responseArray = [
'id' => 1,
'name' => $this->serviceCategoryName,
'alias' => $this->serviceCategoryAlias,
'is_activated' => true,
];
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->serviceCategoryRepository
->expects($this->once())
->method('findByRequestParameter')
->willThrowException(new Exception());
($this->usecase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceCategoryException::findServiceCategories(new Exception())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has unsufficient rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE, false],
]
);
($this->usecase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceCategoryException::accessNotAllowed()->getMessage());
});
it('should present a FindServiceGroupsResponse when a non-admin user has read only rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ, true],
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE, false],
]
);
$this->serviceCategoryRepository
->expects($this->once())
->method('findByRequestParameterAndAccessGroups')
->willReturn([$this->serviceCategory]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindServiceCategoriesResponse::class)
->and($this->presenter->getPresentedData()->serviceCategories[0])
->toBe($this->responseArray);
});
it('should present a FindServiceGroupsResponse when a non-admin user has read/write rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE, true],
]
);
$this->serviceCategoryRepository
->expects($this->once())
->method('findByRequestParameterAndAccessGroups')
->willReturn([$this->serviceCategory]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindServiceCategoriesResponse::class)
->and($this->presenter->getPresentedData()->serviceCategories[0])
->toBe($this->responseArray);
});
it('should present a FindServiceCategoriesResponse with admin user', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->serviceCategoryRepository
->expects($this->once())
->method('findByRequestParameter')
->willReturn([$this->serviceCategory]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindServiceCategoriesResponse::class)
->and($this->presenter->getPresentedData()->serviceCategories[0])
->toBe($this->responseArray);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesTest.php | centreon/tests/php/Core/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\ServiceCategory\Application\Repository\ReadRealTimeServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories\FindRealTimeServiceCategories;
use Core\Tag\RealTime\Domain\Model\Tag;
beforeEach(function (): void {
$this->useCase = new FindRealTimeServiceCategories(
$this->user = $this->createMock(ContactInterface::class),
$this->repository = $this->createMock(ReadRealTimeServiceCategoryRepositoryInterface::class),
$this->configurationRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class),
$this->requestParameters = $this->createMock(RequestParametersInterface::class),
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class)
);
$this->presenter = new FindRealTimeServiceCategoriesPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->accessGroup = new AccessGroup(1, 'AG-name', 'AG-alias');
$this->category = new Tag(1, 'service-category-name', Tag::SERVICE_CATEGORY_TYPE_ID);
});
it('should find all categories as admin', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->repository->expects($this->once())
->method('findAll')
->willReturn([$this->category]);
($this->useCase)($this->presenter);
expect($this->presenter->response->tags)->toHaveCount(1);
expect($this->presenter->response->tags[0]['id'])->toBe($this->category->getId());
expect($this->presenter->response->tags[0]['name'])->toBe($this->category->getName());
});
it('should find all categories as user with no filters on categories', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([$this->accessGroup]);
$this->configurationRepository
->expects($this->once())
->method('hasRestrictedAccessToServiceCategories')
->willReturn(false);
$this->repository->expects($this->once())
->method('findAll')
->willReturn([$this->category]);
($this->useCase)($this->presenter);
expect($this->presenter->response->tags)->toHaveCount(1);
expect($this->presenter->response->tags[0]['id'])->toBe($this->category->getId());
expect($this->presenter->response->tags[0]['name'])->toBe($this->category->getName());
});
it('should find all categories as user with filters on categories', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([$this->accessGroup]);
$this->configurationRepository
->expects($this->once())
->method('hasRestrictedAccessToServiceCategories')
->willReturn(true);
$this->repository->expects($this->once())
->method('findAllByAccessGroupIds')
->willReturn([$this->category]);
($this->useCase)($this->presenter);
expect($this->presenter->response->tags)->toHaveCount(1);
expect($this->presenter->response->tags[0]['id'])->toBe($this->category->getId());
expect($this->presenter->response->tags[0]['name'])->toBe($this->category->getName());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesPresenterStub.php | centreon/tests/php/Core/ServiceCategory/Application/UseCase/FindRealTimeServiceCategories/FindRealTimeServiceCategoriesPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories\FindRealTimeServiceCategoriesPresenterInterface;
use Core\ServiceCategory\Application\UseCase\FindRealTimeServiceCategories\FindRealTimeServiceCategoriesResponse;
class FindRealTimeServiceCategoriesPresenterStub extends AbstractPresenter implements FindRealTimeServiceCategoriesPresenterInterface
{
public FindRealTimeServiceCategoriesResponse|ResponseStatusInterface $response;
public function presentResponse(FindRealTimeServiceCategoriesResponse|ResponseStatusInterface $response): void
{
$this->response = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceCategory/Application/UseCase/DeleteServiceCategory/DeleteServiceCategoryTest.php | centreon/tests/php/Core/ServiceCategory/Application/UseCase/DeleteServiceCategory/DeleteServiceCategoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceCategory\Application\UseCase\DeleteServiceCategory;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceCategory\Application\Exception\ServiceCategoryException;
use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface;
use Core\ServiceCategory\Application\UseCase\DeleteServiceCategory\DeleteServiceCategory;
use Core\ServiceCategory\Domain\Model\ServiceCategory;
beforeEach(function (): void {
$this->writeServiceCategoryRepository = $this->createMock(WriteServiceCategoryRepositoryInterface::class);
$this->readServiceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->user = $this->createMock(ContactInterface::class);
$this->serviceCategory = $this->createMock(ServiceCategory::class);
$this->serviceCategoryId = 1;
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$useCase = new DeleteServiceCategory(
$this->writeServiceCategoryRepository,
$this->readServiceCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->writeServiceCategoryRepository
->expects($this->once())
->method('deleteById')
->willThrowException(new \Exception());
$useCase($this->serviceCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceCategoryException::deleteServiceCategory(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has insufficient rights', function (): void {
$useCase = new DeleteServiceCategory(
$this->writeServiceCategoryRepository,
$this->readServiceCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
$useCase($this->serviceCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceCategoryException::deleteNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the service category does not exist (with admin user)', function (): void {
$useCase = new DeleteServiceCategory(
$this->writeServiceCategoryRepository,
$this->readServiceCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$useCase($this->serviceCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Service category not found');
});
it('should present a NotFoundResponse when the service category does not exist (with non-admin user)', function (): void {
$useCase = new DeleteServiceCategory(
$this->writeServiceCategoryRepository,
$this->readServiceCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceCategoryRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(false);
$useCase($this->serviceCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Service category not found');
});
it('should present a NoContentResponse on success (with admin user)', function (): void {
$useCase = new DeleteServiceCategory(
$this->writeServiceCategoryRepository,
$this->readServiceCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$serviceCategoryId = 1;
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->writeServiceCategoryRepository
->expects($this->once())
->method('deleteById');
$useCase($serviceCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
it('should present a NoContentResponse on success (with non-admin user)', function (): void {
$useCase = new DeleteServiceCategory(
$this->writeServiceCategoryRepository,
$this->readServiceCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceCategoryRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(true);
$this->writeServiceCategoryRepository
->expects($this->once())
->method('deleteById');
$useCase($this->serviceCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceCategory/Domain/Model/NewServiceCategoryTest.php | centreon/tests/php/Core/ServiceCategory/Domain/Model/NewServiceCategoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceCategory\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\ServiceCategory\Domain\Model\NewServiceCategory;
beforeEach(function (): void {
$this->categoryName = 'service-name';
$this->categoryAlias = 'service-alias';
});
it('should return properly set service category instance', function (): void {
$serviceCategory = new NewServiceCategory($this->categoryName, $this->categoryAlias);
expect($serviceCategory->getName())->toBe($this->categoryName)
->and($serviceCategory->getAlias())->toBe($this->categoryAlias);
});
it('should trim the fields "name" and "alias"', function (): void {
$serviceCategory = new NewServiceCategory(
$nameWithSpaces = ' my-name ',
$aliasWithSpaces = ' my-alias '
);
expect($serviceCategory->getName())->toBe(trim($nameWithSpaces))
->and($serviceCategory->getAlias())->toBe(trim($aliasWithSpaces));
});
it('should throw an exception when service category name is empty', function (): void {
new NewServiceCategory('', $this->categoryAlias);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::minLength('', 0, NewServiceCategory::MIN_NAME_LENGTH, 'NewServiceCategory::name')
->getMessage()
);
it('should throw an exception when service category name is too long', function (): void {
new NewServiceCategory(str_repeat('a', NewServiceCategory::MAX_NAME_LENGTH + 1), $this->categoryAlias);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewServiceCategory::MAX_NAME_LENGTH + 1),
NewServiceCategory::MAX_NAME_LENGTH + 1,
NewServiceCategory::MAX_NAME_LENGTH,
'NewServiceCategory::name'
)->getMessage()
);
it('should throw an exception when service category alias is empty', function (): void {
new NewServiceCategory($this->categoryName, '');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::minLength('', 0, NewServiceCategory::MIN_ALIAS_LENGTH, 'NewServiceCategory::alias')
->getMessage()
);
it('should throw an exception when service category alias is too long', function (): void {
new NewServiceCategory($this->categoryName, str_repeat('a', NewServiceCategory::MAX_ALIAS_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewServiceCategory::MAX_ALIAS_LENGTH + 1),
NewServiceCategory::MAX_ALIAS_LENGTH + 1,
NewServiceCategory::MAX_ALIAS_LENGTH,
'NewServiceCategory::alias'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceCategory/Domain/Model/ServiceCategoryTest.php | centreon/tests/php/Core/ServiceCategory/Domain/Model/ServiceCategoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceCategory\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\ServiceCategory\Domain\Model\ServiceCategory;
beforeEach(function (): void {
$this->categoryName = 'service-name';
$this->categoryAlias = 'service-alias';
});
it('should return properly set service category instance', function (): void {
$serviceCategory = new ServiceCategory(1, $this->categoryName, $this->categoryAlias);
expect($serviceCategory->getId())->toBe(1)
->and($serviceCategory->getName())->toBe($this->categoryName)
->and($serviceCategory->getAlias())->toBe($this->categoryAlias);
});
it('should trim the fields "name" and "alias"', function (): void {
$serviceCategory = new ServiceCategory(
1,
$nameWithSpaces = ' my-name ',
$aliasWithSpaces = ' my-alias '
);
expect($serviceCategory->getName())->toBe(trim($nameWithSpaces))
->and($serviceCategory->getAlias())->toBe(trim($aliasWithSpaces));
});
it('should throw an exception when service category name is empty', function (): void {
new ServiceCategory(1, '', $this->categoryAlias);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::minLength('', 0, ServiceCategory::MIN_NAME_LENGTH, 'ServiceCategory::name')
->getMessage()
);
it('should throw an exception when service category name is too long', function (): void {
new ServiceCategory(1, str_repeat('a', ServiceCategory::MAX_NAME_LENGTH + 1), $this->categoryAlias);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', ServiceCategory::MAX_NAME_LENGTH + 1),
ServiceCategory::MAX_NAME_LENGTH + 1,
ServiceCategory::MAX_NAME_LENGTH,
'ServiceCategory::name'
)->getMessage()
);
it('should throw an exception when service category alias is empty', function (): void {
new ServiceCategory(1, $this->categoryName, '');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::minLength('', 0, ServiceCategory::MIN_ALIAS_LENGTH, 'ServiceCategory::alias')
->getMessage()
);
it('should throw an exception when service category alias is too long', function (): void {
new ServiceCategory(1, $this->categoryName, str_repeat('a', ServiceCategory::MAX_ALIAS_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', ServiceCategory::MAX_ALIAS_LENGTH + 1),
ServiceCategory::MAX_ALIAS_LENGTH + 1,
ServiceCategory::MAX_ALIAS_LENGTH,
'ServiceCategory::alias'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/User/Application/UseCase/FindCurrentUserParameters/FindCurrentUserParametersTest.php | centreon/tests/php/Core/User/Application/UseCase/FindCurrentUserParameters/FindCurrentUserParametersTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\User\Application\UseCase\FindCurrentUserParameters;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Menu\Model\Page;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Configuration\User\Exception\UserException;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
use Core\User\Application\UseCase\FindCurrentUserParameters\FindCurrentUserParameters;
use Core\User\Application\UseCase\FindCurrentUserParameters\FindCurrentUserParametersResponse;
use Core\User\Domain\Model\UserInterfaceDensity;
use Core\User\Domain\Model\UserTheme;
use Core\User\Infrastructure\Model\UserInterfaceDensityConverter;
use Core\User\Infrastructure\Model\UserThemeConverter;
use Tests\Core\User\Infrastructure\API\FindCurrentUserParameters\FindCurrentUserParametersPresenterStub;
beforeEach(function (): void {
$this->presenter = new FindCurrentUserParametersPresenterStub();
$this->useCase = new FindCurrentUserParameters(
$this->contact = $this->createMock(ContactInterface::class),
$this->rights = $this->createMock(DashboardRights::class)
);
$this->randomInt = static fn (): int => random_int(1, 1_000_000);
$this->randomBool = static fn (): bool => (bool) random_int(0, 1);
$this->randomString = static fn (): string => 'panel-' . mb_substr(md5(random_bytes(10)), 0, 6);
});
it(
'should present an ErrorResponse when an exception is thrown',
function (): void {
$this->contact->method('getId')->willThrowException($ex = new \Exception());
($this->useCase)($this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(UserException::errorWhileSearchingForUser($ex)->getMessage());
}
);
it(
'should present a valid response when the user is retrieved',
function (): void {
$rand
= $this->contact->method('hasRole')->willReturn($isExportButtonEnabled = true);
$this->contact->method('getId')->willReturn($id = ($this->randomInt)());
$this->contact->method('getName')->willReturn($name = ($this->randomString)());
$this->contact->method('getAlias')->willReturn($alias = ($this->randomString)());
$this->contact->method('getEmail')->willReturn($email = ($this->randomString)());
$this->contact->method('getTimezone')->willReturn($timezone = new \DateTimeZone('UTC'));
$this->contact->method('getLocale')->willReturn($locale = ($this->randomString)());
$this->contact->method('isAdmin')->willReturn($isAdmin = ($this->randomBool)());
$this->contact->method('isUsingDeprecatedPages')->willReturn($useDeprecatedPages = ($this->randomBool)());
$this->contact->method('isUsingDeprecatedCustomViews')->willReturn($useDeprecatedCustomViews = ($this->randomBool)());
$this->contact->method('getTheme')
->willReturn(UserThemeConverter::toString($theme = UserTheme::Dark));
$this->contact->method('getUserInterfaceDensity')
->willReturn(UserInterfaceDensityConverter::toString($uiDensity = UserInterfaceDensity::Extended));
$this->contact->method('getDefaultPage')->willReturn($page = $this->createMock(Page::class));
$page->method('getRedirectionUri')->willReturn($defaultPage = ($this->randomString)());
($this->useCase)($this->presenter);
expect($this->presenter->data)->toBeInstanceOf(FindCurrentUserParametersResponse::class)
->and($this->presenter->data->id)->toBe($id)
->and($this->presenter->data->name)->toBe($name)
->and($this->presenter->data->alias)->toBe($alias)
->and($this->presenter->data->email)->toBe($email)
->and($this->presenter->data->timezone)->toBe($timezone->getName())
->and($this->presenter->data->locale)->toBe($locale)
->and($this->presenter->data->isAdmin)->toBe($isAdmin)
->and($this->presenter->data->useDeprecatedPages)->toBe($useDeprecatedPages)
->and($this->presenter->data->useDeprecatedCustomViews)->toBe($useDeprecatedCustomViews)
->and($this->presenter->data->isExportButtonEnabled)->toBe($isExportButtonEnabled)
->and($this->presenter->data->theme)->toBe($theme)
->and($this->presenter->data->userInterfaceDensity)->toBe($uiDensity)
->and($this->presenter->data->defaultPage)->toBe($defaultPage)
->and($this->presenter->data->dashboardPermissions->hasViewerRole)->toBeFalse()
->and($this->presenter->data->dashboardPermissions->hasCreatorRole)->toBeFalse()
->and($this->presenter->data->dashboardPermissions->hasAdminRole)->toBeFalse()
->and($this->presenter->data->dashboardPermissions->globalRole)->toBeNull();
}
);
it(
'should present a valid dashboard permission dto in the response',
function (DashboardGlobalRole $globalRole): void {
$this->rights->method('hasViewerRole')->willReturn($hasViewerRole = ($this->randomBool)());
$this->rights->method('hasCreatorRole')->willReturn($hasCreatorRole = ($this->randomBool)());
$this->rights->method('hasAdminRole')->willReturn($hasAdminRole = ($this->randomBool)());
$this->rights->method('getGlobalRole')
->willReturn($globalRole);
($this->useCase)($this->presenter);
expect($this->presenter->data)->toBeInstanceOf(FindCurrentUserParametersResponse::class)
->and($this->presenter->data->dashboardPermissions->hasViewerRole)->toBe($hasViewerRole)
->and($this->presenter->data->dashboardPermissions->hasCreatorRole)->toBe($hasCreatorRole)
->and($this->presenter->data->dashboardPermissions->hasAdminRole)->toBe($hasAdminRole)
->and($this->presenter->data->dashboardPermissions->globalRole)->toBe($globalRole);
}
)->with(
iterator_to_array(
(static function (): \Generator {
foreach (DashboardGlobalRole::cases() as $role) {
yield $role->name => [$role];
}
})()
)
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/User/Application/UseCase/FindUsers/FindUsersTest.php | centreon/tests/php/Core/User/Application/UseCase/FindUsers/FindUsersTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\User\Application\UseCase\FindUsers;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\User\Application\Exception\UserException;
use Core\User\Application\Repository\ReadUserRepositoryInterface;
use Core\User\Application\UseCase\FindUsers\FindUsers;
use Core\User\Application\UseCase\FindUsers\FindUsersResponse;
use Core\User\Domain\Model\User;
use Tests\Core\User\Infrastructure\API\FindUsers\FindUsersPresenterStub;
beforeEach(function (): void {
$this->presenter = new FindUsersPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new FindUsers(
$this->readUserRepository = $this->createMock(ReadUserRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
$this->requestParameters = $this->createMock(RequestParametersInterface::class),
$this->isCloudPlatform = false,
$this->adminResolver = $this->createMock(AdminResolver::class)
);
$this->contact = new User(
1,
'alias',
'name',
'email',
true,
User::THEME_LIGHT,
User::USER_INTERFACE_DENSITY_COMPACT,
true
);
});
it(
'should present an ErrorResponse when an exception is thrown',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->willThrowException(new \Exception());
($this->useCase)($this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(UserException::errorWhileSearching(new \Exception())->getMessage());
}
);
it(
'should present an ForbiddenResponse when non-admin user doesn\'t have sufficient rights',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([]);
$this->user
->expects($this->exactly(2))
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(UserException::accessNotAllowed()->getMessage());
}
);
it(
'should present an ErrorResponse when an exception of type RequestParametersTranslatorException is thrown',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$exception = new RequestParametersTranslatorException('Error');
$this->readUserRepository
->expects($this->once())
->method('findAllByRequestParameters')
->willThrowException($exception);
($this->useCase)($this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe($exception->getMessage());
}
);
it(
'should present a valid response when the user has access to all users',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readUserRepository
->expects($this->once())
->method('findAllByRequestParameters')
->willReturn([$this->contact]);
($this->useCase)($this->presenter);
$response = $this->presenter->data;
expect($response)->toBeInstanceOf(FindUsersResponse::class)
->and($response->users[0]->id)->toBe($this->contact->getId())
->and($response->users[0]->name)->toBe($this->contact->getName());
}
);
it(
'should present a valid response when the user has restricted access to users',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([]);
$this->user
->expects($this->exactly(1))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_HOME_DASHBOARD_ADMIN, false],
[Contact::ROLE_CONFIGURATION_CONTACTS_READ, true],
]
);
$this->readUserRepository
->expects($this->once())
->method('findByAccessGroupsUserAndRequestParameters')
->willReturn([$this->contact]);
($this->useCase)($this->presenter);
$response = $this->presenter->data;
expect($response)->toBeInstanceOf(FindUsersResponse::class)
->and($response->users[0]->id)->toBe($this->contact->getId())
->and($response->users[0]->alias)->toBe($this->contact->getAlias());
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/User/Domain/Model/UserTest.php | centreon/tests/php/Core/User/Domain/Model/UserTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\User\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\User\Domain\Model\User;
beforeEach(function (): void {
$this->createUser = static fn (array $fields = []): User => new User(
...[
'id' => 1,
'name' => 'user-name',
'alias' => 'user-alias',
'email' => 'user@email.com',
'isAdmin' => false,
'theme' => User::THEME_LIGHT,
'userInterfaceDensity' => User::USER_INTERFACE_DENSITY_EXTENDED,
'canReachFrontend' => true,
...$fields,
]
);
});
// too short fields
foreach (
[
'name' => User::MIN_NAME_LENGTH,
'alias' => User::MIN_ALIAS_LENGTH,
'email' => User::MIN_EMAIL_LENGTH,
'theme' => User::MIN_THEME_LENGTH,
] as $field => $length
) {
$tooShort = '';
it(
"should throw an exception when user {$field} is too short",
fn () => ($this->createUser)([$field => $tooShort])
)->throws(
InvalidArgumentException::class,
AssertionException::minLength($tooShort, 0, $length, "User::{$field}")->getMessage()
);
}
// too long fields
foreach (
[
'name' => User::MAX_NAME_LENGTH,
'alias' => User::MAX_ALIAS_LENGTH,
'email' => User::MAX_EMAIL_LENGTH,
'theme' => User::MAX_THEME_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when user {$field} is too long",
fn () => ($this->createUser)([$field => $tooLong])
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "User::{$field}")->getMessage()
);
}
// invalid fields
it(
'should throw an exception when user ID is invalid',
fn () => ($this->createUser)(['id' => 0])
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(0, 'User::id')->getMessage()
);
it(
'should throw an exception when user interface density is invalid',
fn () => ($this->createUser)(['userInterfaceDensity' => 'hello world'])
)->throws(
\InvalidArgumentException::class,
'User interface view mode provided not handled'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/User/Infrastructure/API/FindCurrentUserParameters/FindCurrentUserParametersPresenterStub.php | centreon/tests/php/Core/User/Infrastructure/API/FindCurrentUserParameters/FindCurrentUserParametersPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\User\Infrastructure\API\FindCurrentUserParameters;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\User\Application\UseCase\FindCurrentUserParameters\FindCurrentUserParametersPresenterInterface;
use Core\User\Application\UseCase\FindCurrentUserParameters\FindCurrentUserParametersResponse;
class FindCurrentUserParametersPresenterStub implements FindCurrentUserParametersPresenterInterface
{
public FindCurrentUserParametersResponse|ResponseStatusInterface $data;
public function presentResponse(ResponseStatusInterface|FindCurrentUserParametersResponse $data): void
{
$this->data = $data;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/User/Infrastructure/API/FindUsers/FindUsersPresenterStub.php | centreon/tests/php/Core/User/Infrastructure/API/FindUsers/FindUsersPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\User\Infrastructure\API\FindUsers;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\User\Application\UseCase\FindUsers\FindUsersPresenterInterface;
use Core\User\Application\UseCase\FindUsers\FindUsersResponse;
class FindUsersPresenterStub extends AbstractPresenter implements FindUsersPresenterInterface
{
public FindUsersResponse|ResponseStatusInterface $data;
public function presentResponse(ResponseStatusInterface|FindUsersResponse $data): void
{
$this->data = $data;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Application/YesNoDefaultConverterTest.php | centreon/tests/php/Core/Common/Application/YesNoDefaultConverterTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use ValueError;
it('throw an error when value is invalid for convertion', function (): void {
$events = YesNoDefaultConverter::fromScalar('a');
})->throws(
ValueError::class,
'"a" is not a valid backing value for enum YesNoDefault'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Application/Type/NoValueTest.php | centreon/tests/php/Core/Common/Application/Type/NoValueTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Application\Type;
use Core\Common\Application\Type\NoValue;
it(
'should return the same value if not a NoValue object',
fn (mixed $value) => expect(
NoValue::coalesce($value, uniqid('random-default', true))
)->toBe($value)
)->with([
[null],
[123],
[123.456],
[true],
[false],
['a-string'],
[['an' => 'array']],
]);
it(
'should return the default value if it is a NoValue object',
fn () => expect(
NoValue::coalesce(new NoValue(), $default = uniqid('random-default', true))
)->toBe($default)
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Domain/TrimmedStringTest.php | centreon/tests/php/Core/Common/Domain/TrimmedStringTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain;
use Core\Common\Domain\TrimmedString;
it(
'should trim a string',
fn () => expect((new TrimmedString(' Hello World ! '))->value)
->toBe('Hello World !')
);
it(
'should trim a Stringable',
fn () => expect(
(new TrimmedString(
new class () implements \Stringable {
public function __toString(): string
{
return ' Hello World ! ';
}
}
))->value
)->toBe('Hello World !')
);
it(
'should implements a Stringable',
fn () => expect((string) new TrimmedString(' Hello World ! '))
->toBe('Hello World !')
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Domain/Collection/LiteralStringCollectionTest.php | centreon/tests/php/Core/Common/Domain/Collection/LiteralStringCollectionTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain\Collection;
use Core\Common\Domain\Collection\LiteralStringCollection;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\ValueObject\LiteralString;
beforeEach(function (): void {
$this->collection = new LiteralStringCollection();
});
it('clear collection', function (): void {
$this->collection->clear();
expect($this->collection->length())->toBe(0);
});
it('get length', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->add(2, new LiteralString('bar'));
expect($this->collection->length())->toBe(2);
});
it('if empty must be return true', function (): void {
expect($this->collection->isEmpty())->toBeTrue();
});
it('must to be return false if collection is empty', function (): void {
$this->collection->add(1, new LiteralString('foo'));
expect($this->collection->isEmpty())->toBeFalse();
});
it('return true if item exists', function (): void {
$item = new LiteralString('foo');
$this->collection->add(1, $item);
expect($this->collection->contains($item))->toBeTrue();
});
it('return false if item does not exist', function (): void {
$item = new LiteralString('foo');
expect($this->collection->contains($item))->toBeFalse();
});
it('if the key exists, item will be returned', function (): void {
$item = new LiteralString('foo');
$this->collection->add(1, $item);
expect($this->collection->get(1))->toBe($item);
});
it('if the key does not exist, a CollectionException will be thrown', function (): void {
$this->collection->get(3);
})->throws(CollectionException::class);
it('if the key exists, return true', function (): void {
$this->collection->add(1, new LiteralString('foo'));
expect($this->collection->has(1))->toBeTrue();
});
it('if the key does not exist, return false', function (): void {
expect($this->collection->has(3))->toBeFalse();
});
it('return the keys of the collection as an array', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->add(2, new LiteralString('bar'));
expect($this->collection->keys())->toEqual([1, 2]);
});
it('return position of an item of a collection', function (): void {
$item = new LiteralString('foo');
$this->collection->add('bar', $item);
expect($this->collection->indexOf($item))->toBe(0);
});
it('sort a collection by values', function (): void {
$class1 = new LiteralString('foo');
$class2 = new LiteralString('bar');
$orderedArray = [$class2, $class1];
$this->collection->add(1, $class1);
$this->collection->add(2, $class2);
$this->collection->sortByValues(fn ($varA, $varB) => array_search($varA, $orderedArray, true) <=> array_search($varB, $orderedArray, true));
expect($this->collection->get(0))->toBe($class2)
->and($this->collection->get(1))->toBe($class1);
});
it('sort a collection by keys', function (): void {
$class1 = new LiteralString('foo');
$class2 = new LiteralString('bar');
$orderedArray = ['b' => 1, 'a' => 2];
$this->collection->add('a', $class1);
$this->collection->add('b', $class2);
$this->collection->sortByKeys(function ($varA, $varB) use ($orderedArray) {
$indexA = $orderedArray[$varA];
$indexB = $orderedArray[$varB];
return $indexA <=> $indexB;
});
expect($this->collection->indexOf($class1))->toBe(1)
->and($this->collection->indexOf($class2))->toBe(0);
});
it('test filter on values', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->add(2, new LiteralString('bar'));
$collection = $this->collection->filterOnValue(fn (LiteralString $item) => $item->getValue() === 'foo');
expect($collection->length())->toBe(1)
->and($collection->get(1)->getValue())->toBe('foo');
});
it('test filter on keys', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->add(2, new LiteralString('bar'));
$collection = $this->collection->filterOnKey(fn (int $key) => $key === 1);
expect($collection->length())->toBe(1)
->and($collection->get(1)->getValue())->toBe('foo');
});
it('test filter on values and keys', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->add(2, new LiteralString('bar'));
$collection = $this->collection->filterOnValueKey(fn (LiteralString $item, int $key) => $item->getValue() === 'foo' && $key === 1);
expect($collection->length())->toBe(1)
->and($collection->get(1)->getValue())->toBe('foo');
});
it('test merge LiteralString collections', function (): void {
$collection1 = new LiteralStringCollection();
$collection1->add(3, new LiteralString('foo'));
$collection1->add(4, new LiteralString('bar'));
$collection2 = new LiteralStringCollection();
$collection2->add(5, new LiteralString('foo'));
$collection2->add(6, new LiteralString('bar'));
$this->collection->mergeWith($collection1, $collection2);
expect($this->collection->length())->toBe(4)
->and($this->collection->keys())->toEqual([3, 4, 5, 6]);
});
it('return the array of items', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->add(2, new LiteralString('bar'));
expect($this->collection->toArray())->toBeArray()->toHaveCount(2);
});
it('add an item at the collection (add)', function (): void {
$this->collection->add(1, new LiteralString('foo'));
expect($this->collection->length())->toBe(1)
->and($this->collection->keys())->toEqual([1]);
});
it('the item must not to be added, a CollectionException should be thrown (add)', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->add(1, new LiteralString('bar'));
})->throws(CollectionException::class);
it(
'the item must not to be added, a CollectionException should be thrown if the item is not good class (add)',
function (): void {
$this->collection->add(1, new \DateTime());
}
)->throws(CollectionException::class);
it('the item must to be added (put)', function (): void {
$this->collection->put(1, new LiteralString('foo'));
expect($this->collection->length())->toBe(1)
->and($this->collection->keys())->toEqual([1]);
});
it('the item must not to be added with put because the key exists (put)', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->put(1, new LiteralString('foo'));
expect($this->collection->length())->toBe(1)
->and($this->collection->keys())->toEqual([1]);
});
it(
'the item must not to be added, a CollectionException should be thrown if the item is not the good class (put)',
function (): void {
$this->collection->put(1, new \DateTime());
}
)->throws(CollectionException::class);
it('must to remove an item and return true', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$result = $this->collection->remove(1);
expect($this->collection->length())->toBe(0)
->and($this->collection->keys())->toEqual([])
->and($result)->toBeTrue();
});
it('must not to remove an item and return false', function (): void {
$result = $this->collection->remove(1);
expect($this->collection->length())->toBe(0)
->and($this->collection->keys())->toEqual([])
->and($result)->toBeFalse();
});
it('return an iterator', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$items = iterator_to_array($this->collection->getIterator());
expect($items)->toEqual($this->collection->toArray());
});
it('json serialize', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->add(2, new LiteralString('bar'));
expect($this->collection->jsonSerialize())->toBe([1 => 'foo', 2 => 'bar']);
});
it('json encode', function (): void {
$this->collection->add(1, new LiteralString('foo'));
$this->collection->add(2, new LiteralString('bar'));
expect($this->collection->toJson())->toBe(json_encode($this->collection->jsonSerialize()));
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Domain/Collection/ObjectCollectionTest.php | centreon/tests/php/Core/Common/Domain/Collection/ObjectCollectionTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain\Collection;
use Core\Common\Domain\Exception\CollectionException;
beforeEach(function (): void {
$this->collection = new ObjectCollectionStub();
});
it('clear collection', function (): void {
$this->collection->clear();
expect($this->collection->length())->toBe(0);
});
it('get length', function (): void {
$this->collection->add(1, new \stdClass());
$this->collection->add(2, new \stdClass());
expect($this->collection->length())->toBe(2);
});
it('if empty must be return true', function (): void {
expect($this->collection->isEmpty())->toBeTrue();
});
it('must to be return false if collection is empty', function (): void {
$this->collection->add(1, new \stdClass());
expect($this->collection->isEmpty())->toBeFalse();
});
it('return true if item exists', function (): void {
$item = new \stdClass();
$this->collection->add(1, $item);
expect($this->collection->contains($item))->toBeTrue();
});
it('return false if item does not exist', function (): void {
$item = new \stdClass();
expect($this->collection->contains($item))->toBeFalse();
});
it('if the key exists, item will be returned', function (): void {
$item = new \stdClass();
$this->collection->add(1, $item);
expect($this->collection->get(1))->toBe($item);
});
it('if the key does not exist, a CollectionException will be thrown', function (): void {
$this->collection->get(3);
})->throws(CollectionException::class);
it('if the key exists, return true', function (): void {
$this->collection->add(1, new \stdClass());
expect($this->collection->has(1))->toBeTrue();
});
it('if the key does not exist, return false', function (): void {
expect($this->collection->has(3))->toBeFalse();
});
it('return the keys of the collection as an array', function (): void {
$this->collection->add(1, new \stdClass());
$this->collection->add(2, new \stdClass());
expect($this->collection->keys())->toEqual([1, 2]);
});
it('return position of an item of a collection', function (): void {
$item = new \stdClass();
$this->collection->add('foo', $item);
expect($this->collection->indexOf($item))->toBe(0);
});
it('sort a collection by values', function (): void {
$class1 = new \stdClass();
$class1->value = 'foo';
$class2 = new \stdClass();
$class2->value = 'bar';
$orderedArray = [$class2, $class1];
$this->collection->add(1, $class1);
$this->collection->add(2, $class2);
$this->collection->sortByValues(fn ($varA, $varB) => array_search($varA, $orderedArray, true) <=> array_search($varB, $orderedArray, true));
expect($this->collection->get(0))->toBe($class2)
->and($this->collection->get(1))->toBe($class1);
});
it('sort a collection by keys', function (): void {
$class1 = new \stdClass();
$class1->value = 'foo';
$class2 = new \stdClass();
$class2->value = 'bar';
$orderedArray = ['b' => 1, 'a' => 2];
$this->collection->add('a', $class1);
$this->collection->add('b', $class2);
$this->collection->sortByKeys(function ($varA, $varB) use ($orderedArray) {
$indexA = $orderedArray[$varA];
$indexB = $orderedArray[$varB];
return $indexA <=> $indexB;
});
expect($this->collection->indexOf($class1))->toBe(1)
->and($this->collection->indexOf($class2))->toBe(0);
});
it('test filter on values', function (): void {
$class1 = new \stdClass();
$class1->value = 'foo';
$class2 = new \stdClass();
$class2->value = 'bar';
$this->collection->add(1, $class1);
$this->collection->add(2, $class2);
$filtered = $this->collection->filterOnValue(fn ($class) => $class->value === 'foo');
expect($filtered->length())->toBe(1)
->and($filtered->get(1))->toBe($class1);
});
it('test filter on keys', function (): void {
$class1 = new \stdClass();
$class1->value = 'foo';
$class2 = new \stdClass();
$class2->value = 'bar';
$this->collection->add(1, $class1);
$this->collection->add(2, $class2);
$filtered = $this->collection->filterOnKey(fn ($key) => $key === 1);
expect($filtered->length())->toBe(1)
->and($filtered->get(1))->toBe($class1);
});
it('test filter on values and keys', function (): void {
$class1 = new \stdClass();
$class1->value = 'foo';
$class2 = new \stdClass();
$class2->value = 'bar';
$this->collection->add(1, $class1);
$this->collection->add(2, $class2);
$filtered = $this->collection->filterOnValueKey(fn ($class, $key) => $class->value === 'foo' && $key === 1);
expect($filtered->length())->toBe(1)
->and($filtered->get(1))->toBe($class1);
});
it('test merge object collections', function (): void {
$collection1 = new ObjectCollectionStub();
$collection1->add(3, new \stdClass());
$collection1->add(4, new \stdClass());
$collection2 = new ObjectCollectionStub();
$collection2->add(5, new \stdClass());
$collection2->add(6, new \stdClass());
$this->collection->mergeWith($collection1, $collection2);
expect($this->collection->length())->toBe(4)
->and($this->collection->keys())->toEqual([3, 4, 5, 6]);
});
it('return the array of items', function (): void {
$this->collection->add(1, new \stdClass());
$this->collection->add(2, new \stdClass());
expect($this->collection->toArray())->toBeArray()->toHaveCount(2);
});
it('add an item at the collection (add)', function (): void {
$this->collection->add(1, new \stdClass());
expect($this->collection->length())->toBe(1)
->and($this->collection->keys())->toEqual([1]);
});
it('the item must not to be added, a CollectionException should be thrown (add)', function (): void {
$this->collection->add(1, new \stdClass());
$this->collection->add(1, new \stdClass());
})->throws(CollectionException::class);
it(
'the item must not to be added, a CollectionException should be thrown if the item is not good class (add)',
function (): void {
$this->collection->add(1, new \DateTime());
}
)->throws(CollectionException::class);
it('the item must to be added (put)', function (): void {
$this->collection->put(1, new \stdClass());
expect($this->collection->length())->toBe(1)
->and($this->collection->keys())->toEqual([1]);
});
it('the item must not to be added with put because the key exists (put)', function (): void {
$this->collection->add(1, new \stdClass());
$this->collection->put(1, new \stdClass());
expect($this->collection->length())->toBe(1)
->and($this->collection->keys())->toEqual([1]);
});
it(
'the item must not to be added, a CollectionException should be thrown if the item is not the good class (put)',
function (): void {
$this->collection->put(1, new \DateTime());
}
)->throws(CollectionException::class);
it('must to remove an item and return true', function (): void {
$this->collection->add(1, new \stdClass());
$result = $this->collection->remove(1);
expect($this->collection->length())->toBe(0)
->and($this->collection->keys())->toEqual([])
->and($result)->toBeTrue();
});
it('must not to remove an item and return false', function (): void {
$result = $this->collection->remove(1);
expect($this->collection->length())->toBe(0)
->and($this->collection->keys())->toEqual([])
->and($result)->toBeFalse();
});
it('return an iterator', function (): void {
$this->collection->add(1, new \stdClass());
$items = iterator_to_array($this->collection->getIterator());
expect($items)->toEqual($this->collection->toArray());
});
it('json serialize', function (): void {
$this->collection->add(1, new \stdClass());
$this->collection->add(2, new \stdClass());
expect($this->collection->jsonSerialize())->toBe([
1 => get_object_vars(new \stdClass()),
2 => get_object_vars(new \stdClass()),
]);
});
it('json encode', function (): void {
$this->collection->add(1, new \stdClass());
$this->collection->add(2, new \stdClass());
expect($this->collection->toJson())->toBe(json_encode($this->collection->jsonSerialize()));
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Domain/Collection/ObjectCollectionStub.php | centreon/tests/php/Core/Common/Domain/Collection/ObjectCollectionStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Core\Common\Domain\Collection;
use Core\Common\Domain\Collection\ObjectCollection;
class ObjectCollectionStub extends ObjectCollection
{
protected function itemClass(): string
{
return \stdClass::class;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Domain/Collection/StringCollectionTest.php | centreon/tests/php/Core/Common/Domain/Collection/StringCollectionTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain\Collection;
use Core\Common\Domain\Collection\StringCollection;
use Core\Common\Domain\Exception\CollectionException;
beforeEach(function (): void {
$this->collection = new StringCollection();
});
it('clear collection', function (): void {
$this->collection->clear();
expect($this->collection->length())->toBe(0);
});
it('get length', function (): void {
$this->collection->add(1, 'foo');
$this->collection->add(2, 'bar');
expect($this->collection->length())->toBe(2);
});
it('if empty must be return true', function (): void {
expect($this->collection->isEmpty())->toBeTrue();
});
it('must to be return false if collection is empty', function (): void {
$this->collection->add(1, 'foo');
expect($this->collection->isEmpty())->toBeFalse();
});
it('return true if item exists', function (): void {
$item = 'foo';
$this->collection->add(1, $item);
expect($this->collection->contains($item))->toBeTrue();
});
it('return false if item does not exist', function (): void {
$item = 'foo';
expect($this->collection->contains($item))->toBeFalse();
});
it('if the key exists, item will be returned', function (): void {
$item = 'foo';
$this->collection->add(1, $item);
expect($this->collection->get(1))->toBe($item);
});
it('if the key does not exist, a CollectionException will be thrown', function (): void {
$this->collection->get(3);
})->throws(CollectionException::class);
it('if the key exists, return true', function (): void {
$this->collection->add(1, 'foo');
expect($this->collection->has(1))->toBeTrue();
});
it('if the key does not exist, return false', function (): void {
expect($this->collection->has(3))->toBeFalse();
});
it('return the keys of the collection as an array', function (): void {
$this->collection->add(1, 'foo');
$this->collection->add(2, 'bar');
expect($this->collection->keys())->toEqual([1, 2]);
});
it('return position of an item of a collection', function (): void {
$item = 'foo';
$this->collection->add('bar', $item);
expect($this->collection->indexOf($item))->toBe(0);
});
it('sort a collection by values', function (): void {
$item = 'foo';
$item2 = 'bar';
$orderedArray = [$item2, $item];
$this->collection->add(1, $item);
$this->collection->add(2, $item2);
$this->collection->sortByValues(fn ($varA, $varB) => array_search($varA, $orderedArray, true) <=> array_search($varB, $orderedArray, true));
expect($this->collection->get(0))->toBe($item2)
->and($this->collection->get(1))->toBe($item);
});
it('sort a collection by keys', function (): void {
$item = 'foo';
$item2 = 'bar';
$orderedArray = ['b' => 1, 'a' => 2];
$this->collection->add('a', $item);
$this->collection->add('b', $item2);
$this->collection->sortByKeys(function ($varA, $varB) use ($orderedArray) {
$indexA = $orderedArray[$varA];
$indexB = $orderedArray[$varB];
return $indexA <=> $indexB;
});
expect($this->collection->indexOf($item))->toBe(1)
->and($this->collection->indexOf($item2))->toBe(0);
});
it('test filter on values', function (): void {
$this->collection->add(1, 'foo');
$this->collection->add(2, 'bar');
$filtered = $this->collection->filterOnValue(fn ($value) => $value === 'foo');
expect($filtered->length())->toBe(1)
->and($filtered->keys())->toEqual([1])
->and($filtered->get(1))->toBe('foo');
});
it('test filter on keys', function (): void {
$this->collection->add(1, 'foo');
$this->collection->add(2, 'bar');
$filtered = $this->collection->filterOnKey(fn ($key) => $key === 1);
expect($filtered->length())->toBe(1)
->and($filtered->keys())->toEqual([1])
->and($filtered->get(1))->toBe('foo');
});
it('test filter on values and keys', function (): void {
$this->collection->add(1, 'foo');
$this->collection->add(2, 'bar');
$filtered = $this->collection->filterOnValueKey(fn ($value, $key) => $value === 'foo' && $key === 1);
expect($filtered->length())->toBe(1)
->and($filtered->keys())->toEqual([1])
->and($filtered->get(1))->toBe('foo');
});
it('test merge string collections', function (): void {
$collection1 = new StringCollection();
$collection1->add(3, 'foo');
$collection1->add(4, 'bar');
$collection2 = new StringCollection();
$collection2->add(5, 'foo');
$collection2->add(6, 'bar');
$this->collection->mergeWith($collection1, $collection2);
expect($this->collection->length())->toBe(4)
->and($this->collection->keys())->toEqual([3, 4, 5, 6]);
});
it('return the array of items', function (): void {
$this->collection->add(1, 'foo');
$this->collection->add(2, 'bar');
expect($this->collection->toArray())->toBeArray()->toHaveCount(2);
});
it('add an item at the collection (add)', function (): void {
$this->collection->add(1, 'foo');
expect($this->collection->length())->toBe(1)
->and($this->collection->keys())->toEqual([1]);
});
it('the item must not to be added, a CollectionException should be thrown (add)', function (): void {
$this->collection->add(1, 'foo');
$this->collection->add(1, 'foo');
})->throws(CollectionException::class);
it(
'the item must not to be added, a CollectionException should be thrown if the item is not good class (add)',
function (): void {
$this->collection->add(1, new \DateTime());
}
)->throws(CollectionException::class);
it('the item must to be added (put)', function (): void {
$this->collection->put(1, 'foo');
expect($this->collection->length())->toBe(1)
->and($this->collection->keys())->toEqual([1]);
});
it('the item must not to be added with put because the key exists (put)', function (): void {
$this->collection->add(1, 'foo');
$this->collection->put(1, 'foo');
expect($this->collection->length())->toBe(1)
->and($this->collection->keys())->toEqual([1]);
});
it(
'the item must not to be added, a CollectionException should be thrown if the item is not a string (put)',
function (): void {
$this->collection->put(1, new \DateTime());
}
)->throws(CollectionException::class);
it('must to remove an item and return true', function (): void {
$this->collection->add(1, 'foo');
$result = $this->collection->remove(1);
expect($this->collection->length())->toBe(0)
->and($this->collection->keys())->toEqual([])
->and($result)->toBeTrue();
});
it('must not to remove an item and return false', function (): void {
$result = $this->collection->remove(1);
expect($this->collection->length())->toBe(0)
->and($this->collection->keys())->toEqual([])
->and($result)->toBeFalse();
});
it('return an iterator', function (): void {
$this->collection->add(1, 'foo');
$items = iterator_to_array($this->collection->getIterator());
expect($items)->toEqual($this->collection->toArray());
});
it('json serialize', function (): void {
$this->collection->add('key1', 'foo');
$this->collection->add('key2', 'bar');
expect($this->collection->jsonSerialize())->toEqual(['key1' => 'foo', 'key2' => 'bar']);
});
it('json encode', function (): void {
$this->collection->add(1, 'foo');
$this->collection->add(2, 'bar');
expect($this->collection->toJson())->toBe(json_encode($this->collection->jsonSerialize()));
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.