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/HostTemplate/Application/PartialUpdateHostTemplate/PartialUpdateHostTemplateValidationTest.php | centreon/tests/php/Core/HostTemplate/Application/PartialUpdateHostTemplate/PartialUpdateHostTemplateValidationTest.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\HostTemplate\Application\UseCase\PartialUpdateHostTemplate;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\Host\Application\InheritanceManager;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostTemplate\Application\Exception\HostTemplateException;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\UseCase\PartialUpdateHostTemplate\PartialUpdateHostTemplateValidation;
use Core\HostTemplate\Domain\Model\HostTemplate;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\Timezone\Application\Repository\ReadTimezoneRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(function (): void {
$this->validation = new PartialUpdateHostTemplateValidation(
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class),
$this->readViewImgRepository = $this->createMock(ReadViewImgRepositoryInterface::class),
$this->readTimePeriodRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class),
$this->readHostSeverityRepository = $this->createMock(ReadHostSeverityRepositoryInterface::class),
$this->readTimezoneRepository = $this->createMock(ReadTimezoneRepositoryInterface::class),
$this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class),
$this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class),
$this->inheritanceManager = $this->createMock(InheritanceManager::class),
$this->user = $this->createMock(ContactInterface::class),
$this->accessGroup = []
);
});
it('throws an exception when name is already used', function (): void {
$hostTemplate = new HostTemplate(id: 1, name: 'template name', alias: 'template alias');
$this->readHostTemplateRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->validation->assertIsValidName('name test', $hostTemplate);
})->throws(
HostTemplateException::class,
HostTemplateException::nameAlreadyExists(HostTemplate::formatName('name test'), 'name test')->getMessage()
);
it('does not throw an exception when name is identical to given hostTemplate', function (): void {
$hostTemplate = new HostTemplate(id: 1, name: 'name test', alias: 'alias test');
$this->readHostTemplateRepository
->expects($this->exactly(0))
->method('existsByName');
$this->validation->assertIsValidName('name test', $hostTemplate);
});
it('throws an exception when icon ID does not exist', function (): void {
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(false);
$this->validation->assertIsValidIcon(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('iconId', 1)->getMessage()
);
it('throws an exception when time period ID does not exist', function (): void {
$this->readTimePeriodRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidTimePeriod(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('timePeriodId', 1)->getMessage()
);
it('throws an exception when severity ID does not exist', function (): void {
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidSeverity(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('severityId', 1)->getMessage()
);
it('throws an exception when timezone ID does not exist', function (): void {
$this->readTimezoneRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidTimezone(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('timezoneId', 1)->getMessage()
);
it('throws an exception when command ID does not exist', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidCommand(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('commandId', 1)->getMessage()
);
it('throws an exception when command ID does not exist for a specific type', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('existsByIdAndCommandType')
->willReturn(false);
$this->validation->assertIsValidCommand(1, CommandType::Check);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('commandId', 1)->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->readHostCategoryRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidCategories([1, 3]);
})->throws(
HostTemplateException::class,
HostTemplateException::idsDoNotExist('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->readHostCategoryRepository
->expects($this->once())
->method('existByAccessGroups')
->willReturn([]);
$this->validation->assertAreValidCategories([1, 3]);
})->throws(
HostTemplateException::class,
HostTemplateException::idsDoNotExist('categories', [1, 3])->getMessage()
);
it('throws an exception when parent template ID does not exist', function (): void {
$this->readHostTemplateRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidTemplates([1, 3], 4);
})->throws(
HostTemplateException::class,
HostTemplateException::idsDoNotExist('templates', [1, 3])->getMessage()
);
it('throws an exception when parent template ID create a circular inheritance', function (): void {
$this->readHostTemplateRepository
->expects($this->once())
->method('exist')
->willReturn([1, 3]);
$this->validation->assertAreValidTemplates([1, 3], 3);
})->throws(
HostTemplateException::class,
HostTemplateException::circularTemplateInheritance()->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/HostTemplate/Application/AddHostTemplate/AddHostTemplateValidationTest.php | centreon/tests/php/Core/HostTemplate/Application/AddHostTemplate/AddHostTemplateValidationTest.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\HostTemplate\Application\UseCase\AddHostTemplate;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostTemplate\Application\Exception\HostTemplateException;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplateValidation;
use Core\HostTemplate\Domain\Model\HostTemplate;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\Timezone\Application\Repository\ReadTimezoneRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(function (): void {
$this->validation = new AddHostTemplateValidation(
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class),
$this->readViewImgRepository = $this->createMock(ReadViewImgRepositoryInterface::class),
$this->readTimePeriodRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class),
$this->readHostSeverityRepository = $this->createMock(ReadHostSeverityRepositoryInterface::class),
$this->readTimezoneRepository = $this->createMock(ReadTimezoneRepositoryInterface::class),
$this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class),
$this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class)
);
});
it('throws an exception when name is already used', function (): void {
$this->readHostTemplateRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->validation->assertIsValidName('name test');
})->throws(
HostTemplateException::class,
HostTemplateException::nameAlreadyExists(HostTemplate::formatName('name test'), 'name test')->getMessage()
);
it('throws an exception when icon ID does not exist', function (): void {
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(false);
$this->validation->assertIsValidIcon(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('iconId', 1)->getMessage()
);
it('throws an exception when time period ID does not exist', function (): void {
$this->readTimePeriodRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidTimePeriod(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('timePeriodId', 1)->getMessage()
);
it('throws an exception when severity ID does not exist', function (): void {
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidSeverity(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('severityId', 1)->getMessage()
);
it('throws an exception when timezone ID does not exist', function (): void {
$this->readTimezoneRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidTimezone(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('timezoneId', 1)->getMessage()
);
it('throws an exception when command ID does not exist', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidCommand(1);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('commandId', 1)->getMessage()
);
it('throws an exception when command ID does not exist for a specific type', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('existsByIdAndCommandType')
->willReturn(false);
$this->validation->assertIsValidCommand(1, CommandType::Check);
})->throws(
HostTemplateException::class,
HostTemplateException::idDoesNotExist('commandId', 1)->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->readHostCategoryRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidCategories([1, 3]);
})->throws(
HostTemplateException::class,
HostTemplateException::idsDoNotExist('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->readAccessGroupRepository
->expects($this->once())
->method('findByContact');
$this->readHostCategoryRepository
->expects($this->once())
->method('existByAccessGroups')
->willReturn([]);
$this->validation->assertAreValidCategories([1, 3]);
})->throws(
HostTemplateException::class,
HostTemplateException::idsDoNotExist('categories', [1, 3])->getMessage()
);
it('throws an exception when parent template ID create a circular inheritance', function (): void {
$this->validation->assertAreValidTemplates([1, 3], 3);
})->throws(
HostTemplateException::class,
HostTemplateException::circularTemplateInheritance()->getMessage()
);
it('throws an exception when parent template ID does not exist', function (): void {
$this->readHostTemplateRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidTemplates([1, 3], 4);
})->throws(
HostTemplateException::class,
HostTemplateException::idsDoNotExist('templates', [1, 3])->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/HostTemplate/Application/AddHostTemplate/AddHostTemplateTest.php | centreon/tests/php/Core/HostTemplate/Application/AddHostTemplate/AddHostTemplateTest.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\ServiceSeverity\Application\UseCase\AddServiceSeverity;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Option\Option;
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\InvalidArgumentResponse;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\SnmpVersion;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\HostTemplate\Application\Exception\HostTemplateException;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplate;
use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplateRequest;
use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplateResponse;
use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplateValidation;
use Core\HostTemplate\Domain\Model\HostTemplate;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Tests\Core\HostTemplate\Infrastructure\API\AddHostTemplate\AddHostTemplatePresenterStub;
beforeEach(function (): void {
$this->presenter = new AddHostTemplatePresenterStub(
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class)
);
$this->useCase = new AddHostTemplate(
$this->writeHostTemplateRepository = $this->createMock(WriteHostTemplateRepositoryInterface::class),
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class),
$this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class),
$this->writeHostCategoryRepository = $this->createMock(WriteHostCategoryRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readHostMacroRepository = $this->createMock(ReadHostMacroRepositoryInterface::class),
$this->readCommandMacroRepository = $this->createMock(ReadCommandMacroRepositoryInterface::class),
$this->writeHostMacroRepository = $this->createMock(WriteHostMacroRepositoryInterface::class),
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->optionService = $this->createMock(OptionService::class),
$this->user = $this->createMock(ContactInterface::class),
$this->validation = $this->createMock(AddHostTemplateValidation::class),
$this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class),
$this->readVaultRepository = $this->createMock(ReadVaultRepositoryInterface::class),
);
$this->inheritanceModeOption = new Option();
$this->inheritanceModeOption->setName('inheritanceMode')->setValue('1');
// Settup host template
$this->request = new AddHostTemplateRequest();
$this->request->name = ' host template name ';
$this->request->alias = ' host-template-alias ';
$this->request->snmpVersion = SnmpVersion::Two->value;
$this->request->snmpCommunity = 'snmpCommunity-value';
$this->request->timezoneId = 1;
$this->request->severityId = 1;
$this->request->checkCommandId = 1;
$this->request->checkCommandArgs = ['arg1', 'arg2'];
$this->request->checkTimeperiodId = 1;
$this->request->maxCheckAttempts = 5;
$this->request->normalCheckInterval = 5;
$this->request->retryCheckInterval = 5;
$this->request->activeCheckEnabled = 1;
$this->request->passiveCheckEnabled = 1;
$this->request->notificationEnabled = 1;
$this->request->notificationOptions = HostEventConverter::toBitFlag([HostEvent::Down, HostEvent::Unreachable]);
$this->request->notificationInterval = 5;
$this->request->notificationTimeperiodId = 2;
$this->request->addInheritedContactGroup = true;
$this->request->addInheritedContact = true;
$this->request->firstNotificationDelay = 5;
$this->request->recoveryNotificationDelay = 5;
$this->request->acknowledgementTimeout = 5;
$this->request->freshnessChecked = 1;
$this->request->freshnessThreshold = 5;
$this->request->flapDetectionEnabled = 1;
$this->request->lowFlapThreshold = 5;
$this->request->highFlapThreshold = 5;
$this->request->eventHandlerEnabled = YesNoDefaultConverter::fromScalar(1);
$this->request->eventHandlerCommandId = 2;
$this->request->eventHandlerCommandArgs = ['arg3', ' arg4'];
$this->request->noteUrl = 'noteUrl-value';
$this->request->note = 'note-value';
$this->request->actionUrl = 'actionUrl-value';
$this->request->iconId = 1;
$this->request->iconAlternative = 'iconAlternative-value';
$this->request->comment = 'comment-value';
$this->hostTemplate = new HostTemplate(
id: 1,
name: $this->request->name,
alias: $this->request->alias,
snmpVersion: SnmpVersion::from($this->request->snmpVersion),
snmpCommunity: $this->request->snmpCommunity,
timezoneId: $this->request->timezoneId,
severityId: $this->request->severityId,
checkCommandId: $this->request->checkCommandId,
checkCommandArgs: ['arg1', 'test2'],
checkTimeperiodId: $this->request->checkTimeperiodId,
maxCheckAttempts: $this->request->maxCheckAttempts,
normalCheckInterval: $this->request->normalCheckInterval,
retryCheckInterval: $this->request->retryCheckInterval,
activeCheckEnabled: YesNoDefaultConverter::fromScalar($this->request->activeCheckEnabled),
passiveCheckEnabled: YesNoDefaultConverter::fromScalar($this->request->passiveCheckEnabled),
notificationEnabled: YesNoDefaultConverter::fromScalar($this->request->notificationEnabled),
notificationOptions: HostEventConverter::fromBitFlag($this->request->notificationOptions),
notificationInterval: $this->request->notificationInterval,
notificationTimeperiodId: $this->request->notificationTimeperiodId,
addInheritedContactGroup: $this->request->addInheritedContactGroup,
addInheritedContact: $this->request->addInheritedContact,
firstNotificationDelay: $this->request->firstNotificationDelay,
recoveryNotificationDelay: $this->request->recoveryNotificationDelay,
acknowledgementTimeout: $this->request->acknowledgementTimeout,
freshnessChecked: YesNoDefaultConverter::fromScalar($this->request->freshnessChecked),
freshnessThreshold: $this->request->freshnessThreshold,
flapDetectionEnabled: YesNoDefaultConverter::fromScalar($this->request->flapDetectionEnabled),
lowFlapThreshold: $this->request->lowFlapThreshold,
highFlapThreshold: $this->request->highFlapThreshold,
eventHandlerEnabled: $this->request->eventHandlerEnabled,
eventHandlerCommandId: $this->request->eventHandlerCommandId,
eventHandlerCommandArgs: $this->request->eventHandlerCommandArgs,
noteUrl: $this->request->noteUrl,
note: $this->request->note,
actionUrl: $this->request->actionUrl,
iconId: $this->request->iconId,
iconAlternative: $this->request->iconAlternative,
comment: $this->request->comment,
isLocked: false,
);
// Settup categories
$this->categories = [
$this->categoryA = new HostCategory(12, 'cat-name-A', 'cat-alias-A'),
$this->categoryB = new HostCategory(13, 'cat-name-B', 'cat-alias-B'),
];
$this->request->categories = [$this->categoryA->getId(), $this->categoryB->getId()];
// Settup parent templates
$this->request->templates = [4, 8];
$this->parentTemplates = [
['id' => 4, 'name' => 'template-A'],
['id' => 8, 'name' => 'template-B'],
];
// Settup macros
$this->macroA = new Macro(1, $this->hostTemplate->getId(), 'macroNameA', 'macroValueA');
$this->macroA->setOrder(0);
$this->macroB = new Macro(2, $this->hostTemplate->getId(), 'macroNameB', 'macroValueB');
$this->macroB->setOrder(1);
$this->commandMacro = new CommandMacro(1, CommandMacroType::Host, 'commandMacroName');
$this->commandMacros = [
$this->commandMacro->getName() => $this->commandMacro,
];
$this->hostMacros = [
$this->macroA->getName() => $this->macroA,
$this->macroB->getName() => $this->macroB,
];
$this->inheritanceInfos = [
['parent_id' => 4, 'child_id' => 1, 'order' => 1],
['parent_id' => 8, 'child_id' => 1, 'order' => 2],
];
$this->request->macros = [
[
'name' => $this->macroA->getName(),
'value' => $this->macroA->getValue(),
'is_password' => $this->macroA->isPassword(),
'description' => $this->macroA->getDescription(),
],
[
'name' => $this->macroB->getName(),
'value' => $this->macroB->getValue(),
'is_password' => $this->macroB->isPassword(),
'description' => $this->macroB->getDescription(),
],
];
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostTemplateException::addHostTemplate()->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->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostTemplateException::addNotAllowed()->getMessage());
});
it('should present a ConflictResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidName')
->willThrowException(
HostTemplateException::nameAlreadyExists(
HostTemplate::formatName($this->request->name),
$this->request->name
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostTemplateException::nameAlreadyExists(
HostTemplate::formatName($this->request->name),
$this->request->name
)->getMessage()
);
});
it('should present a ConflictResponse when host severity ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidSeverity')
->willThrowException(
HostTemplateException::idDoesNotExist('severityId', $this->request->severityId)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostTemplateException::idDoesNotExist('severityId', $this->request->severityId)->getMessage());
});
it('should present a ConflictResponse when a host timezone ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidTimezone')
->willThrowException(
HostTemplateException::idDoesNotExist('timezoneId', $this->request->timezoneId)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostTemplateException::idDoesNotExist('timezoneId', $this->request->timezoneId)->getMessage());
});
it('should present a ConflictResponse when a timeperiod ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidTimePeriod')
->willThrowException(
HostTemplateException::idDoesNotExist(
'checkTimeperiodId',
$this->request->checkTimeperiodId
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostTemplateException::idDoesNotExist(
'checkTimeperiodId',
$this->request->checkTimeperiodId
)->getMessage()
);
});
it('should present a ConflictResponse when a command ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidCommand')
->willThrowException(
HostTemplateException::idDoesNotExist(
'checkCommandId',
$this->request->checkCommandId
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostTemplateException::idDoesNotExist(
'checkCommandId',
$this->request->checkCommandId
)->getMessage()
);
});
it('should present a ConflictResponse when the host icon ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidIcon')
->willThrowException(
HostTemplateException::idDoesNotExist(
'iconId',
$this->request->iconId
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostTemplateException::idDoesNotExist(
'iconId',
$this->request->iconId
)->getMessage()
);
});
it('should present an InvalidArgumentResponse when a field assert failed', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->request->alias = '';
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->response->getMessage())
->toBe(AssertionException::notEmptyString('NewHostTemplate::alias')->getMessage());
});
it('should present a ConflictResponse when a host category ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->validation
->expects($this->once())
->method('assertAreValidCategories')
->willThrowException(
HostTemplateException::idsDoNotExist(
'categories',
[$this->request->categories[1]]
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostTemplateException::idsDoNotExist(
'categories',
[$this->request->categories[1]]
)->getMessage()
);
});
it('should present a ConflictResponse when a parent template ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->validation
->expects($this->once())
->method('assertAreValidTemplates')
->willThrowException(
HostTemplateException::idsDoNotExist('templates', $this->request->templates)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostTemplateException::idsDoNotExist(
'templates',
$this->request->templates
)->getMessage()
);
});
it('should present an ErrorResponse if the newly created host template cannot be retrieved', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->writeHostTemplateRepository
->expects($this->once())
->method('add')
->willReturn(1);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostTemplateException::errorWhileRetrievingObject()->getMessage());
});
it('should return created object on success (with admin user)', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation->expects($this->once())->method('assertIsValidName');
$this->validation->expects($this->once())->method('assertIsValidSeverity');
$this->validation->expects($this->once())->method('assertIsValidTimezone');
$this->validation->expects($this->exactly(2))->method('assertIsValidTimePeriod');
$this->validation->expects($this->exactly(2))->method('assertIsValidCommand');
$this->validation->expects($this->once())->method('assertIsValidIcon');
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->writeHostTemplateRepository
->expects($this->once())
->method('add')
->willReturn($this->hostTemplate->getId());
$this->validation->expects($this->once())->method('assertAreValidCategories');
$this->writeHostCategoryRepository
->expects($this->once())
->method('linkToHost');
$this->validation->expects($this->once())->method('assertAreValidTemplates');
$this->writeHostTemplateRepository
->expects($this->exactly(2))
->method('addParent');
$this->readHostTemplateRepository
->expects($this->once())
->method('findParents')
->willReturn($this->inheritanceInfos);
$this->readHostMacroRepository
->expects($this->once())
->method('findByHostIds')
->willReturn([]);
$this->readCommandMacroRepository
->expects($this->once())
->method('findByCommandIdAndType')
->willReturn($this->commandMacros);
$this->writeHostMacroRepository
->expects($this->exactly(2))
->method('add');
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostTemplate);
$this->readHostCategoryRepository
->expects($this->once())
->method('findByHost')
->willReturn($this->categories);
$this->readHostTemplateRepository
->expects($this->once())
->method('findNamesByIds')
->willReturn(
array_combine(
array_map((fn ($row) => $row['id']), $this->parentTemplates),
array_map((fn ($row) => $row['name']), $this->parentTemplates)
)
);
$this->readHostMacroRepository
->expects($this->once())
->method('findByHostId')
->willReturn($this->hostMacros);
($this->useCase)($this->request, $this->presenter);
$response = $this->presenter->response;
expect($response)->toBeInstanceOf(AddHostTemplateResponse::class)
->and($response->id)
->toBe($this->hostTemplate->getId())
->and($response->name)
->toBe($this->hostTemplate->getName())
->and($response->alias)
->toBe($this->hostTemplate->getAlias())
->and($response->snmpVersion)
->toBe($this->hostTemplate->getSnmpVersion()->value)
->and($response->timezoneId)
->toBe($this->hostTemplate->getTimezoneId())
->and($response->severityId)
->toBe($this->hostTemplate->getSeverityId())
->and($response->checkCommandId)
->toBe($this->hostTemplate->getCheckCommandId())
->and($response->checkCommandArgs)
->toBe($this->hostTemplate->getCheckCommandArgs())
->and($response->checkTimeperiodId)
->toBe($this->hostTemplate->getCheckTimeperiodId())
->and($response->maxCheckAttempts)
->toBe($this->hostTemplate->getMaxCheckAttempts())
->and($response->normalCheckInterval)
->toBe($this->hostTemplate->getNormalCheckInterval())
->and($response->retryCheckInterval)
->toBe($this->hostTemplate->getRetryCheckInterval())
->and($response->activeCheckEnabled)
->toBe(YesNoDefaultConverter::toInt($this->hostTemplate->getActiveCheckEnabled()))
->and($response->passiveCheckEnabled)
->toBe(YesNoDefaultConverter::toInt($this->hostTemplate->getPassiveCheckEnabled()))
->and($response->notificationEnabled)
->toBe(YesNoDefaultConverter::toInt($this->hostTemplate->getNotificationEnabled()))
->and($response->notificationOptions)
->toBe(HostEventConverter::toBitFlag($this->hostTemplate->getNotificationOptions()))
->and($response->notificationInterval)
->toBe($this->hostTemplate->getNotificationInterval())
->and($response->notificationTimeperiodId)
->toBe($this->hostTemplate->getNotificationTimeperiodId())
->and($response->addInheritedContactGroup)
->toBe($this->hostTemplate->addInheritedContactGroup())
->and($response->addInheritedContact)
->toBe($this->hostTemplate->addInheritedContact())
->and($response->firstNotificationDelay)
->toBe($this->hostTemplate->getFirstNotificationDelay())
->and($response->recoveryNotificationDelay)
->toBe($this->hostTemplate->getRecoveryNotificationDelay())
->and($response->acknowledgementTimeout)
->toBe($this->hostTemplate->getAcknowledgementTimeout())
->and($response->freshnessChecked)
->toBe(YesNoDefaultConverter::toInt($this->hostTemplate->getFreshnessChecked()))
->and($response->freshnessThreshold)
->toBe($this->hostTemplate->getFreshnessThreshold())
->and($response->flapDetectionEnabled)
->toBe(YesNoDefaultConverter::toInt($this->hostTemplate->getFlapDetectionEnabled()))
->and($response->lowFlapThreshold)
->toBe($this->hostTemplate->getLowFlapThreshold())
->and($response->highFlapThreshold)
->toBe($this->hostTemplate->getHighFlapThreshold())
->and($response->eventHandlerEnabled)
->toBe(YesNoDefaultConverter::toInt($this->hostTemplate->getEventHandlerEnabled()))
->and($response->eventHandlerCommandId)
->toBe($this->hostTemplate->getEventHandlerCommandId())
->and($response->eventHandlerCommandArgs)
->toBe($this->hostTemplate->getEventHandlerCommandArgs())
->and($response->noteUrl)
->toBe($this->hostTemplate->getNoteUrl())
->and($response->note)
->toBe($this->hostTemplate->getNote())
->and($response->actionUrl)
->toBe($this->hostTemplate->getActionUrl())
->and($response->iconId)
->toBe($this->hostTemplate->getIconId())
->and($response->iconAlternative)
->toBe($this->hostTemplate->getIconAlternative())
->and($response->comment)
->toBe($this->hostTemplate->getComment())
->and($response->categories)
->toBe(array_map(
(fn ($category) => ['id' => $category->getId(), 'name' => $category->getName()]),
$this->categories
))
->and($response->templates)
->toBe($this->parentTemplates)
->and($response->macros)
->toBe(array_map(
(fn ($macro) => [
'id' => $macro->getId(),
'name' => $macro->getName(),
'value' => $macro->getValue(),
'isPassword' => $macro->isPassword(),
'description' => $macro->getDescription(),
]),
$this->hostMacros
));
});
it('should return created object on success (with non-admin user)', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation->expects($this->once())->method('assertIsValidName');
$this->validation->expects($this->once())->method('assertIsValidSeverity');
$this->validation->expects($this->once())->method('assertIsValidTimezone');
$this->validation->expects($this->exactly(2))->method('assertIsValidTimePeriod');
$this->validation->expects($this->exactly(2))->method('assertIsValidCommand');
$this->validation->expects($this->once())->method('assertIsValidIcon');
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->writeHostTemplateRepository
->expects($this->once())
->method('add')
->willReturn($this->hostTemplate->getId());
$this->validation->expects($this->once())->method('assertAreValidCategories');
$this->writeHostCategoryRepository
->expects($this->once())
->method('linkToHost');
$this->validation->expects($this->once())->method('assertAreValidTemplates');
$this->writeHostTemplateRepository
->expects($this->exactly(2))
->method('addParent');
$this->validation->expects($this->once())->method('assertAreValidTemplates');
$this->writeHostTemplateRepository
->expects($this->exactly(2))
->method('addParent');
$this->readHostTemplateRepository
->expects($this->once())
->method('findParents')
->willReturn($this->inheritanceInfos);
$this->readHostMacroRepository
->expects($this->once())
->method('findByHostIds')
->willReturn([]);
$this->readCommandMacroRepository
->expects($this->once())
->method('findByCommandIdAndType')
->willReturn($this->commandMacros);
$this->writeHostMacroRepository
->expects($this->exactly(2))
->method('add');
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostTemplate);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact');
$this->readHostCategoryRepository
->expects($this->once())
->method('findByHostAndAccessGroups')
->willReturn($this->categories);
$this->readHostTemplateRepository
->expects($this->once())
->method('findNamesByIds')
->willReturn(
array_combine(
array_map((fn ($row) => $row['id']), $this->parentTemplates),
array_map((fn ($row) => $row['name']), $this->parentTemplates)
)
);
$this->readHostMacroRepository
->expects($this->once())
->method('findByHostId')
->willReturn($this->hostMacros);
($this->useCase)($this->request, $this->presenter);
$response = $this->presenter->response;
expect($response)->toBeInstanceOf(AddHostTemplateResponse::class)
->and($response->id)
->toBe($this->hostTemplate->getId())
->and($response->name)
->toBe($this->hostTemplate->getName())
->and($response->alias)
->toBe($this->hostTemplate->getAlias())
->and($response->snmpVersion)
->toBe($this->hostTemplate->getSnmpVersion()->value)
->and($response->timezoneId)
->toBe($this->hostTemplate->getTimezoneId())
->and($response->severityId)
->toBe($this->hostTemplate->getSeverityId())
->and($response->checkCommandId)
->toBe($this->hostTemplate->getCheckCommandId())
->and($response->checkCommandArgs)
->toBe($this->hostTemplate->getCheckCommandArgs())
->and($response->checkTimeperiodId)
->toBe($this->hostTemplate->getCheckTimeperiodId())
->and($response->maxCheckAttempts)
->toBe($this->hostTemplate->getMaxCheckAttempts())
->and($response->normalCheckInterval)
->toBe($this->hostTemplate->getNormalCheckInterval())
| 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/HostTemplate/Application/DeleteHostTemplate/DeleteHostTemplateTest.php | centreon/tests/php/Core/HostTemplate/Application/DeleteHostTemplate/DeleteHostTemplateTest.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\HostTemplate\Application\UseCase\DeleteHostTemplate;
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\HostTemplate\Application\Exception\HostTemplateException;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\UseCase\DeleteHostTemplate\DeleteHostTemplate;
use Core\HostTemplate\Domain\Model\HostTemplate;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
beforeEach(function (): void {
$this->writeHostTemplateRepository = $this->createMock(WriteHostTemplateRepositoryInterface::class);
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->user = $this->createMock(ContactInterface::class);
$this->hostTemplate = $this->createMock(HostTemplate::class);
$this->hostTemplateId = 1;
$this->useCase = new DeleteHostTemplate(
$this->writeHostTemplateRepository,
$this->readHostTemplateRepository,
$this->user,
$this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class),
$this->readHostMacroRepository = $this->createMock(ReadHostMacroRepositoryInterface::class),
);
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostTemplate);
$this->writeHostTemplateRepository
->expects($this->once())
->method('delete')
->willThrowException(new \Exception());
($this->useCase)($this->hostTemplateId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostTemplateException::deleteHostTemplate()->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->hostTemplateId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostTemplateException::deleteNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the host template does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->hostTemplateId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host template not found');
});
it('should present a NoContentResponse on success', function (): void {
$hostTemplateId = 1;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostTemplate);
$this->writeHostTemplateRepository
->expects($this->once())
->method('delete');
($this->useCase)($hostTemplateId, $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/HostTemplate/Application/FindHostTemplates/FindHostTemplatesTest.php | centreon/tests/php/Core/HostTemplate/Application/FindHostTemplates/FindHostTemplatesTest.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\HostTemplate\Application\UseCase\FindHostTemplates;
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\Application\Converter\YesNoDefaultConverter;
use Core\Common\Domain\YesNoDefault;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\SnmpVersion;
use Core\HostTemplate\Application\Exception\HostTemplateException;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\UseCase\FindHostTemplates\FindHostTemplates;
use Core\HostTemplate\Application\UseCase\FindHostTemplates\FindHostTemplatesResponse;
use Core\HostTemplate\Domain\Model\HostTemplate;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Tests\Core\HostTemplate\Infrastructure\API\FindHostTemplates\FindHostTemplatesPresenterStub;
beforeEach(function (): void {
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class);
$this->readAccessGroupsRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->presenter = new FindHostTemplatesPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new FindHostTemplates(
$this->readHostTemplateRepository,
$this->readAccessGroupsRepository,
$this->createMock(RequestParametersInterface::class),
$this->user
);
$this->testedHostTemplate = new HostTemplate(
1,
'host-template-name',
'host-template-alias',
SnmpVersion::Two,
'snmpCommunity-value',
1,
1,
1,
['arg1', 'arg2'],
1,
5,
5,
5,
YesNoDefault::Yes,
YesNoDefault::Yes,
YesNoDefault::Yes,
[HostEvent::Down, HostEvent::Unreachable],
5,
1,
true,
true,
5,
5,
5,
YesNoDefault::Yes,
5,
YesNoDefault::Yes,
5,
5,
YesNoDefault::Yes,
1,
['arg3', 'arg4'],
'noteUrl-value',
'note-value',
'actionUrl-value',
1,
'iconAlternative-value',
'comment-value',
true,
);
$this->testedHostTemplateArray = [
'id' => 1,
'name' => 'host-template-name',
'alias' => 'host-template-alias',
'snmpVersion' => SnmpVersion::Two->value,
'snmpCommunity' => 'snmpCommunity-value',
'timezoneId' => 1,
'severityId' => 1,
'checkCommandId' => 1,
'checkCommandArgs' => ['arg1', 'arg2'],
'checkTimeperiodId' => 1,
'maxCheckAttempts' => 5,
'normalCheckInterval' => 5,
'retryCheckInterval' => 5,
'activeCheckEnabled' => YesNoDefaultConverter::toInt(YesNoDefault::Yes),
'passiveCheckEnabled' => YesNoDefaultConverter::toInt(YesNoDefault::Yes),
'notificationEnabled' => YesNoDefaultConverter::toInt(YesNoDefault::Yes),
'notificationOptions' => HostEventConverter::toBitFlag([HostEvent::Down, HostEvent::Unreachable]),
'notificationInterval' => 5,
'notificationTimeperiodId' => 1,
'addInheritedContactGroup' => true,
'addInheritedContact' => true,
'firstNotificationDelay' => 5,
'recoveryNotificationDelay' => 5,
'acknowledgementTimeout' => 5,
'freshnessChecked' => YesNoDefaultConverter::toInt(YesNoDefault::Yes),
'freshnessThreshold' => 5,
'flapDetectionEnabled' => YesNoDefaultConverter::toInt(YesNoDefault::Yes),
'lowFlapThreshold' => 5,
'highFlapThreshold' => 5,
'eventHandlerEnabled' => YesNoDefaultConverter::toInt(YesNoDefault::Yes),
'eventHandlerCommandId' => 1,
'eventHandlerCommandArgs' => ['arg3', 'arg4'],
'noteUrl' => 'noteUrl-value',
'note' => 'note-value',
'actionUrl' => 'actionUrl-value',
'iconId' => 1,
'iconAlternative' => 'iconAlternative-value',
'comment' => 'comment-value',
'isLocked' => true,
];
});
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->once())
->method('isAdmin')
->willReturn(false);
$this->readHostTemplateRepository
->expects($this->once())
->method('findByRequestParametersAndAccessGroups')
->willThrowException(new \Exception());
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostTemplateException::findHostTemplates()->getMessage());
}
);
it(
'should present a ForbiddenResponse when the user insufficent rights',
function (): void {
$this->user
->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(HostTemplateException::accessNotAllowed()->getMessage());
}
);
it(
'should present a FindHostTemplatesResponse as user with read only rights',
function (): void {
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_TEMPLATES_READ, true],
[Contact::ROLE_CONFIGURATION_HOSTS_TEMPLATES_READ_WRITE, false],
]
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostTemplateRepository
->expects($this->once())
->method('findByRequestParameter')
->willReturn([$this->testedHostTemplate]);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindHostTemplatesResponse::class)
->and($this->presenter->response->hostTemplates[0])
->toBe($this->testedHostTemplateArray);
}
);
it(
'should present a FindHostTemplatesResponse as user with read-wite rights',
function (): void {
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_TEMPLATES_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_TEMPLATES_READ_WRITE, true],
]
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readHostTemplateRepository
->expects($this->once())
->method('findByRequestParametersAndAccessGroups')
->willReturn([$this->testedHostTemplate]);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindHostTemplatesResponse::class)
->and($this->presenter->response->hostTemplates[0])
->toBe($this->testedHostTemplateArray);
}
);
| 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/HostTemplate/Domain/Model/NewHostTemplateTest.php | centreon/tests/php/Core/HostTemplate/Domain/Model/NewHostTemplateTest.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\HostTemplate\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Common\Domain\YesNoDefault;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\SnmpVersion;
use Core\HostTemplate\Domain\Model\NewHostTemplate;
beforeEach(function (): void {
$this->createHostTemplate = static fn (array $fields = []): NewHostTemplate => new NewHostTemplate(
...[
'name' => 'host-template-name',
'alias' => 'host-template-alias',
'snmpVersion' => SnmpVersion::Two,
'snmpCommunity' => 'snmpCommunity-value',
'timezoneId' => 1,
'severityId' => 1,
'checkCommandId' => 1,
'checkCommandArgs' => ['arg1', 'arg2'],
'checkTimeperiodId' => 1,
'maxCheckAttempts' => 5,
'normalCheckInterval' => 5,
'retryCheckInterval' => 5,
'activeCheckEnabled' => YesNoDefault::Yes,
'passiveCheckEnabled' => YesNoDefault::Yes,
'notificationEnabled' => YesNoDefault::Yes,
'notificationOptions' => [HostEvent::Down, HostEvent::Unreachable],
'notificationInterval' => 5,
'notificationTimeperiodId' => 1,
'addInheritedContactGroup' => true,
'addInheritedContact' => true,
'firstNotificationDelay' => 5,
'recoveryNotificationDelay' => 5,
'acknowledgementTimeout' => 5,
'freshnessChecked' => YesNoDefault::Yes,
'freshnessThreshold' => 5,
'flapDetectionEnabled' => YesNoDefault::Yes,
'lowFlapThreshold' => 5,
'highFlapThreshold' => 5,
'eventHandlerEnabled' => YesNoDefault::Yes,
'eventHandlerCommandId' => 1,
'eventHandlerCommandArgs' => ['arg3', 'arg4'],
'noteUrl' => 'noteUrl-value',
'note' => 'note-value',
'actionUrl' => 'actionUrl-value',
'iconId' => 1,
'iconAlternative' => 'iconAlternative-value',
'comment' => 'comment-value',
'isLocked' => true,
...$fields,
]
);
});
it('should return properly set host template instance (all properties)', function (): void {
$hostTemplate = ($this->createHostTemplate)();
expect($hostTemplate->getName())->toBe('host-template-name')
->and($hostTemplate->getAlias())->toBe('host-template-alias')
->and($hostTemplate->getSnmpVersion())->toBe(SnmpVersion::Two)
->and($hostTemplate->getSnmpCommunity())->toBe('snmpCommunity-value')
->and($hostTemplate->getTimezoneId())->toBe(1)
->and($hostTemplate->getSeverityId())->toBe(1)
->and($hostTemplate->getCheckCommandId())->toBe(1)
->and($hostTemplate->getCheckCommandArgs())->toBe(['arg1', 'arg2'])
->and($hostTemplate->getCheckTimeperiodId())->toBe(1)
->and($hostTemplate->getMaxCheckAttempts())->toBe(5)
->and($hostTemplate->getNormalCheckInterval())->toBe(5)
->and($hostTemplate->getRetryCheckInterval())->toBe(5)
->and($hostTemplate->getActiveCheckEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getPassiveCheckEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getNotificationEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getNotificationOptions())->toBe([HostEvent::Down, HostEvent::Unreachable])
->and($hostTemplate->getNotificationInterval())->toBe(5)
->and($hostTemplate->getNotificationTimeperiodId())->toBe(1)
->and($hostTemplate->addInheritedContactGroup())->toBe(true)
->and($hostTemplate->addInheritedContact())->toBe(true)
->and($hostTemplate->getFirstNotificationDelay())->toBe(5)
->and($hostTemplate->getRecoveryNotificationDelay())->toBe(5)
->and($hostTemplate->getAcknowledgementTimeout())->toBe(5)
->and($hostTemplate->getFreshnessChecked())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getFreshnessThreshold())->toBe(5)
->and($hostTemplate->getFlapDetectionEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getLowFlapThreshold())->toBe(5)
->and($hostTemplate->getHighFlapThreshold())->toBe(5)
->and($hostTemplate->getEventHandlerEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getEventHandlerCommandId())->toBe(1)
->and($hostTemplate->getEventHandlerCommandArgs())->toBe(['arg3', 'arg4'])
->and($hostTemplate->getNoteUrl())->toBe('noteUrl-value')
->and($hostTemplate->getNote())->toBe('note-value')
->and($hostTemplate->getActionUrl())->toBe('actionUrl-value')
->and($hostTemplate->getIconId())->toBe(1)
->and($hostTemplate->getIconAlternative())->toBe('iconAlternative-value')
->and($hostTemplate->getComment())->toBe('comment-value')
->and($hostTemplate->isLocked())->toBe(true);
});
it('should return properly set host template instance (mandatory properties only)', function (): void {
$hostTemplate = new NewHostTemplate('host-template-name', 'host-template-alias');
expect($hostTemplate->getName())->toBe('host-template-name')
->and($hostTemplate->getAlias())->toBe('host-template-alias')
->and($hostTemplate->getSnmpVersion())->toBe(null)
->and($hostTemplate->getSnmpCommunity())->toBe('')
->and($hostTemplate->getTimezoneId())->toBe(null)
->and($hostTemplate->getSeverityId())->toBe(null)
->and($hostTemplate->getCheckCommandId())->toBe(null)
->and($hostTemplate->getCheckCommandArgs())->toBe([])
->and($hostTemplate->getCheckTimeperiodId())->toBe(null)
->and($hostTemplate->getMaxCheckAttempts())->toBe(null)
->and($hostTemplate->getNormalCheckInterval())->toBe(null)
->and($hostTemplate->getRetryCheckInterval())->toBe(null)
->and($hostTemplate->getActiveCheckEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getPassiveCheckEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getNotificationEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getNotificationOptions())->toBe([])
->and($hostTemplate->getNotificationInterval())->toBe(null)
->and($hostTemplate->getNotificationTimeperiodId())->toBe(null)
->and($hostTemplate->addInheritedContactGroup())->toBe(false)
->and($hostTemplate->addInheritedContact())->toBe(false)
->and($hostTemplate->getFirstNotificationDelay())->toBe(null)
->and($hostTemplate->getRecoveryNotificationDelay())->toBe(null)
->and($hostTemplate->getAcknowledgementTimeout())->toBe(null)
->and($hostTemplate->getFreshnessChecked())->toBe(YesNoDefault::Default)
->and($hostTemplate->getFreshnessThreshold())->toBe(null)
->and($hostTemplate->getFlapDetectionEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getLowFlapThreshold())->toBe(null)
->and($hostTemplate->getHighFlapThreshold())->toBe(null)
->and($hostTemplate->getEventHandlerEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getEventHandlerCommandId())->toBe(null)
->and($hostTemplate->getEventHandlerCommandArgs())->toBe([])
->and($hostTemplate->getNoteUrl())->toBe('')
->and($hostTemplate->getNote())->toBe('')
->and($hostTemplate->getActionUrl())->toBe('')
->and($hostTemplate->getIconId())->toBe(null)
->and($hostTemplate->getIconAlternative())->toBe('')
->and($hostTemplate->getComment())->toBe('')
->and($hostTemplate->isLocked())->toBe(false);
});
// mandatory fields
foreach (
[
'name',
'alias',
] as $field
) {
it(
"should throw an exception when host template {$field} is an empty string",
fn () => ($this->createHostTemplate)([$field => ' '])
)->throws(
InvalidArgumentException::class,
AssertionException::notEmptyString("NewHostTemplate::{$field}")->getMessage()
);
}
// name and conmmands args should be formated
it('should return trimmed and formatted name field after construct', function (): void {
$hostTemplate = new NewHostTemplate(' host template name ', 'alias');
expect($hostTemplate->getName())->toBe('host_template_name');
});
foreach (
[
'checkCommandArgs',
'eventHandlerCommandArgs',
] as $field
) {
it(
"should return a trimmed field {$field}",
function () use ($field): void {
$hostTemplate = ($this->createHostTemplate)([$field => [' arg1 ', ' arg2 ']]);
$valueFromGetter = $hostTemplate->{'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 {
$hostTemplate = ($this->createHostTemplate)([$field => ' abcd ']);
$valueFromGetter = $hostTemplate->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => NewHostTemplate::MAX_NAME_LENGTH,
'alias' => NewHostTemplate::MAX_ALIAS_LENGTH,
'snmpCommunity' => NewHostTemplate::MAX_SNMP_COMMUNITY_LENGTH,
'noteUrl' => NewHostTemplate::MAX_NOTE_URL_LENGTH,
'note' => NewHostTemplate::MAX_NOTE_LENGTH,
'actionUrl' => NewHostTemplate::MAX_ACTION_URL_LENGTH,
'iconAlternative' => NewHostTemplate::MAX_ICON_ALT_LENGTH,
'comment' => NewHostTemplate::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when host template {$field} is too long",
fn () => ($this->createHostTemplate)([$field => $tooLong])
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "NewHostTemplate::{$field}")->getMessage()
);
}
// foreign keys fields
foreach (
[
'timezoneId',
'severityId',
'checkCommandId',
'checkTimeperiodId',
'notificationTimeperiodId',
'eventHandlerCommandId',
'iconId',
] as $field
) {
it(
"should throw an exception when host template {$field} is not > 0",
fn () => ($this->createHostTemplate)([$field => 0])
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(0, "NewHostTemplate::{$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 template {$field} is not >= 0",
fn () => ($this->createHostTemplate)([$field => -1])
)->throws(
InvalidArgumentException::class,
AssertionException::min(-1, 0, "NewHostTemplate::{$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/HostTemplate/Domain/Model/HostTemplateTest.php | centreon/tests/php/Core/HostTemplate/Domain/Model/HostTemplateTest.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\HostTemplate\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Common\Domain\YesNoDefault;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\SnmpVersion;
use Core\HostTemplate\Domain\Model\HostTemplate;
beforeEach(function (): void {
$this->createHostTemplate = static fn (array $fields = []): HostTemplate => new HostTemplate(
...[
'id' => 1,
'name' => 'host-template-name',
'alias' => 'host-template-alias',
'snmpVersion' => SnmpVersion::Two,
'snmpCommunity' => 'snmpCommunity-value',
'timezoneId' => 1,
'severityId' => 1,
'checkCommandId' => 1,
'checkCommandArgs' => ['arg1', 'arg2'],
'checkTimeperiodId' => 1,
'maxCheckAttempts' => 5,
'normalCheckInterval' => 5,
'retryCheckInterval' => 5,
'activeCheckEnabled' => YesNoDefault::Yes,
'passiveCheckEnabled' => YesNoDefault::Yes,
'notificationEnabled' => YesNoDefault::Yes,
'notificationOptions' => [HostEvent::Down, HostEvent::Unreachable],
'notificationInterval' => 5,
'notificationTimeperiodId' => 1,
'addInheritedContactGroup' => true,
'addInheritedContact' => true,
'firstNotificationDelay' => 5,
'recoveryNotificationDelay' => 5,
'acknowledgementTimeout' => 5,
'freshnessChecked' => YesNoDefault::Yes,
'freshnessThreshold' => 5,
'flapDetectionEnabled' => YesNoDefault::Yes,
'lowFlapThreshold' => 5,
'highFlapThreshold' => 5,
'eventHandlerEnabled' => YesNoDefault::Yes,
'eventHandlerCommandId' => 1,
'eventHandlerCommandArgs' => ['arg3', 'arg4'],
'noteUrl' => 'noteUrl-value',
'note' => 'note-value',
'actionUrl' => 'actionUrl-value',
'iconId' => 1,
'iconAlternative' => 'iconAlternative-value',
'comment' => 'comment-value',
'isLocked' => true,
...$fields,
]
);
});
it('should return properly set host template instance (all properties)', function (): void {
$hostTemplate = ($this->createHostTemplate)();
expect($hostTemplate->getId())->toBe(1)
->and($hostTemplate->getName())->toBe('host-template-name')
->and($hostTemplate->getAlias())->toBe('host-template-alias')
->and($hostTemplate->getSnmpVersion())->toBe(SnmpVersion::Two)
->and($hostTemplate->getSnmpCommunity())->toBe('snmpCommunity-value')
->and($hostTemplate->getTimezoneId())->toBe(1)
->and($hostTemplate->getSeverityId())->toBe(1)
->and($hostTemplate->getCheckCommandId())->toBe(1)
->and($hostTemplate->getCheckCommandArgs())->toBe(['arg1', 'arg2'])
->and($hostTemplate->getCheckTimeperiodId())->toBe(1)
->and($hostTemplate->getMaxCheckAttempts())->toBe(5)
->and($hostTemplate->getNormalCheckInterval())->toBe(5)
->and($hostTemplate->getRetryCheckInterval())->toBe(5)
->and($hostTemplate->getActiveCheckEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getPassiveCheckEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getNotificationEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getNotificationOptions())->toBe([HostEvent::Down, HostEvent::Unreachable])
->and($hostTemplate->getNotificationInterval())->toBe(5)
->and($hostTemplate->getNotificationTimeperiodId())->toBe(1)
->and($hostTemplate->addInheritedContactGroup())->toBe(true)
->and($hostTemplate->addInheritedContact())->toBe(true)
->and($hostTemplate->getFirstNotificationDelay())->toBe(5)
->and($hostTemplate->getRecoveryNotificationDelay())->toBe(5)
->and($hostTemplate->getAcknowledgementTimeout())->toBe(5)
->and($hostTemplate->getFreshnessChecked())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getFreshnessThreshold())->toBe(5)
->and($hostTemplate->getFlapDetectionEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getLowFlapThreshold())->toBe(5)
->and($hostTemplate->getHighFlapThreshold())->toBe(5)
->and($hostTemplate->getEventHandlerEnabled())->toBe(YesNoDefault::Yes)
->and($hostTemplate->getEventHandlerCommandId())->toBe(1)
->and($hostTemplate->getEventHandlerCommandArgs())->toBe(['arg3', 'arg4'])
->and($hostTemplate->getNoteUrl())->toBe('noteUrl-value')
->and($hostTemplate->getNote())->toBe('note-value')
->and($hostTemplate->getActionUrl())->toBe('actionUrl-value')
->and($hostTemplate->getIconId())->toBe(1)
->and($hostTemplate->getIconAlternative())->toBe('iconAlternative-value')
->and($hostTemplate->getComment())->toBe('comment-value')
->and($hostTemplate->isLocked())->toBe(true);
});
it('should return properly set host template instance (mandatory properties only)', function (): void {
$hostTemplate = new HostTemplate(1, 'host-template-name', 'host-template-alias');
expect($hostTemplate->getId())->toBe(1)
->and($hostTemplate->getName())->toBe('host-template-name')
->and($hostTemplate->getAlias())->toBe('host-template-alias')
->and($hostTemplate->getSnmpVersion())->toBe(null)
->and($hostTemplate->getSnmpCommunity())->toBe('')
->and($hostTemplate->getTimezoneId())->toBe(null)
->and($hostTemplate->getSeverityId())->toBe(null)
->and($hostTemplate->getCheckCommandId())->toBe(null)
->and($hostTemplate->getCheckCommandArgs())->toBe([])
->and($hostTemplate->getCheckTimeperiodId())->toBe(null)
->and($hostTemplate->getMaxCheckAttempts())->toBe(null)
->and($hostTemplate->getNormalCheckInterval())->toBe(null)
->and($hostTemplate->getRetryCheckInterval())->toBe(null)
->and($hostTemplate->getActiveCheckEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getPassiveCheckEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getNotificationEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getNotificationOptions())->toBe([])
->and($hostTemplate->getNotificationInterval())->toBe(null)
->and($hostTemplate->getNotificationTimeperiodId())->toBe(null)
->and($hostTemplate->addInheritedContactGroup())->toBe(false)
->and($hostTemplate->addInheritedContact())->toBe(false)
->and($hostTemplate->getFirstNotificationDelay())->toBe(null)
->and($hostTemplate->getRecoveryNotificationDelay())->toBe(null)
->and($hostTemplate->getAcknowledgementTimeout())->toBe(null)
->and($hostTemplate->getFreshnessChecked())->toBe(YesNoDefault::Default)
->and($hostTemplate->getFreshnessThreshold())->toBe(null)
->and($hostTemplate->getFlapDetectionEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getLowFlapThreshold())->toBe(null)
->and($hostTemplate->getHighFlapThreshold())->toBe(null)
->and($hostTemplate->getEventHandlerEnabled())->toBe(YesNoDefault::Default)
->and($hostTemplate->getEventHandlerCommandId())->toBe(null)
->and($hostTemplate->getEventHandlerCommandArgs())->toBe([])
->and($hostTemplate->getNoteUrl())->toBe('')
->and($hostTemplate->getNote())->toBe('')
->and($hostTemplate->getActionUrl())->toBe('')
->and($hostTemplate->getIconId())->toBe(null)
->and($hostTemplate->getIconAlternative())->toBe('')
->and($hostTemplate->getComment())->toBe('')
->and($hostTemplate->isLocked())->toBe(false);
});
// mandatory fields
foreach (
[
'name',
'alias',
] as $field
) {
it(
"should throw an exception when host template {$field} is an empty string",
fn () => ($this->createHostTemplate)([$field => ''])
)->throws(
InvalidArgumentException::class,
AssertionException::notEmptyString("HostTemplate::{$field}")->getMessage()
);
}
foreach (
[
'name',
'alias',
] as $field
) {
it("should throw an exception when host template {$field} is set to an empty string", function () use ($field): void {
$hostTemplate = ($this->createHostTemplate)();
$hostTemplate->{'set' . $field}('');
})->throws(
InvalidArgumentException::class,
AssertionException::notEmptyString("HostTemplate::{$field}")->getMessage()
);
}
// name and conmmands args should be formated
it('should return trimmed and formatted field name after construct', function (): void {
$hostTemplate = new HostTemplate(1, ' host template name ', 'alias');
expect($hostTemplate->getName())->toBe('host_template_name');
});
it('should trimm and format field name when set', function (): void {
$hostTemplate = ($this->createHostTemplate)();
$hostTemplate->setName(' some new name ');
expect($hostTemplate->getName())->toBe('some_new_name');
});
foreach (
[
'checkCommandArgs',
'eventHandlerCommandArgs',
] as $field
) {
it(
"should return a trimmed field {$field}",
function () use ($field): void {
$hostTemplate = ($this->createHostTemplate)([$field => [' arg1 ', ' arg2 ']]);
$valueFromGetter = $hostTemplate->{'get' . $field}();
expect($valueFromGetter)->toBe(['arg1', 'arg2']);
}
);
}
foreach (
[
'checkCommandArgs',
'eventHandlerCommandArgs',
] as $field
) {
it(
"should set a trimmed field {$field}",
function () use ($field): void {
$hostTemplate = ($this->createHostTemplate)();
$hostTemplate->{'set' . $field}([' arg1 ', ' arg2 ']);
expect($hostTemplate->{'get' . $field}())->toBe(['arg1', 'arg2']);
}
);
}
// string field trimmed
foreach (
[
'name',
'alias',
'snmpCommunity',
'noteUrl',
'note',
'actionUrl',
'iconAlternative',
'comment',
] as $field
) {
it(
"should return trim the field {$field} after construct",
function () use ($field): void {
$hostTemplate = ($this->createHostTemplate)([$field => ' abcd ']);
$valueFromGetter = $hostTemplate->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
foreach (
[
'name',
'alias',
'snmpCommunity',
'noteUrl',
'note',
'actionUrl',
'iconAlternative',
'comment',
] as $field
) {
it(
"should set a trimmed field {$field}",
function () use ($field): void {
$hostTemplate = ($this->createHostTemplate)();
$hostTemplate->{'set' . $field}(' abcd ');
expect($hostTemplate->{'get' . $field}())->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => HostTemplate::MAX_NAME_LENGTH,
'alias' => HostTemplate::MAX_ALIAS_LENGTH,
'snmpCommunity' => HostTemplate::MAX_SNMP_COMMUNITY_LENGTH,
'noteUrl' => HostTemplate::MAX_NOTE_URL_LENGTH,
'note' => HostTemplate::MAX_NOTE_LENGTH,
'actionUrl' => HostTemplate::MAX_ACTION_URL_LENGTH,
'iconAlternative' => HostTemplate::MAX_ICON_ALT_LENGTH,
'comment' => HostTemplate::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when host template {$field} is too long",
fn () => ($this->createHostTemplate)([$field => $tooLong])
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "HostTemplate::{$field}")->getMessage()
);
}
foreach (
[
'name' => HostTemplate::MAX_NAME_LENGTH,
'alias' => HostTemplate::MAX_ALIAS_LENGTH,
'snmpCommunity' => HostTemplate::MAX_SNMP_COMMUNITY_LENGTH,
'noteUrl' => HostTemplate::MAX_NOTE_URL_LENGTH,
'note' => HostTemplate::MAX_NOTE_LENGTH,
'actionUrl' => HostTemplate::MAX_ACTION_URL_LENGTH,
'iconAlternative' => HostTemplate::MAX_ICON_ALT_LENGTH,
'comment' => HostTemplate::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLongStr = str_repeat('a', $length + 1);
it(
"should throw an exception when host template {$field} is set too long",
function () use ($field, $tooLongStr): void {
$hostTemplate = ($this->createHostTemplate)();
$hostTemplate->{'set' . $field}($tooLongStr);
}
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLongStr, $length + 1, $length, "HostTemplate::{$field}")->getMessage()
);
}
// foreign keys fields
foreach (
[
'timezoneId',
'severityId',
'checkCommandId',
'checkTimeperiodId',
'notificationTimeperiodId',
'eventHandlerCommandId',
'iconId',
] as $field
) {
it(
"should throw an exception when host template {$field} is not > 0",
fn () => ($this->createHostTemplate)([$field => 0])
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(0, "HostTemplate::{$field}")->getMessage()
);
}
foreach (
[
'timezoneId',
'severityId',
'checkCommandId',
'checkTimeperiodId',
'notificationTimeperiodId',
'eventHandlerCommandId',
'iconId',
] as $field
) {
it(
"should throw an exception when host template {$field} set value is not > 0",
function () use ($field): void {
$hostTemplate = ($this->createHostTemplate)();
$hostTemplate->{'set' . $field}(0);
}
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(0, "HostTemplate::{$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 template {$field} is not >= 0",
fn () => ($this->createHostTemplate)([$field => -1])
)->throws(
InvalidArgumentException::class,
AssertionException::min(-1, 0, "HostTemplate::{$field}")->getMessage()
);
}
foreach (
[
'maxCheckAttempts',
'normalCheckInterval',
'retryCheckInterval',
'notificationInterval',
'firstNotificationDelay',
'recoveryNotificationDelay',
'acknowledgementTimeout',
'freshnessThreshold',
'lowFlapThreshold',
'highFlapThreshold',
] as $field
) {
it(
"should throw an exception when host template {$field} set value is not >= 0",
function () use ($field): void {
$hostTemplate = ($this->createHostTemplate)();
$hostTemplate->{'set' . $field}(-1);
}
)->throws(
InvalidArgumentException::class,
AssertionException::min(-1, 0, "HostTemplate::{$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/HostTemplate/Infrastructure/API/AddHostTemplate/AddHostTemplatePresenterStub.php | centreon/tests/php/Core/HostTemplate/Infrastructure/API/AddHostTemplate/AddHostTemplatePresenterStub.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\HostTemplate\Infrastructure\API\AddHostTemplate;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplatePresenterInterface;
use Core\HostTemplate\Application\UseCase\AddHostTemplate\AddHostTemplateResponse;
class AddHostTemplatePresenterStub extends AbstractPresenter implements AddHostTemplatePresenterInterface
{
public ResponseStatusInterface|AddHostTemplateResponse $response;
public function presentResponse(ResponseStatusInterface|AddHostTemplateResponse $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/HostTemplate/Infrastructure/API/FindHostTemplates/FindHostTemplatesPresenterStub.php | centreon/tests/php/Core/HostTemplate/Infrastructure/API/FindHostTemplates/FindHostTemplatesPresenterStub.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\HostTemplate\Infrastructure\API\FindHostTemplates;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\HostTemplate\Application\UseCase\FindHostTemplates\FindHostTemplatesPresenterInterface;
use Core\HostTemplate\Application\UseCase\FindHostTemplates\FindHostTemplatesResponse;
class FindHostTemplatesPresenterStub extends AbstractPresenter implements FindHostTemplatesPresenterInterface
{
public ResponseStatusInterface|FindHostTemplatesResponse $response;
public function presentResponse(ResponseStatusInterface|FindHostTemplatesResponse $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/Application/RealTime/UseCase/FindMetaService/FindMetaServicePresenterStub.php | centreon/tests/php/Core/Application/RealTime/UseCase/FindMetaService/FindMetaServicePresenterStub.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\Application\RealTime\UseCase\FindMetaService;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\RealTime\UseCase\FindMetaService\FindMetaServicePresenterInterface;
use Core\Application\RealTime\UseCase\FindMetaService\FindMetaServiceResponse;
use Symfony\Component\HttpFoundation\Response;
class FindMetaServicePresenterStub extends AbstractPresenter implements FindMetaServicePresenterInterface
{
/** @var FindMetaServiceResponse */
public $response;
/**
* constructor
*/
public function __construct()
{
}
/**
* @return Response
*/
public function show(): Response
{
return new Response();
}
/**
* @param FindMetaServiceResponse $response
*/
public function present(mixed $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/Application/RealTime/UseCase/FindMetaService/FindMetaServiceTest.php | centreon/tests/php/Core/Application/RealTime/UseCase/FindMetaService/FindMetaServiceTest.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\Application\RealTime\UseCase\FindMetaService;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Configuration\MetaService\Repository\ReadMetaServiceRepositoryInterface as ReadMetaServiceConfigurationRepositoryInterface;
use Core\Application\RealTime\Repository\ReadAcknowledgementRepositoryInterface;
use Core\Application\RealTime\Repository\ReadDowntimeRepositoryInterface;
use Core\Application\RealTime\Repository\ReadMetaServiceRepositoryInterface;
use Core\Application\RealTime\UseCase\FindMetaService\FindMetaService;
use Core\Domain\RealTime\Model\Acknowledgement;
use Core\Domain\RealTime\Model\Downtime;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\RealTime\Api\FindMetaService\FindMetaServicePresenter;
use Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Tests\Core\Domain\Configuration\MetaServiceTest as MetaServiceConfigurationTest;
use Tests\Core\Domain\RealTime\Model\MetaServiceTest;
beforeEach(function (): void {
$this->repository = $this->createMock(ReadMetaServiceRepositoryInterface::class);
$this->configurationRepository = $this->createMock(ReadMetaServiceConfigurationRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->downtimeRepository = $this->createMock(ReadDowntimeRepositoryInterface::class);
$this->acknowledgementRepository = $this->createMock(ReadAcknowledgementRepositoryInterface::class);
$this->hypermediaCreator = $this->createMock(HypermediaCreator::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
});
it('should present a NotFoundResponse if meta service configuration not found as admin', function (): void {
$findMetaService = new FindMetaService(
$this->repository,
$this->configurationRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->configurationRepository
->expects($this->once())
->method('findMetaServiceById')
->willReturn(null);
$presenter = new FindMetaServicePresenter($this->hypermediaCreator, $this->presenterFormatter);
$findMetaService(1, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'MetaService configuration not found'
);
});
it('should present a NotFoundResponse if meta service configuration not found as non-admin', function (): void {
$findMetaService = new FindMetaService(
$this->repository,
$this->configurationRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->configurationRepository
->expects($this->once())
->method('findMetaServiceByIdAndAccessGroupIds')
->willReturn(null);
$presenter = new FindMetaServicePresenter($this->hypermediaCreator, $this->presenterFormatter);
$findMetaService(1, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'MetaService configuration not found'
);
});
it('should present a NotFoundResponse if metaservice requested is not found as admin', function (): void {
$findMetaService = new FindMetaService(
$this->repository,
$this->configurationRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository
);
$configuration = MetaServiceConfigurationTest::createMetaServiceModel();
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->configurationRepository
->expects($this->once())
->method('findMetaServiceById')
->willReturn($configuration);
$this->repository
->expects($this->once())
->method('findMetaServiceById')
->willReturn(null);
$presenter = new FindMetaServicePresenter($this->hypermediaCreator, $this->presenterFormatter);
$findMetaService(1, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'MetaService not found'
);
});
it('should present a NotFoundResponse if metaservice requested is not found as non-admin', function (): void {
$findMetaService = new FindMetaService(
$this->repository,
$this->configurationRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->configurationRepository
->expects($this->once())
->method('findMetaServiceByIdAndAccessGroupIds')
->willReturn(MetaServiceConfigurationTest::createMetaServiceModel());
$this->repository
->expects($this->once())
->method('findMetaServiceByIdAndAccessGroupIds')
->willReturn(null);
$presenter = new FindMetaServicePresenter($this->hypermediaCreator, $this->presenterFormatter);
$findMetaService(1, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'MetaService not found'
);
});
it('should find the metaservice as non-admin', function (): void {
$metaServiceConfiguration = MetaServiceConfigurationTest::createMetaServiceModel();
$metaService = (MetaServiceTest::createMetaServiceModel())
->setIsInDowntime(true)
->setIsAcknowledged(true);
$downtimes[] = (new Downtime(1, 1, 10))
->setCancelled(false);
$acknowledgement = new Acknowledgement(1, 1, 10, new \DateTime('1991-09-10'));
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->downtimeRepository
->expects($this->once())
->method('findOnGoingDowntimesByHostIdAndServiceId')
->willReturn($downtimes);
$this->acknowledgementRepository
->expects($this->once())
->method('findOnGoingAcknowledgementByHostIdAndServiceId')
->willReturn($acknowledgement);
$findMetaService = new FindMetaService(
$this->repository,
$this->configurationRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository
);
$this->configurationRepository
->expects($this->once())
->method('findMetaServiceByIdAndAccessGroupIds')
->willReturn($metaServiceConfiguration);
$this->repository
->expects($this->once())
->method('findMetaServiceByIdAndAccessGroupIds')
->willReturn($metaService);
$presenter = new FindMetaServicePresenterStub();
$findMetaService(1, $presenter);
expect($presenter->response->name)->toBe($metaService->getName());
expect($presenter->response->metaId)->toBe($metaService->getId());
expect($presenter->response->isFlapping)->toBe($metaService->isFlapping());
expect($presenter->response->isAcknowledged)->toBe($metaService->isAcknowledged());
expect($presenter->response->isInDowntime)->toBe($metaService->isInDowntime());
expect($presenter->response->output)->toBe($metaService->getOutput());
expect($presenter->response->commandLine)->toBe($metaService->getCommandLine());
expect($presenter->response->performanceData)->toBe($metaService->getPerformanceData());
expect($presenter->response->notificationNumber)->toBe($metaService->getNotificationNumber());
expect($presenter->response->latency)->toBe($metaService->getLatency());
expect($presenter->response->executionTime)->toBe($metaService->getExecutionTime());
expect($presenter->response->statusChangePercentage)->toBe($metaService->getStatusChangePercentage());
expect($presenter->response->hasActiveChecks)->toBe($metaService->hasActiveChecks());
expect($presenter->response->hasPassiveChecks)->toBe($metaService->hasPassiveChecks());
expect($presenter->response->checkAttempts)->toBe($metaService->getCheckAttempts());
expect($presenter->response->maxCheckAttempts)->toBe($metaService->getMaxCheckAttempts());
expect($presenter->response->lastTimeOk)->toBe($metaService->getLastTimeOk());
expect($presenter->response->lastCheck)->toBe($metaService->getLastCheck());
expect($presenter->response->nextCheck)->toBe($metaService->getNextCheck());
expect($presenter->response->lastNotification)->toBe($metaService->getLastNotification());
expect($presenter->response->lastStatusChange)->toBe($metaService->getLastStatusChange());
expect($presenter->response->status['code'])->toBe($metaService->getStatus()->getCode());
expect($presenter->response->status['name'])->toBe($metaService->getStatus()->getName());
expect($presenter->response->status['type'])->toBe($metaService->getStatus()->getType());
expect($presenter->response->status['severity_code'])->toBe($metaService->getStatus()->getOrder());
expect($presenter->response->downtimes[0]['id'])->toBe($downtimes[0]->getId());
expect($presenter->response->downtimes[0]['service_id'])->toBe($downtimes[0]->getServiceId());
expect($presenter->response->downtimes[0]['host_id'])->toBe($downtimes[0]->getHostId());
expect($presenter->response->acknowledgement['id'])->toBe($acknowledgement->getId());
expect($presenter->response->acknowledgement['service_id'])->toBe($acknowledgement->getServiceId());
expect($presenter->response->acknowledgement['host_id'])->toBe($acknowledgement->getHostId());
expect($presenter->response->calculationType)->toBe($metaServiceConfiguration->getCalculationType());
});
| 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/Application/RealTime/UseCase/FindService/FindServiceTest.php | centreon/tests/php/Core/Application/RealTime/UseCase/FindService/FindServiceTest.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\Application\RealTime\UseCase\FindService;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\RealTime\Repository\ReadAcknowledgementRepositoryInterface;
use Core\Application\RealTime\Repository\ReadDowntimeRepositoryInterface;
use Core\Application\RealTime\Repository\ReadHostRepositoryInterface;
use Core\Application\RealTime\Repository\ReadServicegroupRepositoryInterface;
use Core\Application\RealTime\Repository\ReadServiceRepositoryInterface;
use Core\Application\RealTime\UseCase\FindService\FindService;
use Core\Domain\RealTime\Model\Acknowledgement;
use Core\Domain\RealTime\Model\Downtime;
use Core\Domain\RealTime\Model\Icon;
use Core\Domain\RealTime\Model\Servicegroup;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\RealTime\Api\FindService\FindServicePresenter;
use Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Severity\RealTime\Application\Repository\ReadSeverityRepositoryInterface;
use Core\Severity\RealTime\Domain\Model\Severity;
use Core\Tag\RealTime\Application\Repository\ReadTagRepositoryInterface;
use Core\Tag\RealTime\Domain\Model\Tag;
use Tests\Core\Domain\RealTime\Model\HostTest;
use Tests\Core\Domain\RealTime\Model\ServiceTest;
beforeEach(function (): void {
$this->repository = $this->createMock(ReadServiceRepositoryInterface::class);
$this->servicegroupRepository = $this->createMock(ReadServicegroupRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->downtimeRepository = $this->createMock(ReadDowntimeRepositoryInterface::class);
$this->acknowledgementRepository = $this->createMock(ReadAcknowledgementRepositoryInterface::class);
$this->hypermediaCreator = $this->createMock(HypermediaCreator::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->monitoringService = $this->createMock(MonitoringServiceInterface::class);
$this->hostRepository = $this->createMock(ReadHostRepositoryInterface::class);
$this->tagRepository = $this->createMock(ReadTagRepositoryInterface::class);
$this->severityRepository = $this->createMock(ReadSeverityRepositoryInterface::class);
$this->downtime = (new Downtime(1, 1, 10))
->setCancelled(false);
$this->acknowledgement = new Acknowledgement(1, 1, 10, new \DateTime('1991-09-10'));
$this->contact = $this->createMock(ContactInterface::class);
$this->host = (HostTest::createHostModel())
->setIsInDowntime(true)
->setIsAcknowledged(true);
$this->service = (ServiceTest::createServiceModel())
->setIsInDowntime(true)
->setIsAcknowledged(true);
$this->servicegroup = new Servicegroup(1, 'ALL');
$this->category = new Tag(1, 'service-category-name', Tag::SERVICE_CATEGORY_TYPE_ID);
$icon = (new Icon())->setId(1)->setName('centreon')->setUrl('ppm/centreon.png');
$this->severity = new Severity(1, 'severityName', 10, Severity::SERVICE_SEVERITY_TYPE_ID, $icon);
});
it('should present a NotFoundResponse if host not found as admin', function (): void {
$findService = new FindService(
$this->repository,
$this->hostRepository,
$this->servicegroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->hostRepository
->expects($this->once())
->method('findHostById')
->willReturn(null);
$presenter = new FindServicePresenter($this->hypermediaCreator, $this->presenterFormatter);
$findService(1, 20, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'Host not found'
);
});
it('should present a NotFoundResponse if host not found as non admin', function (): void {
$findService = new FindService(
$this->repository,
$this->hostRepository,
$this->servicegroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([]);
$this->hostRepository
->expects($this->once())
->method('findHostByIdAndAccessGroupIds')
->willReturn(null);
$presenter = new FindServicePresenter($this->hypermediaCreator, $this->presenterFormatter);
$findService(1, 20, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'Host not found'
);
});
it('should present a NotFoundResponse if service not found as admin', function (): void {
$findService = new FindService(
$this->repository,
$this->hostRepository,
$this->servicegroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->hostRepository
->expects($this->once())
->method('findHostById')
->willReturn(HostTest::createHostModel());
$this->repository
->expects($this->once())
->method('findServiceById')
->willReturn(null);
$presenter = new FindServicePresenter($this->hypermediaCreator, $this->presenterFormatter);
$findService(1, 20, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'Service not found'
);
});
it('should present a NotFoundResponse if service not found as non admin', function (): void {
$findService = new FindService(
$this->repository,
$this->hostRepository,
$this->servicegroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([]);
$this->hostRepository
->expects($this->once())
->method('findHostByIdAndAccessGroupIds')
->willReturn(HostTest::createHostModel());
$this->repository
->expects($this->once())
->method('findServiceByIdAndAccessGroupIds')
->willReturn(null);
$presenter = new FindServicePresenter($this->hypermediaCreator, $this->presenterFormatter);
$findService(1, 20, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'Service not found'
);
});
it('should find service as admin', function (): void {
$findService = new FindService(
$this->repository,
$this->hostRepository,
$this->servicegroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->hostRepository
->expects($this->once())
->method('findHostById')
->willReturn($this->host);
$this->repository
->expects($this->once())
->method('findServiceById')
->willReturn($this->service);
$this->servicegroupRepository
->expects($this->once())
->method('findAllByHostIdAndServiceId')
->willReturn([$this->servicegroup]);
$this->tagRepository
->expects($this->once())
->method('findAllByResourceAndTypeId')
->willReturn([$this->category]);
$this->downtimeRepository
->expects($this->once())
->method('findOnGoingDowntimesByHostIdAndServiceId')
->willReturn([$this->downtime]);
$this->acknowledgementRepository
->expects($this->once())
->method('findOnGoingAcknowledgementByHostIdAndServiceId')
->willReturn($this->acknowledgement);
$this->severityRepository
->expects($this->once())
->method('findByResourceAndTypeId')
->willReturn($this->severity);
$presenter = new FindServicePresenterStub();
$findService(1, 10, $presenter);
expect($presenter->response->name)->toBe($this->service->getName());
expect($presenter->response->serviceId)->toBe($this->service->getId());
expect($presenter->response->host['monitoring_server_name'])
->toBe($this->host->getMonitoringServerName());
expect($presenter->response->isFlapping)->toBe($this->service->isFlapping());
expect($presenter->response->isAcknowledged)->toBe($this->service->isAcknowledged());
expect($presenter->response->isInDowntime)->toBe($this->service->isInDowntime());
expect($presenter->response->output)->toBe($this->service->getOutput());
expect($presenter->response->commandLine)->toBe($this->service->getCommandLine());
expect($presenter->response->performanceData)->toBe($this->service->getPerformanceData());
expect($presenter->response->notificationNumber)->toBe($this->service->getNotificationNumber());
expect($presenter->response->latency)->toBe($this->service->getLatency());
expect($presenter->response->executionTime)->toBe($this->service->getExecutionTime());
expect($presenter->response->statusChangePercentage)->toBe($this->service->getStatusChangePercentage());
expect($presenter->response->hasActiveChecks)->toBe($this->service->hasActiveChecks());
expect($presenter->response->hasPassiveChecks)->toBe($this->service->hasPassiveChecks());
expect($presenter->response->checkAttempts)->toBe($this->service->getCheckAttempts());
expect($presenter->response->maxCheckAttempts)->toBe($this->service->getMaxCheckAttempts());
expect($presenter->response->lastTimeOk)->toBe($this->service->getLastTimeOk());
expect($presenter->response->lastCheck)->toBe($this->service->getLastCheck());
expect($presenter->response->nextCheck)->toBe($this->service->getNextCheck());
expect($presenter->response->lastNotification)->toBe($this->service->getLastNotification());
expect($presenter->response->lastStatusChange)->toBe($this->service->getLastStatusChange());
expect($presenter->response->status['code'])->toBe($this->service->getStatus()->getCode());
expect($presenter->response->status['name'])->toBe($this->service->getStatus()->getName());
expect($presenter->response->status['type'])->toBe($this->service->getStatus()->getType());
expect($presenter->response->status['severity_code'])->toBe($this->service->getStatus()->getOrder());
expect($presenter->response->groups[0]['id'])
->toBe($this->service->getGroups()[0]->getId());
expect($presenter->response->groups[0]['name'])
->toBe($this->service->getGroups()[0]->getName());
expect($presenter->response->icon['name'])->toBe($this->service->getIcon()?->getName());
expect($presenter->response->icon['url'])->toBe($this->service->getIcon()?->getUrl());
expect($presenter->response->downtimes[0]['id'])->toBe($this->downtime->getId());
expect($presenter->response->downtimes[0]['service_id'])->toBe($this->downtime->getServiceId());
expect($presenter->response->downtimes[0]['host_id'])->toBe($this->downtime->getHostId());
expect($presenter->response->acknowledgement['id'])->toBe($this->acknowledgement->getId());
expect($presenter->response->acknowledgement['service_id'])
->toBe($this->acknowledgement->getServiceId());
expect($presenter->response->acknowledgement['host_id'])->toBe($this->acknowledgement->getHostId());
/**
* @var array<string, mixed> $severity
*/
$severity = $presenter->response->severity;
expect($severity['id'])->toBe($this->severity->getId());
expect($severity['name'])->toBe($this->severity->getName());
expect($severity['type'])->toBe($this->severity->getTypeAsString());
expect($severity['level'])->toBe($this->severity->getLevel());
expect($severity['icon']['id'])->toBe($this->severity->getIcon()->getId());
expect($severity['icon']['name'])->toBe($this->severity->getIcon()->getName());
expect($severity['icon']['url'])->toBe($this->severity->getIcon()->getUrl());
});
it('FindService service found as non admin', function (): void {
$findService = new FindService(
$this->repository,
$this->hostRepository,
$this->servicegroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->hostRepository
->expects($this->once())
->method('findHostByIdAndAccessGroupIds')
->willReturn($this->host);
$this->repository
->expects($this->once())
->method('findServiceByIdAndAccessGroupIds')
->willReturn($this->service);
$this->servicegroupRepository
->expects($this->once())
->method('findAllByHostIdAndServiceIdAndAccessGroupIds')
->willReturn([$this->servicegroup]);
$this->downtimeRepository
->expects($this->once())
->method('findOnGoingDowntimesByHostIdAndServiceId')
->willReturn([$this->downtime]);
$this->acknowledgementRepository
->expects($this->once())
->method('findOnGoingAcknowledgementByHostIdAndServiceId')
->willReturn($this->acknowledgement);
$this->severityRepository
->expects($this->once())
->method('findByResourceAndTypeId')
->willReturn($this->severity);
$presenter = new FindServicePresenterStub();
$findService(1, 10, $presenter);
expect($presenter->response->name)->toBe($this->service->getName());
expect($presenter->response->serviceId)->toBe($this->service->getId());
expect($presenter->response->host['monitoring_server_name'])
->toBe($this->host->getMonitoringServerName());
expect($presenter->response->isFlapping)->toBe($this->service->isFlapping());
expect($presenter->response->isAcknowledged)->toBe($this->service->isAcknowledged());
expect($presenter->response->isInDowntime)->toBe($this->service->isInDowntime());
expect($presenter->response->output)->toBe($this->service->getOutput());
expect($presenter->response->commandLine)->toBe($this->service->getCommandLine());
expect($presenter->response->performanceData)->toBe($this->service->getPerformanceData());
expect($presenter->response->notificationNumber)->toBe($this->service->getNotificationNumber());
expect($presenter->response->latency)->toBe($this->service->getLatency());
expect($presenter->response->executionTime)->toBe($this->service->getExecutionTime());
expect($presenter->response->statusChangePercentage)->toBe($this->service->getStatusChangePercentage());
expect($presenter->response->hasActiveChecks)->toBe($this->service->hasActiveChecks());
expect($presenter->response->hasPassiveChecks)->toBe($this->service->hasPassiveChecks());
expect($presenter->response->checkAttempts)->toBe($this->service->getCheckAttempts());
expect($presenter->response->maxCheckAttempts)->toBe($this->service->getMaxCheckAttempts());
expect($presenter->response->lastTimeOk)->toBe($this->service->getLastTimeOk());
expect($presenter->response->lastCheck)->toBe($this->service->getLastCheck());
expect($presenter->response->nextCheck)->toBe($this->service->getNextCheck());
expect($presenter->response->lastNotification)->toBe($this->service->getLastNotification());
expect($presenter->response->lastStatusChange)->toBe($this->service->getLastStatusChange());
expect($presenter->response->status['code'])->toBe($this->service->getStatus()->getCode());
expect($presenter->response->status['name'])->toBe($this->service->getStatus()->getName());
expect($presenter->response->status['type'])->toBe($this->service->getStatus()->getType());
expect($presenter->response->status['severity_code'])->toBe($this->service->getStatus()->getOrder());
expect($presenter->response->groups[0]['id'])
->toBe($this->service->getGroups()[0]->getId());
expect($presenter->response->groups[0]['name'])
->toBe($this->service->getGroups()[0]->getName());
expect($presenter->response->icon['name'])->toBe($this->service->getIcon()?->getName());
expect($presenter->response->icon['url'])->toBe($this->service->getIcon()?->getUrl());
expect($presenter->response->downtimes[0]['id'])->toBe($this->downtime->getId());
expect($presenter->response->downtimes[0]['service_id'])->toBe($this->downtime->getServiceId());
expect($presenter->response->downtimes[0]['host_id'])->toBe($this->downtime->getHostId());
expect($presenter->response->acknowledgement['id'])->toBe($this->acknowledgement->getId());
expect($presenter->response->acknowledgement['service_id'])
->toBe($this->acknowledgement->getServiceId());
expect($presenter->response->acknowledgement['host_id'])->toBe($this->acknowledgement->getHostId());
/**
* @var array<string, mixed> $severity
*/
$severity = $presenter->response->severity;
expect($severity['id'])->toBe($this->severity->getId());
expect($severity['name'])->toBe($this->severity->getName());
expect($severity['type'])->toBe($this->severity->getTypeAsString());
expect($severity['level'])->toBe($this->severity->getLevel());
expect($severity['icon']['id'])->toBe($this->severity->getIcon()->getId());
expect($severity['icon']['name'])->toBe($this->severity->getIcon()->getName());
expect($severity['icon']['url'])->toBe($this->severity->getIcon()->getUrl());
});
| 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/Application/RealTime/UseCase/FindService/FindServicePresenterStub.php | centreon/tests/php/Core/Application/RealTime/UseCase/FindService/FindServicePresenterStub.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\Application\RealTime\UseCase\FindService;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\RealTime\UseCase\FindService\FindServicePresenterInterface;
use Core\Application\RealTime\UseCase\FindService\FindServiceResponse;
use Symfony\Component\HttpFoundation\Response;
class FindServicePresenterStub extends AbstractPresenter implements FindServicePresenterInterface
{
/** @var FindServiceResponse */
public $response;
/**
* constructor
*/
public function __construct()
{
}
/**
* @return Response
*/
public function show(): Response
{
return new Response();
}
/**
* @param FindServiceResponse $response
*/
public function present(mixed $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/Application/RealTime/UseCase/FindHost/FindHostPresenterStub.php | centreon/tests/php/Core/Application/RealTime/UseCase/FindHost/FindHostPresenterStub.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\Application\RealTime\UseCase\FindHost;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\RealTime\UseCase\FindHost\FindHostPresenterInterface;
use Core\Application\RealTime\UseCase\FindHost\FindHostResponse;
use Symfony\Component\HttpFoundation\Response;
class FindHostPresenterStub extends AbstractPresenter implements FindHostPresenterInterface
{
/** @var FindHostResponse */
public $response;
/**
* constructor
*/
public function __construct()
{
}
/**
* @return Response
*/
public function show(): Response
{
return new Response();
}
/**
* @param FindHostResponse $response
* @return void
*/
public function present(mixed $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/Application/RealTime/UseCase/FindHost/FindHostTest.php | centreon/tests/php/Core/Application/RealTime/UseCase/FindHost/FindHostTest.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\Application\RealTime\UseCase\FindHost;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\RealTime\Repository\ReadAcknowledgementRepositoryInterface;
use Core\Application\RealTime\Repository\ReadDowntimeRepositoryInterface;
use Core\Application\RealTime\Repository\ReadHostgroupRepositoryInterface;
use Core\Application\RealTime\Repository\ReadHostRepositoryInterface;
use Core\Application\RealTime\UseCase\FindHost\FindHost;
use Core\Domain\RealTime\Model\Acknowledgement;
use Core\Domain\RealTime\Model\Downtime;
use Core\Domain\RealTime\Model\Hostgroup;
use Core\Domain\RealTime\Model\Icon;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\RealTime\Api\FindHost\FindHostPresenter;
use Core\Infrastructure\RealTime\Hypermedia\HypermediaCreator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Severity\RealTime\Application\Repository\ReadSeverityRepositoryInterface;
use Core\Severity\RealTime\Domain\Model\Severity;
use Core\Tag\RealTime\Application\Repository\ReadTagRepositoryInterface;
use Core\Tag\RealTime\Domain\Model\Tag;
use Tests\Core\Domain\RealTime\Model\HostTest;
beforeEach(function (): void {
$this->repository = $this->createMock(ReadHostRepositoryInterface::class);
$this->hostgroupRepository = $this->createMock(ReadHostgroupRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->downtimeRepository = $this->createMock(ReadDowntimeRepositoryInterface::class);
$this->acknowledgementRepository = $this->createMock(ReadAcknowledgementRepositoryInterface::class);
$this->hypermediaCreator = $this->createMock(HypermediaCreator::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->monitoringService = $this->createMock(MonitoringServiceInterface::class);
$this->tagRepository = $this->createMock(ReadTagRepositoryInterface::class);
$this->severityRepository = $this->createMock(ReadSeverityRepositoryInterface::class);
$this->acknowledgement = new Acknowledgement(1, 1, 10, new \DateTime('1991-09-10'));
$this->host = (HostTest::createHostModel())
->setIsInDowntime(true)
->setIsAcknowledged(true);
$this->contact = $this->createMock(ContactInterface::class);
$this->hostgroup = new Hostgroup(10, 'ALL');
$this->category = new Tag(1, 'host-category-name', Tag::HOST_CATEGORY_TYPE_ID);
$this->downtime = (new Downtime(1, 1, 10))
->setCancelled(false);
$icon = (new Icon())->setId(1)->setName('centreon')->setUrl('ppm/centreon.png');
$this->severity = new Severity(1, 'severityName', 10, Severity::HOST_SEVERITY_TYPE_ID, $icon);
});
it('FindHost not found response as admin', function (): void {
$findHost = new FindHost(
$this->repository,
$this->hostgroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->repository
->expects($this->once())
->method('findHostById')
->willReturn(null);
$presenter = new FindHostPresenter($this->hypermediaCreator, $this->presenterFormatter);
$findHost(1, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'Host not found'
);
});
it('should present a not found response as non admin', function (): void {
$findHost = new FindHost(
$this->repository,
$this->hostgroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([]);
$this->repository
->expects($this->once())
->method('findHostByIdAndAccessGroupIds')
->willReturn(null);
$presenter = new FindHostPresenter($this->hypermediaCreator, $this->presenterFormatter);
$findHost(1, $presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class);
expect($presenter->getResponseStatus()?->getMessage())->toBe(
'Host not found'
);
});
it('should find the host as admin', function (): void {
$findHost = new FindHost(
$this->repository,
$this->hostgroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->repository
->expects($this->once())
->method('findHostById')
->willReturn($this->host);
$this->downtimeRepository
->expects($this->once())
->method('findOnGoingDowntimesByHostId')
->willReturn([$this->downtime]);
$this->acknowledgementRepository
->expects($this->once())
->method('findOnGoingAcknowledgementByHostId')
->willReturn($this->acknowledgement);
$this->hostgroupRepository
->expects($this->once())
->method('findAllByHostId')
->willReturn([$this->hostgroup]);
$this->tagRepository
->expects($this->once())
->method('findAllByResourceAndTypeId')
->willReturn([$this->category]);
$this->severityRepository
->expects($this->once())
->method('findByResourceAndTypeId')
->willReturn($this->severity);
$presenter = new FindHostPresenterStub();
$findHost(1, $presenter);
expect($presenter->response->name)->toBe($this->host->getName());
expect($presenter->response->hostId)->toBe($this->host->getId());
expect($presenter->response->address)->toBe($this->host->getAddress());
expect($presenter->response->monitoringServerName)->toBe($this->host->getMonitoringServerName());
expect($presenter->response->timezone)->toBe($this->host->getTimezone());
expect($presenter->response->alias)->toBe($this->host->getAlias());
expect($presenter->response->isFlapping)->toBe($this->host->isFlapping());
expect($presenter->response->isAcknowledged)->toBe($this->host->isAcknowledged());
expect($presenter->response->isInDowntime)->toBe($this->host->isInDowntime());
expect($presenter->response->output)->toBe($this->host->getOutput());
expect($presenter->response->commandLine)->toBe($this->host->getCommandLine());
expect($presenter->response->performanceData)->toBe($this->host->getPerformanceData());
expect($presenter->response->notificationNumber)->toBe($this->host->getNotificationNumber());
expect($presenter->response->latency)->toBe($this->host->getLatency());
expect($presenter->response->executionTime)->toBe($this->host->getExecutionTime());
expect($presenter->response->statusChangePercentage)->toBe($this->host->getStatusChangePercentage());
expect($presenter->response->hasActiveChecks)->toBe($this->host->hasActiveChecks());
expect($presenter->response->hasPassiveChecks)->toBe($this->host->hasPassiveChecks());
expect($presenter->response->checkAttempts)->toBe($this->host->getCheckAttempts());
expect($presenter->response->maxCheckAttempts)->toBe($this->host->getMaxCheckAttempts());
expect($presenter->response->lastTimeUp)->toBe($this->host->getLastTimeUp());
expect($presenter->response->lastCheck)->toBe($this->host->getLastCheck());
expect($presenter->response->nextCheck)->toBe($this->host->getNextCheck());
expect($presenter->response->lastNotification)->toBe($this->host->getLastNotification());
expect($presenter->response->lastStatusChange)->toBe($this->host->getLastStatusChange());
expect($presenter->response->status['code'])->toBe($this->host->getStatus()->getCode());
expect($presenter->response->status['name'])->toBe($this->host->getStatus()->getName());
expect($presenter->response->status['type'])->toBe($this->host->getStatus()->getType());
expect($presenter->response->status['severity_code'])->toBe($this->host->getStatus()->getOrder());
expect($presenter->response->groups[0]['id'])->toBe($this->host->getGroups()[0]->getId());
expect($presenter->response->groups[0]['name'])->toBe($this->host->getGroups()[0]->getName());
expect($presenter->response->icon['name'])->toBe($this->host->getIcon()?->getName());
expect($presenter->response->icon['url'])->toBe($this->host->getIcon()?->getUrl());
expect($presenter->response->downtimes[0]['id'])->toBe($this->downtime->getId());
expect($presenter->response->downtimes[0]['service_id'])->toBe($this->downtime->getServiceId());
expect($presenter->response->downtimes[0]['host_id'])->toBe($this->downtime->getHostId());
expect($presenter->response->acknowledgement['id'])->toBe($this->acknowledgement->getId());
expect($presenter->response->acknowledgement['service_id'])->toBe($this->acknowledgement->getServiceId());
expect($presenter->response->acknowledgement['host_id'])->toBe($this->acknowledgement->getHostId());
expect($presenter->response->categories[0]['id'])->toBe($this->category->getId());
expect($presenter->response->categories[0]['name'])->toBe($this->category->getName());
/**
* @var array<string, mixed> $severity
*/
$severity = $presenter->response->severity;
expect($severity['id'])->toBe($this->severity->getId());
expect($severity['name'])->toBe($this->severity->getName());
expect($severity['type'])->toBe($this->severity->getTypeAsString());
expect($severity['level'])->toBe($this->severity->getLevel());
expect($severity['icon']['id'])->toBe($this->severity->getIcon()->getId());
expect($severity['icon']['name'])->toBe($this->severity->getIcon()->getName());
expect($severity['icon']['url'])->toBe($this->severity->getIcon()->getUrl());
});
it('should find the host as non admin', function (): void {
$findHost = new FindHost(
$this->repository,
$this->hostgroupRepository,
$this->contact,
$this->accessGroupRepository,
$this->downtimeRepository,
$this->acknowledgementRepository,
$this->monitoringService,
$this->tagRepository,
$this->severityRepository
);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->repository
->expects($this->once())
->method('findHostByIdAndAccessGroupIds')
->willReturn($this->host);
$this->downtimeRepository
->expects($this->once())
->method('findOnGoingDowntimesByHostId')
->willReturn([$this->downtime]);
$this->acknowledgementRepository
->expects($this->once())
->method('findOnGoingAcknowledgementByHostId')
->willReturn($this->acknowledgement);
$this->hostgroupRepository
->expects($this->once())
->method('findAllByHostIdAndAccessGroupIds')
->willReturn([$this->hostgroup]);
$this->tagRepository
->expects($this->once())
->method('findAllByResourceAndTypeId')
->willReturn([$this->category]);
$this->severityRepository
->expects($this->once())
->method('findByResourceAndTypeId')
->willReturn($this->severity);
$presenter = new FindHostPresenterStub();
$findHost(1, $presenter);
expect($presenter->response->name)->toBe($this->host->getName());
expect($presenter->response->hostId)->toBe($this->host->getId());
expect($presenter->response->address)->toBe($this->host->getAddress());
expect($presenter->response->monitoringServerName)->toBe($this->host->getMonitoringServerName());
expect($presenter->response->timezone)->toBe($this->host->getTimezone());
expect($presenter->response->alias)->toBe($this->host->getAlias());
expect($presenter->response->isFlapping)->toBe($this->host->isFlapping());
expect($presenter->response->isAcknowledged)->toBe($this->host->isAcknowledged());
expect($presenter->response->isInDowntime)->toBe($this->host->isInDowntime());
expect($presenter->response->output)->toBe($this->host->getOutput());
expect($presenter->response->commandLine)->toBe($this->host->getCommandLine());
expect($presenter->response->performanceData)->toBe($this->host->getPerformanceData());
expect($presenter->response->notificationNumber)->toBe($this->host->getNotificationNumber());
expect($presenter->response->latency)->toBe($this->host->getLatency());
expect($presenter->response->executionTime)->toBe($this->host->getExecutionTime());
expect($presenter->response->statusChangePercentage)->toBe($this->host->getStatusChangePercentage());
expect($presenter->response->hasActiveChecks)->toBe($this->host->hasActiveChecks());
expect($presenter->response->hasPassiveChecks)->toBe($this->host->hasPassiveChecks());
expect($presenter->response->checkAttempts)->toBe($this->host->getCheckAttempts());
expect($presenter->response->maxCheckAttempts)->toBe($this->host->getMaxCheckAttempts());
expect($presenter->response->lastTimeUp)->toBe($this->host->getLastTimeUp());
expect($presenter->response->lastCheck)->toBe($this->host->getLastCheck());
expect($presenter->response->nextCheck)->toBe($this->host->getNextCheck());
expect($presenter->response->lastNotification)->toBe($this->host->getLastNotification());
expect($presenter->response->lastStatusChange)->toBe($this->host->getLastStatusChange());
expect($presenter->response->status['code'])->toBe($this->host->getStatus()->getCode());
expect($presenter->response->status['name'])->toBe($this->host->getStatus()->getName());
expect($presenter->response->status['type'])->toBe($this->host->getStatus()->getType());
expect($presenter->response->status['severity_code'])->toBe($this->host->getStatus()->getOrder());
expect($presenter->response->groups[0]['id'])->toBe($this->host->getGroups()[0]->getId());
expect($presenter->response->groups[0]['name'])->toBe($this->host->getGroups()[0]->getName());
expect($presenter->response->icon['name'])->toBe($this->host->getIcon()?->getName());
expect($presenter->response->icon['url'])->toBe($this->host->getIcon()?->getUrl());
expect($presenter->response->downtimes[0]['id'])->toBe($this->downtime->getId());
expect($presenter->response->downtimes[0]['service_id'])->toBe($this->downtime->getServiceId());
expect($presenter->response->downtimes[0]['host_id'])->toBe($this->downtime->getHostId());
expect($presenter->response->acknowledgement['id'])->toBe($this->acknowledgement->getId());
expect($presenter->response->acknowledgement['service_id'])->toBe($this->acknowledgement->getServiceId());
expect($presenter->response->acknowledgement['host_id'])->toBe($this->acknowledgement->getHostId());
expect($presenter->response->acknowledgement['entry_time'])->toBe($this->acknowledgement->getEntryTime());
expect($presenter->response->categories[0]['id'])->toBe($this->category->getId());
expect($presenter->response->categories[0]['name'])->toBe($this->category->getName());
/**
* @var array<string, mixed> $severity
*/
$severity = $presenter->response->severity;
expect($severity['id'])->toBe($this->severity->getId());
expect($severity['name'])->toBe($this->severity->getName());
expect($severity['type'])->toBe($this->severity->getTypeAsString());
expect($severity['level'])->toBe($this->severity->getLevel());
expect($severity['icon']['id'])->toBe($this->severity->getIcon()->getId());
expect($severity['icon']['name'])->toBe($this->severity->getIcon()->getName());
expect($severity['icon']['url'])->toBe($this->severity->getIcon()->getUrl());
});
| 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/Application/Configuration/NotificationPolicy/UseCase/FindHostNotificationPolicyTest.php | centreon/tests/php/Core/Application/Configuration/NotificationPolicy/UseCase/FindHostNotificationPolicyTest.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\Application\Configuration\NotificationPolicy\UseCase;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Engine\EngineConfiguration;
use Centreon\Domain\Engine\Interfaces\EngineConfigurationServiceInterface;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\HostConfiguration\Interfaces\HostConfigurationRepositoryInterface;
use Centreon\Domain\Option\OptionService;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Configuration\Notification\Repository\ReadHostNotificationRepositoryInterface;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindHostNotificationPolicy;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyPresenterInterface;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyResponse;
use Core\Application\RealTime\Repository\ReadHostRepositoryInterface as ReadRealTimeHostRepositoryInterface;
use Core\Domain\Configuration\Notification\Model\HostNotification;
use Core\Domain\Configuration\Notification\Model\NotifiedContact;
use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup;
use Core\Domain\Configuration\Notification\Model\ServiceNotification;
use Core\Domain\Configuration\TimePeriod\Model\TimePeriod;
use Core\Domain\RealTime\Model\Host as RealTimeHost;
use Core\Domain\RealTime\Model\HostStatus;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->readHostNotificationRepository = $this->createMock(ReadHostNotificationRepositoryInterface::class);
$this->hostRepository = $this->createMock(HostConfigurationRepositoryInterface::class);
$this->engineService = $this->createMock(EngineConfigurationServiceInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->readRealTimeHostRepository = $this->createMock(ReadRealTimeHostRepositoryInterface::class);
$this->optionsService = $this->createMock(OptionService::class);
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class);
$this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class);
$this->host = new Host();
$this->realTimeHost = new RealTimeHost(
1,
'host1',
'127.0.0.1',
'central',
new HostStatus(HostStatus::STATUS_NAME_DOWN, HostStatus::STATUS_CODE_DOWN, 1)
);
$hostNotification = new HostNotification(new TimePeriod(1, '24x7', '24/24 7/7'));
$hostNotification->addEvent(HostNotification::EVENT_HOST_DOWN);
$serviceNotification = new ServiceNotification(new TimePeriod(1, '24x7', '24/24 7/7'));
$serviceNotification->addEvent(ServiceNotification::EVENT_SERVICE_CRITICAL);
$this->notifiedContact = new NotifiedContact(
1,
'contact1',
'contact1',
'contact1@localhost',
$hostNotification,
$serviceNotification,
);
$this->notifiedContactGroup = new NotifiedContactGroup(3, 'cg3', 'cg 3');
$this->findNotificationPolicyPresenter = $this->createMock(FindNotificationPolicyPresenterInterface::class);
$this->useCase = new FindHostNotificationPolicy(
$this->readHostNotificationRepository,
$this->hostRepository,
$this->engineService,
$this->accessGroupRepository,
$this->contact,
$this->readRealTimeHostRepository,
$this->optionsService,
$this->readHostTemplateRepository,
$this->readHostRepository
);
});
it('does not find host notification policy when host is not found by admin user', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->hostRepository
->expects($this->once())
->method('findHost')
->willReturn(null);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('setResponseStatus')
->with(new NotFoundResponse('Host'));
($this->useCase)(1, $this->findNotificationPolicyPresenter);
});
it('does not find host notification policy when host is not found by acl user', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->with($this->contact)
->willReturn([]);
$this->readRealTimeHostRepository
->expects($this->once())
->method('isAllowedToFindHostByAccessGroupIds')
->willReturn(false);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('setResponseStatus')
->with(new NotFoundResponse('Host'));
($this->useCase)(1, $this->findNotificationPolicyPresenter);
});
it('returns users, user groups and notification status', function (): void {
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->hostRepository
->expects($this->once())
->method('findHost')
->willReturn($this->host);
$this->host->setNotificationsEnabledOption(Host::NOTIFICATIONS_OPTION_DISABLED);
$this->readHostNotificationRepository
->expects($this->once())
->method('findNotifiedContactsByIds')
->with(1)
->willReturn([$this->notifiedContact]);
$this->readHostNotificationRepository
->expects($this->once())
->method('findNotifiedContactGroupsByIds')
->with(1)
->willReturn([$this->notifiedContactGroup]);
$this->realTimeHost->setNotificationEnabled(false);
$this->readRealTimeHostRepository
->expects($this->once())
->method('findHostById')
->willReturn($this->realTimeHost);
$engineConfiguration = new EngineConfiguration();
$engineConfiguration->setNotificationsEnabledOption(EngineConfiguration::NOTIFICATIONS_OPTION_DISABLED);
$this->engineService
->expects($this->once())
->method('findEngineConfigurationByHost')
->willReturn($engineConfiguration);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('present')
->with(new FindNotificationPolicyResponse([$this->notifiedContact], [$this->notifiedContactGroup], false));
($this->useCase)(1, $this->findNotificationPolicyPresenter);
});
| 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/Application/Configuration/NotificationPolicy/UseCase/FindMetaServiceNotificationPolicyTest.php | centreon/tests/php/Core/Application/Configuration/NotificationPolicy/UseCase/FindMetaServiceNotificationPolicyTest.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\Application\Configuration\NotificationPolicy\UseCase;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Engine\EngineConfiguration;
use Centreon\Domain\Engine\Interfaces\EngineConfigurationServiceInterface;
use Centreon\Domain\MetaServiceConfiguration\Interfaces\MetaServiceConfigurationReadRepositoryInterface;
use Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfiguration;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Configuration\Notification\Repository\ReadMetaServiceNotificationRepositoryInterface;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindMetaServiceNotificationPolicy;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyPresenterInterface;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyResponse;
use Core\Application\RealTime\Repository\ReadMetaServiceRepositoryInterface as ReadRealTimeMetaServiceRepositoryInterface;
use Core\Domain\Configuration\Notification\Model\HostNotification;
use Core\Domain\Configuration\Notification\Model\NotifiedContact;
use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup;
use Core\Domain\Configuration\Notification\Model\ServiceNotification;
use Core\Domain\Configuration\TimePeriod\Model\TimePeriod;
use Core\Domain\RealTime\Model\MetaService as RealtimeMetaService;
use Core\Domain\RealTime\Model\ServiceStatus;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->readMetaServiceNotificationRepository = $this->createMock(
ReadMetaServiceNotificationRepositoryInterface::class
);
$this->readMetaServiceRepository = $this->createMock(MetaServiceConfigurationReadRepositoryInterface::class);
$this->engineService = $this->createMock(EngineConfigurationServiceInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->readRealTimeMetaServiceRepository = $this->createMock(ReadRealTimeMetaServiceRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->metaService = new MetaServiceConfiguration(
'meta1',
'average',
MetaServiceConfiguration::META_SELECT_MODE_LIST,
);
$this->realTimeMetaService = new RealtimeMetaService(
1,
1,
1,
'meta1',
'central,',
new ServiceStatus(ServiceStatus::STATUS_NAME_CRITICAL, ServiceStatus::STATUS_CODE_CRITICAL, 1),
);
$hostNotification = new HostNotification(new TimePeriod(1, '24x7', '24/24 7/7'));
$hostNotification->addEvent(HostNotification::EVENT_HOST_DOWN);
$serviceNotification = new ServiceNotification(new TimePeriod(1, '24x7', '24/24 7/7'));
$serviceNotification->addEvent(ServiceNotification::EVENT_SERVICE_CRITICAL);
$this->notifiedContact = new NotifiedContact(
1,
'contact1',
'contact1',
'contact1@localhost',
$hostNotification,
$serviceNotification,
);
$this->notifiedContactGroup = new NotifiedContactGroup(3, 'cg3', 'cg 3');
$this->findNotificationPolicyPresenter = $this->createMock(FindNotificationPolicyPresenterInterface::class);
$this->useCase = new FindMetaServiceNotificationPolicy(
$this->readAccessGroupRepository,
$this->readMetaServiceNotificationRepository,
$this->readMetaServiceRepository,
$this->engineService,
$this->contact,
$this->readRealTimeMetaServiceRepository,
);
});
it('does not find meta service notification policy when meta service is not found by admin user', function (): void {
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readMetaServiceRepository
->expects($this->once())
->method('findById')
->willReturn(null);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('setResponseStatus')
->with(new NotFoundResponse('Meta service'));
($this->useCase)(1, $this->findNotificationPolicyPresenter);
});
it('does not find meta service notification policy when meta service is not found by acl user', function (): void {
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->readMetaServiceRepository
->expects($this->once())
->method('findByIdAndContact')
->willReturn(null);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('setResponseStatus')
->with(new NotFoundResponse('Meta service'));
($this->useCase)(1, $this->findNotificationPolicyPresenter);
});
it('returns users, user groups and notification status', function (): void {
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readMetaServiceRepository
->expects($this->once())
->method('findById')
->willReturn($this->metaService);
$this->readMetaServiceNotificationRepository
->expects($this->once())
->method('findNotifiedContactsById')
->with(1)
->willReturn([$this->notifiedContact]);
$this->readMetaServiceNotificationRepository
->expects($this->once())
->method('findNotifiedContactGroupsById')
->with(1)
->willReturn([$this->notifiedContactGroup]);
$this->realTimeMetaService->setNotificationEnabled(false);
$this->readRealTimeMetaServiceRepository
->expects($this->once())
->method('findMetaServiceById')
->willReturn($this->realTimeMetaService);
$engineConfiguration = new EngineConfiguration();
$engineConfiguration->setNotificationsEnabledOption(EngineConfiguration::NOTIFICATIONS_OPTION_DISABLED);
$this->engineService
->expects($this->once())
->method('findCentralEngineConfiguration')
->willReturn($engineConfiguration);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('present')
->with(new FindNotificationPolicyResponse([$this->notifiedContact], [$this->notifiedContactGroup], false));
($this->useCase)(1, $this->findNotificationPolicyPresenter);
});
| 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/Application/Configuration/NotificationPolicy/UseCase/FindNotificationPolicyResponseTest.php | centreon/tests/php/Core/Application/Configuration/NotificationPolicy/UseCase/FindNotificationPolicyResponseTest.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\Application\Configuration\NotificationPolicy\UseCase;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyResponse;
use Core\Domain\Configuration\Notification\Model\HostNotification;
use Core\Domain\Configuration\Notification\Model\NotifiedContact;
use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup;
use Core\Domain\Configuration\Notification\Model\ServiceNotification;
use Core\Domain\Configuration\TimePeriod\Model\TimePeriod;
beforeEach(function (): void {
$hostNotification = new HostNotification(new TimePeriod(1, '24x7', '24/24 7/7'));
$hostNotification->addEvent(HostNotification::EVENT_HOST_DOWN);
$serviceNotification = new ServiceNotification(new TimePeriod(1, '24x7', '24/24 7/7'));
$serviceNotification->addEvent(ServiceNotification::EVENT_SERVICE_CRITICAL);
$this->contact = new NotifiedContact(
2,
'user2',
'user 2',
'user2@localhost',
$hostNotification,
$serviceNotification,
);
$this->contactGroup = new NotifiedContactGroup(3, 'cg3', 'cg 3');
});
it('converts given host notification models to array', function (): void {
$response = new FindNotificationPolicyResponse(
[$this->contact],
[$this->contactGroup],
true,
);
expect($response->notifiedContacts)->toBe([
[
'id' => $this->contact->getId(),
'name' => $this->contact->getName(),
'alias' => $this->contact->getAlias(),
'email' => $this->contact->getEmail(),
'notifications' => [
'host' => [
'events' => ['DOWN'],
'time_period' => [
'id' => 1,
'name' => '24x7',
'alias' => '24/24 7/7',
],
],
'service' => [
'events' => ['CRITICAL'],
'time_period' => [
'id' => 1,
'name' => '24x7',
'alias' => '24/24 7/7',
],
],
],
],
]);
expect($response->notifiedContactGroups)->toBe([
[
'id' => $this->contactGroup->getId(),
'name' => $this->contactGroup->getName(),
'alias' => $this->contactGroup->getAlias(),
],
]);
expect($response->isNotificationEnabled)->toBe(true);
});
it('converts given service notification models to array', function (): void {
$response = new FindNotificationPolicyResponse(
[$this->contact],
[$this->contactGroup],
true,
);
expect($response->notifiedContacts)->toBe([
[
'id' => $this->contact->getId(),
'name' => $this->contact->getName(),
'alias' => $this->contact->getAlias(),
'email' => $this->contact->getEmail(),
'notifications' => [
'host' => [
'events' => ['DOWN'],
'time_period' => [
'id' => 1,
'name' => '24x7',
'alias' => '24/24 7/7',
],
],
'service' => [
'events' => ['CRITICAL'],
'time_period' => [
'id' => 1,
'name' => '24x7',
'alias' => '24/24 7/7',
],
],
],
],
]);
expect($response->notifiedContactGroups)->toBe([
[
'id' => $this->contactGroup->getId(),
'name' => $this->contactGroup->getName(),
'alias' => $this->contactGroup->getAlias(),
],
]);
expect($response->isNotificationEnabled)->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/Application/Configuration/NotificationPolicy/UseCase/FindServiceNotificationPolicyTest.php | centreon/tests/php/Core/Application/Configuration/NotificationPolicy/UseCase/FindServiceNotificationPolicyTest.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\Application\Configuration\NotificationPolicy\UseCase;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Engine\EngineConfiguration;
use Centreon\Domain\Engine\Interfaces\EngineConfigurationServiceInterface;
use Centreon\Domain\HostConfiguration\Host;
use Centreon\Domain\HostConfiguration\Interfaces\HostConfigurationRepositoryInterface;
use Centreon\Domain\ServiceConfiguration\Interfaces\ServiceConfigurationRepositoryInterface;
use Centreon\Domain\ServiceConfiguration\Service;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Configuration\Notification\Repository\ReadServiceNotificationRepositoryInterface;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyPresenterInterface;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyResponse;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindServiceNotificationPolicy;
use Core\Application\RealTime\Repository\ReadHostRepositoryInterface as ReadRealTimeHostRepositoryInterface;
use Core\Application\RealTime\Repository\ReadServiceRepositoryInterface as ReadRealTimeServiceRepositoryInterface;
use Core\Domain\Configuration\Notification\Model\HostNotification;
use Core\Domain\Configuration\Notification\Model\NotifiedContact;
use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup;
use Core\Domain\Configuration\Notification\Model\ServiceNotification;
use Core\Domain\Configuration\TimePeriod\Model\TimePeriod;
use Core\Domain\RealTime\Model\Service as RealTimeService;
use Core\Domain\RealTime\Model\ServiceStatus;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->readServiceNotificationRepository = $this->createMock(ReadServiceNotificationRepositoryInterface::class);
$this->hostRepository = $this->createMock(HostConfigurationRepositoryInterface::class);
$this->serviceRepository = $this->createMock(ServiceConfigurationRepositoryInterface::class);
$this->engineService = $this->createMock(EngineConfigurationServiceInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->readRealTimeHostRepository = $this->createMock(ReadRealTimeHostRepositoryInterface::class);
$this->readRealTimeServiceRepository = $this->createMock(ReadRealTimeServiceRepositoryInterface::class);
$this->host = new Host();
$this->service = new Service();
$this->realTimeService = new RealTimeService(
1,
1,
'Ping',
new ServiceStatus(ServiceStatus::STATUS_NAME_CRITICAL, ServiceStatus::STATUS_CODE_CRITICAL, 1),
);
$hostNotification = new HostNotification(new TimePeriod(1, '24x7', '24/24 7/7'));
$hostNotification->addEvent(HostNotification::EVENT_HOST_DOWN);
$serviceNotification = new ServiceNotification(new TimePeriod(1, '24x7', '24/24 7/7'));
$serviceNotification->addEvent(ServiceNotification::EVENT_SERVICE_CRITICAL);
$this->notifiedContact = new NotifiedContact(
1,
'contact1',
'contact1',
'contact1@localhost',
$hostNotification,
$serviceNotification,
);
$this->notifiedContactGroup = new NotifiedContactGroup(3, 'cg3', 'cg 3');
$this->findNotificationPolicyPresenter = $this->createMock(FindNotificationPolicyPresenterInterface::class);
$this->useCase = new FindServiceNotificationPolicy(
$this->readServiceNotificationRepository,
$this->hostRepository,
$this->serviceRepository,
$this->engineService,
$this->accessGroupRepository,
$this->contact,
$this->readRealTimeHostRepository,
$this->readRealTimeServiceRepository,
);
});
it('does not find service notification policy when host is not found by admin user', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->hostRepository
->expects($this->once())
->method('findHost')
->willReturn(null);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('setResponseStatus')
->with(new NotFoundResponse('Host'));
($this->useCase)(1, 1, $this->findNotificationPolicyPresenter);
});
it('does not find service notification policy when acl user does not have access to host', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readRealTimeHostRepository
->expects($this->once())
->method('isAllowedToFindHostByAccessGroupIds')
->willReturn(false);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('setResponseStatus')
->with(new NotFoundResponse('Host'));
($this->useCase)(1, 1, $this->findNotificationPolicyPresenter);
});
it('does not find service notification policy when acl user does not have access to service', function (): void {
$this->contact
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(false);
$this->readRealTimeHostRepository
->expects($this->once())
->method('isAllowedToFindHostByAccessGroupIds')
->willReturn(true);
$this->hostRepository
->expects($this->once())
->method('findHost')
->willReturn($this->host);
$this->readRealTimeServiceRepository
->expects($this->once())
->method('isAllowedToFindServiceByAccessGroupIds')
->willReturn(false);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('setResponseStatus')
->with(new NotFoundResponse('Service'));
($this->useCase)(1, 1, $this->findNotificationPolicyPresenter);
});
it('does not find service notification policy when service is not found by admin user', function (): void {
$this->contact
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->hostRepository
->expects($this->once())
->method('findHost')
->willReturn($this->host);
$this->serviceRepository
->expects($this->once())
->method('findService')
->willReturn(null);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('setResponseStatus')
->with(new NotFoundResponse('Service'));
($this->useCase)(1, 1, $this->findNotificationPolicyPresenter);
});
it('returns users, user groups and notification status', function (): void {
$this->contact
->expects($this->exactly(3))
->method('isAdmin')
->willReturn(true);
$this->hostRepository
->expects($this->once())
->method('findHost')
->willReturn($this->host);
$this->serviceRepository
->expects($this->once())
->method('findService')
->willReturn($this->service);
$this->service->setNotificationsEnabledOption(Service::NOTIFICATIONS_OPTION_DISABLED);
$this->readServiceNotificationRepository
->expects($this->once())
->method('findNotifiedContactsById')
->with(1)
->willReturn([$this->notifiedContact]);
$this->readServiceNotificationRepository
->expects($this->once())
->method('findNotifiedContactGroupsById')
->with(1)
->willReturn([$this->notifiedContactGroup]);
$this->realTimeService->setNotificationEnabled(false);
$this->readRealTimeServiceRepository
->expects($this->once())
->method('findServiceById')
->willReturn($this->realTimeService);
$engineConfiguration = new EngineConfiguration();
$engineConfiguration->setNotificationsEnabledOption(EngineConfiguration::NOTIFICATIONS_OPTION_DISABLED);
$this->engineService
->expects($this->once())
->method('findEngineConfigurationByHost')
->willReturn($engineConfiguration);
$this->findNotificationPolicyPresenter
->expects($this->once())
->method('present')
->with(new FindNotificationPolicyResponse([$this->notifiedContact], [$this->notifiedContactGroup], false));
($this->useCase)(1, 1, $this->findNotificationPolicyPresenter);
});
| 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/Application/Configuration/User/UseCase/PatchUser/PatchUserTest.php | centreon/tests/php/Core/Application/Configuration/User/UseCase/PatchUser/PatchUserTest.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\Application\Configuration\User\UseCase\PatchUser;
use Core\Application\Common\Session\Repository\ReadSessionRepositoryInterface;
use Core\Application\Common\Session\Repository\WriteSessionRepositoryInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Configuration\User\Exception\UserException;
use Core\Application\Configuration\User\Repository\ReadUserRepositoryInterface;
use Core\Application\Configuration\User\Repository\WriteUserRepositoryInterface;
use Core\Application\Configuration\User\UseCase\PatchUser\PatchUser;
use Core\Application\Configuration\User\UseCase\PatchUser\PatchUserRequest;
use Core\Domain\Configuration\User\Model\User;
use Core\Infrastructure\Common\Presenter\JsonFormatter;
use Core\Infrastructure\Configuration\User\Api\PatchUser\PatchUserPresenter;
beforeEach(function (): void {
$this->writeUserRepository = $this->createMock(WriteUserRepositoryInterface::class);
$this->readUserRepository = $this->createMock(ReadUserRepositoryInterface::class);
$this->readSessionRepository = $this->createMock(ReadSessionRepositoryInterface::class);
$this->writeSessionRepository = $this->createMock(WriteSessionRepositoryInterface::class);
$this->request = new PatchUserRequest();
$this->request->theme = 'light';
$this->request->userInterfaceDensity = 'extended';
$this->request->userId = 1;
$this->presenter = new PatchUserPresenter(new JsonFormatter());
});
it('tests the error message when user is not found', function (): void {
$this->readUserRepository
->expects($this->once())
->method('findById')
->willReturn(null);
$useCase = new PatchUser(
$this->readUserRepository,
$this->writeUserRepository,
$this->readSessionRepository,
$this->writeSessionRepository
);
$useCase($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toEqual(new NotFoundResponse('User'));
});
it('tests the exception while searching for the user', function (): void {
$this->readUserRepository
->expects($this->once())
->method('findById')
->willThrowException(new UserException());
$useCase = new PatchUser(
$this->readUserRepository,
$this->writeUserRepository,
$this->readSessionRepository,
$this->writeSessionRepository
);
$useCase($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toEqual(
new ErrorResponse(UserException::errorWhileSearchingForUser(new \Exception())->getMessage())
);
});
it('tests the error message when there are no available themes', function (): void {
$user = new User(1, 'alias', 'name', 'email', true, 'light', 'compact', true);
$this->readUserRepository
->expects($this->once())
->method('findById')
->willReturn($user);
$this->readUserRepository
->expects($this->once())
->method('findAvailableThemes')
->willReturn([]);
$useCase = new PatchUser(
$this->readUserRepository,
$this->writeUserRepository,
$this->readSessionRepository,
$this->writeSessionRepository
);
$useCase($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toEqual(new ErrorResponse('Abnormally empty list of themes'));
});
it('tests the error message when the given theme is not in the list of available themes', function (): void {
$user = new User(1, 'alias', 'name', 'email', true, 'light', 'compact', true);
$this->readUserRepository
->expects($this->once())
->method('findById')
->willReturn($user);
$this->readUserRepository
->expects($this->once())
->method('findAvailableThemes')
->willReturn(['blue', 'green']);
$useCase = new PatchUser(
$this->readUserRepository,
$this->writeUserRepository,
$this->readSessionRepository,
$this->writeSessionRepository
);
$useCase($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toEqual(new ErrorResponse('Requested theme not found'));
});
it('tests the exception while searching for available themes', function (): void {
$user = new User(1, 'alias', 'name', 'email', true, 'light', 'compact', true);
$this->readUserRepository
->expects($this->once())
->method('findById')
->willReturn($user);
$this->readUserRepository
->expects($this->once())
->method('findAvailableThemes')
->willThrowException(new UserException());
$useCase = new PatchUser(
$this->readUserRepository,
$this->writeUserRepository,
$this->readSessionRepository,
$this->writeSessionRepository
);
$useCase($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toEqual(
new ErrorResponse(UserException::errorInReadingUserThemes(new \Exception())->getMessage())
);
});
it('tests the exception while updating the theme of user', function (): void {
$user = new User(1, 'alias', 'name', 'email', true, 'light', 'compact', true);
$this->readUserRepository
->expects($this->once())
->method('findById')
->willReturn($user);
$this->readUserRepository
->expects($this->once())
->method('findAvailableThemes')
->willReturn([$this->request->theme]);
$user->setTheme($this->request->theme);
$this->writeUserRepository
->expects($this->once())
->method('update')
->with($user)
->willThrowException(new UserException());
$useCase = new PatchUser(
$this->readUserRepository,
$this->writeUserRepository,
$this->readSessionRepository,
$this->writeSessionRepository
);
$useCase($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toEqual(
new ErrorResponse(
UserException::errorOnUpdatingUser(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/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatusPresenterStub.php | centreon/tests/php/Core/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatusPresenterStub.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\Application\Platform\UseCase\FindInstallationStatus;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Application\Platform\UseCase\FindInstallationStatus\FindInstallationStatusPresenterInterface;
use Core\Application\Platform\UseCase\FindInstallationStatus\FindInstallationStatusResponse;
use Symfony\Component\HttpFoundation\Response;
class FindInstallationStatusPresenterStub implements FindInstallationStatusPresenterInterface
{
/** @var FindInstallationStatusResponse */
public $response;
/** @var mixed[] */
public $responseHeaders;
/** @var ResponseStatusInterface|null */
private $responseStatus;
/**
* @inheritDoc
*/
public function present(mixed $response): void
{
$this->response = $response;
}
/**
* @inheritDoc
*/
public function show(): Response
{
return new Response();
}
/**
* @inheritDoc
*/
public function setResponseStatus(?ResponseStatusInterface $responseStatus): void
{
$this->responseStatus = $responseStatus;
}
/**
* @inheritDoc
*/
public function getResponseStatus(): ?ResponseStatusInterface
{
return $this->responseStatus;
}
/**
* @inheritDoc
*/
public function setResponseHeaders(array $responseHeaders): void
{
$this->responseHeaders = $responseHeaders;
}
/**
* @inheritDoc
*/
public function getResponseHeaders(): array
{
return $this->responseHeaders;
}
/**
* @inheritDoc
*/
public function getPresentedData(): mixed
{
return $this->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/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatusTest.php | centreon/tests/php/Core/Application/Platform/UseCase/FindInstallationStatus/FindInstallationStatusTest.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\Application\Platform\UseCase\FindInstallationStatus;
use Core\Application\Platform\UseCase\FindInstallationStatus\FindInstallationStatus;
use Core\Platform\Domain\InstallationVerifierInterface;
use PHPUnit\Framework\TestCase;
class FindInstallationStatusTest extends TestCase
{
/** @var InstallationVerifierInterface&\PHPUnit\Framework\MockObject\MockObject */
public $centreonInstallationVerifier;
public function setUp(): void
{
$this->centreonInstallationVerifier = $this->createMock(InstallationVerifierInterface::class);
}
/**
* Test that the use case will correctly pass the versions to the presenter.
*/
public function testFindInstallationStatus(): void
{
$useCase = new FindInstallationStatus($this->centreonInstallationVerifier);
$presenter = new FindInstallationStatusPresenterStub();
$this->centreonInstallationVerifier
->expects($this->once())
->method('isCentreonWebInstallableOrUpgradable')
->willReturn(true);
$this->centreonInstallationVerifier
->expects($this->once())
->method('isCentreonWebInstalled')
->willReturn(true);
$useCase($presenter);
$this->assertEquals($presenter->response->isCentreonWebInstalled, true);
$this->assertEquals($presenter->response->isCentreonWebUpgradeAvailable, 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/AdditionalConnectorConfiguration/Application/UseCase/DeleteAcc/DeleteAccTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/DeleteAcc/DeleteAccTest.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\AdditionalConnectorConfiguration\Application\UseCase\DeleteAcc;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AdditionalConnectorConfiguration\Application\Exception\AccException;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\DeleteAcc\DeleteAcc;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
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\Infrastructure\FeatureFlags;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new DeleteAcc(
$this->readAccRepository = $this->createMock(ReadAccRepositoryInterface::class),
$this->writeAccRepository = $this->createMock(WriteAccRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
$this->flags = new FeatureFlags(false, ''),
$this->writeVaultAccRepositories = new \ArrayIterator([]),
);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->testedAcc = (new Acc(
id: $this->testedAccId = 1,
name: 'acc-name',
type: Type::VMWARE_V6,
createdBy: $this->testedAccCreatedBy = 2,
updatedBy: $this->testedAccCreatedBy,
createdAt: $this->testedAccCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
updatedAt: $this->testedAccCreatedAt,
parameters: $this->createMock(AccParametersInterface::class),
));
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willThrowException(new \Exception());
($this->useCase)($this->testedAccId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AccException::deleteAcc()->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->testedAccId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AccException::accessNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the Additional Connector Configuration does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willReturn(null);
($this->useCase)($this->testedAccId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Additional Connector Configuration not found');
});
it('should present a NoContentResponse on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willReturn($this->testedAcc);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->writeAccRepository
->expects($this->once())
->method('delete');
($this->useCase)($this->testedAccId, $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/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccTest.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\AdditionalConnectorConfiguration\Application\UseCase\AddAcc;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\AdditionalConnectorConfiguration\Application\Exception\AccException;
use Core\AdditionalConnectorConfiguration\Application\Factory\AccFactory;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAcc;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccRequest;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccResponse;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\Validator;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\NewAcc;
use Core\AdditionalConnectorConfiguration\Domain\Model\Poller;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Common\Infrastructure\FeatureFlags;
beforeEach(function (): void {
$this->presenter = new AddAccPresenterStub();
$this->useCase = new AddAcc(
readAccRepository: $this->readAccRepository = $this->createMock(ReadAccRepositoryInterface::class),
writeAccRepository: $this->writeAccRepository = $this->createMock(WriteAccRepositoryInterface::class),
validator: $this->validator = $this->createMock(Validator::class),
factory: $this->factory = $this->createMock(AccFactory::class),
dataStorageEngine: $this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class),
user: $this->user = $this->createMock(ContactInterface::class),
flags: $this->flags = new FeatureFlags(false, ''),
writeVaultAccRepositories: $this->writeVaultAccRepositories = new \ArrayIterator([])
);
$this->testedAddAccRequest = new AddAccRequest();
$this->testedAddAccRequest->name = 'added-acc';
$this->testedAddAccRequest->type = 'vmware_v6';
$this->testedAddAccRequest->description = 'toto';
$this->testedAddAccRequest->pollers = [1];
$this->testedAddAccRequest->parameters = [
'port' => '4242',
'vcenters' => [
[
'name' => 'my-vcenter',
'url' => 'http://10.10.10.10/sdk',
'username' => 'admin',
'password' => 'my-pwd',
],
],
];
$this->poller = new Poller(1, 'poller-name');
$this->testedNewAcc = new NewAcc(
name: $this->testedAccName = 'acc-name',
type: Type::VMWARE_V6,
createdBy: $this->testedAccCreatedBy = 2,
description: 'some-description',
parameters: $this->createMock(AccParametersInterface::class),
);
$this->testedAcc = new Acc(
id: $this->testedAccId = 1,
name: $this->testedAccName = 'acc-name',
type: Type::VMWARE_V6,
createdBy: $this->testedAccCreatedBy = 2,
updatedBy: $this->testedAccCreatedBy,
createdAt: $this->testedAccCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
updatedAt: $this->testedAccUpdatedAt = $this->testedAccCreatedAt,
description: 'some-description',
parameters: $this->createMock(AccParametersInterface::class),
);
});
it(
'should present a ForbiddenResponse when the user does not have the correct role',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->testedAddAccRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AccException::accessNotAllowed()->getMessage());
}
);
it(
'should present an ErrorResponse when an AccException is thrown',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateRequestOrFail')
->willThrowException(AccException::nameAlreadyExists('invalid-name'));
($this->useCase)($this->testedAddAccRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AccException::nameAlreadyExists('invalid-name')->getMessage());
}
);
it(
'should present an ErrorResponse when a generic exception is thrown',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->any())
->method('getId')
->willReturn($this->testedAccCreatedBy);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->factory
->expects($this->once())
->method('createNewAcc')
->willReturn($this->testedNewAcc);
$this->writeAccRepository
->expects($this->once())
->method('add')
->willThrowException(new \Exception());
($this->useCase)($this->testedAddAccRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AccException::addAcc()->getMessage());
}
);
it(
'should present an InvalidArgumentResponse when a field value is not valid',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->any())
->method('getId')
->willReturn($this->testedAccCreatedBy);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$expectedException = AssertionException::notEmptyString('NewAcc::name');
$this->factory
->expects($this->once())
->method('createNewAcc')
->willThrowException($expectedException);
($this->useCase)($this->testedAddAccRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->data->getMessage())
->toBe($expectedException->getMessage());
}
);
it(
'should present an ErrorResponse if the newly created ACC cannot be retrieved',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->any())
->method('getId')
->willReturn($this->testedAccCreatedBy);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->factory
->expects($this->once())
->method('createNewAcc')
->willReturn($this->testedNewAcc);
$this->writeAccRepository
->expects($this->once())
->method('add')
->willReturn($this->testedAccId);
$this->readAccRepository
->expects($this->once())
->method('find')
->willReturn(null);
($this->useCase)($this->testedAddAccRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AccException::errorWhileRetrievingObject()->getMessage());
}
);
it(
'should present an AddAccResponse when no error occurs',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->any())
->method('getId')
->willReturn($this->testedAccCreatedBy);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->factory
->expects($this->once())
->method('createNewAcc')
->willReturn($this->testedNewAcc);
$this->writeAccRepository
->expects($this->once())
->method('add')
->willReturn($this->testedAccId);
$this->readAccRepository
->expects($this->once())
->method('find')
->willReturn($this->testedAcc);
$this->readAccRepository
->expects($this->once())
->method('findPollersByAccId')
->willReturn([$this->poller]);
($this->useCase)($this->testedAddAccRequest, $this->presenter);
/** @var AddAccResponse $acc */
$acc = $this->presenter->data;
expect($acc)->toBeInstanceOf(AddAccResponse::class)
->and($acc->id)->toBe($this->testedAccId)
->and($acc->name)->toBe($this->testedAccName)
->and($acc->description)->toBe($this->testedAcc->getDescription())
->and($acc->createdAt->getTimestamp())->toBe($this->testedAccCreatedAt->getTimestamp())
->and($acc->updatedAt->getTimestamp())->toBeGreaterThanOrEqual(
$this->testedAccUpdatedAt->getTimestamp()
);
}
);
| 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/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/ValidatorTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/ValidatorTest.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\AdditionalConnectorConfiguration\Application\UseCase\AddAcc;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AdditionalConnectorConfiguration\Application\Exception\AccException;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccRequest;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\Validator;
use Core\AdditionalConnectorConfiguration\Domain\Model\Poller;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use ValueError;
beforeEach(function (): void {
$this->validator = new Validator(
readAccRepository: $this->readAccRepository = $this->createMock(ReadAccRepositoryInterface::class),
user: $this->user = $this->createMock(ContactInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
readMonitoringServerRepository: $this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
parametersValidators: new \ArrayIterator([]),
);
$this->request = new AddAccRequest();
$this->request->name = 'my-ACC';
$this->request->type = 'vmware_v6';
$this->request->description = null;
$this->request->pollers = [1];
$this->request->parameters = [];
$this->poller = new Poller(1, 'poller-name');
});
it('should throw an exception when the name is invalid', function (): void {
$this->readAccRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->validator->validateNameOrFail($this->request);
})->throws(AccException::nameAlreadyExists('my-ACC')->getMessage());
it('should throw an exception when the pollers list is empty', function (): void {
$this->request->pollers = [];
$this->validator->validatePollersOrFail($this->request);
})->throws(AccException::arrayCanNotBeEmpty('pollers')->getMessage());
it('should throw an exception when a poller ID does not exist', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readMonitoringServerRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validator->validatePollersOrFail($this->request);
})->throws(AccException::idsDoNotExist('pollers', [1])->getMessage());
it('should throw an exception when the ACC type is not valid', function (): void {
$this->request->type = '';
$this->validator->validateTypeOrFail($this->request);
})->throws((new ValueError('"" is not a valid backing value for enum Core\AdditionalConnectorConfiguration\Domain\Model\Type'))->getMessage());
it('should throw an exception when the ACC type is already associated to one of the pollers', function (): void {
$this->readAccRepository
->expects($this->once())
->method('findPollersByType')
->willReturn([$this->poller]);
$this->validator->validateTypeOrFail($this->request);
})->throws(AccException::alreadyAssociatedPollers(Type::VMWARE_V6, [1])->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/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccPresenterStub.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/AddAcc/AddAccPresenterStub.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\AdditionalConnectorConfiguration\Application\UseCase\AddAcc;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccPresenterInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
class AddAccPresenterStub implements AddAccPresenterInterface
{
public AddAccResponse|ResponseStatusInterface $data;
public function presentResponse(AddAccResponse|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/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAccTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAccTest.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\AdditionalConnectorConfiguration\Application\UseCase\FindAcc;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AdditionalConnectorConfiguration\Application\Exception\AccException;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc\FindAcc;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc\FindAccResponse;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Poller;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new FindAcc(
$this->readAccRepository = $this->createMock(ReadAccRepositoryInterface::class),
$this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readContactRepository = $this->createMock(ReadContactRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
);
$this->presenter = new FindAccPresenterStub();
$this->acc = new Acc(
id: $this->accId = 1,
name: 'acc-name',
type: Type::VMWARE_V6,
createdBy: $this->createdBy = 2,
updatedBy: $this->createdBy,
createdAt: $this->createdAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
updatedAt: $this->createdAt,
parameters: $this->createMock(AccParametersInterface::class),
);
$this->poller = new Poller(1, 'my-poller');
});
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->accId, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AccException::accessNotAllowed()->getMessage());
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willThrowException(new \Exception());
($this->useCase)($this->accId, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AccException::errorWhileRetrievingObject()->getMessage());
});
it('should present a NotFoundResponse when the ACC ID does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willReturn(null);
($this->useCase)($this->accId, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->data->getMessage())
->toBe('Additional Connector Configuration not found');
});
it('should present a FindAccResponse on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willReturn($this->acc);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('findPollersByAccId')
->willReturn([$this->poller]);
$this->readContactRepository
->expects($this->once())
->method('findNamesByIds')
->willReturn([$this->createdBy => ['id' => $this->createdBy, 'name' => 'username']]);
($this->useCase)($this->accId, $this->presenter);
$result = $this->presenter->data;
expect($result)
->toBeInstanceOf(FindAccResponse::class)
->and($result->name)->toBe($this->acc->getName())
->and($result->type)->toBe($this->acc->getType())
->and($result->pollers)->toBe([$this->poller])
->and($result->parameters)->toBe($this->acc->getParameters()->getDataWithoutCredentials());
});
| 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/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAccPresenterStub.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAcc/FindAccPresenterStub.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\AdditionalConnectorConfiguration\Application\UseCase\FindAcc;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc\FindAccPresenterInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAcc\FindAccResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
class FindAccPresenterStub implements FindAccPresenterInterface
{
public FindAccResponse|ResponseStatusInterface $data;
public function presentResponse(FindAccResponse|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/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccsPresenterStub.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccsPresenterStub.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\AdditionalConnectorConfiguration\Application\UseCase\FindAccs;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs\FindAccsPresenterInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs\FindAccsResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
class FindAccsPresenterStub implements FindAccsPresenterInterface
{
public FindAccsResponse|ResponseStatusInterface $data;
public function presentResponse(FindAccsResponse|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/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccsTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/FindAccs/FindAccsTest.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\AdditionalConnectorConfiguration\Application\UseCase\FindAccs;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\AdditionalConnectorConfiguration\Application\Exception\AccException;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs\FindAccs;
use Core\AdditionalConnectorConfiguration\Application\UseCase\FindAccs\FindAccsResponse;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Poller;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new FindAccs(
$this->requestParameters = $this->createMock(RequestParametersInterface::class),
$this->readAccRepository = $this->createMock(ReadAccRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readContactRepository = $this->createMock(ReadContactRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
);
$this->presenter = new FindAccsPresenterStub();
$this->acc = new Acc(
id: $this->accId = 1,
name: 'acc-name',
type: Type::VMWARE_V6,
createdBy: $this->createdBy = 2,
updatedBy: $this->createdBy,
createdAt: $this->createdAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
updatedAt: $this->createdAt,
parameters: $this->createMock(AccParametersInterface::class),
);
$this->poller = new Poller(1, 'my-poller');
});
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->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AccException::accessNotAllowed()->getMessage());
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('findByRequestParameters')
->willThrowException(new \Exception());
($this->useCase)($this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AccException::findAccs()->getMessage());
});
it('should present a FindAccsResponse on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('findByRequestParameters')
->willReturn([$this->acc]);
$this->readContactRepository
->expects($this->once())
->method('findNamesByIds')
->willReturn([$this->createdBy => ['id' => $this->createdBy, 'name' => 'username']]);
($this->useCase)($this->presenter);
$result = $this->presenter->data;
expect($result)
->toBeInstanceOf(FindAccsResponse::class)
->and($result->accs[0]->name)->toBe($this->acc->getName())
->and($result->accs[0]->type)->toBe($this->acc->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/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/ValidatorTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/ValidatorTest.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\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\Validation;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AdditionalConnectorConfiguration\Application\Exception\AccException;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\UpdateAccRequest;
use Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\Validator;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Poller;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->validator = new Validator(
readAccRepository: $this->readAccRepository = $this->createMock(ReadAccRepositoryInterface::class),
user: $this->user = $this->createMock(ContactInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
readMonitoringServerRepository: $this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
parametersValidators: new \ArrayIterator([]),
);
$this->acc = new Acc(
id: 1,
name: 'my-acc',
type: Type::VMWARE_V6,
createdBy: 1,
updatedBy: 1,
createdAt: new \DateTimeImmutable(),
updatedAt: new \DateTimeImmutable(),
parameters: $this->createMock(AccParametersInterface::class)
);
$this->request = new UpdateAccRequest();
$this->request->name = 'my-ACC';
$this->request->type = 'vmware_v6';
$this->request->description = null;
$this->request->pollers = [1];
$this->request->parameters = [];
$this->poller = new Poller(1, 'poller-name');
$this->pollerBis = new Poller(2, 'poller-name-bis');
});
it('should throw an exception when the name is invalid', function (): void {
$this->readAccRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->validator->validateNameOrFail($this->request, $this->acc);
})->throws(AccException::nameAlreadyExists('my-ACC')->getMessage());
it('should throw an exception when the pollers list is empty', function (): void {
$this->request->pollers = [];
$this->validator->validatePollersOrFail($this->request, $this->acc);
})->throws(AccException::arrayCanNotBeEmpty('pollers')->getMessage());
it('should throw an exception when the ACC type is changed', function (): void {
$this->request->type = '';
$this->validator->validateTypeOrFail($this->request, $this->acc);
})->skip(true, 'Cannot be tested as long as there is only one supported type');
// throws(AccException::typeChangeNotAllowed()->getMessage());
it('should throw an exception when a poller ID does not exist', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readMonitoringServerRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validator->validatePollersOrFail($this->request, $this->acc);
})->throws(AccException::idsDoNotExist('pollers', [1])->getMessage());
it('should throw an exception when the ACC type is already associated to one of the pollers', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readMonitoringServerRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('findPollersByAccId')
->willReturn([$this->pollerBis]);
$this->readAccRepository
->expects($this->once())
->method('findPollersByType')
->willReturn([$this->poller]);
$this->validator->validatePollersOrFail($this->request, $this->acc);
})->throws(AccException::alreadyAssociatedPollers(Type::VMWARE_V6, [1])->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/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/UpdateAccTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/UseCase/UpdateAcc/UpdateAccTest.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\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\AdditionalConnectorConfiguration\Application\Exception\AccException;
use Core\AdditionalConnectorConfiguration\Application\Factory\AccFactory;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\UpdateAcc;
use Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\UpdateAccRequest;
use Core\AdditionalConnectorConfiguration\Application\UseCase\UpdateAcc\Validator;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Poller;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Common\Infrastructure\FeatureFlags;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->useCase = new UpdateAcc(
$this->readAccRepository = $this->createMock(ReadAccRepositoryInterface::class),
$this->writeAccRepository = $this->createMock(WriteAccRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
$this->validator = $this->createMock(Validator::class),
$this->factory = $this->createMock(AccFactory::class),
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->user = $this->createMock(ContactInterface::class),
$this->flags = new FeatureFlags(false, ''),
$this->writeVaultAccRepositories = new \ArrayIterator([]),
$this->readVaultAccRepositories = new \ArrayIterator([])
);
$this->request = new UpdateAccRequest();
$this->request->name = 'acc edited';
$this->request->type = 'vmware_v6';
$this->request->description = 'toto';
$this->request->pollers = [1];
$this->request->parameters = [
'port' => '4242',
'vcenters' => [
[
'name' => 'my-vcenter',
'url' => 'http://10.10.10.10/sdk',
'username' => 'admin',
'password' => 'my-pwd',
],
],
];
$this->poller = new Poller(1, 'poller-name');
$this->acc = new Acc(
id: $this->accId = 1,
name: $this->accName = 'acc-name',
type: $this->accType = Type::VMWARE_V6,
createdBy: $this->accCreatedBy = 2,
updatedBy: $this->accUpdatedBy = $this->accCreatedBy,
createdAt: $this->accCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
updatedAt: $this->accUpdatedAt = $this->accCreatedAt,
description: 'some-description',
parameters: $this->createMock(AccParametersInterface::class),
);
});
it(
'should present a ForbiddenResponse when the user does not have the correct role',
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(AccException::accessNotAllowed()->getMessage());
}
);
it(
'should present an ErrorResponse when a Exception is thrown',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AccException::updateAcc()->getMessage());
}
);
it(
'should present an ErrorResponse when a generic exception is thrown',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willReturn($this->acc);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->writeAccRepository
->expects($this->once())
->method('update')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AccException::updateAcc()->getMessage());
}
);
it(
'should present a InvalidArgumentResponse when a field value is not valid',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willReturn($this->acc);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->request->name = '';
$expectedException = AssertionException::notEmptyString('Acc::name');
$this->factory
->expects($this->once())
->method('updateAcc')
->willThrowException($expectedException);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe($expectedException->getMessage());
}
);
it(
'should present a UpdateAccResponse when no error occurs',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAccRepository
->expects($this->once())
->method('find')
->willReturn($this->acc);
$this->user
->expects($this->any())
->method('getId')
->willReturn($this->accCreatedBy);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->factory
->expects($this->once())
->method('updateAcc');
$this->writeAccRepository
->expects($this->once())
->method('update');
($this->useCase)($this->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/AdditionalConnectorConfiguration/Application/Validation/VmWareV6DataValidatorTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Application/Validation/VmWareV6DataValidatorTest.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 Core\AdditionalConnectorConfiguration\Application\Validation;
use Core\AdditionalConnectorConfiguration\Application\Exception\AccException;
use Core\AdditionalConnectorConfiguration\Application\UseCase\AddAcc\AddAccRequest;
beforeEach(function (): void {
$this->validator = new VmWareV6DataValidator();
$this->request = new AddAccRequest();
$this->request->name = 'my-ACC';
$this->request->type = 'vmware_v6';
$this->request->description = null;
$this->request->pollers = [1];
$this->request->parameters = [
'port' => 4242,
'vcenters' => [
[
'name' => 'my-vcenter',
'url' => 'http://10.10.10.10/sdk',
'username' => 'admin',
'password' => 'pwd',
],
],
];
});
it('should throw an exception when the vcenters have duplicate names', function (): void {
$this->request->parameters['vcenters'][] = $this->request->parameters['vcenters'][0];
$this->validator->validateParametersOrFail($this->request);
})->throws(AccException::duplicatesNotAllowed('parameters.vcenters[].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/AdditionalConnectorConfiguration/Domain/Model/VmWareV6ParametersTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Domain/Model/VmWareV6ParametersTest.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 Core\AdditionalConnectorConfiguration\Application\Validation;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AdditionalConnectorConfiguration\Domain\Model\VmWareV6\VmWareV6Parameters;
use Security\Interfaces\EncryptionInterface;
beforeEach(function (): void {
$this->encryption = $this->createMock(EncryptionInterface::class);
$this->parameters = [
'port' => 4242,
'vcenters' => [
[
'name' => 'my-vcenter',
'scheme' => null,
'url' => 'http://10.10.10.10/sdk',
'username' => 'admin',
'password' => 'pwd',
],
],
];
});
it('should throw an exception when the port is not valid', function (): void {
$this->parameters['port'] = 9999999999;
new VmWareV6Parameters($this->encryption, $this->parameters);
})->throws(AssertionException::range(9999999999, 0, 65535, 'parameters.port')->getMessage());
foreach (
[
'name',
'username',
'password',
'url',
] as $field
) {
$tooLong = str_repeat('a', VmWareV6Parameters::MAX_LENGTH + 1);
it(
"should throw an exception when a vcenter {$field} is too long",
function () use ($field, $tooLong): void {
$this->parameters['vcenters'][0][$field] = $tooLong;
new VmWareV6Parameters($this->encryption, $this->parameters);
}
)->throws(
AssertionException::maxLength(
$tooLong,
VmWareV6Parameters::MAX_LENGTH + 1,
VmWareV6Parameters::MAX_LENGTH,
"parameters.vcenters[0].{$field}"
)->getMessage()
);
}
foreach (
[
'name',
'username',
'password',
'url',
] as $field
) {
it(
"should throw an exception when a vcenter {$field} is too short",
function () use ($field): void {
$this->parameters['vcenters'][0][$field] = '';
new VmWareV6Parameters($this->encryption, $this->parameters);
}
)->throws(
AssertionException::notEmptyString("parameters.vcenters[0].{$field}")->getMessage()
);
}
it(
'should throw an exception when a vcenter URL is invalid',
function (): void {
$this->parameters['vcenters'][0]['url'] = 'invalid@xyz';
new VmWareV6Parameters($this->encryption, $this->parameters);
}
)->throws(
AssertionException::urlOrIpOrDomain('invalid@xyz', 'parameters.vcenters[0].url')->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/AdditionalConnectorConfiguration/Domain/Model/AccTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Domain/Model/AccTest.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\AdditionalConnectorConfiguration\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
beforeEach(function (): void {
$this->testedCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00');
$this->testedUpdatedAt = new \DateTimeImmutable('2023-05-09T16:00:00+00:00');
$this->testedParameters = $this->createMock(AccParametersInterface::class);
$this->testedType = Type::VMWARE_V6;
$this->createAcc = fn (array $fields = []): Acc => new Acc(
id: $fields['id'] ?? 1,
name: $fields['name'] ?? 'acc-name',
type: $this->testedType,
createdBy: \array_key_exists('created_by', $fields) ? $fields['created_by'] : 2,
updatedBy: \array_key_exists('updated_by', $fields) ? $fields['updated_by'] : 3,
createdAt: $this->testedCreatedAt,
updatedAt: $this->testedUpdatedAt,
parameters: $this->testedParameters,
);
});
it('should return properly set ACC instance', function (): void {
$acc = ($this->createAcc)();
expect($acc->getId())->toBe(1)
->and($acc->getName())->toBe('acc-name')
->and($acc->getDescription())->toBe(null)
->and($acc->getType())->toBe($this->testedType)
->and($acc->getUpdatedAt()->getTimestamp())->toBe($this->testedUpdatedAt->getTimestamp())
->and($acc->getCreatedAt()->getTimestamp())->toBe($this->testedCreatedAt->getTimestamp())
->and($acc->getCreatedBy())->toBe(2)
->and($acc->getUpdatedBy())->toBe(3)
->and($acc->getParameters())->toBe($this->testedParameters);
});
// mandatory fields
it(
'should throw an exception when ACC name is an empty string',
fn () => ($this->createAcc)(['name' => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString('Acc::name')->getMessage()
);
// string field trimmed
it('should return trimmed field name after construct', function (): void {
$acc = new Acc(
id: 1,
type: Type::VMWARE_V6,
name: ' abcd ',
createdBy: 1,
updatedBy: 1,
createdAt: new \DateTimeImmutable(),
updatedAt: new \DateTimeImmutable(),
parameters: $this->testedParameters
);
expect($acc->getName())->toBe('abcd');
});
it('should return trimmed field description', function (): void {
$acc = new Acc(
id: 1,
type: Type::VMWARE_V6,
name: 'abcd',
createdBy: 1,
updatedBy: 1,
createdAt: new \DateTimeImmutable(),
updatedAt: new \DateTimeImmutable(),
parameters: $this->testedParameters,
description: ' abcd '
);
expect($acc->getDescription())->toBe('abcd');
});
// updatedAt change
it(
'should NOT change the updatedAt field',
function (): void {
$updatedAtBefore = $this->testedUpdatedAt->getTimestamp();
$acc = ($this->createAcc)();
$updatedAtAfter = $acc->getUpdatedAt()->getTimestamp();
expect($updatedAtAfter)->toBe($updatedAtBefore);
}
);
// too long fields
foreach (
[
'name' => Acc::MAX_NAME_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when ACC {$field} is too long",
fn () => ($this->createAcc)([$field => $tooLong])
)->throws(
AssertionException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "Acc::{$field}")->getMessage()
);
}
// not positive integers
foreach (
[
'created_by' => 'createdBy',
'updated_by' => 'updatedBy',
] as $field => $propertyName
) {
it(
"should throw an exception when ACC {$field} is not a positive integer",
fn () => ($this->createAcc)([$field => 0])
)->throws(
AssertionException::class,
AssertionException::positiveInt(0, 'Acc::' . $propertyName)->getMessage()
);
}
// nullable field allowed
foreach (
[
'created_by' => 'createdBy',
'updated_by' => 'updatedBy',
] as $field => $propertyName
) {
it(
"should return the NULL field {$field} after construct",
function () use ($field, $propertyName): void {
$acc = ($this->createAcc)([$field => null]);
$valueFromGetter = $acc->{'get' . $propertyName}();
expect($valueFromGetter)->toBeNull();
}
);
}
| 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/AdditionalConnectorConfiguration/Domain/Model/NewAccTest.php | centreon/tests/php/Core/AdditionalConnectorConfiguration/Domain/Model/NewAccTest.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\AdditionalConnectorConfiguration\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\NewAcc;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
beforeEach(function (): void {
$this->createAcc = function (array $fields = []): NewAcc {
$acc = new NewAcc(
name: $fields['name'] ?? 'acc-name',
type: Type::VMWARE_V6,
createdBy: $fields['created_by'] ?? 2,
parameters: $this->createMock(AccParametersInterface::class)
);
$acc->setDescription($fields['description'] ?? 'acc-description');
return $acc;
};
});
it('should return properly set ACC instance', function (): void {
$now = time();
$acc = ($this->createAcc)();
expect($acc->getName())->toBe('acc-name')
->and($acc->getDescription())->toBe('acc-description')
->and($acc->getCreatedAt()->getTimestamp())->toBeGreaterThanOrEqual($now)
->and($acc->getUpdatedAt()->getTimestamp())->toBeGreaterThanOrEqual($now)
->and($acc->getCreatedBy())->toBe(2)
->and($acc->getUpdatedBy())->toBe(2);
});
// mandatory fields
it(
'should throw an exception when ACC name is an empty string',
fn () => ($this->createAcc)(['name' => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString('NewAcc::name')->getMessage()
);
// string field trimmed
foreach (
[
'name',
'description',
] as $field
) {
it(
"should return trimmed field {$field} after construct",
function () use ($field): void {
$acc = ($this->createAcc)([$field => ' abcd ']);
$valueFromGetter = $acc->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// updatedAt change
it(
'should change the updatedAt field',
function (): void {
$updatedAtBefore = time();
$acc = ($this->createAcc)();
$updatedAtAfter = $acc->getUpdatedAt()->getTimestamp();
expect($updatedAtAfter)->toBeGreaterThanOrEqual($updatedAtBefore);
}
);
// too long fields
foreach (
[
'name' => Acc::MAX_NAME_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when ACC {$field} is too long",
fn () => ($this->createAcc)([$field => $tooLong])
)->throws(
AssertionException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "NewAcc::{$field}")->getMessage()
);
}
// not positive integers
foreach (
[
'created_by' => 'createdBy',
] as $field => $propertyName
) {
it(
"should throw an exception when ACC {$field} is not a positive integer",
fn () => ($this->createAcc)([$field => 0])
)->throws(
AssertionException::class,
AssertionException::positiveInt(0, 'NewAcc::' . $propertyName)->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/AgentConfiguration/Application/UseCase/FindAgentConfiguration/FindAgentConfigurationTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/FindAgentConfiguration/FindAgentConfigurationTest.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\AgentConfiguration\Application\UseCase\FindAgentConfiguration;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfiguration\FindAgentConfiguration;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfiguration\FindAgentConfigurationResponse;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\TelegrafConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new FindAgentConfiguration(
readRepository: $this->readRepository = $this->createMock(ReadAgentConfigurationRepositoryInterface::class),
readHostRepository: $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
);
});
it('should present a Not Found Response when object does not exist', function (): void {
$this->readRepository
->expects($this->once())
->method('find')
->willReturn(null);
$response = ($this->useCase)(1);
expect($response)
->toBeInstanceOf(NotFoundResponse::class)
->and($response->getMessage())
->toBe('Agent Configuration not found');
});
it('should present an Error Response when an unexpected error occurs', function (): void {
$this->readRepository
->expects($this->once())
->method('find')
->willThrowException(new \Exception());
$response = ($this->useCase)(1);
expect($response)
->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())
->toBe(AgentConfigurationException::errorWhileRetrievingObject()->getMessage());
});
it('should present a FindConfigurationResponse when everything is ok', function (): void {
$configuration = new TelegrafConfigurationParameters(
[
'otel_server_address' => '10.10.10.10',
'otel_server_port' => 453,
'otel_public_certificate' => 'public_certif.crt',
'otel_ca_certificate' => 'ca_certif.cer',
'otel_private_key' => 'otel-key.key',
'conf_server_port' => 454,
'conf_certificate' => 'conf-certif.crt',
'conf_private_key' => 'conf-key.key',
]
);
$pollers = [
new Poller(1, 'pollerOne'),
new Poller(2, 'pollerTwo'),
];
$this->readRepository
->expects($this->once())
->method('find')
->willReturn(
new AgentConfiguration(
id: 1,
name: 'acOne',
type: Type::TELEGRAF,
connectionMode: ConnectionModeEnum::SECURE,
configuration: $configuration
)
);
$this->readRepository
->expects($this->once())
->method('findPollersByAcId')
->willReturn($pollers);
$response = ($this->useCase)(1);
expect($response)
->toBeInstanceOf(FindAgentConfigurationResponse::class)
->and($response->agentConfiguration->getId())->toBe(1)
->and($response->agentConfiguration->getName())->toBe('acOne')
->and($response->agentConfiguration->getType())->toBe(Type::TELEGRAF)
->and($response->agentConfiguration->getConnectionMode())->toBe(ConnectionModeEnum::SECURE)
->and($response->agentConfiguration->getConfiguration()->getData())->toBe([
'otel_server_address' => '10.10.10.10',
'otel_server_port' => 453,
'otel_public_certificate' => '/etc/pki/public_certif.crt',
'otel_ca_certificate' => '/etc/pki/ca_certif.cer',
'otel_private_key' => '/etc/pki/otel-key.key',
'conf_server_port' => 454,
'conf_certificate' => '/etc/pki/conf-certif.crt',
'conf_private_key' => '/etc/pki/conf-key.key',
])
->and($response->pollers[0]->getId())->toBe(1)
->and($response->pollers[0]->getName())->toBe('pollerOne')
->and($response->pollers[1]->getId())->toBe(2)
->and($response->pollers[1]->getName())->toBe('pollerTwo');
});
| 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/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/ValidatorTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/ValidatorTest.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\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\Validation;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\UpdateAgentConfigurationRequest;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\Validator;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->validator = new Validator(
readAcRepository: $this->readAcRepository = $this->createMock(ReadAgentConfigurationRepositoryInterface::class),
user: $this->user = $this->createMock(ContactInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
readMonitoringServerRepository: $this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
parametersValidators: new \ArrayIterator([]),
);
$this->agentConfiguration = new AgentConfiguration(
id: 1,
name: 'my-ac',
type: Type::TELEGRAF,
connectionMode: ConnectionModeEnum::SECURE,
configuration: $this->createMock(ConfigurationParametersInterface::class)
);
$this->request = new UpdateAgentConfigurationRequest();
$this->request->name = 'my-AC';
$this->request->type = 'telegraf';
$this->request->pollerIds = [1];
$this->request->configuration = [];
$this->request->connectionMode = ConnectionModeEnum::SECURE;
$this->poller = new Poller(1, 'poller-name');
$this->pollerBis = new Poller(2, 'poller-name-bis');
});
it('should throw an exception when the name is invalid', function (): void {
$this->readAcRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->validator->validateNameOrFail($this->request, $this->agentConfiguration);
})->throws(AgentConfigurationException::nameAlreadyExists('my-AC')->getMessage());
it('should throw an exception when the poller list is empty', function (): void {
$this->request->pollerIds = [];
$this->validator->validatePollersOrFail($this->request, $this->agentConfiguration);
})->throws(AgentConfigurationException::arrayCanNotBeEmpty('pollerIds')->getMessage());
it('should throw an exception when the type is changed', function (): void {
$this->request->type = 'centreon-agent';
$this->validator->validateTypeOrFail($this->request, $this->agentConfiguration);
})->throws(AgentConfigurationException::typeChangeNotAllowed()->getMessage());
it('should throw an exception when a poller ID does not exist', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readMonitoringServerRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validator->validatePollersOrFail($this->request, $this->agentConfiguration);
})->throws(AgentConfigurationException::idsDoNotExist('pollerIds', [1])->getMessage());
it('should throw an exception when the object is already associated to one of the pollers', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readMonitoringServerRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readAcRepository
->expects($this->any())
->method('findPollersByAcId')
->willReturn([$this->pollerBis]);
$this->readAcRepository
->expects($this->atMost(2))
->method('findPollersByType')
->willReturnMap(
[
[Type::TELEGRAF, [$this->poller]],
[Type::CMA, []],
]
);
$this->validator->validatePollersOrFail($this->request, $this->agentConfiguration);
})->throws(AgentConfigurationException::alreadyAssociatedPollers([1])->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/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/UpdateAgentConfigurationTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/UpdateAgentConfiguration/UpdateAgentConfigurationTest.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\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Repository\WriteAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\UpdateAgentConfiguration;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\UpdateAgentConfigurationRequest;
use Core\AgentConfiguration\Application\UseCase\UpdateAgentConfiguration\Validator;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Common\Application\Repository\RepositoryManagerInterface;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->useCase = new UpdateAgentConfiguration(
readAcRepository: $this->readAgentConfigurationRepository = $this->createMock(ReadAgentConfigurationRepositoryInterface::class),
writeAcRepository: $this->writeAgentConfigurationRepository = $this->createMock(WriteAgentConfigurationRepositoryInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
readMonitoringServerRepository: $this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
validator: $this->validator = $this->createMock(Validator::class),
repositoryManager: $this->dataStorageEngine = $this->createMock(RepositoryManagerInterface::class),
user: $this->user = $this->createMock(ContactInterface::class),
isCloudPlatform: false,
);
$this->request = new UpdateAgentConfigurationRequest();
$this->request->name = 'ac edited';
$this->request->type = 'telegraf';
$this->request->pollerIds = [1];
$this->request->configuration = [
'conf_server_port' => 454,
'otel_public_certificate' => 'public_certif',
'otel_ca_certificate' => 'ca_certif',
'otel_private_key' => 'otel-key',
'conf_certificate' => 'conf-certif',
'conf_private_key' => 'conf-key',
];
$this->request->connectionMode = ConnectionModeEnum::SECURE;
$this->poller = new Poller(1, 'poller-name');
$this->agentConfiguration = new AgentConfiguration(
id: $this->agentConfigurationId = 1,
name: $this->agentConfigurationName = 'ac-name',
type: $this->agentConfigurationType = Type::TELEGRAF,
connectionMode: $this->agentConfigurationConnectionMode = ConnectionModeEnum::SECURE,
configuration: $this->createMock(ConfigurationParametersInterface::class),
);
});
it(
'should present a ForbiddenResponse when the user does not have the correct role',
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(AgentConfigurationException::accessNotAllowed()->getMessage());
}
);
it(
'should present an ErrorResponse when an Exception is thrown',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AgentConfigurationException::updateAc()->getMessage());
}
);
it(
'should present an ErrorResponse when a generic exception is thrown',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn($this->agentConfiguration);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->writeAgentConfigurationRepository
->expects($this->once())
->method('update')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AgentConfigurationException::updateAc()->getMessage());
}
);
it(
'should present an InvalidArgumentResponse when a field value is not valid',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn($this->agentConfiguration);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->request->name = '';
$expectedException = AssertionException::notEmptyString('AgentConfiguration::name');
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe($expectedException->getMessage());
}
);
it(
'should present an UpdateAgentConfigurationResponse when no error occurs',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn($this->agentConfiguration);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->writeAgentConfigurationRepository
->expects($this->once())
->method('update');
($this->useCase)($this->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/AgentConfiguration/Application/UseCase/DeleteAgentConfiguration/DeleteAgentConfigurationTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/DeleteAgentConfiguration/DeleteAgentConfigurationTest.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\AgentConfiguration\Application\UseCase\DeleteAgentConfiguration;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Repository\WriteAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\UseCase\DeleteAgentConfiguration\DeleteAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Type;
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\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new DeleteAgentConfiguration(
$this->readAgentConfigurationRepository = $this->createMock(ReadAgentConfigurationRepositoryInterface::class),
$this->writeAgentConfigurationRepository = $this->createMock(WriteAgentConfigurationRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
false
);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->testedAc = (new AgentConfiguration(
id: $this->testedAcId = 1,
name: 'ac-name',
type: Type::TELEGRAF,
connectionMode: ConnectionModeEnum::SECURE,
configuration: $this->createMock(ConfigurationParametersInterface::class),
));
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willThrowException(new \Exception());
($this->useCase)($this->testedAcId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AgentConfigurationException::deleteAc()->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->testedAcId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AgentConfigurationException::accessNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the host template does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn(null);
($this->useCase)($this->testedAcId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Poller/agent Configuration not found');
});
it('should present a NoContentResponse on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn($this->testedAc);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->writeAgentConfigurationRepository
->expects($this->once())
->method('delete');
($this->useCase)($this->testedAcId, $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/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurationsPresenterStub.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurationsPresenterStub.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\AgentConfiguration\Application\UseCase\FindAgentConfigurations;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfigurations\FindAgentConfigurationsPresenterInterface;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfigurations\FindAgentConfigurationsResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
class FindAgentConfigurationsPresenterStub implements FindAgentConfigurationsPresenterInterface
{
public FindAgentConfigurationsResponse|ResponseStatusInterface $data;
public function presentResponse(FindAgentConfigurationsResponse|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/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurationsTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/FindAgentConfigurations/FindAgentConfigurationsTest.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\AgentConfiguration\Application\UseCase\FindAgentConfigurations;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfigurations\AgentConfigurationDto;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfigurations\FindAgentConfigurations;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfigurations\FindAgentConfigurationsResponse;
use Core\AgentConfiguration\Application\UseCase\FindAgentConfigurations\PollerDto;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\TelegrafConfigurationParameters;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
beforeEach(function (): void {
$this->presenter = new FindAgentConfigurationsPresenterStub();
$this->useCase = new FindAgentConfigurations(
user: $this->user = $this->createMock(ContactInterface::class),
readRepository: $this->readRepository = $this->createMock(ReadAgentConfigurationRepositoryInterface::class),
requestParameters: $this->requestParameters = $this->createMock(RequestParametersInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
);
});
it('should present a Forbidden Response when user does not have topology role', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AgentConfigurationException::accessNotAllowed()->getMessage());
});
it('should retrieve agent configurations without calculating ACL for an admin', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findAllByRequestParameters');
($this->useCase)($this->presenter);
});
it('should retrieve agent configurations without calculating ACL for a non admin', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readRepository
->expects($this->once())
->method('findAllByRequestParametersAndAccessGroups');
($this->useCase)($this->presenter);
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readRepository
->expects($this->once())
->method('findAllByRequestParametersAndAccessGroups')
->willThrowException(new \Exception());
($this->useCase)($this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AgentConfigurationException::errorWhileRetrievingObjects()->getMessage());
});
it('should present a FindAgentConfigurationsResponse when no errors occurred', function (): void {
$acOne = new AgentConfiguration(
id: 1,
name: 'acOne',
type: Type::TELEGRAF,
connectionMode: ConnectionModeEnum::SECURE,
configuration: new TelegrafConfigurationParameters(
[
'otel_server_address' => '10.10.10.10',
'otel_server_port' => 453,
'otel_public_certificate' => 'public_certif',
'otel_ca_certificate' => 'ca_certif',
'otel_private_key' => 'otel-key',
'conf_server_port' => 454,
'conf_certificate' => 'conf-certif',
'conf_private_key' => 'conf-key',
]
)
);
$acTwo = new AgentConfiguration(
id: 2,
name: 'acTwo',
type: Type::TELEGRAF,
connectionMode: ConnectionModeEnum::SECURE,
configuration: new TelegrafConfigurationParameters(
[
'otel_server_address' => '10.10.10.11',
'otel_server_port' => 453,
'otel_public_certificate' => 'public_certif',
'otel_ca_certificate' => 'ca_certif',
'otel_private_key' => 'otel-key',
'conf_server_port' => 454,
'conf_certificate' => 'conf-certif',
'conf_private_key' => 'conf-key',
]
)
);
$pollerOne = new Poller(1, 'poller_1', true);
$pollerTwo = new Poller(2, 'poller_2', false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readRepository
->expects($this->once())
->method('findAllByRequestParametersAndAccessGroups')
->willReturn([$acOne, $acTwo]);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([new AccessGroup(1, 'customer_non_admin_acl', 'not an admin')]);
$this->readRepository
->expects($this->any())
->method('findPollersByAcId')
->willReturn([$pollerOne, $pollerTwo]);
($this->useCase)($this->presenter);
expect(value: $this->presenter->data)
->toBeInstanceOf(FindAgentConfigurationsResponse::class)
->and(value: $this->presenter->data->agentConfigurations)
->toBeArray()
->and($this->presenter->data->agentConfigurations[0])
->toBeInstanceOf(AgentConfigurationDto::class)
->and($this->presenter->data->agentConfigurations[0]->id)
->toBe($acOne->getId())
->and($this->presenter->data->agentConfigurations[0]->name)
->toBe($acOne->getName())
->and($this->presenter->data->agentConfigurations[0]->type)
->toBe($acOne->getType())
->and($this->presenter->data->agentConfigurations[0]->pollers)
->toBeArray()
->and($this->presenter->data->agentConfigurations[0]->pollers[0])
->toBeInstanceOf(PollerDto::class)
->and($this->presenter->data->agentConfigurations[0]->pollers[0]->id)
->toBe($pollerOne->getId())
->and($this->presenter->data->agentConfigurations[0]->pollers[0]->name)
->toBe($pollerOne->getName())
->and($this->presenter->data->agentConfigurations[0]->pollers[1])
->toBeInstanceOf(PollerDto::class)
->and($this->presenter->data->agentConfigurations[0]->pollers[1]->id)
->toBe($pollerTwo->getId())
->and($this->presenter->data->agentConfigurations[0]->pollers[1]->name)
->toBe($pollerTwo->getName())
->and($this->presenter->data->agentConfigurations[1])
->toBeInstanceOf(AgentConfigurationDto::class)
->and($this->presenter->data->agentConfigurations[1]->id)
->toBe($acTwo->getId())
->and($this->presenter->data->agentConfigurations[1]->name)
->toBe($acTwo->getName())
->and($this->presenter->data->agentConfigurations[1]->type)
->toBe($acTwo->getType())
->and($this->presenter->data->agentConfigurations[1]->pollers)
->toBeArray()
->and($this->presenter->data->agentConfigurations[1]->pollers[0])
->toBeInstanceOf(PollerDto::class)
->and($this->presenter->data->agentConfigurations[1]->pollers[0]->id)
->toBe($pollerOne->getId())
->and($this->presenter->data->agentConfigurations[1]->pollers[0]->name)
->toBe($pollerOne->getName())
->and($this->presenter->data->agentConfigurations[1]->pollers[1])
->toBeInstanceOf(PollerDto::class)
->and($this->presenter->data->agentConfigurations[1]->pollers[1]->id)
->toBe($pollerTwo->getId())
->and($this->presenter->data->agentConfigurations[1]->pollers[1]->name)
->toBe($pollerTwo->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/AgentConfiguration/Application/UseCase/DeleteAgentConfigurationPollerLink/DeleteAgentConfigurationPollerLinkTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/DeleteAgentConfigurationPollerLink/DeleteAgentConfigurationPollerLinkTest.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\AgentConfiguration\Application\UseCase\DeleteAgentConfigurationPollerLink;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Repository\WriteAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\UseCase\DeleteAgentConfigurationPollerLink\DeleteAgentConfigurationPollerLink;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
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\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new DeleteAgentConfigurationPollerLink(
$this->readAgentConfigurationRepository = $this->createMock(ReadAgentConfigurationRepositoryInterface::class),
$this->writeAgentConfigurationRepository = $this->createMock(WriteAgentConfigurationRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
false
);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->pollerId = 1;
$this->pollerA = new Poller($this->pollerId, 'pollerA');
$this->pollerB = new Poller($this->pollerId + 1, 'pollerB');
$this->testedAc = (new AgentConfiguration(
id: $this->testedAcId = 1,
name: 'ac-name',
type: Type::TELEGRAF,
connectionMode: ConnectionModeEnum::SECURE,
configuration: $this->createMock(ConfigurationParametersInterface::class),
));
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willThrowException(new \Exception());
($this->useCase)($this->testedAcId, $this->pollerId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AgentConfigurationException::deleteAc()->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->testedAcId, $this->pollerId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(AgentConfigurationException::accessNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the object does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn(null);
($this->useCase)($this->testedAcId, $this->pollerId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Poller/agent Configuration not found');
});
it('should present an ErrorResponse when the poller is the only one linked to the object', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn($this->testedAc);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('findPollersByAcId')
->willReturn([$this->pollerA]);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
($this->useCase)($this->testedAcId, $this->pollerId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(
AgentConfigurationException::onlyOnePoller(
$this->pollerId,
$this->testedAcId
)->getMessage()
);
});
it('should present a NoContentResponse on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn($this->testedAc);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('findPollersByAcId')
->willReturn([$this->pollerA, $this->pollerB]);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->writeAgentConfigurationRepository
->expects($this->once())
->method('removePoller');
($this->useCase)($this->testedAcId, $this->pollerId, $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/AgentConfiguration/Application/UseCase/AddAgentConfiguration/TelegrafValidatorTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/TelegrafValidatorTest.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\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationRequest;
use Core\AgentConfiguration\Application\Validation\TelegrafValidator;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
beforeEach(function (): void {
$this->TelegrafValidator = new TelegrafValidator();
$this->request = new AddAgentConfigurationRequest();
$this->request->name = 'telegraf-test';
$this->request->type = 'telegraf';
$this->request->pollerIds = [1];
$this->request->configuration = [];
$this->poller = new Poller(1, 'poller-name');
});
it('should correctly identify that it handles TELEGRAF type', function (): void {
$result = $this->TelegrafValidator->isValidFor(Type::TELEGRAF);
expect($result)->toBeTrue();
});
it('should correctly identify that it does not handle other types', function (): void {
$result = $this->TelegrafValidator->isValidFor(Type::CMA);
expect($result)->toBeFalse();
});
foreach (
[
'invalidfilename',
'/etc/pki/test.txt',
'/etc/pki/test.doc',
] as $index => $filename
) {
$cleanFilename = str_replace(['/', '.', '..'], '-', $filename);
it("Invalid certificate {$cleanFilename} #{$index}: should throw an exception because of the filename for certificate {$cleanFilename} invalidity", function () use ($filename): void {
$this->request->configuration['conf_certificate'] = $filename;
$this->expectException(AssertionException::class);
$this->TelegrafValidator->validateParametersOrFail($this->request);
});
}
foreach (
[
'/etc/pki/test.crt',
'/etc/pki/test.cer',
'test.crt',
'test.cer',
] as $index => $filename
) {
$cleanFilename = str_replace(['/', '.', '..'], '-', $filename);
it("Valid certificate {$cleanFilename} #{$index}: should not throw an exception when the filename for certificate {$cleanFilename} is valid", function () use ($filename): void {
$this->request->configuration['otel_ca_certificate'] = $filename;
$this->TelegrafValidator->validateParametersOrFail($this->request);
})->expectNotToPerformAssertions();
}
foreach (
[
'invalidfilename',
'/etc/pki/test.txt',
'/etc/pki/test.doc',
] as $index => $filename
) {
$cleanFilename = str_replace(['/', '.', '..'], '-', $filename);
it("Invalid key {$cleanFilename} #{$index}: should throw an exception because of the filename for key {$cleanFilename} invalidity", function () use ($filename): void {
$this->request->configuration['conf_private_key'] = $filename;
$this->expectException(AssertionException::class);
$this->TelegrafValidator->validateParametersOrFail($this->request);
});
}
foreach (
[
'/etc/pki/test.key',
'test.key',
] as $index => $filename
) {
$cleanFilename = str_replace(['/', '.', '..'], '-', $filename);
it("Valid key {$cleanFilename} #{$index}: should not throw an exception when the filename for key {$cleanFilename} is valid", function () use ($filename): void {
$this->request->configuration['otel_private_key'] = $filename;
$this->TelegrafValidator->validateParametersOrFail($this->request);
})->expectNotToPerformAssertions();
}
| 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/AgentConfiguration/Application/UseCase/AddAgentConfiguration/ValidatorTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/ValidatorTest.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\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationRequest;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\Validator;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use ValueError;
beforeEach(function (): void {
$this->validator = new Validator(
readAcRepository: $this->readAgentConfigurationRepository = $this->createMock(ReadAgentConfigurationRepositoryInterface::class),
user: $this->user = $this->createMock(ContactInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
readMonitoringServerRepository: $this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
parametersValidators: new \ArrayIterator([]),
);
$this->request = new AddAgentConfigurationRequest();
$this->request->name = 'my-AC';
$this->request->type = 'telegraf';
$this->request->pollerIds = [1];
$this->request->configuration = [];
$this->poller = new Poller(1, 'poller-name');
});
it('should throw an exception when the name is invalid', function (): void {
$this->readAgentConfigurationRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->validator->validateNameOrFail($this->request);
})->throws(AgentConfigurationException::nameAlreadyExists('my-AC')->getMessage());
it('should throw an exception when the pollers list is empty', function (): void {
$this->request->pollerIds = [];
$this->validator->validatePollersOrFail($this->request);
})->throws(AgentConfigurationException::arrayCanNotBeEmpty('pollerIds')->getMessage());
it('should throw an exception when a poller ID does not exist', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readMonitoringServerRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validator->validatePollersOrFail($this->request);
})->throws(AgentConfigurationException::idsDoNotExist('pollerIds', [1])->getMessage());
it('should throw an exception when the type is not valid', function (): void {
$this->request->type = '';
$this->validator->validateTypeOrFail($this->request);
})->throws((new ValueError('"" is not a valid backing value for enum Core\AgentConfiguration\Domain\Model\Type'))->getMessage());
it('should throw an exception when the object is already associated to one of the pollers', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readMonitoringServerRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readAgentConfigurationRepository
->expects($this->atMost(2))
->method('findPollersByType')
->willReturnMap(
[
[Type::TELEGRAF, [$this->poller]],
[Type::CMA, []],
]
);
$this->validator->validatePollersOrFail($this->request);
})->throws(AgentConfigurationException::alreadyAssociatedPollers([1])->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/AgentConfiguration/Application/UseCase/AddAgentConfiguration/CmaValidatorTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/CmaValidatorTest.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\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationRequest;
use Core\AgentConfiguration\Application\Validation\CmaValidator;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Common\Domain\TrimmedString;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\JwtToken;
beforeEach(function (): void {
$this->cmaValidator = new CmaValidator(
$this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
$this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class),
);
$this->token = new JwtToken(
name: new TrimmedString('tokenName'),
creatorId: 1,
creatorName: new TrimmedString('tokenCreator'),
creationDate: new \DateTimeImmutable(),
expirationDate: null,
);
$this->request = new AddAgentConfigurationRequest();
$this->request->name = 'cmatest';
$this->request->type = 'centeron-agent';
$this->request->pollerIds = [1];
$this->request->connectionMode = ConnectionModeEnum::SECURE;
$this->request->configuration = [
'agent_initiated' => false,
'poller_initiated' => false,
'otel_public_certificate' => '/etc/pki/test.crt',
'otel_private_key' => '/etc/pki/test.key',
'otel_ca_certificate' => '/etc/pki/test.cer',
'port' => 4444,
'tokens' => [
[
'name' => $this->token->getName(),
'creator_id' => $this->token->getCreatorId(),
],
],
'hosts' => [
[
'id' => 1,
'address' => '10.11.12.13',
'port' => 0,
'poller_ca_certificate' => '/etc/pki/test.cer',
'poller_ca_name' => 'poller-name',
'token' => [
'name' => $this->token->getName(),
'creator_id' => $this->token->getCreatorId(),
],
],
],
];
$this->poller = new Poller(1, 'poller-name');
});
/** ------------------------------------------ Validator compatibility ------------------------------------------ */
it('should correctly identify that it handles CMA type', function (): void {
$result = $this->cmaValidator->isValidFor(Type::CMA);
expect($result)->toBeTrue();
});
it('should correctly identify that it does not handle other types', function (): void {
$result = $this->cmaValidator->isValidFor(Type::TELEGRAF);
expect($result)->toBeFalse();
});
/** --------------------------------------- Agent initiated validation --------------------------------------- */
foreach (
[
'invalidfilename',
'/etc/pki/test.txt',
'/etc/pki/test.doc',
] as $index => $filename
) {
$cleanFilename = str_replace(['/', '.', '..'], '-', $filename);
it("Invalid certificate filename #{$index}: should throw an exception because of the filename for certificate {$cleanFilename} invalidity", function () use ($filename): void {
$this->request->configuration['agent_initiated'] = true;
$this->request->configuration['otel_ca_certificate'] = $filename;
$this->expectException(AssertionException::class);
$this->cmaValidator->validateParametersOrFail($this->request);
});
}
foreach (
[
'/etc/pki/test.crt',
'/etc/pki/test.cer',
'test.crt',
'test.cer',
] as $index => $filename
) {
$cleanFilename = str_replace(['/', '.', '..'], '-', $filename);
it("Valid certificate filename #{$index}: should not throw an exception when the filename for certificate {$cleanFilename} is valid", function () use ($filename): void {
$this->request->configuration['poller_initiated'] = true;
$this->request->configuration['hosts'][0]['poller_ca_certificate'] = $filename;
$this->user->method('isAdmin')->willReturn(true);
$this->readHostRepository->expects($this->once())->method('exists')->willReturn(true);
$this->readTokenRepository->expects($this->once())->method('findByNameAndUserId')->willReturn($this->token);
$this->cmaValidator->validateParametersOrFail($this->request);
});
}
foreach (
[
'invalidfilename',
'/etc/pki/test.txt',
'/etc/pki/test.doc',
] as $index => $filename
) {
$cleanFilename = str_replace(['/', '.', '..'], '-', $filename);
it("Invalid key filename #{$index}: should throw an exception because of the filename for key {$cleanFilename} invalidity", function () use ($filename): void {
$this->request->configuration['agent_initiated'] = true;
$this->request->configuration['otel_private_key'] = $filename;
$this->expectException(AssertionException::class);
$this->cmaValidator->validateParametersOrFail($this->request);
});
}
foreach (
[
'/etc/pki/test.key',
'test.key',
] as $index => $filename
) {
$cleanFilename = str_replace(['/', '.', '..'], '-', $filename);
it("Valid key filename #{$index}: should not throw an exception when the filename for key {$cleanFilename} is valid", function () use ($filename): void {
$this->request->configuration['agent_initiated'] = true;
$this->request->configuration['otel_private_key'] = $filename;
$this->user->method('isAdmin')->willReturn(true);
$this->readHostRepository->method('exists')->willReturn(true);
$this->readTokenRepository->method('findByNameAndUserId')->willReturn($this->token);
$this->cmaValidator->validateParametersOrFail($this->request);
})->expectNotToPerformAssertions();
}
it('should throw an exception when a token is not provided and connection is not no_tls or reverse', function (): void {
$this->request->configuration['agent_initiated'] = true;
$this->request->configuration['tokens'] = [];
$this->expectException(AgentConfigurationException::class);
$this->cmaValidator->validateParametersOrFail($this->request);
});
it('should throw an exception when a token is provided but invalid and connection is not no_tls (agent_initiated)', function (): void {
$this->request->configuration['agent_initiated'] = true;
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readTokenRepository
->expects($this->once())
->method('findByNameAndUserId')
->willReturn(null);
$this->expectException(AgentConfigurationException::class);
$this->cmaValidator->validateParametersOrFail($this->request);
});
it('should throw an exception when port is not provided (agent_initiated)', function (): void {
$this->request->configuration['agent_initiated'] = true;
$this->request->configuration['port'] = null;
$this->expectException(AgentConfigurationException::class);
$this->cmaValidator->validateParametersOrFail($this->request);
});
/** --------------------------------------- Poller initiated validation --------------------------------------- */
foreach (
[
'/etc/pki/test.crt',
'/etc/pki/test.cer',
'test.crt',
'test.cer',
] as $filename
) {
it("should not throw an exception when the filename for certificate {$filename} is valid (poller_initiated)", function () use ($filename): void {
$this->request->configuration['poller_initiated'] = true;
$this->request->configuration['hosts'][0]['poller_ca_certificate'] = $filename;
$this->user
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readTokenRepository
->expects($this->once())
->method('findByNameAndUserId')
->willReturn($this->token);
$this->cmaValidator->validateParametersOrFail($this->request);
});
}
it('should throw an exception when the host id is invalid (poller_initiated)', function (): void {
$this->request->configuration['poller_initiated'] = true;
$this->request->configuration['hosts'][0]['id'] = 9999;
$this->readHostRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->cmaValidator->validateParametersOrFail($this->request);
})->throws((AgentConfigurationException::invalidHostId(9999)->getMessage()));
it('should throw an exception when a token is not provided connection is not no_tls (poller_initiated)', function (): void {
$this->request->configuration['poller_initiated'] = true;
$this->request->configuration['hosts'][0]['token'] = null;
$this->expectException(AgentConfigurationException::class);
$this->cmaValidator->validateParametersOrFail($this->request);
});
it('should throw an exception when a token is provided but invalid and connection is not no_tls (poller_initiated)', function (): void {
$this->request->configuration['poller_initiated'] = true;
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readTokenRepository
->expects($this->once())
->method('findByNameAndUserId')
->willReturn(null);
$this->expectException(AgentConfigurationException::class);
$this->cmaValidator->validateParametersOrFail($this->request);
});
| 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/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationPresenterStub.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationPresenterStub.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\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationPresenterInterface;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
class AddAgentConfigurationPresenterStub implements AddAgentConfigurationPresenterInterface
{
public AddAgentConfigurationResponse|ResponseStatusInterface $data;
public function presentResponse(AddAgentConfigurationResponse|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/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationTest.php | centreon/tests/php/Core/AgentConfiguration/Application/UseCase/AddAgentConfiguration/AddAgentConfigurationTest.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\AgentConfiguration\Application\UseCase\AddAgentConfiguration;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\AgentConfiguration\Application\Exception\AgentConfigurationException;
use Core\AgentConfiguration\Application\Repository\ReadAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\Repository\WriteAgentConfigurationRepositoryInterface;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfiguration;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationRequest;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\AddAgentConfigurationResponse;
use Core\AgentConfiguration\Application\UseCase\AddAgentConfiguration\Validator;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\NewAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\Poller;
use Core\AgentConfiguration\Domain\Model\Type;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Common\Application\Repository\RepositoryManagerInterface;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
beforeEach(function (): void {
$this->presenter = new AddAgentConfigurationPresenterStub();
$this->useCase = new AddAgentConfiguration(
readAcRepository: $this->readAgentConfigurationRepository = $this->createMock(ReadAgentConfigurationRepositoryInterface::class),
writeAcRepository: $this->writeAgentConfigurationRepository = $this->createMock(WriteAgentConfigurationRepositoryInterface::class),
readHostRepository: $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
readMsRepository: $this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
validator: $this->validator = $this->createMock(Validator::class),
repositoryManager: $this->dataStorageEngine = $this->createMock(RepositoryManagerInterface::class),
user: $this->user = $this->createMock(ContactInterface::class),
isCloudPlatform: false,
);
$this->testedAddRequest = new AddAgentConfigurationRequest();
$this->testedAddRequest->name = 'added-ac';
$this->testedAddRequest->type = 'telegraf';
$this->testedAddRequest->pollerIds = [1];
$this->testedAddRequest->configuration = [
'otel_server_address' => '10.10.10.10',
'otel_server_port' => 453,
'conf_server_port' => 454,
'otel_public_certificate' => 'public_certif',
'otel_ca_certificate' => 'ca_certif',
'otel_private_key' => 'otel-key',
'conf_certificate' => 'conf-certif',
'conf_private_key' => 'conf-key',
];
$this->poller = new Poller(1, 'poller-name');
$this->testedNewAc = new NewAgentConfiguration(
name: $this->testedAcName = 'ac-name',
type: Type::TELEGRAF,
connectionMode: ConnectionModeEnum::SECURE,
configuration: $this->createMock(ConfigurationParametersInterface::class),
);
$this->testedAc = new AgentConfiguration(
id: $this->testedAcId = 1,
name: $this->testedAcName = 'ac-name',
type: Type::TELEGRAF,
connectionMode: ConnectionModeEnum::SECURE,
configuration: $this->createMock(ConfigurationParametersInterface::class),
);
});
it(
'should present a ForbiddenResponse when the user does not have the correct role',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->testedAddRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AgentConfigurationException::accessNotAllowed()->getMessage());
}
);
it(
'should present an ErrorResponse when an AgentConfigurationException is thrown',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateRequestOrFail')
->willThrowException(AgentConfigurationException::nameAlreadyExists('invalid-name'));
($this->useCase)($this->testedAddRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AgentConfigurationException::nameAlreadyExists('invalid-name')->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('validateRequestOrFail');
$this->writeAgentConfigurationRepository
->expects($this->once())
->method('add')
->willThrowException(new \Exception());
($this->useCase)($this->testedAddRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AgentConfigurationException::addAc()->getMessage());
}
);
it(
'should present an InvalidArgumentResponse when a field value is not valid',
function (): void {
$this->testedAddRequest->name = '';
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$expectedException = AssertionException::notEmptyString('NewAgentConfiguration::name');
($this->useCase)($this->testedAddRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->data->getMessage())
->toBe($expectedException->getMessage());
}
);
it(
'should present an ErrorResponse if the newly created object cannot be retrieved',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->writeAgentConfigurationRepository
->expects($this->once())
->method('add')
->willReturn($this->testedAcId);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn(null);
($this->useCase)($this->testedAddRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(AgentConfigurationException::errorWhileRetrievingObject()->getMessage());
}
);
it(
'should present an AddAgentConfigurationResponse when no error occurs',
function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateRequestOrFail');
$this->writeAgentConfigurationRepository
->expects($this->once())
->method('add')
->willReturn($this->testedAcId);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('findPollersWithBrokerDirective')
->willReturn([$this->poller->id]);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('find')
->willReturn($this->testedAc);
$this->readAgentConfigurationRepository
->expects($this->once())
->method('findPollersByAcId')
->willReturn([$this->poller]);
($this->useCase)($this->testedAddRequest, $this->presenter);
/** @var AddAgentConfigurationResponse $agentConfiguration */
$agentConfiguration = $this->presenter->data;
expect($agentConfiguration)->toBeInstanceOf(AddAgentConfigurationResponse::class)
->and($agentConfiguration->id)->toBe($this->testedAcId)
->and($agentConfiguration->name)->toBe($this->testedAcName);
}
);
| 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/AgentConfiguration/Domain/Model/CmaConfigurationParametersTest.php | centreon/tests/php/Core/AgentConfiguration/Domain/Model/CmaConfigurationParametersTest.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\AgentConfiguration\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\CmaConfigurationParameters;
beforeEach(function (): void {
$this->parameters = [
'agent_initiated' => true,
'poller_initiated' => true,
'otel_public_certificate' => 'otel_certif_filename',
'otel_ca_certificate' => 'ca_certif_filename',
'otel_private_key' => 'otel_key_filename',
'tokens' => [
[
'name' => 'tokenName',
'creator_id' => 1,
],
],
'port' => AgentConfiguration::DEFAULT_PORT,
'hosts' => [
[
'id' => 1,
'address' => '0.0.0.0',
'port' => 442,
'poller_ca_certificate' => 'poller_certif',
'poller_ca_name' => 'ca_name',
'token' => [
'name' => 'tokenName',
'creator_id' => 1,
],
],
],
];
});
foreach (
[
'port',
] as $field
) {
it(
"should throw an exception when the hosts[].{$field} is not valid",
function () use ($field): void {
$this->parameters['hosts'][0][$field] = 9999999999;
new CmaConfigurationParameters($this->parameters);
}
)->throws(
AssertionException::range(
9999999999,
0,
65535,
"configuration.hosts[].{$field}"
)->getMessage()
);
}
foreach (
[
'otel_public_certificate',
'otel_ca_certificate',
'otel_private_key',
] as $field
) {
$tooLong = str_repeat('a', CmaConfigurationParameters::MAX_LENGTH);
it(
"should throw an exception when a {$field} is too long",
function () use ($field, $tooLong): void {
$this->parameters[$field] = $tooLong;
new CmaConfigurationParameters($this->parameters);
}
)->throws(
AssertionException::maxLength(
CmaConfigurationParameters::CERTIFICATE_BASE_PATH . $tooLong,
CmaConfigurationParameters::MAX_LENGTH + mb_strlen(CmaConfigurationParameters::CERTIFICATE_BASE_PATH),
CmaConfigurationParameters::MAX_LENGTH,
"configuration.{$field}"
)->getMessage()
);
}
foreach (
[
'otel_ca_certificate',
'otel_public_certificate',
'otel_private_key',
'poller_ca_certificate',
] as $field
) {
it(
"should add the certificate base path prefix to {$field} when it is not present",
function () use ($field): void {
$field === 'poller_ca_certificate' ? $this->parameters['hosts'][0][$field] = 'test.crt' : $this->parameters[$field] = 'test.crt';
$cmaConfig = new CmaConfigurationParameters($this->parameters);
$result = $cmaConfig->getData();
$field === 'poller_ca_certificate'
? $this->assertEquals($result['hosts'][0][$field], CmaConfigurationParameters::CERTIFICATE_BASE_PATH . 'test.crt')
: $this->assertEquals($result[$field], CmaConfigurationParameters::CERTIFICATE_BASE_PATH . 'test.crt');
}
);
}
foreach (
[
'otel_ca_certificate',
'otel_public_certificate',
'otel_private_key',
'poller_ca_certificate',
] as $field
) {
it(
"should not add the certificate base path prefix to {$field} when it is present",
function () use ($field): void {
$field === 'poller_ca_certificate' ? $this->parameters['hosts'][0][$field] = '/etc/pki/test.crt' : $this->parameters[$field] = '/etc/pki/test.crt';
$cmaConfig = new CmaConfigurationParameters($this->parameters);
$result = $cmaConfig->getData();
$field === 'poller_ca_certificate'
? $this->assertEquals($result['hosts'][0][$field], CmaConfigurationParameters::CERTIFICATE_BASE_PATH . 'test.crt')
: $this->assertEquals($result[$field], CmaConfigurationParameters::CERTIFICATE_BASE_PATH . 'test.crt');
}
);
}
it('should empty the related properties when agent_initiated is false', function (): void {
$this->parameters['agent_initiated'] = false;
$cmaConfig = new CmaConfigurationParameters($this->parameters);
$result = $cmaConfig->getData();
$this->assertEquals($result['otel_public_certificate'], null);
$this->assertEquals($result['otel_private_key'], null);
$this->assertEquals($result['otel_ca_certificate'], null);
$this->assertEquals($result['tokens'], []);
});
it('should empty the related properties when poller_initiated is false', function (): void {
$this->parameters['poller_initiated'] = false;
$cmaConfig = new CmaConfigurationParameters($this->parameters);
$result = $cmaConfig->getData();
$this->assertEquals($result['hosts'], []);
});
// Path security validation tests
foreach (
[
'../cert.crt' => 'relative path with ../',
'./cert.crt' => 'relative path with ./',
'path//cert.crt' => 'double slashes',
'.hidden/cert.crt' => 'hidden directory',
'/.ssh/cert.crt' => 'hidden directory in root',
'/tmp/cert.crt' => 'forbidden directory /tmp',
'/root/cert.crt' => 'forbidden directory /root',
'/proc/cert.crt' => 'forbidden directory /proc',
'/etc/ssl/cert.crt' => '/etc subdirectory other than /etc/pki',
] as $path => $reason
) {
it("should throw an exception for {$reason}: {$path}", function () use ($path): void {
$this->parameters['otel_public_certificate'] = $path;
new CmaConfigurationParameters($this->parameters);
})->throws(AssertionException::class);
}
// Valid custom paths
foreach (
[
'/usr/local/certs/cert.crt',
'/opt/ssl/cert.crt',
'/etc/pki/cert.crt',
'/etc/pki/subdir/cert.crt',
] as $path
) {
it("should accept valid custom path: {$path}", function () use ($path): void {
$this->parameters['otel_public_certificate'] = $path;
$cmaConfig = new CmaConfigurationParameters($this->parameters);
$result = $cmaConfig->getData();
$this->assertEquals($result['otel_public_certificate'], $path);
});
}
| 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/AgentConfiguration/Domain/Model/AgentConfigurationTest.php | centreon/tests/php/Core/AgentConfiguration/Domain/Model/AgentConfigurationTest.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\AgentConfiguration\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AgentConfiguration\Domain\Model\AgentConfiguration;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\Type;
beforeEach(function (): void {
$this->testedCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00');
$this->testedUpdatedAt = new \DateTimeImmutable('2023-05-09T16:00:00+00:00');
$this->testedParameters = $this->createMock(ConfigurationParametersInterface::class);
$this->testedType = Type::TELEGRAF;
$this->createAc = fn (array $fields = []): AgentConfiguration => new AgentConfiguration(
id: $fields['id'] ?? 1,
name: $fields['name'] ?? 'ac-name',
type: $this->testedType,
connectionMode: $fields['connection_mode'] ?? ConnectionModeEnum::SECURE,
configuration: $this->testedParameters,
);
});
it('should return properly set instance', function (): void {
$agentconfiguration = ($this->createAc)();
expect($agentconfiguration->getId())->toBe(1)
->and($agentconfiguration->getName())->toBe('ac-name')
->and($agentconfiguration->getType())->toBe($this->testedType)
->and($agentconfiguration->getConfiguration())->toBe($this->testedParameters);
});
// mandatory fields
it(
'should throw an exception when name is an empty string',
fn () => ($this->createAc)(['name' => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString('AgentConfiguration::name')->getMessage()
);
// string field trimmed
it('should return trimmed field name after construct', function (): void {
$agentconfiguration = new AgentConfiguration(
id: 1,
type: Type::TELEGRAF,
name: ' abcd ',
connectionMode: ConnectionModeEnum::SECURE,
configuration: $this->testedParameters
);
expect($agentconfiguration->getName())->toBe('abcd');
});
// too long fields
foreach (
[
'name' => AgentConfiguration::MAX_NAME_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when {$field} is too long",
fn () => ($this->createAc)([$field => $tooLong])
)->throws(
AssertionException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "AgentConfiguration::{$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/AgentConfiguration/Domain/Model/TelegrafConfigurationParametersTest.php | centreon/tests/php/Core/AgentConfiguration/Domain/Model/TelegrafConfigurationParametersTest.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 Core\AdditionalConnectorConfiguration\Application\Validation;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AgentConfiguration\Domain\Model\ConfigurationParameters\TelegrafConfigurationParameters;
beforeEach(function (): void {
$this->parameters = [
'otel_public_certificate' => 'otel_certif_filename',
'otel_ca_certificate' => 'ca_certif_filename',
'otel_private_key' => 'otel_key_filename',
'conf_server_port' => 489,
'conf_certificate' => 'conf_certif_filename',
'conf_private_key' => 'conf_key_filename',
];
});
foreach (
[
'conf_server_port',
] as $field
) {
it(
"should throw an exception when the {$field} is not valid",
function () use ($field): void {
$this->parameters[$field] = 9999999999;
new TelegrafConfigurationParameters($this->parameters);
}
)->throws(
AssertionException::range(
9999999999,
0,
65535,
"configuration.{$field}"
)->getMessage()
);
}
foreach (
[
'otel_public_certificate',
'otel_ca_certificate',
'otel_private_key',
'conf_certificate',
'conf_private_key',
] as $field
) {
$tooLong = str_repeat('a', TelegrafConfigurationParameters::MAX_LENGTH);
it(
"should throw an exception when a {$field} is too long",
function () use ($field, $tooLong): void {
$this->parameters[$field] = $tooLong;
new TelegrafConfigurationParameters($this->parameters);
}
)->throws(
AssertionException::maxLength(
TelegrafConfigurationParameters::CERTIFICATE_BASE_PATH . $tooLong,
TelegrafConfigurationParameters::MAX_LENGTH + mb_strlen(TelegrafConfigurationParameters::CERTIFICATE_BASE_PATH),
TelegrafConfigurationParameters::MAX_LENGTH,
"configuration.{$field}"
)->getMessage()
);
}
foreach (
[
'conf_certificate',
'conf_private_key',
'otel_ca_certificate',
'otel_private_key',
'otel_public_certificate',
] as $field
) {
it(
"should add the certificate base path prefix to {$field} when it is not present",
function () use ($field): void {
$field === 'poller_ca_certificate' ? $this->parameters['hosts'][0][$field] = 'test.crt' : $this->parameters[$field] = 'test.crt';
$cmaConfig = new TelegrafConfigurationParameters($this->parameters);
$result = $cmaConfig->getData();
$field === 'poller_ca_certificate'
? $this->assertEquals($result['hosts'][0][$field], TelegrafConfigurationParameters::CERTIFICATE_BASE_PATH . 'test.crt')
: $this->assertEquals($result[$field], TelegrafConfigurationParameters::CERTIFICATE_BASE_PATH . 'test.crt');
}
);
}
foreach (
[
'conf_certificate',
'conf_private_key',
'otel_ca_certificate',
'otel_private_key',
'otel_public_certificate',
] as $field
) {
it(
"should not add the certificate base path prefix to {$field} when it is present",
function () use ($field): void {
$field === 'poller_ca_certificate' ? $this->parameters['hosts'][0][$field] = 'test.crt' : $this->parameters[$field] = '/etc/pki/test.crt';
$cmaConfig = new TelegrafConfigurationParameters($this->parameters);
$result = $cmaConfig->getData();
$field === 'poller_ca_certificate'
? $this->assertEquals($result['hosts'][0][$field], TelegrafConfigurationParameters::CERTIFICATE_BASE_PATH . 'test.crt')
: $this->assertEquals($result[$field], TelegrafConfigurationParameters::CERTIFICATE_BASE_PATH . 'test.crt');
}
);
}
// Path security validation tests
foreach (
[
'../cert.crt' => 'relative path with ../',
'./cert.crt' => 'relative path with ./',
'path//cert.crt' => 'double slashes',
'.hidden/cert.crt' => 'hidden directory',
'/.ssh/cert.crt' => 'hidden directory in root',
'/tmp/cert.crt' => 'forbidden directory /tmp',
'/root/cert.crt' => 'forbidden directory /root',
'/proc/cert.crt' => 'forbidden directory /proc',
'/etc/ssl/cert.crt' => '/etc subdirectory other than /etc/pki',
] as $path => $reason
) {
it("should throw an exception for {$reason}: {$path}", function () use ($path): void {
$this->parameters['otel_public_certificate'] = $path;
new TelegrafConfigurationParameters($this->parameters);
})->throws(AssertionException::class);
}
// Valid custom paths
foreach (
[
'/usr/local/certs/cert.crt',
'/opt/ssl/cert.crt',
'/etc/pki/cert.crt',
'/etc/pki/subdir/cert.crt',
] as $path
) {
it("should accept valid custom path: {$path}", function () use ($path): void {
$this->parameters['otel_public_certificate'] = $path;
$telegrafConfig = new TelegrafConfigurationParameters($this->parameters);
$result = $telegrafConfig->getData();
$this->assertEquals($result['otel_public_certificate'], $path);
});
}
| 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/AgentConfiguration/Domain/Model/NewAgentConfigurationTest.php | centreon/tests/php/Core/AgentConfiguration/Domain/Model/NewAgentConfigurationTest.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\AgentConfiguration\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\AgentConfiguration\Domain\Model\ConfigurationParametersInterface;
use Core\AgentConfiguration\Domain\Model\ConnectionModeEnum;
use Core\AgentConfiguration\Domain\Model\NewAgentConfiguration;
use Core\AgentConfiguration\Domain\Model\Type;
beforeEach(function (): void {
$this->createAc = fn (array $fields = []): NewAgentConfiguration => new NewAgentConfiguration(
name: $fields['name'] ?? 'ac-name',
type: Type::TELEGRAF,
connectionMode: $fields['connection_mode'] ?? ConnectionModeEnum::SECURE,
configuration: $this->createMock(ConfigurationParametersInterface::class)
);
});
it('should return properly set instance', function (): void {
$now = time();
$agentconfiguration = ($this->createAc)();
expect($agentconfiguration->getName())->toBe('ac-name');
});
// mandatory fields
it(
'should throw an exception when name is an empty string',
fn () => ($this->createAc)(['name' => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString('NewAgentConfiguration::name')->getMessage()
);
// string field trimmed
foreach (
[
'name',
] as $field
) {
it(
"should return trimmed field {$field} after construct",
function () use ($field): void {
$agentconfiguration = ($this->createAc)([$field => ' abcd ']);
$valueFromGetter = $agentconfiguration->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => NewAgentConfiguration::MAX_NAME_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when {$field} is too long",
fn () => ($this->createAc)([$field => $tooLong])
)->throws(
AssertionException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "NewAgentConfiguration::{$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/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardTest.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\Dashboard\Application\UseCase\ShareDashboard;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\WriteDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\ShareDashboard\ShareDashboard;
use Core\Dashboard\Application\UseCase\ShareDashboard\ShareDashboardRequest;
use Core\Dashboard\Application\UseCase\ShareDashboard\ShareDashboardValidator;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->rights = $this->createMock(DashboardRights::class);
$this->validator = $this->createMock(ShareDashboardValidator::class);
$this->writeDashboardShareRepository = $this->createMock(WriteDashboardShareRepositoryInterface::class);
$this->readContactRepository = $this->createMock(ReadContactRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->readContactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class);
$this->useCase = new ShareDashboard(
$this->rights,
$this->validator,
$this->writeDashboardShareRepository,
$this->readContactRepository,
$this->readAccessGroupRepository,
$this->readContactGroupRepository,
$this->contact,
$this->dataStorageEngine,
$this->isCloudPlatform = false
);
});
it('should present a Not Found Response when the dashboard does not exist', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateDashboard')
->willThrowException(DashboardException::theDashboardDoesNotExist($request->dashboardId));
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(NotFoundResponse::class)
->and($response->getMessage())
->toBe(DashboardException::theDashboardDoesNotExist($request->dashboardId)->getMessage());
});
it('should present a Forbidden Response when the dashboard is not shared with the user', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$this->validator
->expects($this->once())
->method('validateDashboard')
->willThrowException(DashboardException::dashboardAccessRightsNotAllowedForWriting($request->dashboardId));
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(ForbiddenResponse::class)
->and($response->getMessage())
->toBe(DashboardException::dashboardAccessRightsNotAllowedForWriting($request->dashboardId)->getMessage());
});
it('should present an Invalid Argument Response when the edited contacts do not exist', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contacts = [
[
'id' => 1,
'role' => 'editor',
],
];
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateContactsForOnPremise')
->willThrowException(DashboardException::theContactsDoNotExist([1]));
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(DashboardException::theContactsDoNotExist([1])->getMessage());
});
it('should present an Invalid Argument Response when the contacts are duplicated', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contacts = [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 1,
'role' => 'editor',
],
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateContactsForOnPremise')
->willThrowException(DashboardException::contactForShareShouldBeUnique());
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(DashboardException::contactForShareShouldBeUnique()->getMessage());
});
it('should present an Invalid Argument Response when the users have insufficient ACLs', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contacts = [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateContactsForOnPremise')
->willThrowException(DashboardException::theContactGroupsDoesNotHaveDashboardAccessRights([2]));
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(DashboardException::theContactGroupsDoesNotHaveDashboardAccessRights([2])->getMessage());
});
it(
'should present an Invalid Argument Response when the user is not admin '
. 'and the request users are not members of his access groups',
function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contacts = [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$this->validator
->expects($this->once())
->method('validateContactsForOnPremise')
->willThrowException(DashboardException::userAreNotInAccessGroups([2]));
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(DashboardException::userAreNotInAccessGroups([2])->getMessage());
}
);
it('should present an Invalid Argument Response when the edited contact groups do not exist', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contactGroups = [
[
'id' => 1,
'role' => 'editor',
],
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateContactGroupsForOnPremise')
->willThrowException(DashboardException::theContactGroupsDoNotExist([1]));
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(DashboardException::theContactGroupsDoNotExist([1])->getMessage());
});
it('should present an Invalid Argument Response when the contact groups are duplicated', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contactGroups = [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 1,
'role' => 'editor',
],
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateContactGroupsForOnPremise')
->willThrowException(DashboardException::contactGroupForShareShouldBeUnique());
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(DashboardException::contactGroupForShareShouldBeUnique()->getMessage());
});
it('should present an Invalid Argument Response when the contact groups have insufficient ACLs', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contactGroups = [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->validator
->expects($this->once())
->method('validateContactGroupsForOnPremise')
->willThrowException(DashboardException::theContactGroupsDoesNotHaveDashboardAccessRights([2]));
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(DashboardException::theContactGroupsDoesNotHaveDashboardAccessRights([2])->getMessage());
});
it(
'should present an Invalid Argument Response when the user is not admin '
. 'and the request contact groups are not members of his contact groups',
function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contactGroups = [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$this->validator
->expects($this->once())
->method('validateContactGroupsForOnPremise')
->willThrowException(DashboardException::contactGroupIsNotInUserContactGroups([2]));
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(DashboardException::contactGroupIsNotInUserContactGroups([2])->getMessage());
}
);
it('should present an Error Response when an unhandled error occurs', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contactGroups = [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$this->readContactRepository
->expects($this->once())
->method('findContactIdsByAccessGroups')
->willThrowException(new \Exception());
$response = ($this->useCase)($request);
expect($response)->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())
->toBe(DashboardException::errorWhileUpdatingDashboardShare()->getMessage());
});
it('should present a No Content Response when no error occurs', function (): void {
$request = new ShareDashboardRequest();
$request->dashboardId = 1;
$request->contactGroups = [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
];
$this->rights
->expects($this->any())
->method('hasAdminRole')
->willReturn(true);
$this->writeDashboardShareRepository
->expects($this->once())
->method('deleteDashboardShares');
$this->writeDashboardShareRepository
->expects($this->once())
->method('addDashboardContactShares');
$this->writeDashboardShareRepository
->expects($this->once())
->method('addDashboardContactGroupShares');
$response = ($this->useCase)($request);
expect($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/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardValidatorTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/ShareDashboard/ShareDashboardValidatorTest.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\Dashboard\Application\UseCase\ShareDashboard;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\ShareDashboard\ShareDashboardValidator;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardContactGroupRole;
use Core\Dashboard\Domain\Model\Role\DashboardContactRole;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
beforeEach(function (): void {
$this->contact = $this->createMock(ContactInterface::class);
$this->rights = $this->createMock(DashboardRights::class);
$this->readDashboardRepository = $this->createMock(ReadDashboardRepositoryInterface::class);
$this->readDashboardShareRepository = $this->createMock(ReadDashboardShareRepositoryInterface::class);
$this->readContactRepository = $this->createMock(ReadContactRepositoryInterface::class);
$this->readContactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class);
$this->validator = new ShareDashboardValidator(
$this->contact,
$this->readDashboardRepository,
$this->readDashboardShareRepository,
$this->readContactRepository,
$this->readContactGroupRepository
);
});
it('should throw a Dashboard Exception when the dashboard does not exist', function (): void {
$this->readDashboardRepository
->method('existsOne')
->willReturn(false);
$this->validator->validateDashboard(1, true);
})->throws(DashboardException::theDashboardDoesNotExist(1)->getMessage());
it('should throw a Dashboard Exception when the dashboard is not shared has editor', function (): void {
$this->readDashboardRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->readDashboardShareRepository
->expects($this->once())
->method('existsAsEditor')
->willReturn(false);
$this->validator->validateDashboard(1, false);
})->throws(DashboardException::dashboardAccessRightsNotAllowedForWriting(1)->getMessage());
it('should throw a Dashboard Exception when the contacts does not exists', function (): void {
$this->readContactRepository
->expects($this->once())
->method('exist')
->willReturn([1]);
$this->validator->validateContactsForOnPremise(
isAdmin: true,
contacts: [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
[
'id' => 3,
'role' => 'editor',
],
],
);
})->throws(DashboardException::theContactsDoNotExist([2, 3])->getMessage());
it('should throw a Dashboard Exception when the contacts are duplicated', function (): void {
$this->readContactRepository
->expects($this->once())
->method('exist')
->willReturn([1]);
$this->validator->validateContactsForOnPremise(
isAdmin: true,
contacts: [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 1,
'role' => 'editor',
],
],
);
})->throws(DashboardException::contactForShareShouldBeUnique()->getMessage());
it('should throw a Dashboard Exception when the request contacts does not have Dashboard ACLs', function (): void {
$this->readContactRepository
->expects($this->once())
->method('exist')
->willReturn([1, 2]);
$this->readDashboardShareRepository
->expects($this->once())
->method('findContactsWithAccessRightByContactIds')
->willReturn([
new DashboardContactRole(
1,
'user',
'user@email.com',
[DashboardGlobalRole::Creator]
),
]);
$this->validator->validateContactsForOnPremise(
isAdmin: true,
contacts: [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
],
);
})->throws(DashboardException::theContactsDoesNotHaveDashboardAccessRights([2])->getMessage());
it('should throw a Dashboard Exception when the request contacts does not have sufficient ACLs level', function (): void {
$this->readContactRepository
->expects($this->once())
->method('exist')
->willReturn([1, 2]);
$this->readDashboardShareRepository
->expects($this->once())
->method('findContactsWithAccessRightByContactIds')
->willReturn([
new DashboardContactRole(
1,
'user',
'user@email.com',
[DashboardGlobalRole::Viewer]
),
]);
$this->validator->validateContactsForOnPremise(
isAdmin: true,
contacts: [
[
'id' => 1,
'role' => 'editor',
],
],
);
})->throws(DashboardException::notSufficientAccessRightForUser('user', 'editor')->getMessage());
it('should throw a Dashboard Exception when the request contacts are not members of user Access Groups', function (): void {
$this->readContactRepository
->expects($this->once())
->method('exist')
->willReturn([1]);
$this->readDashboardShareRepository
->expects($this->once())
->method('findContactsWithAccessRightByContactIds')
->willReturn([
new DashboardContactRole(
1,
'user',
'user@email.com',
[DashboardGlobalRole::Creator]
),
]);
$this->validator->validateContactsForOnPremise(
isAdmin: false,
contacts: [
[
'id' => 1,
'role' => 'editor',
],
],
);
})->throws(DashboardException::userAreNotInAccessGroups([1])->getMessage());
it('should throw a Dashboard Exception when the contact groups do not exist', function (): void {
$this->readContactGroupRepository
->expects($this->once())
->method('exist')
->willReturn([1]);
$this->validator->validateContactGroupsForOnPremise(
isAdmin: true,
contactGroups: [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
[
'id' => 3,
'role' => 'editor',
],
],
);
})->throws(DashboardException::theContactGroupsDoNotExist([2, 3])->getMessage());
it('should throw a Dashboard Exception when the contact groups are duplicated', function (): void {
$this->readContactGroupRepository
->expects($this->once())
->method('exist')
->willReturn([1]);
$this->validator->validateContactGroupsForOnPremise(
isAdmin: true,
contactGroups: [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 1,
'role' => 'editor',
],
],
);
})->throws(DashboardException::contactGroupForShareShouldBeUnique()->getMessage());
it('should throw a Dashboard Exception when the contact groups does not have Dashboard ACLs', function (): void {
$this->readContactGroupRepository
->expects($this->once())
->method('exist')
->willReturn([1, 2]);
$this->readDashboardShareRepository
->expects($this->once())
->method('findContactGroupsWithAccessRightByContactGroupIds')
->willReturn([
new DashboardContactGroupRole(
1,
'CG1',
[DashboardGlobalRole::Creator]
),
]);
$this->validator->validateContactGroupsForOnPremise(
isAdmin: true,
contactGroups: [
[
'id' => 1,
'role' => 'editor',
],
[
'id' => 2,
'role' => 'editor',
],
],
);
})->throws(DashboardException::theContactGroupsDoesNotHaveDashboardAccessRights([2])->getMessage());
it('should throw a Dashboard Exception when the contact groups are not members of user contact groups', function (): void {
$this->readContactGroupRepository
->expects($this->once())
->method('exist')
->willReturn([1]);
$this->readDashboardShareRepository
->expects($this->once())
->method('findContactGroupsWithAccessRightByContactGroupIds')
->willReturn([
new DashboardContactGroupRole(
1,
'CG1',
[DashboardGlobalRole::Creator]
),
]);
$this->validator->validateContactGroupsForOnPremise(
isAdmin: false,
contactGroups: [
[
'id' => 1,
'role' => 'editor',
],
],
);
})->throws(DashboardException::contactGroupIsNotInUserContactGroups(
[1]
)->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/Dashboard/Application/UseCase/FindDashboards/FindDashboardsPresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindDashboards/FindDashboardsPresenterStub.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\Dashboard\Application\UseCase\FindDashboards;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindDashboards\FindDashboardsPresenterInterface;
use Core\Dashboard\Application\UseCase\FindDashboards\FindDashboardsResponse;
class FindDashboardsPresenterStub implements FindDashboardsPresenterInterface
{
public ResponseStatusInterface|FindDashboardsResponse $data;
public function presentResponse(FindDashboardsResponse|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/Dashboard/Application/UseCase/FindDashboards/FindDashboardsTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindDashboards/FindDashboardsTest.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\Dashboard\Application\UseCase\FindDashboards;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindDashboards\FindDashboards;
use Core\Dashboard\Application\UseCase\FindDashboards\FindDashboardsResponse;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\UserProfile\Application\Repository\ReadUserProfileRepositoryInterface;
use Core\UserProfile\Domain\Model\UserProfile;
beforeEach(function (): void {
$this->presenter = new FindDashboardsPresenterStub();
$this->useCase = new FindDashboards(
$this->readDashboardRepository = $this->createMock(ReadDashboardRepositoryInterface::class),
$this->createMock(ReadDashboardShareRepositoryInterface::class),
$this->createMock(RequestParametersInterface::class),
$this->createMock(ReadContactRepositoryInterface::class),
$this->rights = $this->createMock(DashboardRights::class),
$this->contact = $this->createMock(ContactInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->userProfileReader = $this->createMock(ReadUserProfileRepositoryInterface::class),
$this->iscloudPlatform = false
);
$this->userProfile = (new UserProfile(id: 1, userId: 1))->setFavoriteDashboards([1]);
$this->testedDashboard = new Dashboard(
$this->testedDashboardId = 1,
$this->testedDashboardName = 'dashboard-name',
$this->testedDashboardCreatedBy = 2,
$this->testedDashboardUpdatedBy = 3,
$this->testedDashboardCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
$this->testedDashboardUpdatedAt = new \DateTimeImmutable('2023-05-09T16:00:00+00:00'),
$this->testedDashboardGlobalRefresh = new Refresh(RefreshType::Global, null),
);
});
it(
'should present an ErrorResponse when an exception is thrown',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findByRequestParameter')->willThrowException(new \Exception());
($this->useCase)($this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::errorWhileSearching()->getMessage());
}
);
it(
'should present a FindDashboardsResponse as admin',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->userProfileReader->expects($this->once())
->method('findByContact')->willReturn($this->userProfile);
$this->readDashboardRepository->expects($this->once())
->method('findByRequestParameter')->willReturn([$this->testedDashboard]);
($this->useCase)($this->presenter);
/** @var FindDashboardsResponse $presentedData */
$presentedData = $this->presenter->data;
$dashboard = $presentedData->dashboards[0] ?? [];
expect($presentedData)->toBeInstanceOf(FindDashboardsResponse::class)
->and($dashboard->id ?? null)->toBe($this->testedDashboardId)
->and($dashboard->name ?? null)->toBe($this->testedDashboardName)
->and($dashboard->description)->toBe(null)
->and(($dashboard->createdAt ?? null)?->getTimestamp())->toBe(
$this->testedDashboardCreatedAt->getTimestamp()
)
->and(($dashboard->updatedAt ?? null)?->getTimestamp())->toBeGreaterThanOrEqual(
$this->testedDashboardUpdatedAt->getTimestamp()
)
->and($dashboard->isFavorite)->toBe(true);
}
);
it(
'should present a FindDashboardsResponse as allowed ADMIN user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->userProfileReader->expects($this->once())
->method('findByContact')->willReturn($this->userProfile);
$this->readDashboardRepository->expects($this->once())
->method('findByRequestParameter')->willReturn([$this->testedDashboard]);
($this->useCase)($this->presenter);
/** @var FindDashboardsResponse $presentedData */
$presentedData = $this->presenter->data;
$dashboard = $presentedData->dashboards[0] ?? [];
expect($presentedData)->toBeInstanceOf(FindDashboardsResponse::class)
->and($dashboard->id ?? null)->toBe($this->testedDashboardId)
->and($dashboard->name ?? null)->toBe($this->testedDashboardName)
->and($dashboard->description)->toBe(null)
->and(($dashboard->createdAt ?? null)?->getTimestamp())
->toBe($this->testedDashboardCreatedAt->getTimestamp())
->and(($dashboard->updatedAt ?? null)?->getTimestamp())
->toBeGreaterThanOrEqual($this->testedDashboardUpdatedAt->getTimestamp())
->and($dashboard->isFavorite)->toBe(true);
}
);
it(
'should present a FindDashboardsResponse as allowed VIEWER user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->readDashboardRepository->expects($this->once())
->method('findByRequestParameterAndContact')->willReturn([$this->testedDashboard]);
($this->useCase)($this->presenter);
/** @var FindDashboardsResponse $presentedData */
$presentedData = $this->presenter->data;
$dashboard = $presentedData->dashboards[0] ?? [];
expect($presentedData)->toBeInstanceOf(FindDashboardsResponse::class)
->and($dashboard->id ?? null)->toBe($this->testedDashboardId)
->and($dashboard->name ?? null)->toBe($this->testedDashboardName)
->and($dashboard->description)->toBe(null)
->and(($dashboard->createdAt ?? null)?->getTimestamp())
->toBe($this->testedDashboardCreatedAt->getTimestamp())
->and(($dashboard->updatedAt ?? null)?->getTimestamp())
->toBeGreaterThanOrEqual($this->testedDashboardUpdatedAt->getTimestamp());
}
);
| 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/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopPresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopPresenterStub.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\Dashboard\Application\UseCase\FindMetricsTop;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindMetricsTop\FindMetricsTopPresenterInterface;
use Core\Dashboard\Application\UseCase\FindMetricsTop\FindMetricsTopResponse;
class FindMetricsTopPresenterStub implements FindMetricsTopPresenterInterface
{
public ResponseStatusInterface|FindMetricsTopResponse $data;
public function presentResponse(FindMetricsTopResponse|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/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindMetricsTop/FindMetricsTopTest.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\Dashboard\Application\UseCase\FindMetricsTop;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPerformanceMetricRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindMetricsTop\FindMetricsTop;
use Core\Dashboard\Application\UseCase\FindMetricsTop\FindMetricsTopRequest;
use Core\Dashboard\Application\UseCase\FindMetricsTop\FindMetricsTopResponse;
use Core\Dashboard\Application\UseCase\FindMetricsTop\Response\MetricInformationDto;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Metric\PerformanceMetric;
use Core\Dashboard\Domain\Model\Metric\ResourceMetric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->nonAdminUser = (new Contact())->setId(1)->setAdmin(false);
$this->adminUser = (new Contact())->setId(1)->setAdmin(true);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->metricRepository = $this->createMock(ReadDashboardPerformanceMetricRepositoryInterface::class);
$this->rights = $this->createMock(DashboardRights::class);
$this->isCloudPlatform = false;
});
it('should present a ForbiddenResponse when the user does not has sufficient rights', function (): void {
$presenter = new FindMetricsTopPresenterStub();
$request = new FindMetricsTopRequest('rta');
$useCase = new FindMetricsTop(
$this->nonAdminUser,
$this->requestParameters,
$this->accessGroupRepository,
$this->metricRepository,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('canAccess')
->willReturn(false);
$useCase($presenter, $request);
$this->expect($presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($presenter->data->getMessage())->toBe(DashboardException::accessNotAllowed()->getMessage());
});
it('should present an ErrorResponse when an error occurs', function (): void {
$presenter = new FindMetricsTopPresenterStub();
$request = new FindMetricsTopRequest('rta');
$useCase = new FindMetricsTop(
$this->adminUser,
$this->requestParameters,
$this->accessGroupRepository,
$this->metricRepository,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->metricRepository
->expects($this->once())
->method('findByRequestParametersAndMetricName')
->willThrowException(
new RepositoryException(
'An error occurred while trying to find performance metrics by request parameters and metric name.'
)
);
$useCase($presenter, $request);
$this->expect($presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($presenter->data->getMessage())->toBe('An error occured while retrieving top metrics');
});
it('should present a NotFoundResponse when no metrics are found', function (): void {
$presenter = new FindMetricsTopPresenterStub();
$request = new FindMetricsTopRequest('rta');
$useCase = new FindMetricsTop(
$this->adminUser,
$this->requestParameters,
$this->accessGroupRepository,
$this->metricRepository,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->metricRepository
->expects($this->once())
->method('findByRequestParametersAndMetricName')
->willReturn([]);
$useCase($presenter, $request);
$this->expect($presenter->data)
->toBeInstanceOf(NotFoundResponse::class)
->and($presenter->data->getMessage())->toBe((new NotFoundResponse('metrics'))->getMessage());
});
it('should take account of access groups when the user is not admin', function (): void {
$presenter = new FindMetricsTopPresenterStub();
$request = new FindMetricsTopRequest('rta');
$useCase = new FindMetricsTop(
$this->nonAdminUser,
$this->requestParameters,
$this->accessGroupRepository,
$this->metricRepository,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('canAccess')
->willReturn(true);
$this->metricRepository
->expects($this->once())
->method('findByRequestParametersAndAccessGroupsAndMetricName');
$useCase($presenter, $request);
});
it('should present a FindMetricsTopResponse when metrics are found', function (): void {
$presenter = new FindMetricsTopPresenterStub();
$request = new FindMetricsTopRequest('rta');
$useCase = new FindMetricsTop(
$this->adminUser,
$this->requestParameters,
$this->accessGroupRepository,
$this->metricRepository,
$this->rights,
$this->isCloudPlatform
);
$response = [
new ResourceMetric(
1,
'Ping',
'Centreon-Server',
3,
[
new PerformanceMetric(2, 'rta', 'ms', 20, 50, 0, 11.2, 12.2, 8.2, 14.2),
]
),
new ResourceMetric(
2,
'Ping_1',
'Centreon-Server',
3,
[
new PerformanceMetric(5, 'rta', 'ms', 20, 50, null, 21.2, 22.2, 21.2, 24.2),
]
),
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->metricRepository
->expects($this->once())
->method('findByRequestParametersAndMetricName')
->with($this->requestParameters, $request->metricName)
->willReturn($response);
$useCase($presenter, $request);
$this->expect($presenter->data)
->toBeInstanceOf(FindMetricsTopResponse::class);
$this->expect($presenter->data->metricName)->toBe('rta');
$this->expect($presenter->data->metricUnit)->toBe('ms');
$this->expect($presenter->data->resourceMetrics)->toBeArray();
$metricOne = $presenter->data->resourceMetrics[0];
$metricTwo = $presenter->data->resourceMetrics[1];
$this->expect($metricOne)->toBeInstanceOf(MetricInformationDto::class);
$this->expect($metricOne->serviceId)->toBe(1);
$this->expect($metricOne->parentId)->toBe(3);
$this->expect($metricOne->resourceName)->toBe('Ping');
$this->expect($metricOne->parentName)->toBe('Centreon-Server');
$this->expect($metricOne->currentValue)->toBe(12.2);
$this->expect($metricOne->warningHighThreshold)->toBe(20.0);
$this->expect($metricOne->criticalHighThreshold)->toBe(50.0);
$this->expect($metricOne->warningLowThreshold)->toBe(0.0);
$this->expect($metricOne->criticalLowThreshold)->toBe(11.2);
$this->expect($metricOne->minimumValue)->toBe(8.2);
$this->expect($metricOne->maximumValue)->toBe(14.2);
$this->expect($metricTwo)->toBeInstanceOf(MetricInformationDto::class);
$this->expect($metricTwo->serviceId)->toBe(2);
$this->expect($metricTwo->parentId)->toBe(3);
$this->expect($metricTwo->resourceName)->toBe('Ping_1');
$this->expect($metricTwo->parentName)->toBe('Centreon-Server');
$this->expect($metricTwo->currentValue)->toBe(22.2);
$this->expect($metricTwo->warningHighThreshold)->toBe(20.0);
$this->expect($metricTwo->criticalHighThreshold)->toBe(50.0);
$this->expect($metricTwo->warningLowThreshold)->toBe(null);
$this->expect($metricTwo->criticalLowThreshold)->toBe(21.2);
$this->expect($metricTwo->minimumValue)->toBe(21.2);
$this->expect($metricTwo->maximumValue)->toBe(24.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/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetricTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindSingleMetric/FindSingleMetricTest.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\Dashboard\Application\UseCase\FindSingleMetric;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Dashboard\Application\UseCase\FindSingleMetric\{
FindSingleMetric,
FindSingleMetricPresenterInterface,
FindSingleMetricRequest,
FindSingleMetricResponse
};
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Metric\Domain\Model\Metric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Repository\ReadRealTimeServiceRepositoryInterface;
use Mockery;
beforeEach(function (): void {
$this->contact = Mockery::mock(ContactInterface::class);
$this->metricRepo = Mockery::mock(ReadMetricRepositoryInterface::class);
$this->serviceRepo = Mockery::mock(ReadRealTimeServiceRepositoryInterface::class);
$this->accessGroupRepo = Mockery::mock(ReadAccessGroupRepositoryInterface::class);
$this->requestParameters = Mockery::mock(RequestParametersInterface::class);
$this->contact->shouldReceive('getId')->andReturn(1);
$this->presenter = new class () implements FindSingleMetricPresenterInterface {
public mixed $response = null;
public function presentResponse(mixed $response): void
{
$this->response = $response;
}
};
});
it('returns a FindSingleMetricResponse for an admin user', function (): void {
$this->contact->shouldReceive('isAdmin')->once()->andReturn(true);
$hostId = 10;
$serviceId = 20;
$this->serviceRepo
->shouldReceive('exists')
->once()
->with($serviceId, $hostId)
->andReturn(true);
$metric = new Metric(
id: 1,
name: 'cpu'
);
$metric->setCurrentValue(12.34);
$metric->setUnit('%');
$this->metricRepo
->shouldReceive('findSingleMetricValue')
->once()
->with($hostId, $serviceId, 'cpu', $this->requestParameters)
->andReturn($metric);
$this->accessGroupRepo->shouldNotReceive('findByContact');
$useCase = new FindSingleMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters,
);
$useCase(new FindSingleMetricRequest(10, 20, 'cpu'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindSingleMetricResponse::class)
->and($this->presenter->response->id)->toBe(1)
->and($this->presenter->response->name)->toBe('cpu')
->and($this->presenter->response->currentValue)->toBe(12.34);
});
it('passes access groups to the repository for non-admin users', function (): void {
$this->contact->shouldReceive('isAdmin')->once()->andReturn(false);
$hostId = 11;
$serviceId = 22;
$this->serviceRepo
->shouldReceive('exists')
->once()
->with($serviceId, $hostId)
->andReturn(true);
$fakeGroups = ['g1', 'g2'];
$this->accessGroupRepo
->shouldReceive('findByContact')
->once()
->with($this->contact)
->andReturn($fakeGroups);
$metric = new Metric(
id: 2,
name: 'mem'
);
$metric->setUnit('MB');
$metric->setCurrentValue(256.0);
$this->metricRepo
->shouldReceive('findSingleMetricValue')
->once()
->with($hostId, $serviceId, 'mem', $this->requestParameters, $fakeGroups)
->andReturn($metric);
$useCase = new FindSingleMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters
);
$useCase(new FindSingleMetricRequest(11, 22, 'mem'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindSingleMetricResponse::class)
->and($this->presenter->response->id)->toBe(2)
->and($this->presenter->response->name)->toBe('mem');
});
it('returns NotFoundResponse when service does not exist', function (): void {
$hostId = 5;
$serviceId = 6;
$this->serviceRepo
->shouldReceive('exists')
->once()
->with($serviceId, $hostId)
->andReturn(false);
$useCase = new FindSingleMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters
);
$useCase(new FindSingleMetricRequest($hostId, $serviceId, 'disk'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->response->getMessage())->toBe('Service not found');
});
it('maps a "not found" exception to NotFoundResponse', function (): void {
$this->contact->shouldReceive('isAdmin')->once()->andReturn(true);
$this->serviceRepo->shouldReceive('exists')->once()->andReturn(true);
$this->metricRepo
->shouldReceive('findSingleMetricValue')
->once()
->andReturn(null);
$useCase = new FindSingleMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters
);
$useCase(new FindSingleMetricRequest(1, 2, 'foo'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(NotFoundResponse::class);
});
it('maps other exceptions to ErrorResponse', function (): void {
$this->contact->shouldReceive('isAdmin')->once()->andReturn(true);
$this->serviceRepo->shouldReceive('exists')->once()->andReturn(true);
$this->metricRepo
->shouldReceive('findSingleMetricValue')
->once()
->andThrow(new RepositoryException(
"Error retrieving metric 'foo' for host 1, service 2",
['metricName' => 'bar', 'hostId' => 1, 'serviceId' => 2]
));
$useCase = new FindSingleMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters
);
$useCase(new FindSingleMetricRequest(1, 2, 'bar'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class);
});
it('throws InvalidArgumentException for non-positive hostId', function (): void {
$this->expectException(\InvalidArgumentException::class);
new FindSingleMetricRequest(0, 1, 'metric');
});
it('throws InvalidArgumentException for non-positive serviceId', function (): void {
$this->expectException(\InvalidArgumentException::class);
new FindSingleMetricRequest(1, 0, 'metric');
});
it('throws InvalidArgumentException for empty metricName', function (): void {
$this->expectException(\InvalidArgumentException::class);
new FindSingleMetricRequest(1, 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/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetricTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindSingleMetaMetric/FindSingleMetaMetricTest.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\Dashboard\Application\UseCase\FindSingleMetaMetric;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Dashboard\Application\UseCase\FindSingleMetaMetric\{
FindSingleMetaMetric,
FindSingleMetaMetricPresenterInterface,
FindSingleMetaMetricRequest,
FindSingleMetaMetricResponse
};
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Metric\Domain\Model\Metric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Repository\ReadRealTimeServiceRepositoryInterface;
use Mockery;
beforeEach(function (): void {
$this->contact = Mockery::mock(ContactInterface::class);
$this->metricRepo = Mockery::mock(ReadMetricRepositoryInterface::class);
$this->serviceRepo = Mockery::mock(ReadRealTimeServiceRepositoryInterface::class);
$this->accessGroupRepo = Mockery::mock(ReadAccessGroupRepositoryInterface::class);
$this->requestParameters = Mockery::mock(RequestParametersInterface::class);
$this->contact->shouldReceive('getId')->andReturn(1);
$this->presenter = new class () implements FindSingleMetaMetricPresenterInterface {
public mixed $response = null;
public function presentResponse(mixed $response): void
{
$this->response = $response;
}
};
$this->service = [
'host_id' => 15,
'service_id' => 29,
];
});
it('returns a FindSingleMetaMetricResponse for an admin user', function (): void {
$this->contact->shouldReceive('isAdmin')->once()->andReturn(true);
$metaServiceId = 20;
$service = $this->serviceRepo
->shouldReceive('existsByDescription')
->once()
->with($metaServiceId)
->andReturn($this->service);
$metric = new Metric(
id: 1,
name: 'cpu'
);
$metric->setCurrentValue(12.34);
$metric->setUnit('%');
$this->metricRepo
->shouldReceive('findSingleMetaMetricValue')
->once()
->with($this->service, 'cpu', $this->requestParameters)
->andReturn($metric);
$this->accessGroupRepo->shouldNotReceive('findByContact');
$useCase = new FindSingleMetaMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters,
);
$useCase(new FindSingleMetaMetricRequest($metaServiceId, 'cpu'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindSingleMetaMetricResponse::class)
->and($this->presenter->response->id)->toBe(1)
->and($this->presenter->response->name)->toBe('cpu')
->and($this->presenter->response->currentValue)->toBe(12.34);
});
it('passes access groups to the repository for non-admin users', function (): void {
$this->contact->shouldReceive('isAdmin')->once()->andReturn(false);
$metaServiceId = 22;
$service = $this->serviceRepo
->shouldReceive('existsByDescription')
->once()
->with($metaServiceId)
->andReturn($this->service);
$fakeGroups = ['g1', 'g2'];
$this->accessGroupRepo
->shouldReceive('findByContact')
->once()
->with($this->contact)
->andReturn($fakeGroups);
$metric = new Metric(
id: 2,
name: 'mem'
);
$metric->setUnit('MB');
$metric->setCurrentValue(256.0);
$this->metricRepo
->shouldReceive('findSingleMetaMetricValue')
->once()
->with($this->service, 'mem', $this->requestParameters, $fakeGroups)
->andReturn($metric);
$useCase = new FindSingleMetaMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters
);
$useCase(new FindSingleMetaMetricRequest($metaServiceId, 'mem'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindSingleMetaMetricResponse::class)
->and($this->presenter->response->id)->toBe(2)
->and($this->presenter->response->name)->toBe('mem');
});
it('returns NotFoundResponse when service does not exist', function (): void {
$metaServiceId = 6;
$service = $this->serviceRepo
->shouldReceive('existsByDescription')
->once()
->with($metaServiceId)
->andReturn(false);
$useCase = new FindSingleMetaMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters
);
$useCase(new FindSingleMetaMetricRequest($metaServiceId, 'disk'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->response->getMessage())->toBe('MetaService not found');
});
it('maps a "not found" exception to NotFoundResponse', function (): void {
$metaServiceId = 6;
$this->contact->shouldReceive('isAdmin')->once()->andReturn(true);
$this->serviceRepo->shouldReceive('existsByDescription')->once()->andReturn($this->service);
$this->metricRepo
->shouldReceive('findSingleMetaMetricValue')
->once()
->andReturn(null);
$useCase = new FindSingleMetaMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters
);
$useCase(new FindSingleMetaMetricRequest($metaServiceId, 'foo'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(NotFoundResponse::class);
});
it('maps other exceptions to ErrorResponse', function (): void {
$metaServiceId = 6;
$this->contact->shouldReceive('isAdmin')->once()->andReturn(true);
$service = $this->serviceRepo->shouldReceive('existsByDescription')->once()->andReturn($this->service);
$this->metricRepo
->shouldReceive('findSingleMetaMetricValue')
->once()
->andThrow(new RepositoryException(
"Error retrieving metric 'foo' for host 1, service 2",
['metricName' => 'bar', 'hostId' => 1, 'serviceId' => 2]
));
$useCase = new FindSingleMetaMetric(
$this->contact,
$this->metricRepo,
$this->serviceRepo,
$this->accessGroupRepo,
$this->requestParameters
);
$useCase(new FindSingleMetaMetricRequest($metaServiceId, 'bar'), $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class);
});
it('throws InvalidArgumentException for non-positive metaServiceId', function (): void {
$this->expectException(\InvalidArgumentException::class);
new FindSingleMetaMetricRequest(0, 'metric');
});
it('throws InvalidArgumentException for empty metricName', function (): void {
$this->expectException(\InvalidArgumentException::class);
new FindSingleMetaMetricRequest(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/Dashboard/Application/UseCase/AddDashboard/AddDashboardTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/AddDashboard/AddDashboardTest.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\Dashboard\Application\UseCase\AddDashboard;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\AddDashboard\AddDashboard;
use Core\Dashboard\Application\UseCase\AddDashboard\AddDashboardRequest;
use Core\Dashboard\Application\UseCase\AddDashboard\AddDashboardResponse;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardPanel;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->presenter = new AddDashboardPresenterStub();
$this->useCase = new AddDashboard(
$this->readDashboardRepository = $this->createMock(ReadDashboardRepositoryInterface::class),
$this->writeDashboardRepository = $this->createMock(WriteDashboardRepositoryInterface::class),
$this->writeDashboardRelationRepository = $this->createMock(WriteDashboardShareRepositoryInterface::class),
$this->createMock(DataStorageEngineInterface::class),
$this->rights = $this->createMock(DashboardRights::class),
$this->contact = $this->createMock(ContactInterface::class),
$this->writeDashboardPanelRepository = $this->createMock(WriteDashboardPanelRepositoryInterface::class),
$this->readDashboardPanelRepository = $this->createMock(ReadDashboardPanelRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->isCloudPlatform = false
);
$this->testedAddDashboardRequest = new AddDashboardRequest();
$this->testedAddDashboardRequest->name = 'added-dashboard';
$this->testedDashboard = (new Dashboard(
$this->testedDashboardId = 1,
$this->testedDashboardName = 'dashboard-name',
$this->testedDashboardCreatedBy = 2,
$this->testedDashboardUpdatedBy = 3,
$this->testedDashboardCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
$this->testedDashboardUpdatedAt = new \DateTimeImmutable('2023-05-09T16:00:00+00:00'),
$this->testedDashboardGlobalRefresh = new Refresh(RefreshType::Global, null),
))->setDescription('toto');
});
it(
'should present an ErrorResponse when a generic exception is thrown',
function (): void {
$this->rights->expects($this->once())
->method('hasCreatorRole')->willThrowException(new \Exception());
($this->useCase)($this->testedAddDashboardRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::errorWhileAdding()->getMessage());
}
);
it(
'should present an ErrorResponse with a custom message when a DashboardException is thrown',
function (): void {
$this->rights->expects($this->once())
->method('hasCreatorRole')
->willThrowException(new DashboardException($msg = uniqid('fake message ', true)));
($this->useCase)($this->testedAddDashboardRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe($msg);
}
);
it(
'should present a InvalidArgumentResponse when a model field value is not valid',
function (): void {
$this->rights->expects($this->once())
->method('hasCreatorRole')->willReturn(true);
$this->testedAddDashboardRequest->name = '';
$expectedException = AssertionException::notEmptyString('NewDashboard::name');
($this->useCase)($this->testedAddDashboardRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->data->getMessage())
->toBe($expectedException->getMessage());
}
);
it(
'should present an ErrorResponse if the newly created dashboard cannot be retrieved as ADMIN',
function (): void {
$this->rights->expects($this->once())
->method('hasCreatorRole')->willReturn(true);
$this->contact->expects($this->atLeastOnce())
->method('getId')->willReturn(1);
$this->writeDashboardRepository->expects($this->once())
->method('add')->willReturn($this->testedDashboard->getId());
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn(null); // the failure
($this->useCase)($this->testedAddDashboardRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::errorWhileRetrievingJustCreated()->getMessage());
}
);
it(
'should present a ForbiddenResponse when the user does not have the correct role',
function (): void {
$this->rights->expects($this->once())
->method('hasCreatorRole')->willReturn(false);
($this->useCase)($this->testedAddDashboardRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::accessNotAllowedForWriting()->getMessage());
}
);
it(
'should present a AddDashboardResponse when no error occurs',
function (): void {
$panels = [
new DashboardPanel(
1,
'panel',
'centreon-top-bottom',
[],
1,
1,
1,
1,
1,
1
),
];
$this->rights
->expects($this->once())
->method('hasCreatorRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('getId')
->willReturn(1);
$this->writeDashboardRepository
->expects($this->once())
->method('add')
->willReturn($this->testedDashboard->getId());
$this->readDashboardRepository
->expects($this->once())
->method('findOneByContact')
->willReturn($this->testedDashboard);
$this->readDashboardPanelRepository
->expects($this->once())
->method('findPanelsByDashboardId')
->willReturn($panels);
($this->useCase)($this->testedAddDashboardRequest, $this->presenter);
/** @var AddDashboardResponse $dashboard */
$dashboard = $this->presenter->data;
expect($dashboard)->toBeInstanceOf(AddDashboardResponse::class)
->and($dashboard->id)->toBe($this->testedDashboardId)
->and($dashboard->name)->toBe($this->testedDashboardName)
->and($dashboard->description)->toBe($this->testedDashboard->getDescription())
->and($dashboard->createdAt->getTimestamp())->toBe($this->testedDashboardCreatedAt->getTimestamp())
->and($dashboard->updatedAt->getTimestamp())->toBeGreaterThanOrEqual(
$this->testedDashboardUpdatedAt->getTimestamp()
);
}
);
| 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/Dashboard/Application/UseCase/AddDashboard/AddDashboardPresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/AddDashboard/AddDashboardPresenterStub.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\Dashboard\Application\UseCase\AddDashboard;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\AddDashboard\AddDashboardPresenterInterface;
use Core\Dashboard\Application\UseCase\AddDashboard\AddDashboardResponse;
class AddDashboardPresenterStub implements AddDashboardPresenterInterface
{
public AddDashboardResponse|ResponseStatusInterface $data;
public function presentResponse(AddDashboardResponse|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/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataTest.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\Dashboard\Application\UseCase\FindPerformanceMetricsData;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Metric\Interfaces\MetricRepositoryInterface;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\UseCase\FindPerformanceMetricsData\FindPerformanceMetricsData;
use Core\Dashboard\Application\UseCase\FindPerformanceMetricsData\FindPerformanceMetricsDataRequestDto;
use Core\Dashboard\Application\UseCase\FindPerformanceMetricsData\FindPerformanceMetricsDataResponse;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Metric\Application\Repository\ReadMetricRepositoryInterface;
use Core\Metric\Domain\Model\MetricInformation\GeneralInformation;
use Core\Metric\Domain\Model\MetricInformation\MetricInformation;
use Core\Metric\Domain\Model\MetricInformation\ThresholdInformation;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->adminUser = (new Contact())->setAdmin(true)->setId(1);
$this->nonAdminUser = (new Contact())->setAdmin(false)->setId(1);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->rights = $this->createMock(DashboardRights::class);
$this->metricRepositoryLegacy = $this->createMock(MetricRepositoryInterface::class);
$this->metricRepository = $this->createMock(ReadMetricRepositoryInterface::class);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->isCloudPlatform = false;
});
it('should present a ForbiddenResponse when the user does not has sufficient rights', function (): void {
$presenter = new FindPerformanceMetricsDataPresenterStub();
$request = new FindPerformanceMetricsDataRequestDto(new \DateTime(), new \DateTime(), ['rta']);
$useCase = new FindPerformanceMetricsData(
$this->nonAdminUser,
$this->requestParameters,
$this->metricRepositoryLegacy,
$this->metricRepository,
$this->accessGroupRepository,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('canAccess')
->willReturn(false);
$useCase($presenter, $request);
$this->expect($presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($presenter->data->getMessage())->toBe(DashboardException::accessNotAllowed()->getMessage());
});
it('should present an ErrorResponse when an error occurs', function (): void {
$presenter = new FindPerformanceMetricsDataPresenterStub();
$request = new FindPerformanceMetricsDataRequestDto(new \DateTime(), new \DateTime(), ['rta', 'pl']);
$useCase = new FindPerformanceMetricsData(
$this->nonAdminUser,
$this->requestParameters,
$this->metricRepositoryLegacy,
$this->metricRepository,
$this->accessGroupRepository,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('canAccess')
->willReturn(true);
$this->metricRepository
->expects($this->once())
->method('findServicesByMetricNamesAndAccessGroupsAndRequestParameters')
->willThrowException(new \Exception());
$useCase($presenter, $request);
$this->expect($presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($presenter->data->getMessage())->toBe('An error occurred while retrieving metrics data');
});
it('should get the metrics with access group management when the user is not admin', function (): void {
$presenter = new FindPerformanceMetricsDataPresenterStub();
$request = new FindPerformanceMetricsDataRequestDto(new \DateTime(), new \DateTime(), ['rta', 'pl']);
$useCase = new FindPerformanceMetricsData(
$this->nonAdminUser,
$this->requestParameters,
$this->metricRepositoryLegacy,
$this->metricRepository,
$this->accessGroupRepository,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('canAccess')
->willReturn(true);
$this->metricRepository
->expects($this->once())
->method('findServicesByMetricNamesAndAccessGroupsAndRequestParameters');
$useCase($presenter, $request);
});
it('should get the metrics without access group management when the user is admin', function (): void {
$presenter = new FindPerformanceMetricsDataPresenterStub();
$request = new FindPerformanceMetricsDataRequestDto(new \DateTime(), new \DateTime(), ['rta', 'pl']);
$useCase = new FindPerformanceMetricsData(
$this->adminUser,
$this->requestParameters,
$this->metricRepositoryLegacy,
$this->metricRepository,
$this->accessGroupRepository,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->metricRepository
->expects($this->once())
->method('findServicesByMetricNamesAndRequestParameters');
$useCase($presenter, $request);
});
it('should take account of access groups to retrieve metrics when the user is not admin', function (): void {
$presenter = new FindPerformanceMetricsDataPresenterStub();
$request = new FindPerformanceMetricsDataRequestDto(new \DateTime(), new \DateTime(), ['rta', 'pl']);
$useCase = new FindPerformanceMetricsData(
$this->adminUser,
$this->requestParameters,
$this->metricRepositoryLegacy,
$this->metricRepository,
$this->accessGroupRepository,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('canAccess')
->willReturn(true);
$this->metricRepository
->expects($this->once())
->method('findServicesByMetricNamesAndAccessGroupsAndRequestParameters');
$useCase($presenter, $request);
});
it('should present a FindPerformanceMetricsDataResponse when metrics are correctly retrieve', function (): void {
$presenter = new FindPerformanceMetricsDataPresenterStub();
$request = new FindPerformanceMetricsDataRequestDto(new \DateTime(), new \DateTime(), ['pl']);
$useCase = new FindPerformanceMetricsData(
$this->adminUser,
$this->requestParameters,
$this->metricRepositoryLegacy,
$this->metricRepository,
$this->accessGroupRepository,
$this->rights,
$this->isCloudPlatform
);
$service = (new Service())
->setId(1)
->setHost(
(new Host())->setId(2)->setName('myHost')
->setName('Ping')
);
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->metricRepository
->expects($this->once())
->method('findServicesByMetricNamesAndRequestParameters')
->willReturn([$service]);
$this->metricRepositoryLegacy
->expects($this->once())
->method('setContact')
->with($this->adminUser);
$this->metricRepositoryLegacy
->expects($this->once())
->method('findMetricsByService')
->with($service, $request->startDate, $request->endDate)
->willReturn(
[
'global' => [
'base' => 1000,
'title' => 'Ping graph on myHost',
'host_name' => 'myHost',
'service_description' => 'Ping',
],
'metrics' => [
[
'index_id' => 1,
'metric_id' => 1,
'metric' => 'pl',
'metric_legend' => 'pl',
'unit' => '%',
'hidden' => 0,
'legend' => 'Packet-Loss',
'virtual' => 0,
'stack' => 0,
'ds_order' => 1,
'ds_data' => [
'ds_min' => null,
'ds_max' => null,
'ds_minmax_int' => null,
'ds_last' => null,
'ds_average' => null,
'ds_total' => null,
'ds_tickness' => 1,
'ds_color_line_mode' => '0',
'ds_color_line' => '#f0f',
],
'warn' => null,
'warn_low' => null,
'crit' => null,
'crit_low' => null,
'ds_color_area_warn' => '#f0f',
'ds_color_area_crit' => '#f0f',
'data' => [0, 0, 0, null],
'prints' => [['Min:0.0'], ['Average:0.0']],
'min' => null,
'max' => null,
'last_value' => null,
'minimum_value' => null,
'maximum_value' => null,
'average_value' => null,
],
],
'times' => [
'1690732800',
'1690790400',
],
]
);
$useCase($presenter, $request);
$this->expect($presenter->data)->toBeInstanceOf(FindPerformanceMetricsDataResponse::class);
$this->expect($presenter->data->base)->toBe(1000);
$this->expect($presenter->data->metricsInformation[0])->toBeInstanceOf(MetricInformation::class)
->and($presenter->data->metricsInformation[0]->getGeneralInformation())
->toBeInstanceOf(GeneralInformation::class)
->and($presenter->data->metricsInformation[0]->getThresholdInformation())
->toBeInstanceOf(ThresholdInformation::class);
$this->expect($presenter->data->times)->toBeArray()
->and($presenter->data->times[0])->toBeInstanceOf(\DateTimeImmutable::class)
->and($presenter->data->times[1])->toBeInstanceOf(\DateTimeImmutable::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/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataPresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindPerformanceMetricsData/FindPerformanceMetricsDataPresenterStub.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\Dashboard\Application\UseCase\FindPerformanceMetricsData;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindPerformanceMetricsData\FindPerformanceMetricsDataPresenterInterface;
use Core\Dashboard\Application\UseCase\FindPerformanceMetricsData\FindPerformanceMetricsDataResponse;
class FindPerformanceMetricsDataPresenterStub implements FindPerformanceMetricsDataPresenterInterface
{
public ResponseStatusInterface|FindPerformanceMetricsDataResponse $data;
public function presentResponse(FindPerformanceMetricsDataResponse|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/Dashboard/Application/UseCase/FindDashboardContactGroups/FindDashboardContactGroupsTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindDashboardContactGroups/FindDashboardContactGroupsTest.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\Dashboard\Application\UseCase\FindDashboardContactGroups;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindDashboardContactGroups\FindDashboardContactGroups;
use Core\Dashboard\Application\UseCase\FindDashboardContactGroups\FindDashboardContactGroupsResponse;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardContactGroupRole;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->rights = $this->createMock(DashboardRights::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->readDashboardShareRepository = $this->createMock(ReadDashboardShareRepositoryInterface::class);
$this->readAccessgroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->useCaseOnPremise = new FindDashboardContactGroups(
$this->requestParameters,
$this->rights,
$this->contact,
$this->readDashboardShareRepository,
$this->readAccessgroupRepository,
false
);
$this->useCaseCloud = new FindDashboardContactGroups(
$this->requestParameters,
$this->rights,
$this->contact,
$this->readDashboardShareRepository,
$this->readAccessgroupRepository,
true
);
});
it(
'should return an ErrorResponse if an error is raised',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->readDashboardShareRepository->expects($this->once())
->method('findContactGroupsWithAccessRightByRequestParameters')
->willThrowException(new \Exception());
$response = ($this->useCaseOnPremise)();
expect($response)->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())
->toBe(DashboardException::errorWhileSearchingSharableContactGroups()->getMessage());
}
);
it(
'should return a FindDashboardContactGroupsResponse if no error is raised - AS ADMIN - OnPremise',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$contactGroupRole = new DashboardContactGroupRole(
contactGroupId: 1,
contactGroupName: 'name',
roles: [DashboardGlobalRole::Creator]
);
$this->readDashboardShareRepository->expects($this->once())
->method('findContactGroupsWithAccessRightByRequestParameters')
->willReturn([$contactGroupRole]);
$response = ($this->useCaseOnPremise)();
$contactGroups = $response->getData();
expect($response)->toBeInstanceOf(FindDashboardContactGroupsResponse::class)
->and($contactGroups[0]->id)
->toBe($contactGroupRole->getContactGroupId())
->and($contactGroups[0]->name)
->toBe($contactGroupRole->getContactGroupName())
->and($contactGroups[0]->mostPermissiveRole)
->toBe($contactGroupRole->getMostPermissiveRole());
}
);
it(
'should return a FindDashboardContactGroupsResponse if no error is raised - AS USER - OnPremise',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$contactGroupRole = new DashboardContactGroupRole(
contactGroupId: 1,
contactGroupName: 'name',
roles: [DashboardGlobalRole::Creator]
);
$this->readDashboardShareRepository->expects($this->once())
->method('findContactGroupsWithAccessRightByUserAndRequestParameters')
->willReturn([$contactGroupRole]);
$response = ($this->useCaseOnPremise)();
$contactGroups = $response->getData();
expect($response)->toBeInstanceOf(FindDashboardContactGroupsResponse::class)
->and($contactGroups[0]->id)
->toBe($contactGroupRole->getContactGroupId())
->and($contactGroups[0]->name)
->toBe($contactGroupRole->getContactGroupName())
->and($contactGroups[0]->mostPermissiveRole)
->toBe($contactGroupRole->getMostPermissiveRole());
}
);
it(
'should return a FindDashboardContactGroupsResponse if no error is raised - AS ADMIN - Cloud',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$contactGroupRole = new DashboardContactGroupRole(
contactGroupId: 1,
contactGroupName: 'name',
roles: [DashboardGlobalRole::Viewer]
);
$this->readDashboardShareRepository->expects($this->once())
->method('findContactGroupsByRequestParameters')
->willReturn([$contactGroupRole]);
$response = ($this->useCaseCloud)();
$contactGroups = $response->getData();
expect($response)->toBeInstanceOf(FindDashboardContactGroupsResponse::class)
->and($contactGroups[0]->id)
->toBe($contactGroupRole->getContactGroupId())
->and($contactGroups[0]->name)
->toBe($contactGroupRole->getContactGroupName())
->and($contactGroups[0]->mostPermissiveRole)
->toBe($contactGroupRole->getMostPermissiveRole());
}
);
it(
'should return a FindDashboardContactGroupsResponse if no error is raised - AS USER - Cloud',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$contactGroupRole = new DashboardContactGroupRole(
contactGroupId: 1,
contactGroupName: 'name',
roles: [DashboardGlobalRole::Viewer]
);
$this->readDashboardShareRepository->expects($this->once())
->method('findContactGroupsByUserAndRequestParameters')
->willReturn([$contactGroupRole]);
$response = ($this->useCaseCloud)();
$contactGroups = $response->getData();
expect($response)->toBeInstanceOf(FindDashboardContactGroupsResponse::class)
->and($contactGroups[0]->id)
->toBe($contactGroupRole->getContactGroupId())
->and($contactGroups[0]->name)
->toBe($contactGroupRole->getContactGroupName())
->and($contactGroups[0]->mostPermissiveRole)
->toBe($contactGroupRole->getMostPermissiveRole());
}
);
| 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/Dashboard/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetricsTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetricsTest.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\Dashboard\Application\UseCase\FindPerformanceMetrics;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPerformanceMetricRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindPerformanceMetrics\FindPerformanceMetrics;
use Core\Dashboard\Application\UseCase\FindPerformanceMetrics\FindPerformanceMetricsResponse;
use Core\Dashboard\Application\UseCase\FindPerformanceMetrics\ResourceMetricDto;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Metric\PerformanceMetric;
use Core\Dashboard\Domain\Model\Metric\ResourceMetric;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->adminUser = (new Contact())->setAdmin(true)->setId(1);
$this->nonAdminUser = (new Contact())->setAdmin(false)->setId(1);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->readDashboardPerformanceMetric = $this->createMock(ReadDashboardPerformanceMetricRepositoryInterface::class);
$this->rights = $this->createMock(DashboardRights::class);
$this->isCloudPlatform = false;
});
it('should present an ErrorResponse when something occurs in the repository', function (): void {
$useCase = new FindPerformanceMetrics(
$this->adminUser,
$this->requestParameters,
$this->accessGroupRepository,
$this->readDashboardPerformanceMetric,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->readDashboardPerformanceMetric
->expects($this->once())
->method('findByRequestParameters')
->willThrowException(
new RepositoryException('An error occurred while trying to find performance metrics by request parameters.')
);
$presenter = new FindPerformanceMetricsPresenterStub();
$useCase($presenter);
expect($presenter->data)->toBeInstanceOf(ErrorResponse::class)
->and($presenter->data->getMessage())
->toBe('An error occured while retrieving metrics');
});
it('should present a FindPerformanceMetricsResponse when metrics are found', function (): void {
$useCase = new FindPerformanceMetrics(
$this->adminUser,
$this->requestParameters,
$this->accessGroupRepository,
$this->readDashboardPerformanceMetric,
$this->rights,
$this->isCloudPlatform
);
$response = [
new ResourceMetric(
1,
'Ping',
'Centreon-Server',
3,
[
new PerformanceMetric(1, 'pl', '%', 400.3, null, null, null, null, null, null),
new PerformanceMetric(2, 'rta', 'ms', 20, 50, null, null, null, null, null),
new PerformanceMetric(3, 'rtmax', 'ms', null, null, null, null, null, null, null),
new PerformanceMetric(4, 'rtmin', 'ms', null, null, null, null, null, null, null),
]
),
new ResourceMetric(
2,
'Traffic',
'Centreon-Server',
3,
[
new PerformanceMetric(5, 'traffic_in', 'M', null, null, null, null, null, null, null),
new PerformanceMetric(6, 'traffic_out', 'M', null, null, null, null, null, null, null),
]
),
];
$this->rights
->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->readDashboardPerformanceMetric
->expects($this->once())
->method('findByRequestParameters')
->willReturn($response);
$presenter = new FindPerformanceMetricsPresenterStub();
$useCase($presenter);
expect($presenter->data)->toBeInstanceOf(FindPerformanceMetricsResponse::class)
->and($presenter->data->resourceMetrics)
->toBeArray()
->and($presenter->data->resourceMetrics[0])
->toBeInstanceOf(ResourceMetricDto::class)
->and($presenter->data->resourceMetrics[0]->serviceId)->toBe(1)
->and($presenter->data->resourceMetrics[0]->resourceName)->toBe('Ping')
->and($presenter->data->resourceMetrics[0]->parentName)->toBe('Centreon-Server')
->and($presenter->data->resourceMetrics[0]->metrics)->toBe(
[
[
'id' => 1,
'name' => 'pl',
'unit' => '%',
'warning_high_threshold' => 400.3,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
[
'id' => 2,
'name' => 'rta',
'unit' => 'ms',
'warning_high_threshold' => 20.0,
'critical_high_threshold' => 50.0,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
[
'id' => 3,
'name' => 'rtmax',
'unit' => 'ms',
'warning_high_threshold' => null,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
[
'id' => 4,
'name' => 'rtmin',
'unit' => 'ms',
'warning_high_threshold' => null,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
]
)
->and($presenter->data->resourceMetrics[1])
->toBeInstanceOf(ResourceMetricDto::class)
->and($presenter->data->resourceMetrics[1]->serviceId)->toBe(2)
->and($presenter->data->resourceMetrics[1]->resourceName)->toBe('Traffic')
->and($presenter->data->resourceMetrics[1]->parentName)->toBe('Centreon-Server')
->and($presenter->data->resourceMetrics[1]->metrics)->toBe(
[
[
'id' => 5,
'name' => 'traffic_in',
'unit' => 'M',
'warning_high_threshold' => null,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
[
'id' => 6,
'name' => 'traffic_out',
'unit' => 'M',
'warning_high_threshold' => null,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
]
);
});
it('should present a FindPerformanceMetricsResponse when metrics are found as non-admin', function (): void {
$useCase = new FindPerformanceMetrics(
$this->nonAdminUser,
$this->requestParameters,
$this->accessGroupRepository,
$this->readDashboardPerformanceMetric,
$this->rights,
$this->isCloudPlatform
);
$response = [
new ResourceMetric(
1,
'Ping',
'Centreon-Server',
3,
[
new PerformanceMetric(1, 'pl', '%', 400.3, null, null, null, null, null, null),
new PerformanceMetric(2, 'rta', 'ms', 20, 50, null, null, null, null, null),
new PerformanceMetric(3, 'rtmax', 'ms', null, null, null, null, null, null, null),
new PerformanceMetric(4, 'rtmin', 'ms', null, null, null, null, null, null, null),
]
),
new ResourceMetric(
2,
'Traffic',
'Centreon-Server',
3,
[
new PerformanceMetric(5, 'traffic_in', 'M', null, null, null, null, null, null, null),
new PerformanceMetric(6, 'traffic_out', 'M', null, null, null, null, null, null, null),
]
),
];
$this->rights
->expects($this->once())
->method('canAccess')
->willReturn(true);
$this->readDashboardPerformanceMetric
->expects($this->once())
->method('findByRequestParametersAndAccessGroups')
->willReturn($response);
$presenter = new FindPerformanceMetricsPresenterStub();
$useCase($presenter);
expect($presenter->data)->toBeInstanceOf(FindPerformanceMetricsResponse::class)
->and($presenter->data->resourceMetrics)
->toBeArray()
->and($presenter->data->resourceMetrics[0])
->toBeInstanceOf(ResourceMetricDto::class)
->and($presenter->data->resourceMetrics[0]->serviceId)->toBe(1)
->and($presenter->data->resourceMetrics[0]->resourceName)->toBe('Ping')
->and($presenter->data->resourceMetrics[0]->parentName)->toBe('Centreon-Server')
->and($presenter->data->resourceMetrics[0]->metrics)->toBe(
[
[
'id' => 1,
'name' => 'pl',
'unit' => '%',
'warning_high_threshold' => 400.3,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
[
'id' => 2,
'name' => 'rta',
'unit' => 'ms',
'warning_high_threshold' => 20.0,
'critical_high_threshold' => 50.0,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
[
'id' => 3,
'name' => 'rtmax',
'unit' => 'ms',
'warning_high_threshold' => null,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
[
'id' => 4,
'name' => 'rtmin',
'unit' => 'ms',
'warning_high_threshold' => null,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
]
)
->and($presenter->data->resourceMetrics[1])
->toBeInstanceOf(ResourceMetricDto::class)
->and($presenter->data->resourceMetrics[1]->serviceId)->toBe(2)
->and($presenter->data->resourceMetrics[1]->resourceName)->toBe('Traffic')
->and($presenter->data->resourceMetrics[1]->parentName)->toBe('Centreon-Server')
->and($presenter->data->resourceMetrics[1]->metrics)->toBe(
[
[
'id' => 5,
'name' => 'traffic_in',
'unit' => 'M',
'warning_high_threshold' => null,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
[
'id' => 6,
'name' => 'traffic_out',
'unit' => 'M',
'warning_high_threshold' => null,
'critical_high_threshold' => null,
'warning_low_threshold' => null,
'critical_low_threshold' => null,
],
]
);
});
it('should present a ForbiddenResponse when user has unsufficient rights', function (): void {
$useCase = new FindPerformanceMetrics(
$this->nonAdminUser,
$this->requestParameters,
$this->accessGroupRepository,
$this->readDashboardPerformanceMetric,
$this->rights,
$this->isCloudPlatform
);
$this->rights
->expects($this->once())
->method('canAccess')
->willReturn(false);
$presenter = new FindPerformanceMetricsPresenterStub();
$useCase($presenter);
expect($presenter->data)->toBeInstanceOf(ForbiddenResponse::class)
->and($presenter->data->getMessage())
->toBe(DashboardException::accessNotAllowed()->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/Dashboard/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetricsPresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindPerformanceMetrics/FindPerformanceMetricsPresenterStub.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\Dashboard\Application\UseCase\FindPerformanceMetrics;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindPerformanceMetrics\FindPerformanceMetricsPresenterInterface;
use Core\Dashboard\Application\UseCase\FindPerformanceMetrics\FindPerformanceMetricsResponse;
class FindPerformanceMetricsPresenterStub implements FindPerformanceMetricsPresenterInterface
{
public ResponseStatusInterface|FindPerformanceMetricsResponse $data;
public function presentResponse(FindPerformanceMetricsResponse|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/Dashboard/Application/UseCase/FindDashboardContacts/FindDashboardContactsTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindDashboardContacts/FindDashboardContactsTest.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\Dashboard\Application\UseCase\FindDashboardContacts;
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\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindDashboardContacts\FindDashboardContacts;
use Core\Dashboard\Application\UseCase\FindDashboardContacts\FindDashboardContactsResponse;
use Core\Dashboard\Application\UseCase\FindDashboardContacts\Response\ContactsResponseDto;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Role\DashboardContactRole;
use Core\Dashboard\Domain\Model\Role\DashboardGlobalRole;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
beforeEach(function (): void {
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->rights = $this->createMock(DashboardRights::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->readDashboardShareRepository = $this->createMock(ReadDashboardShareRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->readContactRepository = $this->createMock(ReadContactRepositoryInterface::class);
$this->readContactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class);
$this->useCaseOnPremise = new FindDashboardContacts(
$this->requestParameters,
$this->rights,
$this->contact,
$this->readDashboardShareRepository,
$this->readAccessGroupRepository,
$this->readContactRepository,
$this->readContactGroupRepository,
$this->isCloudPlatform = false
);
$this->useCaseCloud = new FindDashboardContacts(
$this->requestParameters,
$this->rights,
$this->contact,
$this->readDashboardShareRepository,
$this->readAccessGroupRepository,
$this->readContactRepository,
$this->readContactGroupRepository,
$this->isCloudPlatform = true
);
});
it(
'should return an ErrorResponse if an error is raised during user search - AS ADMIN - OnPremise',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->readDashboardShareRepository->expects($this->once())
->method('findContactsWithAccessRightByRequestParameters')
->willThrowException(new \Exception());
$response = ($this->useCaseOnPremise)();
expect($response)->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())->toBe(DashboardException::errorWhileSearchingSharableContacts()->getMessage());
}
);
it(
'should return an ErrorResponse if an error is raised during admin search - AS ADMIN - OnPremise',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$this->readDashboardShareRepository->expects($this->once())
->method('findContactsWithAccessRightByRequestParameters')
->willReturn([]);
$this->readContactRepository->expects($this->once())
->method('findAdminWithRequestParameters')
->willThrowException(new \Exception());
$response = ($this->useCaseOnPremise)();
expect($response)->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())->toBe(DashboardException::errorWhileSearchingSharableContacts()->getMessage());
}
);
it(
'should return a FindDashboardContactsResponse if no error is raised - AS ADMIN - OnPremise',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$userDashboardRole = new DashboardContactRole(
contactId: 1,
contactName: 'test',
contactEmail: 'email',
roles: [DashboardGlobalRole::Creator]
);
$adminContact = (new Contact())
->setAdmin(true)
->setName('adminUser')
->setId(2)
->setEmail('email');
$this->readDashboardShareRepository->expects($this->once())
->method('findContactsWithAccessRightByRequestParameters')
->willReturn([$userDashboardRole]);
$this->readContactRepository->expects($this->once())
->method('findAdminWithRequestParameters')
->willReturn([$adminContact]);
$response = ($this->useCaseOnPremise)();
$contacts = $response->getData();
expect($response)->toBeInstanceOf(FindDashboardContactsResponse::class)
->and($contacts[0])->toBeInstanceOf(ContactsResponseDto::class)
->and($contacts[0]->id)->toBe(1)
->and($contacts[0]->name)->toBe('test')
->and($contacts[0]->email)->toBe('email')
->and($contacts[0]->mostPermissiveRole)->toBe(DashboardGlobalRole::Creator)
->and($contacts[1])->toBeInstanceOf(ContactsResponseDto::class)
->and($contacts[1]->id)->toBe(2)
->and($contacts[1]->name)->toBe('adminUser')
->and($contacts[1]->email)->toBe('email')
->and($contacts[1]->mostPermissiveRole)->toBe(DashboardGlobalRole::Creator);
}
);
it(
'should return an ErrorResponse if an error is raised during user access group search - AS USER - OnPremise',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$this->readAccessGroupRepository->expects($this->once())
->method('findByContact')
->willThrowException(new \Exception());
$response = ($this->useCaseOnPremise)();
expect($response)->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())->toBe(DashboardException::errorWhileSearchingSharableContacts()->getMessage());
}
);
it(
'should return an ErrorResponse if an error is raised during user search - AS USER - OnPremise',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$this->readAccessGroupRepository->expects($this->any())
->method('findByContact')
->willReturn([new AccessGroup(1, 'name', 'alias')]);
$this->readDashboardShareRepository->expects($this->once())
->method('findContactsWithAccessRightByACLGroupsAndRequestParameters')
->willThrowException(new \Exception());
$response = ($this->useCaseOnPremise)();
expect($response)->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())->toBe(DashboardException::errorWhileSearchingSharableContacts()->getMessage());
}
);
it(
'should return a FindDashboardContactsResponse if no error is raised - AS USER - OnPremise',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$this->readAccessGroupRepository->expects($this->any())
->method('findByContact')
->willReturn([new AccessGroup(1, 'name', 'alias')]);
$userDashboardRole = new DashboardContactRole(
contactId: 1,
contactName: 'test',
contactEmail: 'email',
roles: [DashboardGlobalRole::Creator]
);
$this->readDashboardShareRepository->expects($this->once())
->method('findContactsWithAccessRightByACLGroupsAndRequestParameters')
->willReturn([$userDashboardRole]);
$response = ($this->useCaseOnPremise)();
$contacts = $response->getData();
expect($response)->toBeInstanceOf(FindDashboardContactsResponse::class)
->and($contacts[0])->toBeInstanceOf(ContactsResponseDto::class)
->and($contacts[0]->id)->toBe(1)
->and($contacts[0]->name)->toBe('test')
->and($contacts[0]->email)->toBe('email')
->and($contacts[0]->mostPermissiveRole)->toBe(DashboardGlobalRole::Creator);
}
);
it(
'should return a FindDashboardContactsResponse if no error is raised - AS ADMIN - Cloud',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(true);
$userDashboardRoles = [
new DashboardContactRole(
contactId: 1,
contactName: 'test',
contactEmail: 'email',
roles: [DashboardGlobalRole::Creator]
),
new DashboardContactRole(
contactId: 2,
contactName: 'test-cloud-admin',
contactEmail: 'email',
roles: [DashboardGlobalRole::Administrator]
),
];
$this->readDashboardShareRepository->expects($this->once())
->method('findContactsWithAccessRightByRequestParameters')
->willReturn($userDashboardRoles);
$response = ($this->useCaseCloud)();
$contacts = $response->getData();
expect($response)->toBeInstanceOf(FindDashboardContactsResponse::class)
->and($contacts[0])->toBeInstanceOf(ContactsResponseDto::class)
->and($contacts[0]->id)->toBe(1)
->and($contacts[0]->name)->toBe('test')
->and($contacts[0]->email)->toBe('email')
->and($contacts[0]->mostPermissiveRole)->toBe(DashboardGlobalRole::Creator)
->and($contacts[1])->toBeInstanceOf(ContactsResponseDto::class)
->and($contacts[1]->id)->toBe(2)
->and($contacts[1]->name)->toBe('test-cloud-admin')
->and($contacts[1]->email)->toBe('email')
->and($contacts[1]->mostPermissiveRole)->toBe(DashboardGlobalRole::Creator);
}
);
it(
'should return a FindDashboardContactsResponse if no error is raised - AS USER - Cloud',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')
->willReturn(false);
$this->readContactGroupRepository->expects($this->once())
->method('findAllByUserId')
->willReturn([new ContactGroup(1, 'name', 'alias')]);
$userDashboardRoles = [
new DashboardContactRole(
contactId: 1,
contactName: 'test',
contactEmail: 'email',
roles: [DashboardGlobalRole::Creator]
),
new DashboardContactRole(
contactId: 2,
contactName: 'test-cloud-admin',
contactEmail: 'email',
roles: [DashboardGlobalRole::Administrator]
),
];
$this->readDashboardShareRepository->expects($this->once())
->method('findContactsWithAccessRightsByContactGroupsAndRequestParameters')
->willReturn($userDashboardRoles);
$response = ($this->useCaseCloud)();
$contacts = $response->getData();
expect($response)->toBeInstanceOf(FindDashboardContactsResponse::class)
->and($contacts[0])->toBeInstanceOf(ContactsResponseDto::class)
->and($contacts[0]->id)->toBe(1)
->and($contacts[0]->name)->toBe('test')
->and($contacts[0]->email)->toBe('email')
->and($contacts[0]->mostPermissiveRole)->toBe(DashboardGlobalRole::Creator)
->and($contacts[1])->toBeInstanceOf(ContactsResponseDto::class)
->and($contacts[1]->id)->toBe(2)
->and($contacts[1]->name)->toBe('test-cloud-admin')
->and($contacts[1]->email)->toBe('email')
->and($contacts[1]->mostPermissiveRole)->toBe(DashboardGlobalRole::Creator);
}
);
| 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/Dashboard/Application/UseCase/DeleteContactDashboardShare/DeleteContactDashboardSharePresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/DeleteContactDashboardShare/DeleteContactDashboardSharePresenterStub.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\Dashboard\Application\UseCase\DeleteContactDashboardShare;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\DeleteContactDashboardShare\DeleteContactDashboardSharePresenterInterface;
class DeleteContactDashboardSharePresenterStub implements DeleteContactDashboardSharePresenterInterface
{
public 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/Dashboard/Application/UseCase/DeleteContactDashboardShare/DeleteContactDashboardShareTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/DeleteContactDashboardShare/DeleteContactDashboardShareTest.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\Dashboard\Application\UseCase\DeleteContactDashboardShare;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Contact\Interfaces\ContactRepositoryInterface;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\DeleteContactDashboardShare\DeleteContactDashboardShare;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(closure: function (): void {
$this->presenter = new DeleteContactDashboardSharePresenterStub();
$this->useCase = new DeleteContactDashboardShare(
$this->readDashboardShareRepository = $this->createMock(ReadDashboardShareRepositoryInterface::class),
$this->readDashboardRepository = $this->createMock(ReadDashboardRepositoryInterface::class),
$this->writeDashboardShareRepository = $this->createMock(WriteDashboardShareRepositoryInterface::class),
$this->contactRepository = $this->createMock(ContactRepositoryInterface::class),
$this->rights = $this->createMock(DashboardRights::class),
$this->contact = $this->createMock(ContactInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readContactRepository = $this->createMock(ReadContactRepositoryInterface::class),
$this->isCloudPlatform = false
);
$this->testedDashboard = new Dashboard(
random_int(1, 1_000_000),
uniqid('dashboard_', true),
null,
null,
new \DateTimeImmutable(),
new \DateTimeImmutable(),
new Refresh(RefreshType::Global, null),
);
$this->testedContact = $this->createMock(Contact::class);
$this->testedContact->method('getId')->willReturn(random_int(1, 1_000_000));
$this->testedContact->method('getName')->willReturn(uniqid('name_', true));
$this->testedContact->method('getEmail')->willReturn(uniqid('email_', true));
});
it(
'should present a ForbiddenResponse when the user has no rights',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())->method('canCreate')->willReturn(false);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContact->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::accessNotAllowedForWriting()->getMessage());
}
);
it(
'should present a NotFoundResponse when the dashboard does not exist',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())->method('findOne')->willReturn(null);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContact->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should present a NotFoundResponse when the contact does not exist',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
$this->contactRepository->expects($this->once())->method('findById')->willReturn(null);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContact->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should present a NotFoundResponse when the share does not exist',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
$this->contactRepository->expects($this->once())->method('findById')
->willReturn($this->testedContact);
$this->writeDashboardShareRepository->expects($this->once())->method('deleteContactShare')
->willReturn(false);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContact->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should present a proper NoContentResponse as an ADMIN',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
$this->contactRepository->expects($this->once())->method('findById')
->willReturn($this->testedContact);
$this->writeDashboardShareRepository->expects($this->once())->method('deleteContactShare')
->willReturn(true);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContact->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should present a proper NoContentResponse as a user with allowed ROLE',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())->method('canCreate')->willReturn(true);
$this->rights->expects($this->once())->method('canDeleteShare')->willReturn(true);
$this->readContactRepository->expects($this->once())->method('existInAccessGroups')
->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn($this->testedDashboard);
$this->contactRepository->expects($this->once())->method('findById')
->willReturn($this->testedContact);
$this->writeDashboardShareRepository->expects($this->once())->method('deleteContactShare')
->willReturn(true);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContact->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should present a proper ForbiddenResponse as a user with NOT allowed ROLE',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())->method('canCreate')->willReturn(true);
$this->rights->expects($this->once())->method('canDeleteShare')->willReturn(false);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn($this->testedDashboard);
$this->contactRepository->expects($this->once())->method('findById')
->willReturn($this->testedContact);
$this->writeDashboardShareRepository->expects($this->never())->method('deleteContactShare');
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContact->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(ForbiddenResponse::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/Dashboard/Application/UseCase/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardSharePresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardSharePresenterStub.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\Dashboard\Application\UseCase\DeleteContactGroupDashboardShare;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\DeleteContactGroupDashboardShare\DeleteContactGroupDashboardSharePresenterInterface;
class DeleteContactGroupDashboardSharePresenterStub implements DeleteContactGroupDashboardSharePresenterInterface
{
public 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/Dashboard/Application/UseCase/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardShareTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/DeleteContactGroupDashboardShare/DeleteContactGroupDashboardShareTest.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\Dashboard\Application\UseCase\DeleteContactGroupDashboardShare;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Domain\Model\ContactGroup;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\DeleteContactGroupDashboardShare\DeleteContactGroupDashboardShare;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(closure: function (): void {
$this->presenter = new DeleteContactGroupDashboardSharePresenterStub();
$this->useCase = new DeleteContactGroupDashboardShare(
$this->readDashboardShareRepository = $this->createMock(ReadDashboardShareRepositoryInterface::class),
$this->readDashboardRepository = $this->createMock(ReadDashboardRepositoryInterface::class),
$this->writeDashboardShareRepository = $this->createMock(WriteDashboardShareRepositoryInterface::class),
$this->readContactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->rights = $this->createMock(DashboardRights::class),
$this->contact = $this->createMock(ContactInterface::class),
$this->isCloudPlatform = false
);
$this->testedDashboard = new Dashboard(
random_int(1, 1_000_000),
uniqid('dashboard_', true),
null,
null,
new \DateTimeImmutable(),
new \DateTimeImmutable(),
new Refresh(RefreshType::Global, null),
);
$this->testedContactGroup = $this->createMock(ContactGroup::class);
$this->testedContactGroup->method('getId')->willReturn(random_int(1, 1_000_000));
$this->testedContactGroup->method('getName')->willReturn(uniqid('name_', true));
});
it(
'should present a ForbiddenResponse when the user has no rights',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())->method('canCreate')->willReturn(false);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContactGroup->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::accessNotAllowedForWriting()->getMessage());
}
);
it(
'should present a NotFoundResponse when the dashboard does not exist',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())->method('findOne')->willReturn(null);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContactGroup->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should present a NotFoundResponse when the contact does not exist',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
$this->readContactGroupRepository->expects($this->once())->method('find')->willReturn(null);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContactGroup->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should present a NotFoundResponse when the share does not exist',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
$this->readContactGroupRepository->expects($this->once())->method('find')
->willReturn($this->testedContactGroup);
$this->writeDashboardShareRepository->expects($this->once())->method('deleteContactGroupShare')
->willReturn(false);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContactGroup->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should present a proper NoContentResponse as an ADMIN',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
$this->readContactGroupRepository->expects($this->once())->method('find')
->willReturn($this->testedContactGroup);
$this->writeDashboardShareRepository->expects($this->once())->method('deleteContactGroupShare')
->willReturn(true);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContactGroup->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should present a proper NoContentResponse as a user with allowed ROLE',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())->method('canCreate')->willReturn(true);
$this->rights->expects($this->once())->method('canDeleteShare')->willReturn(true);
$this->readContactGroupRepository->expects($this->once())->method('existsInAccessGroups')
->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn($this->testedDashboard);
$this->readContactGroupRepository->expects($this->once())->method('find')
->willReturn($this->testedContactGroup);
$this->writeDashboardShareRepository->expects($this->once())->method('deleteContactGroupShare')
->willReturn(true);
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContactGroup->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should present a proper ForbiddenResponse as a user with NOT allowed ROLE',
function (): void {
$this->rights->expects($this->once())->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())->method('canCreate')->willReturn(true);
$this->rights->expects($this->once())->method('canDeleteShare')->willReturn(false);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn($this->testedDashboard);
$this->readContactGroupRepository->expects($this->once())->method('find')
->willReturn($this->testedContactGroup);
$this->writeDashboardShareRepository->expects($this->never())->method('deleteContactGroupShare');
($this->useCase)(
$this->testedDashboard->getId(),
$this->testedContactGroup->getId(),
$this->presenter
);
expect($this->presenter->data)->toBeInstanceOf(ForbiddenResponse::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/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardPanelsDifferenceTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardPanelsDifferenceTest.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\Dashboard\Application\UseCase\PartialUpdateDashboard;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\PartialUpdateDashboardPanelsDifference;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\PanelRequestDto;
beforeEach(function (): void {
$this->randomName = static fn (): string => 'panel-' . mb_substr(md5(random_bytes(10)), 0, 6);
});
it(
'should return items to Delete',
function (): void {
$difference = new PartialUpdateDashboardPanelsDifference(
panelIdsFromRepository: [1, 2, 3],
panelsFromRequest: []
);
$toDelete = $difference->getPanelIdsToDelete();
$toCreate = $difference->getPanelsToCreate();
$toUpdate = $difference->getPanelsToUpdate();
expect($toDelete)->toHaveCount(3)
->and($toCreate)->toHaveCount(0)
->and($toUpdate)->toHaveCount(0)
->and($toDelete)->toBe([1, 2, 3]);
}
);
it(
'should return items to Create',
function (): void {
$difference = new PartialUpdateDashboardPanelsDifference(
panelIdsFromRepository: [],
panelsFromRequest: [
new PanelRequestDto(name: $panelName1 = ($this->randomName)(), widgetType: 'non-empty'),
new PanelRequestDto(name: $panelName2 = ($this->randomName)(), widgetType: 'non-empty'),
]
);
$toDelete = $difference->getPanelIdsToDelete();
$toCreate = $difference->getPanelsToCreate();
$toUpdate = $difference->getPanelsToUpdate();
expect($toDelete)->toHaveCount(0)
->and($toCreate)->toHaveCount(2)
->and($toUpdate)->toHaveCount(0)
->and($toCreate[0]->getName())->toBe($panelName1)
->and($toCreate[1]->getName())->toBe($panelName2);
}
);
it(
'should return items to Update',
function (): void {
$difference = new PartialUpdateDashboardPanelsDifference(
panelIdsFromRepository: [1, 2],
panelsFromRequest: [
new PanelRequestDto(id: 1, name: $panelName1 = ($this->randomName)(), widgetType: 'non-empty'),
new PanelRequestDto(id: 2, name: $panelName2 = ($this->randomName)(), widgetType: 'non-empty'),
]
);
$toDelete = $difference->getPanelIdsToDelete();
$toCreate = $difference->getPanelsToCreate();
$toUpdate = $difference->getPanelsToUpdate();
expect($toDelete)->toHaveCount(0)
->and($toCreate)->toHaveCount(0)
->and($toUpdate)->toHaveCount(2)
->and($toUpdate[0]->getId())->toBe(1)->and($toUpdate[0]->getName())->toBe($panelName1)
->and($toUpdate[1]->getId())->toBe(2)->and($toUpdate[1]->getName())->toBe($panelName2);
}
);
it(
'should return items to Create + Update + Update',
function (): void {
$difference = new PartialUpdateDashboardPanelsDifference(
panelIdsFromRepository: [1, 2, 3, 4],
panelsFromRequest: [
new PanelRequestDto(id: 1, name: $panelName1 = ($this->randomName)(), widgetType: 'non-empty'),
new PanelRequestDto(name: $panelName2 = ($this->randomName)(), widgetType: 'non-empty'),
new PanelRequestDto(name: $panelName3 = ($this->randomName)(), widgetType: 'non-empty'),
]
);
$toDelete = $difference->getPanelIdsToDelete();
$toCreate = $difference->getPanelsToCreate();
$toUpdate = $difference->getPanelsToUpdate();
expect($toDelete)->toHaveCount(3)
->and($toCreate)->toHaveCount(2)
->and($toUpdate)->toHaveCount(1)
->and($toDelete)->toBe([2, 3, 4])
->and($toCreate[0]->getName())->toBe($panelName2)
->and($toCreate[1]->getName())->toBe($panelName3)
->and($toUpdate[0]->getId())->toBe(1)->and($toUpdate[0]->getName())->toBe($panelName1);
}
);
it(
'should raise a DashboardException when trying to update a panel which does not belongs to the dashboard',
function (array $existingIds, int $newPanelId): void {
$this->expectExceptionObject(
DashboardException::errorTryingToUpdateAPanelWhichDoesNotBelongsToTheDashboard()
);
new PartialUpdateDashboardPanelsDifference(
panelIdsFromRepository: $existingIds,
panelsFromRequest: [new PanelRequestDto(id: $newPanelId, name: 'any-name', widgetType: 'non-empty')]
);
}
)->with([
[[/* no ids */], 42],
[[1, 2], 42],
]);
| 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/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardPresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardPresenterStub.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\Dashboard\Application\UseCase\PartialUpdateDashboard;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\PartialUpdateDashboardPresenterInterface;
class PartialUpdateDashboardPresenterStub implements PartialUpdateDashboardPresenterInterface
{
public ResponseStatusInterface|NoContentResponse $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/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/PartialUpdateDashboard/PartialUpdateDashboardTest.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\Dashboard\Application\UseCase\PartialUpdateDashboard;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardRepositoryInterface;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\PartialUpdateDashboard;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\PartialUpdateDashboardRequest;
use Core\Dashboard\Application\UseCase\PartialUpdateDashboard\Request\ThumbnailRequestDto;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
beforeEach(function (): void {
$this->presenter = new PartialUpdateDashboardPresenterStub();
$this->useCase = new PartialUpdateDashboard(
$this->readDashboardRepository = $this->createMock(ReadDashboardRepositoryInterface::class),
$this->writeDashboardRepository = $this->createMock(WriteDashboardRepositoryInterface::class),
$this->readDashboardPanelRepository = $this->createMock(ReadDashboardPanelRepositoryInterface::class),
$this->readDashboardShareRepository = $this->createMock(ReadDashboardShareRepositoryInterface::class),
$this->writeDashboardPanelRepository = $this->createMock(WriteDashboardPanelRepositoryInterface::class),
$this->createMock(DataStorageEngineInterface::class),
$this->rights = $this->createMock(DashboardRights::class),
$this->contact = $this->createMock(ContactInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->eventDispatcher = $this->createMock(EventDispatcher::class),
$this->isCloudPlatform = false
);
$this->testedPartialUpdateDashboardRequest = new PartialUpdateDashboardRequest();
$this->testedPartialUpdateDashboardRequest->name = 'updated-dashboard';
$this->testedPartialUpdateDashboardRequest->thumbnail = new ThumbnailRequestDto(null, __DIR__, 'logo.jpg');
$this->testedPartialUpdateDashboardRequest->thumbnail->content = file_get_contents(__DIR__ . '/logo.jpg');
$this->testedDashboard = new Dashboard(
$this->testedDashboardId = random_int(1, 1_000_000),
$this->testedDashboardName = uniqid('name', true),
$this->testedDashboardCreatedBy = random_int(1, 1_000_000),
$this->testedDashboardUpdatedBy = random_int(1, 1_000_000),
$this->testedDashboardCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
$this->testedDashboardUpdatedAt = new \DateTimeImmutable('2023-05-09T16:00:00+00:00'),
$this->testedDashboardGlobalRefresh = new Refresh(RefreshType::Global, null)
);
});
it(
'should present an ErrorResponse when a generic exception is thrown',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willThrowException(new \Exception());
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::errorWhileUpdating()->getMessage());
}
);
it(
'should present an ErrorResponse with a custom message when a DashboardException is thrown',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')
->willThrowException(new DashboardException($msg = uniqid('fake message ', true)));
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe($msg);
}
);
it(
'should present an InvalidArgumentResponse when a model field value is not valid',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
$this->testedPartialUpdateDashboardRequest->name = '';
$expectedException = AssertionException::notEmptyString('Dashboard::name');
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->data->getMessage())
->toBe($expectedException->getMessage());
}
);
it(
'should present a ForbiddenResponse when the user does not have the correct role',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())
->method('canCreate')->willReturn(false);
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::accessNotAllowedForWriting()->getMessage());
}
);
it(
'should present a NoContentResponse as admin',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->contact->expects($this->atLeastOnce())
->method('getId')->willReturn(1);
$this->writeDashboardRepository->expects($this->once())
->method('update');
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
/** @var NoContentResponse $presentedData */
$presentedData = $this->presenter->data;
expect($presentedData)->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should update the updatedAt field',
function (): void {
$updatedAt = null;
$updatedAtBeforeUseCase = $this->testedDashboardUpdatedAt->getTimestamp();
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->contact->expects($this->atLeastOnce())
->method('getId')->willReturn(1);
$this->writeDashboardRepository
->expects($this->once())
->method('update')
->with(
$this->callback(function (Dashboard $dashboard) use (&$updatedAt): bool {
$updatedAt = $dashboard->getUpdatedAt();
return true;
})
);
$this->readDashboardRepository
->expects($this->once())
->method('findOne')
->willReturn($this->testedDashboard);
$timeBeforeUsecase = time();
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
expect($updatedAt)->not()->toBeNull()
->and($updatedAt->getTimestamp())->toBeGreaterThanOrEqual($updatedAtBeforeUseCase)
->and($updatedAt->getTimestamp())->toBeGreaterThanOrEqual($timeBeforeUsecase);
}
);
it(
'should present a ForbiddenResponse as not allowed user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())
->method('canCreate')->willReturn(false);
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
expect($this->presenter->data)->toBeInstanceOf(ForbiddenResponse::class);
}
);
it(
'should present a NoContentResponse as allowed ADMIN user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->contact->expects($this->atLeastOnce())
->method('getId')->willReturn(1);
$this->writeDashboardRepository->expects($this->once())
->method('update');
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
/** @var NoContentResponse $presentedData */
$presentedData = $this->presenter->data;
expect($presentedData)->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should present a ForbiddenResponse as NOT allowed SHARED user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())
->method('canCreate')->willReturn(true);
$this->contact->expects($this->atLeastOnce())
->method('getId')->willReturn(1);
$this->rights->expects($this->once())
->method('canUpdate')->willReturn(false);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn($this->testedDashboard);
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
/** @var NoContentResponse $presentedData */
$presentedData = $this->presenter->data;
expect($presentedData)->toBeInstanceOf(ForbiddenResponse::class);
}
);
it(
'should present a NoContentResponse as allowed SHARED user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())
->method('canCreate')->willReturn(true);
$this->contact->expects($this->atLeastOnce())
->method('getId')->willReturn(1);
$this->writeDashboardRepository->expects($this->once())
->method('update');
$this->rights->expects($this->once())
->method('canUpdate')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn($this->testedDashboard);
($this->useCase)($this->testedDashboardId, $this->testedPartialUpdateDashboardRequest, $this->presenter);
/** @var NoContentResponse $presentedData */
$presentedData = $this->presenter->data;
expect($presentedData)->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/Dashboard/Application/UseCase/FindDashboard/FindDashboardTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindDashboard/FindDashboardTest.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\Dashboard\Application\UseCase\FindDashboard;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardPanelRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\UseCase\FindDashboard\FindDashboard;
use Core\Dashboard\Application\UseCase\FindDashboard\FindDashboardResponse;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardPanel;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\UserProfile\Application\Repository\ReadUserProfileRepositoryInterface;
use Core\UserProfile\Domain\Model\UserProfile;
beforeEach(function (): void {
$this->presenter = new FindDashboardPresenterStub();
$this->useCase = new FindDashboard(
$this->readDashboardRepository = $this->createMock(ReadDashboardRepositoryInterface::class),
$this->readDashboardPanelRepository = $this->createMock(ReadDashboardPanelRepositoryInterface::class),
$this->readDashboardRelationRepository = $this->createMock(ReadDashboardShareRepositoryInterface::class),
$this->readContactRepository = $this->createMock(ReadContactRepositoryInterface::class),
$this->rights = $this->createMock(DashboardRights::class),
$this->contact = $this->createMock(ContactInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->userProfileReader = $this->createMock(ReadUserProfileRepositoryInterface::class),
$this->isCloudPlatform = false
);
$this->userProfile = (new UserProfile(id: 1, userId: 1))->setFavoriteDashboards([1]);
$this->testedDashboard = new Dashboard(
$this->testedDashboardId = 1,
$this->testedDashboardName = uniqid('name', true),
$this->testedDashboardCreatedBy = random_int(1, 1_000_000),
$this->testedDashboardUpdatedBy = random_int(1, 1_000_000),
$this->testedDashboardCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
$this->testedDashboardUpdatedAt = new \DateTimeImmutable('2023-05-09T16:00:00+00:00'),
$this->testedDashboardGlobalRefresh = new Refresh(RefreshType::Global, null),
);
$this->testedDashboardPanel = new DashboardPanel(
$this->testedPanelId = 1,
$this->testedPanelName = uniqid('name', true),
$this->testedPanelWidgetType = uniqid('widgetType', true),
$this->testedPanelWidgetSettings = [uniqid('key', true) => 42],
$this->testedPanelLayoutX = random_int(1, 1_000),
$this->testedPanelLayoutY = random_int(1, 1_000),
$this->testedPanelLayoutWidth = random_int(1, 1_000),
$this->testedPanelLayoutHeight = random_int(1, 1_000),
$this->testedPanelLayoutMinWidth = random_int(1, 1_000),
$this->testedPanelLayoutMinHeight = random_int(1, 1_000),
);
});
it(
'should present an ErrorResponse when an exception is thrown',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willThrowException(new \Exception());
($this->useCase)(1, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::errorWhileRetrieving()->getMessage());
}
);
it(
'should present a NotFoundResponse when an exception is thrown',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn(null);
($this->useCase)(1, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should present a FindDashboardResponse as ADMIN',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->userProfileReader->expects($this->once())
->method('findByContact')->willReturn($this->userProfile);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
$this->readContactRepository->expects($this->once())
->method('findNamesByIds')
->willReturn([
$this->testedDashboardCreatedBy => ['id' => $this->testedDashboardCreatedBy, 'name' => $creator = uniqid('creator', true)],
$this->testedDashboardUpdatedBy => ['id' => $this->testedDashboardUpdatedBy, 'name' => $updater = uniqid('updater', true)],
]);
$this->readDashboardPanelRepository->expects($this->once())->method('findPanelsByDashboardId')
->willReturn([$this->testedDashboardPanel]);
($this->useCase)(1, $this->presenter);
$dashboard = $this->presenter->data;
expect($dashboard)->toBeInstanceOf(FindDashboardResponse::class)
->and($dashboard->id)->toBe($this->testedDashboardId)
->and($dashboard->name)->toBe($this->testedDashboardName)
->and($dashboard->panels)->toHaveCount(1)
->and($dashboard->isFavorite)->toBe(true)
->and($dashboard->panels[0]->id)->toBe($this->testedPanelId)
->and($dashboard->panels[0]->name)->toBe($this->testedPanelName)
->and($dashboard->panels[0]->widgetType)->toBe($this->testedPanelWidgetType)
->and($dashboard->panels[0]->widgetSettings)->toBe($this->testedPanelWidgetSettings)
->and($dashboard->panels[0]->layout->posX)->toBe($this->testedPanelLayoutX)
->and($dashboard->panels[0]->layout->posY)->toBe($this->testedPanelLayoutY)
->and($dashboard->panels[0]->layout->width)->toBe($this->testedPanelLayoutWidth)
->and($dashboard->panels[0]->layout->height)->toBe($this->testedPanelLayoutHeight)
->and($dashboard->panels[0]->layout->minWidth)->toBe($this->testedPanelLayoutMinWidth)
->and($dashboard->panels[0]->layout->minHeight)->toBe($this->testedPanelLayoutMinHeight)
->and($dashboard->createdBy->id)->toBe($this->testedDashboardCreatedBy)
->and($dashboard->createdBy->name)->toBe($creator)
->and($dashboard->updatedBy->id)->toBe($this->testedDashboardUpdatedBy)
->and($dashboard->updatedBy->name)->toBe($updater)
->and($dashboard->description)->toBe(null)
->and($dashboard->createdAt->getTimestamp())->toBe($this->testedDashboardCreatedAt->getTimestamp())
->and($dashboard->updatedAt->getTimestamp())->toBeGreaterThanOrEqual($this->testedDashboardUpdatedAt->getTimestamp());
}
);
it(
'should present a FindDashboardResponse as allowed ADMIN user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->userProfileReader->expects($this->once())
->method('findByContact')->willReturn($this->userProfile);
$this->readDashboardRepository->expects($this->once())
->method('findOne')->willReturn($this->testedDashboard);
($this->useCase)(1, $this->presenter);
/** @var FindDashboardResponse $dashboard */
$dashboard = $this->presenter->data;
expect($dashboard)->toBeInstanceOf(FindDashboardResponse::class)
->and($dashboard->id)->toBe($this->testedDashboardId)
->and($dashboard->name)->toBe($this->testedDashboardName)
->and($dashboard->isFavorite)->toBe(true)
->and($dashboard->description)->toBe(null)
->and($dashboard->createdAt->getTimestamp())->toBe($this->testedDashboardCreatedAt->getTimestamp())
->and($dashboard->updatedAt->getTimestamp())->toBeGreaterThanOrEqual($this->testedDashboardUpdatedAt->getTimestamp());
}
);
it(
'should present a FindDashboardResponse as allowed VIEWER user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->userProfileReader->expects($this->once())
->method('findByContact')->willReturn($this->userProfile);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn($this->testedDashboard);
($this->useCase)(1, $this->presenter);
/** @var FindDashboardResponse $dashboard */
$dashboard = $this->presenter->data;
expect($dashboard)->toBeInstanceOf(FindDashboardResponse::class)
->and($dashboard->id)->toBe($this->testedDashboardId)
->and($dashboard->name)->toBe($this->testedDashboardName)
->and($dashboard->description)->toBe(null)
->and($dashboard->createdAt->getTimestamp())->toBe($this->testedDashboardCreatedAt->getTimestamp())
->and($dashboard->updatedAt->getTimestamp())->toBeGreaterThanOrEqual($this->testedDashboardUpdatedAt->getTimestamp());
}
);
| 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/Dashboard/Application/UseCase/FindDashboard/FindDashboardPresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/FindDashboard/FindDashboardPresenterStub.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\Dashboard\Application\UseCase\FindDashboard;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\FindDashboard\FindDashboardPresenterInterface;
use Core\Dashboard\Application\UseCase\FindDashboard\FindDashboardResponse;
class FindDashboardPresenterStub implements FindDashboardPresenterInterface
{
public FindDashboardResponse|ResponseStatusInterface $data;
public function presentResponse(FindDashboardResponse|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/Dashboard/Application/UseCase/DeleteDashboard/DeleteDashboardTest.php | centreon/tests/php/Core/Dashboard/Application/UseCase/DeleteDashboard/DeleteDashboardTest.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\Dashboard\Application\UseCase\DeleteDashboard;
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\Dashboard\Application\Exception\DashboardException;
use Core\Dashboard\Application\Repository\ReadDashboardRepositoryInterface;
use Core\Dashboard\Application\Repository\ReadDashboardShareRepositoryInterface;
use Core\Dashboard\Application\Repository\WriteDashboardRepositoryInterface;
use Core\Dashboard\Application\UseCase\DeleteDashboard\DeleteDashboard;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\DashboardRights;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->presenter = new DeleteDashboardPresenterStub();
$this->useCase = new DeleteDashboard(
$this->readDashboardRepository = $this->createMock(ReadDashboardRepositoryInterface::class),
$this->writeDashboardRepository = $this->createMock(WriteDashboardRepositoryInterface::class),
$this->readDashboardShareRepository = $this->createMock(ReadDashboardShareRepositoryInterface::class),
$this->rights = $this->createMock(DashboardRights::class),
$this->contact = $this->createMock(ContactInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->mediaRepository = $this->createMock(WriteMediaRepositoryInterface::class),
$this->isCloudPlatform = false
);
$this->testedDashboard = new Dashboard(
$this->testedDashboardId = 1,
$this->testedDashboardName = 'dashboard-name',
$this->testedDashboardCreatedBy = 2,
$this->testedDashboardUpdatedBy = 3,
$this->testedDashboardCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00'),
$this->testedDashboardUpdatedAt = new \DateTimeImmutable('2023-05-09T16:00:00+00:00'),
$this->testedDashboardGlobalRefresh = new Refresh(RefreshType::Global, null),
);
});
it(
'should present an ErrorResponse when an exception is thrown',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('existsOne')->willThrowException(new \Exception());
($this->useCase)($this->testedDashboardId, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::errorWhileDeleting()->getMessage());
}
);
it(
'should present a ForbiddenResponse when the user does not have the correct role',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())
->method('canCreate')->willReturn(false);
($this->useCase)($this->testedDashboardId, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->data->getMessage())
->toBe(DashboardException::accessNotAllowedForWriting()->getMessage());
}
);
it(
'should present a NoContentResponse as ADMIN',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('existsOne')->willReturn(true);
($this->useCase)($this->testedDashboardId, $this->presenter);
expect($this->presenter->data)
->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should present a NoContentResponse as allowed CREATOR user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())
->method('canCreate')->willReturn(true);
$this->rights->expects($this->once())
->method('canDelete')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn($this->testedDashboard);
$this->writeDashboardRepository->expects($this->once())
->method('delete');
($this->useCase)($this->testedDashboardId, $this->presenter);
expect($this->presenter->data)->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should present a ForbiddenResponse as NOT allowed CREATOR user',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())
->method('canCreate')->willReturn(true);
$this->rights->expects($this->once())
->method('canDelete')->willReturn(false);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn($this->testedDashboard);
$this->writeDashboardRepository->expects($this->never())
->method('delete');
($this->useCase)($this->testedDashboardId, $this->presenter);
expect($this->presenter->data)->toBeInstanceOf(ForbiddenResponse::class);
}
);
it(
'should present a NotFoundResponse when the dashboard does not exist',
function (): void {
$this->rights->expects($this->once())
->method('hasAdminRole')->willReturn(false);
$this->rights->expects($this->once())
->method('canCreate')->willReturn(true);
$this->readDashboardRepository->expects($this->once())
->method('findOneByContact')->willReturn(null);
($this->useCase)($this->testedDashboardId, $this->presenter);
expect($this->presenter->data)->toBeInstanceOf(NotFoundResponse::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/Dashboard/Application/UseCase/DeleteDashboard/DeleteDashboardPresenterStub.php | centreon/tests/php/Core/Dashboard/Application/UseCase/DeleteDashboard/DeleteDashboardPresenterStub.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\Dashboard\Application\UseCase\DeleteDashboard;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Dashboard\Application\UseCase\DeleteDashboard\DeleteDashboardPresenterInterface;
class DeleteDashboardPresenterStub implements DeleteDashboardPresenterInterface
{
public ResponseStatusInterface|NoContentResponse $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/Dashboard/Domain/Model/DashboardRightsTest.php | centreon/tests/php/Core/Dashboard/Domain/Model/DashboardRightsTest.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\Dashboard\Domain\Model;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Dashboard\Domain\Model\DashboardRights;
beforeEach(function (): void {
$this->createContact = function (bool $viewer, bool $creator, bool $admin, bool $superAdmin) {
$contact = $this->createMock(ContactInterface::class);
$contact->expects($this->never())->method('isAdmin');
$contact->expects($this->atLeast($viewer || $creator || $admin ? 1 : 0))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_HOME_DASHBOARD_VIEWER, $viewer],
[Contact::ROLE_HOME_DASHBOARD_CREATOR, $creator],
[Contact::ROLE_HOME_DASHBOARD_ADMIN, $admin],
]
);
return $contact;
};
});
it(
'should work properly without any rights',
function (): void {
$rights = new DashboardRights(
($this->createContact)(
viewer: false,
creator: false,
admin: false,
superAdmin: false,
)
);
expect($rights->canCreate())->toBeFalse()
->and($rights->canAccess())->toBeFalse()
->and($rights->hasAdminRole())->toBeFalse()
->and($rights->hasCreatorRole())->toBeFalse()
->and($rights->hasViewerRole())->toBeFalse();
}
);
it(
'should work properly with a centreon dashboard VIEWER',
function (): void {
$rights = new DashboardRights(
($this->createContact)(
viewer: true,
creator: false,
admin: false,
superAdmin: false,
)
);
expect($rights->canCreate())->toBeFalse()
->and($rights->canAccess())->toBeTrue()
->and($rights->hasAdminRole())->toBeFalse()
->and($rights->hasCreatorRole())->toBeFalse()
->and($rights->hasViewerRole())->toBeTrue();
}
);
it(
'should work properly with a centreon dashboard CREATOR',
function (): void {
$rights = new DashboardRights(
($this->createContact)(
viewer: false,
creator: true,
admin: false,
superAdmin: false,
)
);
expect($rights->canCreate())->toBeTrue()
->and($rights->canAccess())->toBeTrue()
->and($rights->hasAdminRole())->toBeFalse()
->and($rights->hasCreatorRole())->toBeTrue()
->and($rights->hasViewerRole())->toBeTrue();
}
);
it(
'should work properly with a centreon dashboard ADMIN',
function (): void {
$rights = new DashboardRights(
($this->createContact)(
viewer: false,
creator: false,
admin: true,
superAdmin: false,
)
);
expect($rights->canCreate())->toBeTrue()
->and($rights->canAccess())->toBeTrue()
->and($rights->hasAdminRole())->toBeTrue()
->and($rights->hasCreatorRole())->toBeTrue()
->and($rights->hasViewerRole())->toBeTrue();
}
);
it(
'should work properly with a centreon administrator',
function (): void {
$rights = new DashboardRights(
($this->createContact)(
viewer: false,
creator: false,
admin: false,
superAdmin: true,
)
);
expect($rights->canCreate())->toBeFalse()
->and($rights->canAccess())->toBeFalse()
->and($rights->hasAdminRole())->toBeFalse()
->and($rights->hasCreatorRole())->toBeFalse()
->and($rights->hasViewerRole())->toBeFalse();
}
);
| 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/Dashboard/Domain/Model/DashboardTest.php | centreon/tests/php/Core/Dashboard/Domain/Model/DashboardTest.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\Dashboard\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
beforeEach(function (): void {
$this->testedCreatedAt = new \DateTimeImmutable('2023-05-09T12:00:00+00:00');
$this->testedUpdatedAt = new \DateTimeImmutable('2023-05-09T16:00:00+00:00');
$this->testedGlobalRefresh = new Refresh(RefreshType::Manual, 30);
$this->createDashboard = fn (array $fields = []): Dashboard => new Dashboard(
$fields['id'] ?? 1,
$fields['name'] ?? 'dashboard-name',
\array_key_exists('created_by', $fields) ? $fields['created_by'] : 2,
\array_key_exists('updated_by', $fields) ? $fields['updated_by'] : 3,
$this->testedCreatedAt,
$this->testedUpdatedAt,
$this->testedGlobalRefresh,
);
});
it('should return properly set dashboard instance', function (): void {
$dashboard = ($this->createDashboard)();
expect($dashboard->getId())->toBe(1)
->and($dashboard->getName())->toBe('dashboard-name')
->and($dashboard->getDescription())->toBe(null)
->and($dashboard->getUpdatedAt()->getTimestamp())->toBe($this->testedUpdatedAt->getTimestamp())
->and($dashboard->getCreatedAt()->getTimestamp())->toBe($this->testedCreatedAt->getTimestamp())
->and($dashboard->getCreatedBy())->toBe(2)
->and($dashboard->getUpdatedBy())->toBe(3)
->and($dashboard->getRefresh())->toBe($this->testedGlobalRefresh);
});
// mandatory fields
it(
'should throw an exception when dashboard name is an empty string',
fn () => ($this->createDashboard)(['name' => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString('Dashboard::name')->getMessage()
);
// string field trimmed
it('should return trim the field name after construct', function (): void {
$dashboard = new Dashboard(
1,
' abcd ',
1,
1,
new \DateTimeImmutable(),
new \DateTimeImmutable(),
new Refresh(RefreshType::Global, null)
);
expect($dashboard->getName())->toBe('abcd');
});
it('should return trim the field description', function (): void {
$dashboard = (new Dashboard(
1,
'abcd',
1,
1,
new \DateTimeImmutable(),
new \DateTimeImmutable(),
new Refresh(RefreshType::Global, null)
))->setDescription(' abcd ');
expect($dashboard->getDescription())->toBe('abcd');
});
// updatedAt change
it(
'should NOT change the updatedAt field',
function (): void {
$updatedAtBefore = $this->testedUpdatedAt->getTimestamp();
$dashboard = ($this->createDashboard)();
$updatedAtAfter = $dashboard->getUpdatedAt()->getTimestamp();
expect($updatedAtAfter)->toBe($updatedAtBefore);
}
);
// too long fields
foreach (
[
'name' => Dashboard::MAX_NAME_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.
// 'description' => Dashboard::MAX_DESCRIPTION_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when dashboard {$field} is too long",
fn () => ($this->createDashboard)([$field => $tooLong])
)->throws(
AssertionException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "Dashboard::{$field}")->getMessage()
);
}
// not positive integers
foreach (
[
'created_by' => 'createdBy',
'updated_by' => 'updatedBy',
] as $field => $propertyName
) {
it(
"should throw an exception when dashboard {$field} is not a positive integer",
fn () => ($this->createDashboard)([$field => 0])
)->throws(
AssertionException::class,
AssertionException::positiveInt(0, 'Dashboard::' . $propertyName)->getMessage()
);
}
// nullable field allowed
foreach (
[
'created_by' => 'createdBy',
'updated_by' => 'updatedBy',
] as $field => $propertyName
) {
it(
"should return the NULL field {$field} after construct",
function () use ($field, $propertyName): void {
$dashboard = ($this->createDashboard)([$field => null]);
$valueFromGetter = $dashboard->{'get' . $propertyName}();
expect($valueFromGetter)->toBeNull();
}
);
}
| 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/Dashboard/Domain/Model/NewDashboardTest.php | centreon/tests/php/Core/Dashboard/Domain/Model/NewDashboardTest.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\Dashboard\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\NewDashboard;
use Core\Dashboard\Domain\Model\Refresh;
beforeEach(function (): void {
$this->createDashboard = static function (array $fields = []): NewDashboard {
$refresh = new Refresh(Refresh\RefreshType::Global, null);
$dashboard = new NewDashboard(
$fields['name'] ?? 'dashboard-name',
$fields['created_by'] ?? 2,
$refresh
);
$dashboard->setDescription($fields['description'] ?? 'dashboard-description');
$dashboard->setUpdatedBy($fields['updated_by'] ?? 3);
return $dashboard;
};
});
it('should return properly set dashboard instance', function (): void {
$now = time();
$dashboard = ($this->createDashboard)();
expect($dashboard->getName())->toBe('dashboard-name')
->and($dashboard->getDescription())->toBe('dashboard-description')
->and($dashboard->getCreatedAt()->getTimestamp())->toBeGreaterThanOrEqual($now)
->and($dashboard->getUpdatedAt()->getTimestamp())->toBeGreaterThanOrEqual($now)
->and($dashboard->getCreatedBy())->toBe(2)
->and($dashboard->getUpdatedBy())->toBe(3);
});
// mandatory fields
it(
'should throw an exception when dashboard name is an empty string',
fn () => ($this->createDashboard)(['name' => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString('NewDashboard::name')->getMessage()
);
// string field trimmed
foreach (
[
'name',
'description',
] as $field
) {
it(
"should return trim the field {$field} after construct",
function () use ($field): void {
$dashboard = ($this->createDashboard)([$field => ' abcd ']);
$valueFromGetter = $dashboard->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// updatedAt change
it(
'should change the updatedAt field',
function (): void {
$updatedAtBefore = time();
$dashboard = ($this->createDashboard)();
$updatedAtAfter = $dashboard->getUpdatedAt()->getTimestamp();
expect($updatedAtAfter)->toBeGreaterThanOrEqual($updatedAtBefore);
}
);
// too long fields
foreach (
[
'name' => Dashboard::MAX_NAME_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.
// 'description' => NewDashboard::MAX_DESCRIPTION_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when dashboard {$field} is too long",
fn () => ($this->createDashboard)([$field => $tooLong])
)->throws(
AssertionException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "NewDashboard::{$field}")->getMessage()
);
}
// not positive integers
foreach (
[
'created_by' => 'createdBy',
'updated_by' => 'updatedBy',
] as $field => $propertyName
) {
it(
"should throw an exception when dashboard {$field} is not a positive integer",
fn () => ($this->createDashboard)([$field => 0])
)->throws(
AssertionException::class,
AssertionException::positiveInt(0, 'NewDashboard::' . $propertyName)->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/Dashboard/Domain/Model/DashboardPanelTest.php | centreon/tests/php/Core/Dashboard/Domain/Model/DashboardPanelTest.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\Dashboard\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Dashboard\Domain\Model\DashboardPanel;
beforeEach(function (): void {
$this->createPanel = fn (array $fields = []): DashboardPanel => new DashboardPanel(
id: $fields['id'] ?? 123,
name: $fields['name'] ?? 'panel-name',
widgetType: $fields['widgetType'] ?? 'widget-type',
widgetSettings: $fields['widgetSettings'] ?? ['foo' => 'bar'],
layoutX: $fields['layoutX'] ?? 1,
layoutY: $fields['layoutY'] ?? 2,
layoutWidth: $fields['layoutWidth'] ?? 3,
layoutHeight: $fields['layoutHeight'] ?? 4,
layoutMinWidth: $fields['layoutMinWidth'] ?? 5,
layoutMinHeight: $fields['layoutMinHeight'] ?? 6,
);
});
it('should return properly set dashboard panel instance', function (): void {
$panel = ($this->createPanel)();
expect($panel->getId())->toBe(123)
->and($panel->getName())->toBe('panel-name')
->and($panel->getWidgetType())->toBe('widget-type')
->and($panel->getWidgetSettings())->toBe(['foo' => 'bar'])
->and($panel->getLayoutX())->toBe(1)
->and($panel->getLayoutY())->toBe(2)
->and($panel->getLayoutWidth())->toBe(3)
->and($panel->getLayoutHeight())->toBe(4)
->and($panel->getLayoutMinWidth())->toBe(5)
->and($panel->getLayoutMinHeight())->toBe(6);
});
// mandatory fields
foreach (
[
'widgetType',
] as $field
) {
it(
"should throw an exception when dashboard panel {$field} is an empty string",
fn () => ($this->createPanel)([$field => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString("DashboardPanel::{$field}")->getMessage()
);
}
// string field trimmed
foreach (
[
'name',
'widgetType',
] as $field
) {
it(
"should return trim the field {$field} after construct",
function () use ($field): void {
$dashboard = ($this->createPanel)([$field => ' abcd ']);
$valueFromGetter = $dashboard->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => DashboardPanel::MAX_NAME_LENGTH,
'widgetType' => DashboardPanel::MAX_WIDGET_TYPE_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when dashboard panel {$field} is too long",
fn () => ($this->createPanel)([$field => $tooLong])
)->throws(
AssertionException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "DashboardPanel::{$field}")->getMessage()
);
}
// not in range integers
foreach (
[
'layoutX' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutY' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutWidth' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutHeight' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutMinWidth' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutMinHeight' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
] as $field => [$min, $max]
) {
it(
"should throw an exception when dashboard panel {$field} is too low",
fn () => ($this->createPanel)([$field => $min - 1])
)->throws(
AssertionException::class,
AssertionException::range($min - 1, $min, $max, 'DashboardPanel::' . $field)->getMessage()
);
it(
"should throw an exception when dashboard panel {$field} is too high",
fn () => ($this->createPanel)([$field => $max + 1])
)->throws(
AssertionException::class,
AssertionException::range($max + 1, $min, $max, 'DashboardPanel::' . $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/Dashboard/Domain/Model/NewDashboardPanelTest.php | centreon/tests/php/Core/Dashboard/Domain/Model/NewDashboardPanelTest.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\Dashboard\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Dashboard\Domain\Model\DashboardPanel;
use Core\Dashboard\Domain\Model\NewDashboardPanel;
beforeEach(function (): void {
$this->createPanel = function (array $fields = []): NewDashboardPanel {
$panel = new NewDashboardPanel(
name: $fields['name'] ?? 'panel-name',
widgetType: $fields['widgetType'] ?? 'widget-type'
);
$panel->setWidgetSettings($fields['widgetSettings'] ?? ['foo' => 'bar']);
$panel->setLayoutX($fields['layoutX'] ?? 1);
$panel->setLayoutY($fields['layoutY'] ?? 2);
$panel->setLayoutWidth($fields['layoutWidth'] ?? 3);
$panel->setLayoutHeight($fields['layoutHeight'] ?? 4);
$panel->setLayoutMinWidth($fields['layoutMinWidth'] ?? 5);
$panel->setLayoutMinHeight($fields['layoutMinHeight'] ?? 6);
return $panel;
};
});
it('should return properly set dashboard panel instance', function (): void {
$panel = ($this->createPanel)();
expect($panel->getName())->toBe('panel-name')
->and($panel->getWidgetType())->toBe('widget-type')
->and($panel->getWidgetSettings())->toBe(['foo' => 'bar'])
->and($panel->getLayoutX())->toBe(1)
->and($panel->getLayoutY())->toBe(2)
->and($panel->getLayoutWidth())->toBe(3)
->and($panel->getLayoutHeight())->toBe(4)
->and($panel->getLayoutMinWidth())->toBe(5)
->and($panel->getLayoutMinHeight())->toBe(6);
});
// mandatory fields
foreach (
[
'widgetType',
] as $field
) {
it(
"should throw an exception when dashboard panel {$field} is an empty string",
fn () => ($this->createPanel)([$field => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString("NewDashboardPanel::{$field}")->getMessage()
);
}
// string field trimmed
foreach (
[
'name',
'widgetType',
] as $field
) {
it(
"should return trim the field {$field} after construct",
function () use ($field): void {
$dashboard = ($this->createPanel)([$field => ' abcd ']);
$valueFromGetter = $dashboard->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => DashboardPanel::MAX_NAME_LENGTH,
'widgetType' => DashboardPanel::MAX_WIDGET_TYPE_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when dashboard panel {$field} is too long",
fn () => ($this->createPanel)([$field => $tooLong])
)->throws(
AssertionException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "NewDashboardPanel::{$field}")->getMessage()
);
}
// not in range integers
foreach (
[
'layoutX' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutY' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutWidth' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutHeight' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutMinWidth' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
'layoutMinHeight' => [DashboardPanel::MIN_SMALL_INTEGER, DashboardPanel::MAX_SMALL_INTEGER],
] as $field => [$min, $max]
) {
it(
"should throw an exception when dashboard panel {$field} is too low",
fn () => ($this->createPanel)([$field => $min - 1])
)->throws(
AssertionException::class,
AssertionException::range($min - 1, $min, $max, 'NewDashboardPanel::' . $field)->getMessage()
);
it(
"should throw an exception when dashboard panel {$field} is too high",
fn () => ($this->createPanel)([$field => $max + 1])
)->throws(
AssertionException::class,
AssertionException::range($max + 1, $min, $max, 'NewDashboardPanel::' . $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/Dashboard/Domain/Model/Share/DashboardContactShareTest.php | centreon/tests/php/Core/Dashboard/Domain/Model/Share/DashboardContactShareTest.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\Dashboard\Domain\Model\Share;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Domain\Model\Share\DashboardContactShare;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
beforeEach(function (): void {
$this->createDashboardContactShare = fn (array $fields = []): DashboardContactShare => new DashboardContactShare(
new Dashboard(
99,
'dashboard-name',
null,
null,
new \DateTimeImmutable(),
new \DateTimeImmutable(),
new Refresh(RefreshType::Global, null),
),
$fields['id'] ?? 1,
$fields['name'] ?? 'contact-name',
$fields['email'] ?? 'contact-email',
DashboardSharingRoleConverter::fromString($fields['role'] ?? 'viewer')
);
});
it(
'should return properly set a dashboard contact share instance',
function (): void {
$share = ($this->createDashboardContactShare)();
expect($share->getDashboard()->getId())->toBe(99)
->and($share->getContactId())->toBe(1)
->and($share->getContactName())->toBe('contact-name')
->and($share->getRole()->name)->toBe(DashboardSharingRole::Viewer->name);
}
);
// mandatory fields
it(
'should throw an exception when dashboard contact share name is an empty string',
fn () => ($this->createDashboardContactShare)(['name' => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString('DashboardContactShare::contactName')->getMessage()
);
it(
'should throw an exception when dashboard contact share email is an empty string',
fn () => ($this->createDashboardContactShare)(['email' => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString('DashboardContactShare::contactEmail')->getMessage()
);
// not positive integers
it(
'should throw an exception when dashboard contact share id is not a positive integer',
fn () => ($this->createDashboardContactShare)(['id' => 0])
)->throws(
AssertionException::class,
AssertionException::positiveInt(0, 'DashboardContactShare::contactId')->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/Dashboard/Domain/Model/Share/DashboardContactGroupShareTest.php | centreon/tests/php/Core/Dashboard/Domain/Model/Share/DashboardContactGroupShareTest.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\Dashboard\Domain\Model\Share;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Domain\Model\Share\DashboardContactGroupShare;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
beforeEach(function (): void {
$this->createDashboardContactGroupShare = fn (array $fields = []): DashboardContactGroupShare => new DashboardContactGroupShare(
new Dashboard(
99,
'dashboard-name',
null,
null,
new \DateTimeImmutable(),
new \DateTimeImmutable(),
new Refresh(RefreshType::Global, null),
),
$fields['id'] ?? 1,
$fields['name'] ?? 'contact-group-name',
DashboardSharingRoleConverter::fromString($fields['role'] ?? 'viewer')
);
});
it(
'should return properly set a dashboard contact group share instance',
function (): void {
$share = ($this->createDashboardContactGroupShare)();
expect($share->getDashboard()->getId())->toBe(99)
->and($share->getContactGroupId())->toBe(1)
->and($share->getContactGroupName())->toBe('contact-group-name')
->and($share->getRole()->name)->toBe(DashboardSharingRole::Viewer->name);
}
);
// mandatory fields
it(
'should throw an exception when dashboard contact group share name is an empty string',
fn () => ($this->createDashboardContactGroupShare)(['name' => ''])
)->throws(
AssertionException::class,
AssertionException::notEmptyString('DashboardContactGroupShare::contactGroupName')->getMessage()
);
// not positive integers
it(
'should throw an exception when dashboard contact group share id is not a positive integer',
fn () => ($this->createDashboardContactGroupShare)(['id' => 0])
)->throws(
AssertionException::class,
AssertionException::positiveInt(0, 'DashboardContactGroupShare::contactGroupId')->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/Dashboard/Domain/Model/Share/DashboardSharingRolesTest.php | centreon/tests/php/Core/Dashboard/Domain/Model/Share/DashboardSharingRolesTest.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\Dashboard\Domain\Model\Share;
use Core\Dashboard\Domain\Model\Dashboard;
use Core\Dashboard\Domain\Model\Refresh;
use Core\Dashboard\Domain\Model\Refresh\RefreshType;
use Core\Dashboard\Domain\Model\Role\DashboardSharingRole;
use Core\Dashboard\Domain\Model\Share\DashboardContactGroupShare;
use Core\Dashboard\Domain\Model\Share\DashboardContactShare;
use Core\Dashboard\Domain\Model\Share\DashboardSharingRoles;
use Core\Dashboard\Infrastructure\Model\DashboardSharingRoleConverter;
beforeEach(function (): void {
$this->testedDashboard = new Dashboard(
1,
'dashboard-name',
null,
null,
new \DateTimeImmutable(),
new \DateTimeImmutable(),
new Refresh(RefreshType::Global, null)
);
$this->createContactShare = fn (DashboardSharingRole $role) => new DashboardContactShare(
$this->testedDashboard,
2,
'name',
'email',
$role
);
$this->createContactGroupShares = function (DashboardSharingRole ...$roles) {
$shares = [];
foreach ($roles as $index => $role) {
$shares[] = new DashboardContactGroupShare(
$this->testedDashboard,
3 + $index,
'name',
$role
);
}
return $shares;
};
});
it(
'should return properly set a dashboard sharing roles instance',
function (): void {
$sharingRoles = new DashboardSharingRoles(
$this->testedDashboard,
$testedContactShare = ($this->createContactShare)(DashboardSharingRole::Viewer),
$testedContactGroupShare = ($this->createContactGroupShares)(DashboardSharingRole::Viewer),
);
expect($sharingRoles->getDashboard())->toBe($this->testedDashboard)
->and($sharingRoles->getContactShare())->toBe($testedContactShare)
->and($sharingRoles->getContactGroupShares()[0])->toBe($testedContactGroupShare[0]);
}
);
it(
'should return the correct most permissive role',
function (
?string $expected,
?string $contactRole,
array $contactGroupRoles,
): void {
$toEnum = static fn (?string $string): ?DashboardSharingRole => $string
? DashboardSharingRoleConverter::fromString($string)
: null;
$sharingRoles = new DashboardSharingRoles(
$this->testedDashboard,
$contactRole ? ($this->createContactShare)($toEnum($contactRole)) : null,
($this->createContactGroupShares)(...array_map($toEnum, $contactGroupRoles)),
);
expect($sharingRoles->getTheMostPermissiveRole()?->name)->toBe($toEnum($expected)?->name);
}
)->with([
[null, null, []],
['viewer', null, ['viewer']],
['viewer', 'viewer', []],
['viewer', 'viewer', ['viewer']],
['viewer', 'viewer', ['viewer', 'viewer']],
['editor', null, ['editor']],
['editor', null, ['viewer', 'editor']],
['editor', null, ['editor', 'viewer']],
['editor', 'viewer', ['editor']],
['editor', 'editor', ['viewer', 'viewer']],
]);
| 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/Macro/Domain/Model/MacroManagerTest.php | centreon/tests/php/Core/Macro/Domain/Model/MacroManagerTest.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\HostTemplate\Domain\Model;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Macro\Domain\Model\Macro;
use Core\Macro\Domain\Model\MacroDifference;
use Core\Macro\Domain\Model\MacroManager;
it('should resolve command macro inheritance', function (): void {
$macros = [
$macroA = new CommandMacro(1, CommandMacroType::Host, 'macroA'),
$macroB = new CommandMacro(1, CommandMacroType::Host, 'macroB'),
$macroC1 = new CommandMacro(1, CommandMacroType::Host, 'macroC'),
$macroC2 = new CommandMacro(1, CommandMacroType::Host, 'macroC'),
];
$commandMacros = MacroManager::resolveInheritanceForCommandMacro($macros);
expect($commandMacros)->toBe([
$macroA->getName() => $macroA,
$macroB->getName() => $macroB,
$macroC1->getName() => $macroC1,
]);
});
it('should set macros order property', function (): void {
$macroA = new Macro(null, 1, 'nameA', 'valueA');
$macroA->setOrder(0);
$macroB = new Macro(null, 1, 'nameB', 'valueB');
$macroB->setOrder(1);
$macroC = new Macro(null, 1, 'nameC', 'valueC');
$macroC->setOrder(2);
$macroD = new Macro(null, 1, 'nameD', 'valueD');
$macroD->setOrder(3);
$macroE = new Macro(null, 2, 'nameE', 'valueE');
$macroF = new Macro(null, 1, 'nameF', 'valueF');
$directMacros = [
$macroA->getName() => $macroA,
$macroB->getName() => $macroB,
$macroC->getName() => $macroC,
$macroD->getName() => $macroD,
];
$macros = [
$macroA->getName() => $macroA,
$macroB->getName() => $macroB,
$macroD->getName() => $macroD,
$macroE->getName() => $macroE,
$macroF->getName() => $macroF,
];
$macrosDiff = new MacroDifference();
$macrosDiff->addedMacros = [
$macroF->getName() => $macroF,
];
$macrosDiff->updatedMacros = [
$macroB->getName() => $macroB,
];
$macrosDiff->removedMacros = [
$macroC->getName() => $macroC,
];
$macrosDiff->unchangedMacros = [
$macroA->getName() => $macroA,
$macroD->getName() => $macroD,
$macroE->getName() => $macroE,
];
MacroManager::setOrder($macrosDiff, $macros, $directMacros);
expect($macroA->getOrder())->toBe(0)
->and($macroB->getOrder())->toBe(1)
->and($macroD->getOrder())->toBe(2)
->and($macroF->getOrder())->toBe(3);
});
| 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/Macro/Domain/Model/MacroTest.php | centreon/tests/php/Core/Macro/Domain/Model/MacroTest.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\HostMacro\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Macro\Domain\Model\Macro;
it('should return properly set host macro instance', function (): void {
$macro = new Macro(null, 1, 'macroName', 'macroValue');
$macro->setIsPassword(true);
$macro->setDescription('macroDescription');
expect($macro->getOwnerId())->toBe(1)
->and($macro->getName())->toBe('MACRONAME')
->and($macro->getValue())->toBe('macroValue');
});
it('should throw an exception when host macro name is empty', function (): void {
new Macro(null, 1, '', 'macroValue');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Macro::name')->getMessage()
);
it('should throw an exception when host macro name is too long', function (): void {
new Macro(null, 1, str_repeat('a', Macro::MAX_NAME_LENGTH + 1), 'macroValue');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('A', Macro::MAX_NAME_LENGTH + 1),
Macro::MAX_NAME_LENGTH + 1,
Macro::MAX_NAME_LENGTH,
'Macro::name'
)->getMessage()
);
it('should throw an exception when host macro value is too long', function (): void {
new Macro(null, 1, 'macroName', str_repeat('a', Macro::MAX_VALUE_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Macro::MAX_VALUE_LENGTH + 1),
Macro::MAX_VALUE_LENGTH + 1,
Macro::MAX_VALUE_LENGTH,
'Macro::value'
)->getMessage()
);
it('should throw an exception when host macro description is too long', function (): void {
$macro = new Macro(null, 1, 'macroName', 'macroValue');
$macro->setDescription(str_repeat('a', Macro::MAX_DESCRIPTION_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Macro::MAX_DESCRIPTION_LENGTH + 1),
Macro::MAX_DESCRIPTION_LENGTH + 1,
Macro::MAX_DESCRIPTION_LENGTH,
'Macro::description'
)->getMessage()
);
it('should resolve macro inheritance', function (): void {
$templateId = 1;
$templateInheritanceLine = [2, 3, 4];
$macros = [
$macroA = new Macro(null, 1, 'nameA', 'valueA'),
$macroB2 = new Macro(null, 1, 'nameB', 'valueB-edited'),
$macroB1 = new Macro(null, 4, 'nameB', 'valueB-original'),
$macroC = new Macro(null, 2, 'nameC', 'valueC'),
$macroD = new Macro(null, 3, 'nameD', 'valueD'),
$macroE2 = new Macro(null, 3, 'nameE', 'valueE-edited'),
$macroE1 = new Macro(null, 4, 'nameE', 'valueE-original'),
];
[$directMacros, $inheritedMacros]
= Macro::resolveInheritance($macros, $templateInheritanceLine, $templateId);
expect($directMacros)->toBe([
$macroA->getName() => $macroA,
$macroB2->getName() => $macroB2,
])
->and($inheritedMacros)->toBe([
$macroC->getName() => $macroC,
$macroD->getName() => $macroD,
$macroE2->getName() => $macroE2,
$macroB1->getName() => $macroB1,
]);
});
| 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/Macro/Domain/Model/MacroDifferenceTest.php | centreon/tests/php/Core/Macro/Domain/Model/MacroDifferenceTest.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\HostMacro\Domain\Model;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Macro\Domain\Model\Macro;
use Core\Macro\Domain\Model\MacroDifference;
beforeEach(function (): void {
// DIRECT MACROS - not changed
$this->hostMacroA = new Macro(null, 1, 'NAMEA', 'valueA');
$this->hostMacroB = new Macro(null, 1, 'NAMEB', 'valueB');
// DIRECT MACROS - deleted
$this->hostMacroC = new Macro(null, 1, 'NAMEC', 'valueC');
// DIRECT MACROS - added
$this->hostMacroD = new Macro(null, 1, 'NAMED', 'valueD');
// DIRECT MACROS - value changed => updated
$this->hostMacroE = new Macro(null, 1, 'NAMEE', 'valueE');
$this->hostMacroE_edit = new Macro(null, 1, 'NAMEE', 'valueE_edit');
// DIRECT MACROS - description changed => updated
$this->hostMacroF = new Macro(null, 1, 'NAMEF', 'valueF');
$this->hostMacroF->setDescription('descriptionF');
$this->hostMacroF_edit = new Macro(null, 1, 'NAMEF', 'valueF');
$this->hostMacroF_edit->setDescription('descriptionF_edit');
// DIRECT MACROS - isPassword changed => updated
$this->hostMacroG = new Macro(null, 1, 'NAMEG', 'valueG');
$this->hostMacroG_edit = new Macro(null, 1, 'NAMEG', 'valueG');
$this->hostMacroG_edit->setIsPassword(true);
// INHERITED MACROS - not changed
$this->hostMacroH = new Macro(null, 2, 'NAMEH', 'valueH');
$this->hostMacroH_edit = new Macro(null, 1, 'NAMEH', 'valueH');
// INHERITED MACROS - value changed => added
$this->hostMacroI = new Macro(null, 2, 'NAMEI', 'valueI');
$this->hostMacroI_edit = new Macro(null, 1, 'NAMEI', 'valueI_edit');
// INHERITED MACROS - isPassword changed => added
$this->hostMacroJ = new Macro(null, 2, 'NAMEJ', 'valueJ');
$this->hostMacroJ_edit = new Macro(null, 1, 'NAMEJ', 'valueJ');
$this->hostMacroJ_edit->setIsPassword(true);
// INHERITED MACROS - set description on unchanged inherited macro => common
$this->hostMacroK = new Macro(null, 2, 'NAMEK', 'valueK');
$this->hostMacroK_edit = new Macro(null, 1, 'NAMEK', 'valueK');
$this->hostMacroK_edit->setDescription('descriptionK');
// INHERITED MACROS - value reverted to inherted => deleted
$this->hostMacroL_inherited = new Macro(null, 2, 'NAMEL', 'valueL_inherit');
$this->hostMacroL = new Macro(null, 1, 'NAMEL', 'valueL');
$this->hostMacroL_edit = new Macro(null, 1, 'NAMEL', 'valueL_inherit');
// COMMAND MACROS - value is set => added
$this->commandMacroM = new CommandMacro(1, CommandMacroType::Host, 'NAMEM');
$this->hostMacroM = new Macro(null, 1, 'NAMEM', 'valueM');
// COMMAND MACROS - isPassword is set => added
$this->commandMacroN = new CommandMacro(1, CommandMacroType::Host, 'NAMEN');
$this->hostMacroN = new Macro(null, 1, 'NAMEN', '');
$this->hostMacroN->setIsPassword(true);
// COMMAND MACROS - value is reverted/let to empty => deleted
$this->commandMacroO = new CommandMacro(1, CommandMacroType::Host, 'NAMEO');
$this->hostMacroO = new Macro(null, 1, 'NAMEO', 'valueO');
$this->hostMacroO_edit = new Macro(null, 1, 'NAMEO', '');
});
it('should compute macros has expected', function (): void {
$directMacros = [
$this->hostMacroA->getName() => $this->hostMacroA,
$this->hostMacroB->getName() => $this->hostMacroB,
$this->hostMacroC->getName() => $this->hostMacroC,
$this->hostMacroE->getName() => $this->hostMacroE,
$this->hostMacroF->getName() => $this->hostMacroF,
$this->hostMacroG->getName() => $this->hostMacroG,
$this->hostMacroL->getName() => $this->hostMacroL,
$this->hostMacroO->getName() => $this->hostMacroO,
];
$inheritedMacros = [
$this->hostMacroH->getName() => $this->hostMacroH,
$this->hostMacroI->getName() => $this->hostMacroI,
$this->hostMacroJ->getName() => $this->hostMacroJ,
$this->hostMacroK->getName() => $this->hostMacroK,
$this->hostMacroL_inherited->getName() => $this->hostMacroL_inherited,
];
$commandMacros = [
$this->commandMacroM->getName() => $this->commandMacroM,
$this->commandMacroN->getName() => $this->commandMacroN,
$this->commandMacroO->getName() => $this->commandMacroO,
];
$afterMacros = [
$this->hostMacroA->getName() => $this->hostMacroA,
$this->hostMacroB->getName() => $this->hostMacroB,
$this->hostMacroD->getName() => $this->hostMacroD,
$this->hostMacroE_edit->getName() => $this->hostMacroE_edit,
$this->hostMacroF_edit->getName() => $this->hostMacroF_edit,
$this->hostMacroG_edit->getName() => $this->hostMacroG_edit,
$this->hostMacroH_edit->getName() => $this->hostMacroH_edit,
$this->hostMacroI_edit->getName() => $this->hostMacroI_edit,
$this->hostMacroJ_edit->getName() => $this->hostMacroJ_edit,
$this->hostMacroK_edit->getName() => $this->hostMacroK_edit,
$this->hostMacroL_edit->getName() => $this->hostMacroL_edit,
$this->hostMacroM->getName() => $this->hostMacroM,
$this->hostMacroN->getName() => $this->hostMacroN,
$this->hostMacroO_edit->getName() => $this->hostMacroO_edit,
];
$addedMacros = [
$this->hostMacroD->getName() => $this->hostMacroD,
$this->hostMacroI_edit->getName() => $this->hostMacroI_edit,
$this->hostMacroJ_edit->getName() => $this->hostMacroJ_edit,
$this->hostMacroM->getName() => $this->hostMacroM,
$this->hostMacroN->getName() => $this->hostMacroN,
];
$removedMacros = [
$this->hostMacroL->getName() => $this->hostMacroL,
$this->hostMacroO->getName() => $this->hostMacroO,
$this->hostMacroC->getName() => $this->hostMacroC,
];
$updatedMacros = [
$this->hostMacroE_edit->getName() => $this->hostMacroE_edit,
$this->hostMacroF_edit->getName() => $this->hostMacroF_edit,
$this->hostMacroG_edit->getName() => $this->hostMacroG_edit,
];
$unchangedMacros = [
$this->hostMacroA->getName() => $this->hostMacroA,
$this->hostMacroB->getName() => $this->hostMacroB,
$this->hostMacroH_edit->getName() => $this->hostMacroH_edit,
$this->hostMacroK_edit->getName() => $this->hostMacroK_edit,
];
$macrosDiff = new MacroDifference();
$macrosDiff->compute($directMacros, $inheritedMacros, $commandMacros, $afterMacros);
expect($macrosDiff->addedMacros)->toEqual($addedMacros)
->and($macrosDiff->updatedMacros)->toEqual($updatedMacros)
->and($macrosDiff->removedMacros)->toEqual($removedMacros)
->and($macrosDiff->unchangedMacros)->toEqual($unchangedMacros);
});
| 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/Application/InheritanceManagerTest.php | centreon/tests/php/Core/Host/Application/InheritanceManagerTest.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\Application;
use Core\Host\Application\InheritanceManager;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
it('return inheritance line in the expected order', function (): void {
$hostId = 1;
$parents = [
['child_id' => 5, 'parent_id' => 9, 'order' => 2],
['child_id' => 1, 'parent_id' => 2, 'order' => 0],
['child_id' => 2, 'parent_id' => 3, 'order' => 0],
['child_id' => 2, 'parent_id' => 4, 'order' => 1],
['child_id' => 3, 'parent_id' => 4, 'order' => 0],
['child_id' => 4, 'parent_id' => 5, 'order' => 0],
['child_id' => 5, 'parent_id' => 8, 'order' => 1],
['child_id' => 5, 'parent_id' => 6, 'order' => 0],
['child_id' => 6, 'parent_id' => 7, 'order' => 0],
];
$inheritanceLine = InheritanceManager::findInheritanceLine($hostId, $parents);
expect($inheritanceLine)->toBe([2, 3, 4, 5, 6, 7, 8, 9]);
});
it('return false when a circular inheritance is detected', function (): void {
$hostId = 1;
$parents = [2, 5];
$manager = new InheritanceManager(
$this->repository = $this->createMock(ReadHostTemplateRepositoryInterface::class)
);
$this->repository
->expects($this->exactly(2))
->method('findParents')
->willReturnMap([
[
2,
[
['child_id' => 2, 'parent_id' => 3, 'order' => 0],
['child_id' => 3, 'parent_id' => 4, 'order' => 0],
],
],
[
5,
[
['child_id' => 5, 'parent_id' => 6, 'order' => 0],
['child_id' => 6, 'parent_id' => 1, 'order' => 0],
],
],
]);
expect($manager->isValidInheritanceTree($hostId, $parents))->toBe(false);
});
it('return true when an inheritance tree is valid', function (): void {
$hostId = 1;
$parents = [2, 5];
$manager = new InheritanceManager(
$this->repository = $this->createMock(ReadHostTemplateRepositoryInterface::class)
);
$this->repository
->expects($this->exactly(2))
->method('findParents')
->willReturnMap([
[
2,
[
['child_id' => 2, 'parent_id' => 3, 'order' => 0],
['child_id' => 3, 'parent_id' => 4, 'order' => 0],
],
],
[
5,
[
['child_id' => 5, 'parent_id' => 6, 'order' => 0],
['child_id' => 6, 'parent_id' => 7, 'order' => 0],
],
],
]);
expect($manager->isValidInheritanceTree($hostId, $parents))->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/Host/Application/UseCase/AddHost/AddHostTest.php | centreon/tests/php/Core/Host/Application/UseCase/AddHost/AddHostTest.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\ServiceSeverity\Application\UseCase\AddServiceSeverity;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Option\Option;
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\InvalidArgumentResponse;
use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Domain\Common\GeoCoords;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Application\Repository\WriteRealTimeHostRepositoryInterface;
use Core\Host\Application\UseCase\AddHost\AddHost;
use Core\Host\Application\UseCase\AddHost\AddHostRequest;
use Core\Host\Application\UseCase\AddHost\AddHostResponse;
use Core\Host\Application\UseCase\AddHost\AddHostValidation;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\SnmpVersion;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Tests\Core\Host\Infrastructure\API\AddHost\AddHostPresenterStub;
beforeEach(function (): void {
$this->presenter = new AddHostPresenterStub(
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class)
);
$this->useCase = new AddHost(
writeHostRepository: $this->writeHostRepository = $this->createMock(WriteHostRepositoryInterface::class),
readHostRepository: $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
writeMonitoringServerRepository: $this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class),
readHostTemplateRepository: $this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class),
readHostCategoryRepository: $this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class),
readHostGroupRepository: $this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
writeHostCategoryRepository: $this->writeHostCategoryRepository = $this->createMock(WriteHostCategoryRepositoryInterface::class),
writeHostGroupRepository: $this->writeHostGroupRepository = $this->createMock(WriteHostGroupRepositoryInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
readHostMacroRepository: $this->readHostMacroRepository = $this->createMock(ReadHostMacroRepositoryInterface::class),
readCommandMacroRepository: $this->readCommandMacroRepository = $this->createMock(ReadCommandMacroRepositoryInterface::class),
writeHostMacroRepository: $this->writeHostMacroRepository = $this->createMock(WriteHostMacroRepositoryInterface::class),
dataStorageEngine: $this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class),
optionService: $this->optionService = $this->createMock(OptionService::class),
user: $this->user = $this->createMock(ContactInterface::class),
validation: $this->validation = $this->createMock(AddHostValidation::class),
writeVaultRepository: $this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class),
readVaultRepository: $this->readVaultRepository = $this->createMock(ReadVaultRepositoryInterface::class),
writeRealTimeHostRepository: $this->writeRealTimeHostRepository = $this->createMock(WriteRealTimeHostRepositoryInterface::class),
);
$this->inheritanceModeOption = new Option();
$this->inheritanceModeOption->setName('inheritanceMode')->setValue('1');
// Settup host
$this->request = new AddHostRequest();
$this->request->monitoringServerId = 1;
$this->request->name = ' host name ';
$this->request->address = '127.0.0.1';
$this->request->snmpVersion = SnmpVersion::Two->value;
$this->request->geoCoordinates = '48.1,12.20';
$this->request->notificationOptions = HostEventConverter::toBitFlag([HostEvent::Down, HostEvent::Unreachable]);
$this->request->alias = ' host-alias ';
$this->request->snmpCommunity = 'snmpCommunity-value';
$this->request->noteUrl = 'noteUrl-value';
$this->request->note = 'note-value';
$this->request->actionUrl = 'actionUrl-value';
$this->request->iconAlternative = 'iconAlternative-value';
$this->request->comment = 'comment-value';
$this->request->checkCommandArgs = ['arg1', 'arg2'];
$this->request->eventHandlerCommandArgs = ['arg3', ' arg4'];
$this->request->timezoneId = 1;
$this->request->severityId = 1;
$this->request->checkCommandId = 1;
$this->request->checkTimeperiodId = 1;
$this->request->maxCheckAttempts = 5;
$this->request->normalCheckInterval = 5;
$this->request->retryCheckInterval = 5;
$this->request->notificationInterval = 5;
$this->request->notificationTimeperiodId = 2;
$this->request->eventHandlerCommandId = 2;
$this->request->iconId = 1;
$this->request->firstNotificationDelay = 5;
$this->request->recoveryNotificationDelay = 5;
$this->request->acknowledgementTimeout = 5;
$this->request->freshnessThreshold = 5;
$this->request->lowFlapThreshold = 5;
$this->request->highFlapThreshold = 5;
$this->request->activeCheckEnabled = 1;
$this->request->passiveCheckEnabled = 1;
$this->request->notificationEnabled = 1;
$this->request->freshnessChecked = 1;
$this->request->flapDetectionEnabled = 1;
$this->request->eventHandlerEnabled = 1;
$this->request->addInheritedContactGroup = true;
$this->request->addInheritedContact = true;
$this->request->isActivated = false;
$this->host = new Host(
id: 1,
monitoringServerId: $this->request->monitoringServerId,
name: $this->request->name,
address: $this->request->address,
snmpVersion: SnmpVersion::from($this->request->snmpVersion),
geoCoordinates: GeoCoords::fromString($this->request->geoCoordinates),
alias: $this->request->alias,
snmpCommunity: $this->request->snmpCommunity,
noteUrl: $this->request->noteUrl,
note: $this->request->note,
actionUrl: $this->request->actionUrl,
iconAlternative: $this->request->iconAlternative,
comment: $this->request->comment,
checkCommandArgs: ['arg1', 'test2'], // $this->request->checkCommandArgs,
eventHandlerCommandArgs: $this->request->eventHandlerCommandArgs,
notificationOptions: HostEventConverter::fromBitFlag($this->request->notificationOptions),
timezoneId: $this->request->timezoneId,
severityId: $this->request->severityId,
checkCommandId: $this->request->checkCommandId,
checkTimeperiodId: $this->request->checkTimeperiodId,
notificationTimeperiodId: $this->request->notificationTimeperiodId,
eventHandlerCommandId: $this->request->eventHandlerCommandId,
iconId: $this->request->iconId,
maxCheckAttempts: $this->request->maxCheckAttempts,
normalCheckInterval: $this->request->normalCheckInterval,
retryCheckInterval: $this->request->retryCheckInterval,
notificationInterval: $this->request->notificationInterval,
firstNotificationDelay: $this->request->firstNotificationDelay,
recoveryNotificationDelay: $this->request->recoveryNotificationDelay,
acknowledgementTimeout: $this->request->acknowledgementTimeout,
freshnessThreshold: $this->request->freshnessThreshold,
lowFlapThreshold: $this->request->lowFlapThreshold,
highFlapThreshold: $this->request->highFlapThreshold,
activeCheckEnabled: YesNoDefaultConverter::fromScalar($this->request->activeCheckEnabled),
passiveCheckEnabled: YesNoDefaultConverter::fromScalar($this->request->passiveCheckEnabled),
notificationEnabled: YesNoDefaultConverter::fromScalar($this->request->notificationEnabled),
freshnessChecked: YesNoDefaultConverter::fromScalar($this->request->freshnessChecked),
flapDetectionEnabled: YesNoDefaultConverter::fromScalar($this->request->flapDetectionEnabled),
eventHandlerEnabled: YesNoDefaultConverter::fromScalar($this->request->eventHandlerEnabled),
addInheritedContactGroup: $this->request->addInheritedContactGroup,
addInheritedContact: $this->request->addInheritedContact,
isActivated: $this->request->isActivated,
);
// Settup categories
$this->categories = [
$this->categoryA = new HostCategory(12, 'cat-name-A', 'cat-alias-A'),
$this->categoryB = new HostCategory(13, 'cat-name-B', 'cat-alias-B'),
];
$this->request->categories = [$this->categoryA->getId(), $this->categoryB->getId()];
// Settup groups
$this->groups = [
$this->groupA = new HostGroup(
id: 6,
name: 'grp-name-A',
alias: 'grp-alias-A',
iconId: null,
geoCoords: null,
comment: '',
isActivated: true
),
$this->groupB = new HostGroup(
id: 7,
name: 'grp-name-B',
alias: 'grp-alias-B',
iconId: null,
geoCoords: null,
comment: '',
isActivated: true
),
];
$this->request->groups = [$this->groupA->getId(), $this->groupB->getId()];
// Settup parent templates
$this->request->templates = [4, 8];
$this->parentTemplates = [
['id' => 4, 'name' => 'template-A'],
['id' => 8, 'name' => 'template-B'],
];
// Settup macros
$this->macroA = new Macro(1, $this->host->getId(), 'macroNameA', 'macroValueA');
$this->macroA->setOrder(0);
$this->macroB = new Macro(2, $this->host->getId(), 'macroNameB', 'macroValueB');
$this->macroB->setOrder(1);
$this->commandMacro = new CommandMacro(1, CommandMacroType::Host, 'commandMacroName');
$this->commandMacros = [
$this->commandMacro->getName() => $this->commandMacro,
];
$this->hostMacros = [
$this->macroA->getName() => $this->macroA,
$this->macroB->getName() => $this->macroB,
];
$this->inheritanceInfos = [
['parent_id' => 4, 'child_id' => 1, 'order' => 1],
['parent_id' => 8, 'child_id' => 1, 'order' => 2],
];
$this->request->macros = [
[
'name' => $this->macroA->getName(),
'value' => $this->macroA->getValue(),
'is_password' => $this->macroA->isPassword(),
'description' => $this->macroA->getDescription(),
],
[
'name' => $this->macroB->getName(),
'value' => $this->macroB->getValue(),
'is_password' => $this->macroB->isPassword(),
'description' => $this->macroB->getDescription(),
],
];
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::addHost()->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->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::addNotAllowed()->getMessage());
});
it('should present a ConflictResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidName')
->willThrowException(
HostException::nameAlreadyExists(
Host::formatName($this->request->name),
$this->request->name
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::nameAlreadyExists(
Host::formatName($this->request->name),
$this->request->name
)->getMessage()
);
});
it('should present a ConflictResponse when monitoring server ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidMonitoringServer')
->willThrowException(
HostException::idDoesNotExist('monitoringServerId', $this->request->monitoringServerId)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::idDoesNotExist('monitoringServerId', $this->request->monitoringServerId)->getMessage());
});
it('should present a ConflictResponse when host severity ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidSeverity')
->willThrowException(
HostException::idDoesNotExist('severityId', $this->request->severityId)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::idDoesNotExist('severityId', $this->request->severityId)->getMessage());
});
it('should present a ConflictResponse when a host timezone ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidTimezone')
->willThrowException(
HostException::idDoesNotExist('timezoneId', $this->request->timezoneId)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::idDoesNotExist('timezoneId', $this->request->timezoneId)->getMessage());
});
it('should present a ConflictResponse when a timeperiod ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidTimePeriod')
->willThrowException(
HostException::idDoesNotExist(
'checkTimeperiodId',
$this->request->checkTimeperiodId
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idDoesNotExist(
'checkTimeperiodId',
$this->request->checkTimeperiodId
)->getMessage()
);
});
it('should present a ConflictResponse when a command ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidCommand')
->willThrowException(
HostException::idDoesNotExist(
'checkCommandId',
$this->request->checkCommandId
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idDoesNotExist(
'checkCommandId',
$this->request->checkCommandId
)->getMessage()
);
});
it('should present a ConflictResponse when the host icon ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation
->expects($this->once())
->method('assertIsValidIcon')
->willThrowException(
HostException::idDoesNotExist(
'iconId',
$this->request->iconId
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idDoesNotExist(
'iconId',
$this->request->iconId
)->getMessage()
);
});
it('should present an InvalidArgumentResponse when a field assert failed', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->request->name = '';
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->response->getMessage())
->toBe(AssertionException::notEmptyString('NewHost::name')->getMessage());
});
it('should present a ConflictResponse when a host category ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->validation
->expects($this->once())
->method('assertAreValidCategories')
->willThrowException(
HostException::idsDoNotExist(
'categories',
[$this->request->categories[1]]
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idsDoNotExist(
'categories',
[$this->request->categories[1]]
)->getMessage()
);
});
it('should present a ConflictResponse when a host group ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->validation
->expects($this->once())
->method('assertAreValidGroups')
->willThrowException(
HostException::idsDoNotExist(
'groups',
[$this->request->groups[1]]
)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idsDoNotExist(
'groups',
[$this->request->groups[1]]
)->getMessage()
);
});
it('should present a ConflictResponse when a parent template ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->validation
->expects($this->once())
->method('assertAreValidTemplates')
->willThrowException(
HostException::idsDoNotExist('templates', $this->request->templates)
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idsDoNotExist(
'templates',
$this->request->templates
)->getMessage()
);
});
it('should present an ErrorResponse if the newly created host cannot be retrieved', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->writeHostRepository
->expects($this->once())
->method('add')
->willReturn(1);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::errorWhileRetrievingObject()->getMessage());
});
it('should return created object on success (with admin user)', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->validation->expects($this->once())->method('assertIsValidMonitoringServer');
$this->validation->expects($this->once())->method('assertIsValidName');
$this->validation->expects($this->once())->method('assertIsValidSeverity');
$this->validation->expects($this->once())->method('assertIsValidTimezone');
$this->validation->expects($this->exactly(2))->method('assertIsValidTimePeriod');
$this->validation->expects($this->exactly(2))->method('assertIsValidCommand');
$this->validation->expects($this->once())->method('assertIsValidIcon');
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn(['inheritance_mode' => $this->inheritanceModeOption]);
$this->writeHostRepository
->expects($this->once())
->method('add')
->willReturn($this->host->getId());
$this->validation->expects($this->once())->method('assertAreValidCategories');
$this->writeHostCategoryRepository
->expects($this->once())
->method('linkToHost');
$this->validation->expects($this->once())->method('assertAreValidGroups');
$this->writeHostGroupRepository
->expects($this->once())
->method('linkToHost');
$this->validation->expects($this->once())->method('assertAreValidTemplates');
$this->writeHostRepository
->expects($this->exactly(2))
->method('addParent');
$this->readHostRepository
->expects($this->once())
->method('findParents')
->willReturn($this->inheritanceInfos);
$this->readHostMacroRepository
->expects($this->once())
->method('findByHostIds')
->willReturn([]);
$this->readCommandMacroRepository
->expects($this->once())
->method('findByCommandIdAndType')
->willReturn($this->commandMacros);
$this->writeHostMacroRepository
->expects($this->exactly(2))
->method('add');
$this->writeMonitoringServerRepository
->expects($this->once())
->method('notifyConfigurationChange');
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->host);
$this->readHostCategoryRepository
->expects($this->once())
->method('findByHost')
->willReturn($this->categories);
$this->readHostGroupRepository
->expects($this->once())
->method('findByHost')
->willReturn($this->groups);
$this->readHostTemplateRepository
->expects($this->once())
->method('findNamesByIds')
->willReturn(
array_combine(
array_map((fn ($row) => $row['id']), $this->parentTemplates),
array_map((fn ($row) => $row['name']), $this->parentTemplates)
)
);
$this->readHostMacroRepository
->expects($this->once())
->method('findByHostId')
->willReturn($this->hostMacros);
($this->useCase)($this->request, $this->presenter);
$response = $this->presenter->response;
expect($response)->toBeInstanceOf(AddHostResponse::class)
->and($response->id)
->toBe($this->host->getId())
->and($response->monitoringServerId)
->toBe($this->host->getMonitoringServerId())
->and($response->name)
->toBe($this->host->getName())
->and($response->address)
->toBe($this->host->getAddress())
->and($response->snmpVersion)
->toBe($this->host->getSnmpVersion()->value)
->and($response->geoCoords)
->toBe($this->host->getGeoCoordinates()?->__toString())
->and($response->alias)
->toBe($this->host->getAlias())
->and($response->snmpCommunity)
->toBe($this->host->getSnmpCommunity())
->and($response->noteUrl)
->toBe($this->host->getNoteUrl())
->and($response->note)
->toBe($this->host->getNote())
->and($response->actionUrl)
->toBe($this->host->getActionUrl())
->and($response->iconAlternative)
->toBe($this->host->getIconAlternative())
->and($response->comment)
->toBe($this->host->getComment())
->and($response->eventHandlerCommandArgs)
->toBe($this->host->getEventHandlerCommandArgs())
->and($response->checkCommandArgs)
->toBe($this->host->getCheckCommandArgs())
->and($response->notificationOptions)
->toBe(HostEventConverter::toBitFlag($this->host->getNotificationOptions()))
->and($response->timezoneId)
->toBe($this->host->getTimezoneId())
->and($response->severityId)
->toBe($this->host->getSeverityId())
->and($response->checkCommandId)
->toBe($this->host->getCheckCommandId())
->and($response->checkTimeperiodId)
->toBe($this->host->getCheckTimeperiodId())
->and($response->notificationTimeperiodId)
->toBe($this->host->getNotificationTimeperiodId())
->and($response->eventHandlerCommandId)
->toBe($this->host->getEventHandlerCommandId())
->and($response->iconId)
->toBe($this->host->getIconId())
->and($response->maxCheckAttempts)
->toBe($this->host->getMaxCheckAttempts())
->and($response->normalCheckInterval)
->toBe($this->host->getNormalCheckInterval())
->and($response->retryCheckInterval)
->toBe($this->host->getRetryCheckInterval())
->and($response->notificationInterval)
->toBe($this->host->getNotificationInterval())
->and($response->firstNotificationDelay)
->toBe($this->host->getFirstNotificationDelay())
->and($response->recoveryNotificationDelay)
->toBe($this->host->getRecoveryNotificationDelay())
->and($response->acknowledgementTimeout)
->toBe($this->host->getAcknowledgementTimeout())
->and($response->freshnessThreshold)
->toBe($this->host->getFreshnessThreshold())
->and($response->lowFlapThreshold)
->toBe($this->host->getLowFlapThreshold())
->and($response->highFlapThreshold)
->toBe($this->host->getHighFlapThreshold())
->and($response->activeCheckEnabled)
->toBe(YesNoDefaultConverter::toInt($this->host->getActiveCheckEnabled()))
->and($response->passiveCheckEnabled)
->toBe(YesNoDefaultConverter::toInt($this->host->getPassiveCheckEnabled()))
->and($response->notificationEnabled)
->toBe(YesNoDefaultConverter::toInt($this->host->getNotificationEnabled()))
->and($response->freshnessChecked)
->toBe(YesNoDefaultConverter::toInt($this->host->getFreshnessChecked()))
->and($response->flapDetectionEnabled)
->toBe(YesNoDefaultConverter::toInt($this->host->getFlapDetectionEnabled()))
->and($response->eventHandlerEnabled)
->toBe(YesNoDefaultConverter::toInt($this->host->getEventHandlerEnabled()))
->and($response->categories)
->toBe(array_map(
(fn ($category) => ['id' => $category->getId(), 'name' => $category->getName()]),
$this->categories
))
->and($response->groups)
->toBe(array_map(
(fn ($group) => ['id' => $group->getId(), 'name' => $group->getName()]),
$this->groups
))
->and($response->templates)
->toBe(array_map(
(fn ($template) => ['id' => $template['id'], 'name' => $template['name']]),
$this->parentTemplates
))
->and($response->macros)
->toBe(array_map(
(fn ($macro) => [
'id' => $macro->getId(),
'name' => $macro->getName(),
'value' => $macro->getValue(),
'isPassword' => $macro->isPassword(),
| 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/Host/Application/UseCase/AddHost/AddHostValidationTest.php | centreon/tests/php/Core/Host/Application/UseCase/AddHost/AddHostValidationTest.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\Application\UseCase\AddHost;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\UseCase\AddHost\AddHostValidation;
use Core\Host\Domain\Model\Host;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\Timezone\Application\Repository\ReadTimezoneRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(function (): void {
$this->validation = new AddHostValidation(
$this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
$this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
$this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class),
$this->readViewImgRepository = $this->createMock(ReadViewImgRepositoryInterface::class),
$this->readTimePeriodRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class),
$this->readHostSeverityRepository = $this->createMock(ReadHostSeverityRepositoryInterface::class),
$this->readTimezoneRepository = $this->createMock(ReadTimezoneRepositoryInterface::class),
$this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class),
$this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class),
$this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class)
);
});
it('throws an exception when name is already used', function (): void {
$this->readHostRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->validation->assertIsValidName('name test');
})->throws(
HostException::class,
HostException::nameAlreadyExists(Host::formatName('name test'), 'name test')->getMessage()
);
it('throws an exception when name is invalid', function (): void {
$this->readHostRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->validation->assertIsValidName('_Module_test');
})->throws(
HostException::class,
HostException::nameIsInvalid()->getMessage()
);
it('throws an exception when name contains invalid characters', function (): void {
$this->readHostRepository
->expects($this->never())
->method('existsByName');
$this->validation->assertIsValidName('hôst~3!');
})->throws(
\InvalidArgumentException::class,
'[Host::name] The value contains unauthorized characters: ~!'
);
it('does not throw when name contains only valid characters', function (): void {
$this->readHostRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
// Example with valid characters
$this->validation->assertIsValidName('valid_name123');
});
it('throws an exception when monitoring server ID does not exist', function (): void {
$this->readMonitoringServerRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidMonitoringServer(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('monitoringServerId', 1)->getMessage()
);
it('throws an exception when icon ID does not exist', function (): void {
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(false);
$this->validation->assertIsValidIcon(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('iconId', 1)->getMessage()
);
it('throws an exception when time period ID does not exist', function (): void {
$this->readTimePeriodRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidTimePeriod(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('timePeriodId', 1)->getMessage()
);
it('throws an exception when severity ID does not exist', function (): void {
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidSeverity(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('severityId', 1)->getMessage()
);
it('throws an exception when timezone ID does not exist', function (): void {
$this->readTimezoneRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidTimezone(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('timezoneId', 1)->getMessage()
);
it('throws an exception when command ID does not exist', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidCommand(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('commandId', 1)->getMessage()
);
it('throws an exception when command ID does not exist for a specific type', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('existsByIdAndCommandType')
->willReturn(false);
$this->validation->assertIsValidCommand(1, CommandType::Check);
})->throws(
HostException::class,
HostException::idDoesNotExist('commandId', 1)->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->readHostCategoryRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidCategories([1, 3]);
})->throws(
HostException::class,
HostException::idsDoNotExist('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->readAccessGroupRepository
->expects($this->once())
->method('findByContact');
$this->readHostCategoryRepository
->expects($this->once())
->method('existByAccessGroups')
->willReturn([]);
$this->validation->assertAreValidCategories([1, 3]);
})->throws(
HostException::class,
HostException::idsDoNotExist('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->readHostGroupRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidGroups([1, 3]);
})->throws(
HostException::class,
HostException::idsDoNotExist('groups', [1, 3])->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->readAccessGroupRepository
->expects($this->once())
->method('findByContact');
$this->readHostGroupRepository
->expects($this->once())
->method('existByAccessGroups')
->willReturn([]);
$this->validation->assertAreValidGroups([1, 3]);
})->throws(
HostException::class,
HostException::idsDoNotExist('groups', [1, 3])->getMessage()
);
it('throws an exception when parent template ID creates a circular inheritance', function (): void {
$this->validation->assertAreValidTemplates([1, 3], 3);
})->throws(
HostException::class,
HostException::circularTemplateInheritance()->getMessage()
);
it('throws an exception when parent template ID does not exist', function (): void {
$this->readHostTemplateRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidTemplates([1, 3], 4);
})->throws(
HostException::class,
HostException::idsDoNotExist('templates', [1, 3])->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/Application/UseCase/DeleteHost/DeleteHostTest.php | centreon/tests/php/Core/Host/Application/UseCase/DeleteHost/DeleteHostTest.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);
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
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\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Application\UseCase\DeleteHost\DeleteHost;
use Core\Host\Domain\Model\Host;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
use Tests\Core\Host\Infrastructure\API\DeleteHost\DeleteHostPresenterStub;
beforeEach(closure: function (): void {
$this->presenter = new DeleteHostPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class);
$this->useCase = new DeleteHost(
readHostRepository: $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
writeHostRepository: $this->writeHostRepository = $this->createMock(WriteHostRepositoryInterface::class),
readServiceRepository: $this->readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class),
writeServiceRepository: $this->writeServiceRepository = $this->createMock(WriteServiceRepositoryInterface::class),
contact: $this->contact = $this->createMock(ContactInterface::class),
storageEngine: $this->storageEngine = $this->createMock(DataStorageEngineInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
writeMonitoringServerRepository: $this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class),
writeVaultRepository: $this->createMock(WriteVaultRepositoryInterface::class),
readHostMacroRepository: $this->createMock(ReadHostMacroRepositoryInterface::class),
readServiceMacroRepository: $this->createMock(ReadServiceMacroRepositoryInterface::class),
);
$this->host = new Host(
id: 1,
monitoringServerId: 2,
name: 'host-name',
address: '127.0.0.1',
);
});
it('should present a ForbiddenResponse when the user has insufficient rights', function (): void {
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturnMap([[Contact::ROLE_CONFIGURATION_HOSTS_WRITE, false]]);
($this->useCase)(1, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::deleteNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the service template is not found', function (): void {
$hostId = 1;
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('exists')
->with($hostId)
->willReturn(false);
($this->useCase)($hostId, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->response->getMessage())
->toBe((new NotFoundResponse('Host'))->getMessage());
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$hostId = 1;
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('exists')
->with($hostId)
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->host);
$this->storageEngine
->expects($this->once())
->method('startTransaction');
$this->readServiceRepository
->expects($this->once())
->method('findServiceIdsExclusivelyLinkedToHostId')
->with($hostId)
->willThrowException(new Exception());
$this->storageEngine
->expects($this->once())
->method('rollbackTransaction');
($this->useCase)($hostId, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::errorWhileDeleting(new Exception())->getMessage());
});
it('should present a NoContentResponse when the service template has been deleted', function (): void {
$hostId = 1;
$serviceIdsFound = [11, 18];
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->storageEngine
->expects($this->once())
->method('startTransaction');
$this->readHostRepository
->expects($this->once())
->method('exists')
->with($hostId)
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->host);
$this->readServiceRepository
->expects($this->once())
->method('findServiceIdsExclusivelyLinkedToHostId')
->with($hostId)
->willReturn($serviceIdsFound);
$this->writeServiceRepository
->expects($this->once())
->method('deleteByIds')
->with(...$serviceIdsFound);
$this->writeHostRepository
->expects($this->once())
->method('deleteById')
->with($hostId);
$this->storageEngine
->expects($this->once())
->method('commitTransaction');
($this->useCase)(1, $this->presenter);
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/Host/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountTest.php | centreon/tests/php/Core/Host/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountTest.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\Application\UseCase\FindRealTimeHostStatusesCount;
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\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadRealTimeHostRepositoryInterface;
use Core\Host\Application\UseCase\FindRealTimeHostStatusesCount\FindRealTimeHostStatusesCount;
use Core\Host\Application\UseCase\FindRealTimeHostStatusesCount\FindRealTimeHostStatusesCountResponse;
use Core\Host\Domain\Model\HostStatusesCount;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(closure: function (): void {
$this->useCase = new FindRealTimeHostStatusesCount(
$this->user = $this->createMock(ContactInterface::class),
$this->repository = $this->createMock(ReadRealTimeHostRepositoryInterface::class),
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->requestParameters = $this->createMock(RequestParametersInterface::class),
);
$this->presenter = new FindRealTimeHostStatusesCountPresenterStub($this->createMock(PresenterFormatterInterface::class));
});
it('should present an Error response when something goes wrong in repository', function (): void {
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$exception = new \Exception();
$this->repository
->expects($this->once())
->method('findStatusesByRequestParameters')
->willThrowException($exception);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::errorWhileRetrievingHostStatusesCount()->getMessage());
});
it('should present an Error response when something goes wrong with RequestParameters', function (): void {
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->repository
->expects($this->once())
->method('findStatusesByRequestParameters')
->willThrowException(new RequestParametersTranslatorException());
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class);
});
it('should present a Forbidden response when user does not have sufficient rights', function (): void {
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->exactly(2))
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::accessNotAllowedForRealTime()->getMessage());
});
it('should present a FindRealTimeHostStatusesCountResponse when ok - ADMIN', function (): void {
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$statuses = new HostStatusesCount(totalUp: 1, totalDown: 1, totalUnreachable: 1, totalPending: 1);
$this->repository
->expects($this->once())
->method('findStatusesByRequestParameters')
->willReturn($statuses);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindRealTimeHostStatusesCountResponse::class)
->and($this->presenter->response->upStatuses)
->toBe($statuses->getTotalUp())
->and($this->presenter->response->downStatuses)
->toBe($statuses->getTotalDown())
->and($this->presenter->response->unreachableStatuses)
->toBe($statuses->getTotalUnreachable())
->and($this->presenter->response->pendingStatuses)
->toBe($statuses->getTotalPending())
->and($this->presenter->response->total)
->toBe($statuses->getTotal());
});
| 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/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountPresenterStub.php | centreon/tests/php/Core/Host/Application/UseCase/FindRealTimeHostStatusesCount/FindRealTimeHostStatusesCountPresenterStub.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\Application\UseCase\FindRealTimeHostStatusesCount;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Host\Application\UseCase\FindRealTimeHostStatusesCount\FindRealTimeHostStatusesCountPresenterInterface;
use Core\Host\Application\UseCase\FindRealTimeHostStatusesCount\FindRealTimeHostStatusesCountResponse;
class FindRealTimeHostStatusesCountPresenterStub extends AbstractPresenter implements FindRealTimeHostStatusesCountPresenterInterface
{
public FindRealTimeHostStatusesCountResponse|ResponseStatusInterface $response;
public function presentResponse(FindRealTimeHostStatusesCountResponse|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/Application/UseCase/FindHosts/FindHostsTest.php | centreon/tests/php/Core/Host/Application/UseCase/FindHosts/FindHostsTest.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\Application\UseCase\FindHosts;
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\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Contact\Domain\AdminResolver;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\UseCase\FindHosts\FindHosts;
use Core\Host\Application\UseCase\FindHosts\FindHostsResponse;
use Core\Host\Domain\Model\SmallHost;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\HostTemplate\Domain\Model\HostTemplate;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Tests\Core\Host\Infrastructure\API\FindHosts\FindHostsPresenterStub;
beforeEach(closure: function (): void {
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->hostRepository = $this->createMock(ReadHostRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->hostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class);
$this->hostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class);
$this->hostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class);
$this->presenter = new FindHostsPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->adminResolver = $this->createMock(AdminResolver::class);
$this->useCase = new FindHosts(
$this->requestParameters,
$this->user,
$this->hostRepository,
$this->accessGroupRepository,
$this->hostCategoryRepository,
$this->hostTemplateRepository,
$this->hostGroupRepository,
$this->adminResolver
);
});
it('should present a Forbidden response when a non-admin user does not have rights', function (): void {
$this->user
->expects($this->exactly(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_WRITE, false],
]
);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::listingNotAllowed()->getMessage());
});
it('should present an ErrorResponse when an error occurs concerning the request parameters', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->with(Contact::ROLE_CONFIGURATION_HOSTS_READ)
->willReturn(true);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->with($this->user)
->willThrowException(new RequestParametersTranslatorException());
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class);
});
it('should present an ErrorResponse when an exception occurs', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->with(Contact::ROLE_CONFIGURATION_HOSTS_READ)
->willReturn(true);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$exception = new \Exception();
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->with($this->user)
->willThrowException($exception);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::errorWhileSearchingForHosts($exception)->getMessage());
});
it('should present a FindHostsResponse when no error occurs for an admin user', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->with(Contact::ROLE_CONFIGURATION_HOSTS_READ)
->willReturn(true);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$oneHost = new SmallHost(
1,
new TrimmedString('my_host'),
new TrimmedString('my_alias'),
new TrimmedString('127.0.0.1'),
1,
2,
true,
new SimpleEntity(1, new TrimmedString('poller1'), 'Host'),
new SimpleEntity(10, new TrimmedString('24x7'), 'Host'),
new SimpleEntity(20, new TrimmedString('none'), 'Host'),
new SimpleEntity(30, new TrimmedString('sev1'), 'Host'),
);
$oneHost->addTemplateId(12);
$oneHost->addGroupId(33);
$oneHost->addCategoryId(44);
$hostsFound = [$oneHost];
$this->hostRepository
->expects($this->once())
->method('findByRequestParameters')
->with($this->requestParameters)
->willReturn($hostsFound);
$hostGroup = new HostGroup(
id: $oneHost->getGroupIds()[0],
name: 'hostgroup_name',
alias: '',
iconId: null,
geoCoords: null,
comment: '',
isActivated: true,
);
$this->hostGroupRepository
->expects($this->once())
->method('findByIds')
->with(...$oneHost->getGroupIds())
->willReturn([$hostGroup]);
$hostTemplate = new HostTemplate($oneHost->getTemplateIds()[0], 'htpl_name', 'htpl_alias');
$this->hostTemplateRepository
->expects($this->once())
->method('findByIds')
->with(...$oneHost->getTemplateIds())
->willReturn([$hostTemplate]);
$hostCategory = new HostCategory($oneHost->getCategoryIds()[0], 'cat1_name', 'cat1_alias');
$this->hostCategoryRepository
->expects($this->once())
->method('findByIds')
->with(...$oneHost->getCategoryIds())
->willReturn([$hostCategory]);
($this->useCase)($this->presenter);
$response = $this->presenter->response;
expect($response)->toBeInstanceOf(FindHostsResponse::class)
->and($response->hostDto[0]->id)->toBe($oneHost->getId())
->and($response->hostDto[0]->name)->toBe((string) $oneHost->getName())
->and($response->hostDto[0]->alias)->toBe((string) $oneHost->getAlias())
->and($response->hostDto[0]->ipAddress)->toBe((string) $oneHost->getIpAddress())
->and($response->hostDto[0]->isActivated)->toBe($oneHost->isActivated())
->and($response->hostDto[0]->poller->id)->toBe($oneHost->getMonitoringServer()->getId())
->and($response->hostDto[0]->poller->name)->toBe($oneHost->getMonitoringServer()->getName())
->and($response->hostDto[0]->checkTimeperiod->id)->toBe($oneHost->getCheckTimePeriod()->getId())
->and($response->hostDto[0]->checkTimeperiod->name)->toBe($oneHost->getCheckTimePeriod()->getName())
->and($response->hostDto[0]->notificationTimeperiod->id)->toBe($oneHost->getNotificationTimePeriod()->getId())
->and($response->hostDto[0]->notificationTimeperiod->name)->toBe($oneHost->getNotificationTimePeriod()
->getName())
->and($response->hostDto[0]->retryCheckInterval)->toBe($oneHost->getRetryCheckInterval())
->and($response->hostDto[0]->normalCheckInterval)->toBe($oneHost->getNormalCheckInterval())
->and($response->hostDto[0]->severity->id)->toBe($oneHost->getSeverity()->getId())
->and($response->hostDto[0]->severity->name)->toBe($oneHost->getSeverity()->getName())
->and($response->hostDto[0]->groups[0]->id)->toBe($oneHost->getGroupIds()[0])
->and($response->hostDto[0]->groups[0]->name)->toBe($hostGroup->getName())
->and($response->hostDto[0]->templateParents[0]->id)->toBe($oneHost->getTemplateIds()[0])
->and($response->hostDto[0]->templateParents[0]->name)->toBe($hostTemplate->getName())
->and($response->hostDto[0]->categories[0]->id)->toBe($oneHost->getCategoryIds()[0])
->and($response->hostDto[0]->categories[0]->name)->toBe($hostCategory->getName());
});
it('should present a FindHostsResponse when no error occurs for a non-admin user', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->with(Contact::ROLE_CONFIGURATION_HOSTS_READ)
->willReturn(true);
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$accessGroups = [new AccessGroup(1, 'acg_name', 'acg_alias')];
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->with($this->user)
->willReturn($accessGroups);
$this->hostRepository
->expects($this->once())
->method('findByRequestParametersAndAccessGroups')
->with($this->requestParameters, $accessGroups)
->willReturn([]);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindHostsResponse::class)
->and($this->presenter->response->hostDto)->toHaveCount(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/Host/Application/UseCase/PartialUpdateHost/PartialUpdateHostTest.php | centreon/tests/php/Core/Host/Application/UseCase/PartialUpdateHost/PartialUpdateHostTest.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\Application\UseCase\PartialUpdateHost;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Option\Option;
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\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Application\Converter\YesNoDefaultConverter;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Application\UseCase\PartialUpdateHost\PartialUpdateHost;
use Core\Host\Application\UseCase\PartialUpdateHost\PartialUpdateHostRequest;
use Core\Host\Application\UseCase\PartialUpdateHost\PartialUpdateHostValidation;
use Core\Host\Domain\Model\Host;
use Core\Host\Domain\Model\HostEvent;
use Core\Host\Domain\Model\SnmpVersion;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Tests\Core\Host\Infrastructure\API\PartialUpdateHost\PartialUpdateHostPresenterStub;
beforeEach(function (): void {
$this->presenter = new PartialUpdateHostPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new PartialUpdateHost(
writeHostRepository: $this->writeHostRepository = $this->createMock(WriteHostRepositoryInterface::class),
readHostRepository: $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
writeMonitoringServerRepository: $this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class),
readHostCategoryRepository: $this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class),
readHostGroupRepository: $this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
writeHostCategoryRepository: $this->writeHostCategoryRepository = $this->createMock(WriteHostCategoryRepositoryInterface::class),
writeHostGroupRepository: $this->writeHostGroupRepository = $this->createMock(WriteHostGroupRepositoryInterface::class),
readAccessGroupRepository: $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
readHostMacroRepository: $this->readHostMacroRepository = $this->createMock(ReadHostMacroRepositoryInterface::class),
readCommandMacroRepository: $this->readCommandMacroRepository = $this->createMock(ReadCommandMacroRepositoryInterface::class),
writeHostMacroRepository: $this->writeHostMacroRepository = $this->createMock(WriteHostMacroRepositoryInterface::class),
dataStorageEngine: $this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class),
optionService: $this->optionService = $this->createMock(OptionService::class),
user: $this->user = $this->createMock(ContactInterface::class),
validation: $this->validation = $this->createMock(PartialUpdateHostValidation::class),
writeVaultRepository: $this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class),
readVaultRepository: $this->readVaultRepository = $this->createMock(ReadVaultRepositoryInterface::class),
);
$this->inheritanceModeOption = new Option();
$this->inheritanceModeOption->setName('inheritanceMode')->setValue('1');
// Settup host template
$this->hostId = 1;
$this->checkCommandId = 1;
$this->originalHost = new Host(
id: $this->hostId,
monitoringServerId: 2,
name: 'host_template_name',
alias: 'host_template_alias',
address: '127.0.0.1',
snmpVersion: SnmpVersion::Three,
snmpCommunity: 'someCommunity',
noteUrl: 'some note url',
note: 'a note',
actionUrl: 'some action url',
comment: 'a comment'
);
$this->request = new PartialUpdateHostRequest();
$this->request->monitoringServerId = 3;
$this->request->name = $this->originalHost->getName() . ' edit ';
$this->request->alias = $this->originalHost->getAlias() . ' edit ';
$this->request->address = '1.2.3.4';
$this->request->snmpVersion = SnmpVersion::Two->value;
$this->request->snmpCommunity = 'snmpCommunity-value edit';
$this->request->timezoneId = 1;
$this->request->severityId = 1;
$this->request->checkCommandId = $this->checkCommandId;
$this->request->checkCommandArgs = ['arg1', 'arg2'];
$this->request->checkTimeperiodId = 1;
$this->request->maxCheckAttempts = 5;
$this->request->normalCheckInterval = 5;
$this->request->retryCheckInterval = 5;
$this->request->activeCheckEnabled = 1;
$this->request->passiveCheckEnabled = 1;
$this->request->notificationEnabled = 1;
$this->request->notificationOptions = HostEventConverter::toBitFlag([HostEvent::Down, HostEvent::Unreachable]);
$this->request->notificationInterval = 5;
$this->request->notificationTimeperiodId = 2;
$this->request->addInheritedContactGroup = true;
$this->request->addInheritedContact = true;
$this->request->firstNotificationDelay = 5;
$this->request->recoveryNotificationDelay = 5;
$this->request->acknowledgementTimeout = 5;
$this->request->freshnessChecked = 1;
$this->request->freshnessThreshold = 5;
$this->request->flapDetectionEnabled = 1;
$this->request->lowFlapThreshold = 5;
$this->request->highFlapThreshold = 5;
$this->request->eventHandlerEnabled = 1;
$this->request->eventHandlerCommandId = 2;
$this->request->eventHandlerCommandArgs = ['arg3', ' arg4'];
$this->request->noteUrl = 'noteUrl-value edit';
$this->request->note = 'note-value edit';
$this->request->actionUrl = 'actionUrl-value edit';
$this->request->iconId = 1;
$this->request->iconAlternative = 'iconAlternative-value';
$this->request->comment = 'comment-value edit';
$this->editedHost = new Host(
id: $this->hostId,
monitoringServerId: $this->request->monitoringServerId,
name: $this->request->name,
alias: $this->request->alias,
address: $this->request->address,
snmpVersion: SnmpVersion::from($this->request->snmpVersion),
snmpCommunity: $this->request->snmpCommunity,
timezoneId: $this->request->timezoneId,
severityId: $this->request->severityId,
checkCommandId: $this->request->checkCommandId,
checkCommandArgs: ['arg1', 'test2'],
checkTimeperiodId: $this->request->checkTimeperiodId,
maxCheckAttempts: $this->request->maxCheckAttempts,
normalCheckInterval: $this->request->normalCheckInterval,
retryCheckInterval: $this->request->retryCheckInterval,
activeCheckEnabled: YesNoDefaultConverter::fromScalar($this->request->activeCheckEnabled),
passiveCheckEnabled: YesNoDefaultConverter::fromScalar($this->request->passiveCheckEnabled),
notificationEnabled: YesNoDefaultConverter::fromScalar($this->request->notificationEnabled),
notificationOptions: HostEventConverter::fromBitFlag($this->request->notificationOptions),
notificationInterval: $this->request->notificationInterval,
notificationTimeperiodId: $this->request->notificationTimeperiodId,
addInheritedContactGroup: $this->request->addInheritedContactGroup,
addInheritedContact: $this->request->addInheritedContact,
firstNotificationDelay: $this->request->firstNotificationDelay,
recoveryNotificationDelay: $this->request->recoveryNotificationDelay,
acknowledgementTimeout: $this->request->acknowledgementTimeout,
freshnessChecked: YesNoDefaultConverter::fromScalar($this->request->freshnessChecked),
freshnessThreshold: $this->request->freshnessThreshold,
flapDetectionEnabled: YesNoDefaultConverter::fromScalar($this->request->flapDetectionEnabled),
lowFlapThreshold: $this->request->lowFlapThreshold,
highFlapThreshold: $this->request->highFlapThreshold,
eventHandlerEnabled: YesNoDefaultConverter::fromScalar($this->request->eventHandlerEnabled),
eventHandlerCommandId: $this->request->eventHandlerCommandId,
eventHandlerCommandArgs: $this->request->eventHandlerCommandArgs,
noteUrl: $this->request->noteUrl,
note: $this->request->note,
actionUrl: $this->request->actionUrl,
iconId: $this->request->iconId,
iconAlternative: $this->request->iconAlternative,
comment: $this->request->comment,
);
// Settup parent templates
$this->parentTemplates = [2, 3];
$this->request->templates = $this->parentTemplates;
// Settup macros
$this->macroA = new Macro(null, $this->hostId, 'macroNameA', 'macroValueA');
$this->macroA->setOrder(0);
$this->macroB = new Macro(null, $this->hostId, 'macroNameB', 'macroValueB');
$this->macroB->setOrder(1);
$this->commandMacro = new CommandMacro(1, CommandMacroType::Host, 'commandMacroName');
$this->commandMacros = [
$this->commandMacro->getName() => $this->commandMacro,
];
$this->hostMacros = [
$this->macroA->getName() => $this->macroA,
$this->macroB->getName() => $this->macroB,
];
$this->inheritanceLineIds = [
['child_id' => 1, 'parent_id' => $this->parentTemplates[0], 'order' => 0],
['child_id' => $this->parentTemplates[0], 'parent_id' => $this->parentTemplates[1], 'order' => 1],
];
$this->request->macros = [
[
'name' => $this->macroA->getName(),
'value' => $this->macroA->getValue() . '_edit',
'is_password' => $this->macroA->isPassword(),
'description' => $this->macroA->getDescription(),
],
[
'name' => 'macroNameC',
'value' => 'macroValueC',
'is_password' => false,
'description' => null,
],
];
// Settup categories
$this->categoryA = new HostCategory(1, 'cat-name-A', 'cat-alias-A');
$this->categoryB = new HostCategory(2, 'cat-name-B', 'cat-alias-B');
$this->request->categories = [$this->categoryB->getId()];
// Settup groups
$this->groups = [
$this->groupA = new HostGroup(
id: 6,
name: 'grp-name-A',
alias: 'grp-alias-A',
iconId: null,
geoCoords: null,
comment: '',
isActivated: true
),
$this->groupB = new HostGroup(
id: 7,
name: 'grp-name-B',
alias: 'grp-alias-B',
iconId: null,
geoCoords: null,
comment: '',
isActivated: true
),
];
$this->request->groups = [$this->groupA->getId(), $this->groupB->getId()];
});
// Generic usecase tests
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, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::editNotAllowed()->getMessage());
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::editHost()->getMessage());
});
it('should present a NotFoundResponse when the host does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->response->getMessage())
->toBe('Host not found');
});
// Tests for host
it('should present a ConflictResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
$this->validation
->expects($this->once())
->method('assertIsValidName')
->willThrowException(
HostException::nameAlreadyExists(
Host::formatName($this->request->name),
$this->request->name
)
);
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::nameAlreadyExists(
Host::formatName($this->request->name),
$this->request->name
)->getMessage()
);
});
it('should present a ConflictResponse when host severity ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
$this->validation
->expects($this->once())
->method('assertIsValidSeverity')
->willThrowException(
HostException::idDoesNotExist('severityId', $this->request->severityId)
);
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::idDoesNotExist('severityId', $this->request->severityId)->getMessage());
});
it('should present a ConflictResponse when a host timezone ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
$this->validation
->expects($this->once())
->method('assertIsValidTimezone')
->willThrowException(
HostException::idDoesNotExist('timezoneId', $this->request->timezoneId)
);
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::idDoesNotExist('timezoneId', $this->request->timezoneId)->getMessage());
});
it('should present a ConflictResponse when a timeperiod ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
$this->validation
->expects($this->once())
->method('assertIsValidTimePeriod')
->willThrowException(
HostException::idDoesNotExist(
'checkTimeperiodId',
$this->request->checkTimeperiodId
)
);
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idDoesNotExist(
'checkTimeperiodId',
$this->request->checkTimeperiodId
)->getMessage()
);
});
it('should present a ConflictResponse when a command ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
$this->validation
->expects($this->once())
->method('assertIsValidCommand')
->willThrowException(
HostException::idDoesNotExist(
'checkCommandId',
$this->request->checkCommandId
)
);
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idDoesNotExist(
'checkCommandId',
$this->request->checkCommandId
)->getMessage()
);
});
it('should present a ConflictResponse when the host icon ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
$this->validation
->expects($this->once())
->method('assertIsValidIcon')
->willThrowException(
HostException::idDoesNotExist(
'iconId',
$this->request->iconId
)
);
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idDoesNotExist(
'iconId',
$this->request->iconId
)->getMessage()
);
});
// Tests for categories
it('should present a ConflictResponse when a host category does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(2))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
// Host
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn([$this->inheritanceModeOption]);
$this->writeHostRepository
->expects($this->once())
->method('update');
// Categories
$this->validation
->expects($this->once())
->method('assertAreValidCategories')
->willThrowException(HostException::idsDoNotExist('categories', $this->request->categories));
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::idsDoNotExist('categories', $this->request->categories)->getMessage());
});
// Tests for groups
it('should present a ConflictResponse when a host group does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(3))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
// Host
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn([$this->inheritanceModeOption]);
$this->writeHostRepository
->expects($this->once())
->method('update');
// Categories
$this->readHostCategoryRepository
->expects($this->once())
->method('findByHost')
->willReturn([]);
$this->writeHostCategoryRepository
->expects($this->once())
->method('linkToHost');
// Groups
$this->validation
->expects($this->once())
->method('assertAreValidGroups')
->willThrowException(HostException::idsDoNotExist('groups', $this->request->groups));
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(HostException::idsDoNotExist('groups', $this->request->groups)->getMessage());
});
// Tests for parents templates
it('should present a ConflictResponse when a parent template ID is not valid', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(4))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
// Host
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn([$this->inheritanceModeOption]);
$this->writeHostRepository
->expects($this->once())
->method('update');
// Categories
$this->readHostCategoryRepository
->expects($this->once())
->method('findByHost')
->willReturn([]);
$this->writeHostCategoryRepository
->expects($this->once())
->method('linkToHost');
// Groups
$this->readHostGroupRepository
->expects($this->once())
->method('findByHost')
->willReturn([]);
$this->writeHostGroupRepository
->expects($this->once())
->method('linkToHost');
// Parent templates
$this->validation
->expects($this->once())
->method('assertAreValidTemplates')
->willThrowException(HostException::idsDoNotExist('templates', $this->request->templates));
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::idsDoNotExist(
'templates',
$this->request->templates
)->getMessage()
);
});
it('should present a ConflictResponse when a parent template creates a circular inheritance', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(4))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
// Host
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn([$this->inheritanceModeOption]);
$this->writeHostRepository
->expects($this->once())
->method('update');
// Categories
$this->readHostCategoryRepository
->expects($this->once())
->method('findByHost')
->willReturn([]);
$this->writeHostCategoryRepository
->expects($this->once())
->method('linkToHost');
// Groups
$this->readHostGroupRepository
->expects($this->once())
->method('findByHost')
->willReturn([]);
$this->writeHostGroupRepository
->expects($this->once())
->method('linkToHost');
// Parent templates
$this->validation
->expects($this->once())
->method('assertAreValidTemplates')
->willThrowException(HostException::circularTemplateInheritance());
($this->useCase)($this->request, $this->presenter, $this->hostId);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(
HostException::circularTemplateInheritance()->getMessage()
);
});
// Test for successful request
it('should present a NoContentResponse on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->exactly(4))
->method('isAdmin')
->willReturn(true);
$this->readHostRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHost);
// Host
$this->optionService
->expects($this->once())
->method('findSelectedOptions')
->willReturn([$this->inheritanceModeOption]);
$this->validation->expects($this->once())->method('assertIsValidName');
$this->validation->expects($this->once())->method('assertIsValidSeverity');
$this->validation->expects($this->once())->method('assertIsValidTimezone');
$this->validation->expects($this->exactly(2))->method('assertIsValidTimePeriod');
$this->validation->expects($this->exactly(2))->method('assertIsValidCommand');
$this->validation->expects($this->once())->method('assertIsValidIcon');
$this->writeHostRepository
->expects($this->once())
->method('update');
// Categories
$this->validation
->expects($this->once())
->method('assertAreValidCategories');
$this->readHostCategoryRepository
->expects($this->once())
->method('findByHost')
->willReturn([$this->categoryA]);
$this->writeHostCategoryRepository
->expects($this->once())
->method('linkToHost');
$this->writeHostCategoryRepository
->expects($this->once())
->method('unlinkFromHost');
// Groups
$this->validation
->expects($this->once())
->method('assertAreValidGroups');
$this->readHostGroupRepository
->expects($this->once())
->method('findByHost')
->willReturn([$this->groupA]);
$this->writeHostGroupRepository
->expects($this->once())
->method('linkToHost');
$this->writeHostGroupRepository
->expects($this->once())
->method('unlinkFromHost');
// Parent templates
$this->validation
->expects($this->once())
->method('assertAreValidTemplates');
$this->writeHostRepository
->expects($this->once())
->method('deleteParents');
$this->writeHostRepository
->expects($this->exactly(2))
->method('addParent');
// Macros
$this->readHostRepository
->expects($this->once())
->method('findParents')
->willReturn($this->inheritanceLineIds);
$this->readHostMacroRepository
->expects($this->once())
->method('findByHostIds')
->willReturn($this->hostMacros);
$this->readCommandMacroRepository
->expects($this->once())
->method('findByCommandIdAndType')
->willReturn($this->commandMacros);
$this->writeHostMacroRepository
->expects($this->once())
->method('delete');
$this->writeHostMacroRepository
->expects($this->once())
->method('add');
$this->writeHostMacroRepository
->expects($this->once())
->method('update');
($this->useCase)($this->request, $this->presenter, $this->hostId);
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/Host/Application/UseCase/PartialUpdateHost/PartialUpdateHostValidationTest.php | centreon/tests/php/Core/Host/Application/UseCase/PartialUpdateHost/PartialUpdateHostValidationTest.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\Application\UseCase\PartialUpdateHost;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Domain\Model\CommandType;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\InheritanceManager;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\UseCase\PartialUpdateHost\PartialUpdateHostValidation;
use Core\Host\Domain\Model\Host;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\Timezone\Application\Repository\ReadTimezoneRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(function (): void {
$this->validation = new PartialUpdateHostValidation(
readHostRepository: $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
readMonitoringServerRepository: $this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
readHostTemplateRepository: $this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class),
readViewImgRepository: $this->readViewImgRepository = $this->createMock(ReadViewImgRepositoryInterface::class),
readTimePeriodRepository: $this->readTimePeriodRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class),
readHostSeverityRepository: $this->readHostSeverityRepository = $this->createMock(ReadHostSeverityRepositoryInterface::class),
readTimezoneRepository: $this->readTimezoneRepository = $this->createMock(ReadTimezoneRepositoryInterface::class),
readCommandRepository: $this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class),
readHostCategoryRepository: $this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class),
readHostGroupRepository: $this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
inheritanceManager: $this->inheritanceManager = $this->createMock(InheritanceManager::class),
user: $this->user = $this->createMock(ContactInterface::class),
accessGroups: $this->accessGroup = []
);
});
it('throws an exception when name is already used', function (): void {
$host = new Host(
id: 1,
monitoringServerId: 2,
name: 'host name',
address: '127.0.0.1'
);
$this->readHostRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->validation->assertIsValidName('name test', $host);
})->throws(
HostException::class,
HostException::nameAlreadyExists(Host::formatName('name test'), 'name test')->getMessage()
);
it('throws an exception when name is invalid', function (): void {
$host = new Host(
id: 1,
monitoringServerId: 2,
name: 'host name',
address: '127.0.0.1'
);
$this->readHostRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->validation->assertIsValidName('_Module_test', $host);
})->throws(
HostException::class,
HostException::nameIsInvalid()->getMessage()
);
it('throws an exception when name contains invalid characters', function (): void {
$host = new Host(
id: 1,
monitoringServerId: 2,
name: 'host name',
address: '127.0.0.1'
);
$this->validation->assertIsValidName('hôst~3!', $host);
})->throws(
\InvalidArgumentException::class,
'[Host::name] The value contains unauthorized characters: ~!'
);
it('does not throw an exception when name is identical to given host', function (): void {
$host = new Host(
id: 1,
monitoringServerId: 2,
name: 'host name',
address: '127.0.0.1'
);
$this->readHostTemplateRepository
->expects($this->exactly(0))
->method('existsByName');
$this->validation->assertIsValidName('name test', $host);
});
it('throws an exception when icon ID does not exist', function (): void {
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(false);
$this->validation->assertIsValidIcon(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('iconId', 1)->getMessage()
);
it('throws an exception when time period ID does not exist', function (): void {
$this->readTimePeriodRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidTimePeriod(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('timePeriodId', 1)->getMessage()
);
it('throws an exception when severity ID does not exist', function (): void {
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidSeverity(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('severityId', 1)->getMessage()
);
it('throws an exception when timezone ID does not exist', function (): void {
$this->readTimezoneRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidTimezone(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('timezoneId', 1)->getMessage()
);
it('throws an exception when command ID does not exist', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidCommand(1);
})->throws(
HostException::class,
HostException::idDoesNotExist('commandId', 1)->getMessage()
);
it('throws an exception when command ID does not exist for a specific type', function (): void {
$this->readCommandRepository
->expects($this->once())
->method('existsByIdAndCommandType')
->willReturn(false);
$this->validation->assertIsValidCommand(1, CommandType::Check);
})->throws(
HostException::class,
HostException::idDoesNotExist('commandId', 1)->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->readHostCategoryRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidCategories([1, 3]);
})->throws(
HostException::class,
HostException::idsDoNotExist('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->readHostCategoryRepository
->expects($this->once())
->method('existByAccessGroups')
->willReturn([]);
$this->validation->assertAreValidCategories([1, 3]);
})->throws(
HostException::class,
HostException::idsDoNotExist('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->readHostGroupRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidGroups([1, 3]);
})->throws(
HostException::class,
HostException::idsDoNotExist('groups', [1, 3])->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->readHostGroupRepository
->expects($this->once())
->method('existByAccessGroups')
->willReturn([]);
$this->validation->assertAreValidGroups([1, 3]);
})->throws(
HostException::class,
HostException::idsDoNotExist('groups', [1, 3])->getMessage()
);
it('throws an exception when parent template ID does not exist', function (): void {
$this->readHostTemplateRepository
->expects($this->once())
->method('exist')
->willReturn([]);
$this->validation->assertAreValidTemplates([1, 3], 4);
})->throws(
HostException::class,
HostException::idsDoNotExist('templates', [1, 3])->getMessage()
);
it('throws an exception when parent template ID creates a circular inheritance', function (): void {
$this->readHostTemplateRepository
->expects($this->once())
->method('exist')
->willReturn([1, 3]);
$this->validation->assertAreValidTemplates([1, 3], 3);
})->throws(
HostException::class,
HostException::circularTemplateInheritance()->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/Application/Converter/HostEventConverterTest.php | centreon/tests/php/Core/Host/Application/Converter/HostEventConverterTest.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\Application\Converter;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Host\Domain\Model\HostEvent;
use ValueError;
it('trim the legacy string when converting to enum array', function (): void {
$events = HostEventConverter::fromString(' d , u ');
expect($events)->toBe([HostEvent::Down, HostEvent::Unreachable]);
});
it('remove duplicates when converting to enum array', function (): void {
$events = HostEventConverter::fromString('d,u,d');
expect($events)->toBe([HostEvent::Down, HostEvent::Unreachable]);
});
it('remove duplicates when converting to legacy string', function (): void {
$events = HostEventConverter::toString([HostEvent::Down, HostEvent::Unreachable, HostEvent::Down]);
expect($events)->toBe('d,u');
});
it('ignore unknown symbols when converting to legacy string', function (): void {
$events = HostEventConverter::fromString('d,x,y,z,foo,bar,u');
expect($events)->toBe([HostEvent::Down, HostEvent::Unreachable]);
});
it('throw an error when bitmask is invalid', function (): void {
$events = HostEventConverter::fromBitFlag(HostEventConverter::MAX_BITFLAG | 0b100000);
})->throws(
ValueError::class,
'"' . (HostEventConverter::MAX_BITFLAG | 0b100000) . '" is not a valid value for enum HostEvent'
);
it('return an empty bitmask when array contains HostEvent::None', function (): void {
$events = HostEventConverter::toBitFlag([HostEvent::Down, HostEvent::Unreachable, HostEvent::None]);
expect($events)->toBe(0b00000);
});
it('return null when bitmask when array is empty', function (): void {
$events = HostEventConverter::toBitFlag([]);
expect($events)->toBe(null);
});
| 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.