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/Proxy/Domain/Model/ProxyTest.php | centreon/tests/php/Core/Proxy/Domain/Model/ProxyTest.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\Proxy\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Proxy\Domain\Model\Proxy;
beforeEach(function (): void {
$this->createProxy = fn (array $arguments = []): Proxy => new Proxy(...[
'url' => 'localhost',
'port' => 0,
'login' => 'login',
'password' => 'password',
...$arguments,
]);
});
it('should throw an exception when the URL property is empty', function (): void {
($this->createProxy)(['url' => ' ']);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Proxy:url')->getMessage()
);
it('should throw an exception when the port property is negative', function (): void {
($this->createProxy)(['port' => -1]);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::min(-1, 0, 'Proxy:port')->getMessage()
);
it('should throw an exception when the login property is empty', function (): void {
($this->createProxy)(['login' => ' ']);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Proxy:login')->getMessage()
);
it('should throw an exception when the password property is empty', function (): void {
($this->createProxy)(['password' => ' ']);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Proxy:password')->getMessage()
);
it('should be generated correctly as a character string', function (): void {
$proxy = new Proxy('localhost');
expect((string) $proxy)->toBe('http://localhost');
$proxy = new Proxy('localhost', 80);
expect((string) $proxy)->toBe('http://localhost:80');
$proxy = new Proxy('localhost', 80, 'login');
expect((string) $proxy)->toBe('http://login:@localhost:80');
$proxy = new Proxy('localhost', 80, 'login', 'password');
expect((string) $proxy)->toBe('http://login:password@localhost:80');
$proxy = new Proxy('localhost', 80, null, 'password');
expect((string) $proxy)->toBe('http://localhost:80');
$proxy = new Proxy('localhost', null, null, 'password');
expect((string) $proxy)->toBe('http://localhost');
$proxy = new Proxy('https://localhost');
expect((string) $proxy)->toBe('https://localhost');
$proxy = new Proxy('https://localhost', 80);
expect((string) $proxy)->toBe('https://localhost:80');
$proxy = new Proxy('https://localhost', 80, 'login');
expect((string) $proxy)->toBe('https://login:@localhost:80');
$proxy = new Proxy('https://localhost', 80, 'login', 'password');
expect((string) $proxy)->toBe('https://login:password@localhost:80');
$proxy = new Proxy('https://localhost', 80, null, 'password');
expect((string) $proxy)->toBe('https://localhost:80');
$proxy = new Proxy('https://localhost', null, null, 'password');
expect((string) $proxy)->toBe('https://localhost');
});
| 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/Command/Application/UseCase/MigrateAllCommands/MigrateAllCommandsTest.php | centreon/tests/php/Core/Command/Application/UseCase/MigrateAllCommands/MigrateAllCommandsTest.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\Command\Application\UseCase\MigrateAllCommands;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Application\Repository\WriteCommandRepositoryInterface;
use Core\Command\Application\UseCase\MigrateAllCommands\CommandRecordedDto;
use Core\Command\Application\UseCase\MigrateAllCommands\MigrateAllCommands;
use Core\Command\Application\UseCase\MigrateAllCommands\MigrateAllCommandsResponse;
use Core\Command\Domain\Model\Command;
use Psr\Log\LoggerInterface;
use Tests\Core\Command\Infrastructure\Command\MigrateAllCommands\MigrateAllCommandsPresenterStub;
beforeEach(function (): void {
$this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class);
$this->writeCommandRepository = $this->createMock(WriteCommandRepositoryInterface::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->useCase = new MigrateAllCommands($this->readCommandRepository, $this->writeCommandRepository, $this->logger);
$this->presenter = new MigrateAllCommandsPresenterStub();
});
it('should present a MigrateAllCommandsResponse', function (): void {
$commandA = new Command(1, 'command-name A', 'command line A');
$commandB = new Command(2, 'command-name B', 'command line B');
$this->readCommandRepository
->expects($this->once())
->method('findAll')
->willReturn(new \ArrayIterator([$commandA, $commandB]));
($this->useCase)($this->presenter);
$firstResponseCommand = $this->presenter->response->results->current();
expect($this->presenter->response)
->toBeInstanceOf(MigrateAllCommandsResponse::class)
->and($firstResponseCommand->name)
->tobe('command-name A');
$this->presenter->response->results->next();
/** @var CommandRecordedDto $secondeResponseCommand */
$secondeResponseCommand = $this->presenter->response->results->current();
expect($this->presenter->response)
->toBeInstanceOf(MigrateAllCommandsResponse::class)
->and($secondeResponseCommand->name)
->tobe('command-name B');
});
| 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/Command/Application/UseCase/AddCommand/AddCommandValidationTest.php | centreon/tests/php/Core/Command/Application/UseCase/AddCommand/AddCommandValidationTest.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\Command\Application\UseCase\AddCommand;
use Core\Command\Application\Exception\CommandException;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Application\UseCase\AddCommand\AddCommandRequest;
use Core\Command\Application\UseCase\AddCommand\AddCommandValidation;
use Core\Command\Application\UseCase\AddCommand\ArgumentDto;
use Core\Command\Application\UseCase\AddCommand\MacroDto;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Connector\Application\Repository\ReadConnectorRepositoryInterface;
use Core\GraphTemplate\Application\Repository\ReadGraphTemplateRepositoryInterface;
beforeEach(function (): void {
$this->validation = new AddCommandValidation(
readCommandRepository: $this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class),
readConnectorRepository: $this->readConnectorRepository = $this->createMock(ReadConnectorRepositoryInterface::class),
readGraphTemplateRepository: $this->readGraphTemplateRepository = $this->createMock(ReadGraphTemplateRepositoryInterface::class),
);
});
it('throws an exception when name is already used', function (): void {
$request = new AddCommandRequest();
$request->name = 'name test';
$this->readCommandRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
$this->validation->assertIsValidName($request);
})->throws(
CommandException::class,
CommandException::nameAlreadyExists('name test')->getMessage()
);
it('throws an exception when an argument is invalid', function (): void {
$request = new AddCommandRequest();
$request->arguments[] = new ArgumentDto('arg-name', 'arg-desc');
$this->validation->assertAreValidArguments($request);
})->throws(
CommandException::class,
CommandException::invalidArguments(['arg-name'])->getMessage()
);
it('throws an exception when a macro is invalid', function (): void {
$request = new AddCommandRequest();
$request->macros[] = new MacroDto('macro-name', CommandMacroType::Host, 'macro-desc');
$this->validation->assertAreValidMacros($request);
})->throws(
CommandException::class,
CommandException::invalidMacros(['macro-name'])->getMessage()
);
it('throws an exception when connector ID does not exist', function (): void {
$request = new AddCommandRequest();
$request->connectorId = 12;
$this->readConnectorRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidConnector($request);
})->throws(
CommandException::class,
CommandException::idDoesNotExist('connectorId', 12)->getMessage()
);
it('throws an exception when graph template ID does not exist', function (): void {
$request = new AddCommandRequest();
$request->graphTemplateId = 12;
$this->readGraphTemplateRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidGraphTemplate($request);
})->throws(
CommandException::class,
CommandException::idDoesNotExist('graphTemplateId', 12)->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/Command/Application/UseCase/AddCommand/AddCommandTest.php | centreon/tests/php/Core/Command/Application/UseCase/AddCommand/AddCommandTest.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\Command\Application\UseCase\AddCommand;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Command\Application\Exception\CommandException;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Application\Repository\WriteCommandRepositoryInterface;
use Core\Command\Application\UseCase\AddCommand\AddCommand;
use Core\Command\Application\UseCase\AddCommand\AddCommandRequest;
use Core\Command\Application\UseCase\AddCommand\AddCommandResponse;
use Core\Command\Application\UseCase\AddCommand\AddCommandValidation;
use Core\Command\Application\UseCase\AddCommand\ArgumentDto;
use Core\Command\Application\UseCase\AddCommand\MacroDto;
use Core\Command\Domain\Model\Argument;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\CommandType;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Tests\Core\Command\Infrastructure\API\AddCommand\AddCommandPresenterStub;
beforeEach(closure: function (): void {
$this->presenter = new AddCommandPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new AddCommand(
readCommandRepository: $this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class),
writeCommandRepository: $this->writeCommandRepository = $this->createMock(WriteCommandRepositoryInterface::class),
validation: $this->validation = $this->createMock(AddCommandValidation::class),
user: $this->user = $this->createMock(ContactInterface::class),
);
$this->request = new AddCommandRequest();
$this->request->name = 'command-name';
$this->request->commandLine = '$ARG1, $_HOSTmacro-name$';
$this->request->type = CommandType::Notification;
$this->request->isShellEnabled = true;
$this->request->argumentExample = 'argExample';
$this->request->arguments = [new ArgumentDto(
name: 'ARG1',
description: 'arg-desc'
)];
$this->request->macros = [new MacroDto(
type: CommandMacroType::Host,
name: 'macro-name',
description: 'macro-description'
)];
$this->request->connectorId = 1;
$this->request->graphTemplateId = 2;
$this->command = new Command(
id: 1,
name: 'command-name',
commandLine: 'commandline',
type: CommandType::Check,
isShellEnabled: true,
isActivated: false,
isLocked: true,
argumentExample: 'argExample',
arguments: [new Argument(
name: new TrimmedString('ARG1'),
description: new TrimmedString('arg-desc')
)],
macros: [new CommandMacro(
commandId: 1,
type: CommandMacroType::Host,
name: 'macro-name'
)],
connector: new SimpleEntity(
id: 1,
name: new TrimmedString('connector-name'),
objectName: 'connector'
),
graphTemplate: new SimpleEntity(
id: 2,
name: new TrimmedString('graphTemplate-name'),
objectName: 'graphTemplate'
),
);
});
it('should present a ForbiddenResponse when the user has insufficient rights', function (): void {
$this->user
->expects($this->atMost(4))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_RW, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_RW, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_RW, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_RW, false],
]
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(CommandException::addNotAllowed()->getMessage());
});
it(
'should present a ForbiddenResponse when the user has insufficient rights on the required command type',
function (): void {
$this->user
->expects($this->atMost(4))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_RW, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_RW, true],
]
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(CommandException::addNotAllowed()->getMessage());
}
);
it(
'should present a ConflictResponse when an a request parameter is invalid',
function (): void {
$this->user
->expects($this->atMost(4))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_RW, true],
]
);
$this->validation
->expects($this->once())
->method('assertIsValidName')
->willThrowException(CommandException::nameAlreadyExists('invalid-name'));
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->response->getMessage())
->toBe(CommandException::nameAlreadyExists('invalid-name')->getMessage());
}
);
it(
'should present an ErrorResponse when an exception of type Exception is thrown',
function (): void {
$this->user
->expects($this->atMost(4))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_RW, true],
]
);
$this->validation->expects($this->once())->method('assertIsValidName');
$this->validation->expects($this->once())->method('assertAreValidArguments');
$this->validation->expects($this->once())->method('assertAreValidMacros');
$this->validation->expects($this->once())->method('assertIsValidConnector');
$this->validation->expects($this->once())->method('assertIsValidGraphTemplate');
$this->writeCommandRepository
->expects($this->once())
->method('add')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(CommandException::errorWhileAdding(new \Exception())->getMessage());
}
);
it(
'should present an AddCommandResponse when everything has gone well',
function (): void {
$this->user
->expects($this->atMost(4))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_RW, true],
[Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_RW, true],
]
);
$this->validation->expects($this->once())->method('assertIsValidName');
$this->validation->expects($this->once())->method('assertAreValidArguments');
$this->validation->expects($this->once())->method('assertAreValidMacros');
$this->validation->expects($this->once())->method('assertIsValidConnector');
$this->validation->expects($this->once())->method('assertIsValidGraphTemplate');
$this->writeCommandRepository
->expects($this->once())
->method('add')
->willReturn($this->command->getId());
$this->readCommandRepository
->expects($this->once())
->method('findById')
->willReturn($this->command);
($this->useCase)($this->request, $this->presenter);
$response = $this->presenter->response;
expect($response)->toBeInstanceOf(AddCommandResponse::class)
->and($response->id)->toBe($this->command->getId())
->and($response->name)->toBe($this->command->getName())
->and($response->commandLine)->toBe($this->command->getCommandLine())
->and($response->type)->toBe($this->command->getType())
->and($response->isShellEnabled)->toBe($this->command->isShellEnabled())
->and($response->isLocked)->toBe($this->command->isLocked())
->and($response->isActivated)->toBe($this->command->isActivated())
->and($response->argumentExample)->tobe($this->command->getArgumentExample())
->and($response->connector)->toBe([
'id' => $this->command->getConnector()->getId(),
'name' => $this->command->getConnector()->getName(),
])
->and($response->graphTemplate)->toBe([
'id' => $this->command->getGraphTemplate()->getId(),
'name' => $this->command->getGraphTemplate()->getName(),
])
->and($response->arguments)->tobe([[
'name' => $this->command->getArguments()[0]->getName(),
'description' => $this->command->getArguments()[0]->getDescription(),
]])
->and($response->macros)->tobe([[
'name' => $this->command->getMacros()[0]->getName(),
'description' => $this->command->getMacros()[0]->getDescription(),
'type' => $this->command->getMacros()[0]->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/Command/Application/UseCase/FindCommands/FindCommandsTest.php | centreon/tests/php/Core/Command/Application/UseCase/FindCommands/FindCommandsTest.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\Command\Application\UseCase\FindCommands;
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\Command\Application\Exception\CommandException;
use Core\Command\Application\Repository\ReadCommandRepositoryInterface;
use Core\Command\Application\UseCase\FindCommands\FindCommands;
use Core\Command\Application\UseCase\FindCommands\FindCommandsResponse;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\CommandType;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Tests\Core\Command\Infrastructure\API\FindCommands\FindCommandsPresenterStub;
beforeEach(closure: function (): void {
$this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->presenter = new FindCommandsPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new FindCommands(
$this->createMock(RequestParametersInterface::class),
$this->readCommandRepository,
$this->contact
);
});
it('should present a ForbiddenResponse when the user has insufficient rights', function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(8))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_R, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_CHECKS_RW, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_R, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_NOTIFICATIONS_RW, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_R, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_MISCELLANEOUS_RW, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_R, false],
[Contact::ROLE_CONFIGURATION_COMMANDS_DISCOVERY_RW, false],
]
);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->response->getMessage())
->toBe(CommandException::accessNotAllowed()->getMessage());
});
it(
'should present an ErrorResponse when an exception of type RequestParametersTranslatorException is thrown',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$exception = new RequestParametersTranslatorException('Error');
$this->readCommandRepository
->expects($this->once())
->method('findByRequestParameterAndTypes')
->willThrowException($exception);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe($exception->getMessage());
}
);
it(
'should present an ErrorResponse when an exception of type Exception is thrown',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$exception = new \Exception('Error');
$this->readCommandRepository
->expects($this->once())
->method('findByRequestParameterAndTypes')
->willThrowException($exception);
($this->useCase)($this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(CommandException::errorWhileSearching($exception)->getMessage());
}
);
it(
'should present a FindCommandsResponse when everything has gone well',
function (): void {
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$command = new Command(
id: 1,
name: 'fake',
commandLine: 'line',
type: CommandType::Check,
isShellEnabled: true,
isActivated: true,
isLocked: true
);
$this->readCommandRepository
->expects($this->once())
->method('findByRequestParameterAndTypes')
->willReturn([$command]);
($this->useCase)($this->presenter);
$commandsResponse = $this->presenter->response;
expect($commandsResponse)->toBeInstanceOf(FindCommandsResponse::class);
expect($commandsResponse->commands[0]->id)->toBe($command->getId());
expect($commandsResponse->commands[0]->name)->toBe($command->getName());
expect($commandsResponse->commands[0]->commandLine)->toBe($command->getCommandLine());
expect($commandsResponse->commands[0]->type)->toBe($command->getType());
expect($commandsResponse->commands[0]->isShellEnabled)->toBe($command->isShellEnabled());
expect($commandsResponse->commands[0]->isLocked)->toBe($command->isLocked());
expect($commandsResponse->commands[0]->isActivated)->toBe($command->isActivated());
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Command/Domain/Model/ArgumentTest.php | centreon/tests/php/Core/Command/Domain/Model/ArgumentTest.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\Command\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Command\Domain\Model\Argument;
use Core\Common\Domain\TrimmedString;
it('should return properly set argument instance', function (): void {
$argument = new Argument(new TrimmedString('ARG1'), new TrimmedString('argDescription'));
expect($argument->getName())->toBe('ARG1')
->and($argument->getDescription())->toBe('argDescription');
});
it('should throw an exception when name is empty', function (): void {
new Argument(new TrimmedString(''), new TrimmedString('argDescription'));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Argument::name')->getMessage()
);
it('should throw an exception when name is too long', function (): void {
new Argument(
new TrimmedString(str_repeat('a', Argument::NAME_MAX_LENGTH + 1)),
new TrimmedString('argDescription')
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Argument::NAME_MAX_LENGTH + 1),
Argument::NAME_MAX_LENGTH + 1,
Argument::NAME_MAX_LENGTH,
'Argument::name'
)->getMessage()
);
it('should throw an exception when name does not respect format', function (): void {
new Argument(
new TrimmedString('test'),
new TrimmedString('argDescription')
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::matchRegex(
'test',
'/^ARG\d+$/',
'Argument::name'
)->getMessage()
);
it('should throw an exception when description is too long', function (): void {
new Argument(
new TrimmedString('ARG1'),
new TrimmedString(str_repeat('a', Argument::DESCRIPTION_MAX_LENGTH + 1))
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Argument::DESCRIPTION_MAX_LENGTH + 1),
Argument::DESCRIPTION_MAX_LENGTH + 1,
Argument::DESCRIPTION_MAX_LENGTH,
'Argument::description'
)->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/Command/Domain/Model/CommandTest.php | centreon/tests/php/Core/Command/Domain/Model/CommandTest.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\Command\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Command\Domain\Model\Argument;
use Core\Command\Domain\Model\Command;
use Core\Command\Domain\Model\CommandType;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\MonitoringServer\Model\MonitoringServer;
it('should return properly set instance', function (): void {
$command = new Command(
id: 1,
name: 'command-name',
commandLine: 'commandline',
type: CommandType::Check,
isShellEnabled: true,
isActivated: false,
isLocked: true,
argumentExample: 'argExample',
arguments: [new Argument(
name: new TrimmedString('ARG1'),
description: new TrimmedString('arg-desc')
)],
macros: [new CommandMacro(
commandId: 1,
type: CommandMacroType::Host,
name: 'macro-name'
)],
connector: new SimpleEntity(
id: 1,
name: new TrimmedString('connector-name'),
objectName: 'connector'
),
graphTemplate: new SimpleEntity(
id: 1,
name: new TrimmedString('graphTemplate-name'),
objectName: 'graphTemplate'
),
);
expect($command->getId())->toBe(1)
->and($command->getName())->toBe('command-name')
->and($command->getCommandLine())->toBe('commandline')
->and($command->getType())->toBe(CommandType::Check)
->and($command->isShellEnabled())->toBe(true)
->and($command->isActivated())->toBe(false)
->and($command->isLocked())->toBe(true)
->and($command->getArgumentExample())->toBe('argExample')
->and($command->getArguments()[0]->getName())->toBe('ARG1')
->and($command->getMacros()[0]->getName())->toBe('macro-name')
->and($command->getConnector()->getName())->toBe('connector-name')
->and($command->getGraphTemplate()->getName())->toBe('graphTemplate-name');
});
it('should throw an exception when ID is < 0', function (): void {
new Command(
id: 0,
name: 'command-name',
commandLine: 'commandline'
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::positiveInt(0, 'Command::id')->getMessage()
);
it('should throw an exception when name is empty', function (): void {
new Command(
id: 1,
name: '',
commandLine: 'commandline',
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Command::name')->getMessage()
);
it('should throw an exception when name is too long', function (): void {
new Command(
id: 1,
name: str_repeat('a', Command::NAME_MAX_LENGTH + 1),
commandLine: 'commandline',
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Command::NAME_MAX_LENGTH + 1),
Command::NAME_MAX_LENGTH + 1,
Command::NAME_MAX_LENGTH,
'Command::name'
)->getMessage()
);
it('should throw an exception when name contains invalid characters', function (): void {
new Command(
id: 1,
name: 'command-name-' . MonitoringServer::ILLEGAL_CHARACTERS[0] . '-test',
commandLine: 'commandline',
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::unauthorizedCharacters(
'command-name-' . MonitoringServer::ILLEGAL_CHARACTERS[0] . '-test',
MonitoringServer::ILLEGAL_CHARACTERS[0],
'Command::name'
)->getMessage()
);
it('should throw an exception when command line is empty', function (): void {
new Command(
id: 1,
name: 'command-line',
commandLine: '',
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Command::commandLine')->getMessage()
);
it('should throw an exception when command line is too long', function (): void {
new Command(
id: 1,
name: 'command-name',
commandLine: str_repeat('a', Command::COMMAND_MAX_LENGTH + 1),
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Command::COMMAND_MAX_LENGTH + 1),
Command::COMMAND_MAX_LENGTH + 1,
Command::COMMAND_MAX_LENGTH,
'Command::commandLine'
)->getMessage()
);
it('should throw an exception when argument example is too long', function (): void {
new Command(
id: 1,
name: 'command-name',
commandLine: 'commandLine',
type: CommandType::Check,
argumentExample: str_repeat('a', Command::EXAMPLE_MAX_LENGTH + 1),
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Command::EXAMPLE_MAX_LENGTH + 1),
Command::EXAMPLE_MAX_LENGTH + 1,
Command::EXAMPLE_MAX_LENGTH,
'Command::argumentExample'
)->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/Command/Domain/Model/NewCommandTest.php | centreon/tests/php/Core/Command/Domain/Model/NewCommandTest.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\Command\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Command\Domain\Model\Argument;
use Core\Command\Domain\Model\CommandType;
use Core\Command\Domain\Model\NewCommand;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\CommandMacro\Domain\Model\NewCommandMacro;
use Core\Common\Domain\TrimmedString;
use Core\MonitoringServer\Model\MonitoringServer;
it('should return properly set instance', function (): void {
$command = new NewCommand(
name: new TrimmedString('command-name'),
commandLine: new TrimmedString('commandline'),
type: CommandType::Check,
isShellEnabled: false,
argumentExample: new TrimmedString('argExample'),
arguments: [new Argument(new TrimmedString('ARG1'), new TrimmedString('arg-desc'))],
macros: [new NewCommandMacro(CommandMacroType::Host, 'macro-name')],
connectorId: 1,
graphTemplateId: 2,
);
expect($command->getName())->toBe('command-name')
->and($command->getCommandLine())->toBe('commandline')
->and($command->getType())->toBe(CommandType::Check)
->and($command->isShellEnabled())->toBe(false)
->and($command->getArgumentExample())->toBe('argExample')
->and($command->getArguments()[0]->getName())->toBe('ARG1')
->and($command->getMacros()[0]->getName())->toBe('macro-name')
->and($command->getConnectorId())->toBe(1)
->and($command->getGraphTemplateId())->toBe(2);
});
it('should throw an exception when name is empty', function (): void {
new NewCommand(
name: new TrimmedString(''),
commandLine: new TrimmedString('commandline'),
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewCommand::name')->getMessage()
);
it('should throw an exception when name is too long', function (): void {
new NewCommand(
name: new TrimmedString(str_repeat('a', NewCommand::NAME_MAX_LENGTH + 1)),
commandLine: new TrimmedString('commandline'),
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewCommand::NAME_MAX_LENGTH + 1),
NewCommand::NAME_MAX_LENGTH + 1,
NewCommand::NAME_MAX_LENGTH,
'NewCommand::name'
)->getMessage()
);
it('should throw an exception when name contains invalid characters', function (): void {
new NewCommand(
name: new TrimmedString('command-name-' . MonitoringServer::ILLEGAL_CHARACTERS[0] . '-test'),
commandLine: new TrimmedString('commandline'),
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::unauthorizedCharacters(
'command-name-' . MonitoringServer::ILLEGAL_CHARACTERS[0] . '-test',
MonitoringServer::ILLEGAL_CHARACTERS[0],
'NewCommand::name'
)->getMessage()
);
it('should throw an exception when command line is empty', function (): void {
new NewCommand(
name: new TrimmedString('command-line'),
commandLine: new TrimmedString(''),
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewCommand::commandLine')->getMessage()
);
it('should throw an exception when command line is too long', function (): void {
new NewCommand(
name: new TrimmedString('command-name'),
commandLine: new TrimmedString(str_repeat('a', NewCommand::COMMAND_MAX_LENGTH + 1)),
type: CommandType::Check
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewCommand::COMMAND_MAX_LENGTH + 1),
NewCommand::COMMAND_MAX_LENGTH + 1,
NewCommand::COMMAND_MAX_LENGTH,
'NewCommand::commandLine'
)->getMessage()
);
it('should throw an exception when argument example is too long', function (): void {
new NewCommand(
name: new TrimmedString('command-name'),
commandLine: new TrimmedString('commandLine'),
type: CommandType::Check,
argumentExample: new TrimmedString(str_repeat('a', NewCommand::EXAMPLE_MAX_LENGTH + 1)),
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewCommand::EXAMPLE_MAX_LENGTH + 1),
NewCommand::EXAMPLE_MAX_LENGTH + 1,
NewCommand::EXAMPLE_MAX_LENGTH,
'NewCommand::argumentExample'
)->getMessage()
);
it('should throw an exception when connector ID is < 1', function (): void {
new NewCommand(
name: new TrimmedString('command-name'),
commandLine: new TrimmedString('commandline'),
type: CommandType::Check,
connectorId: 0
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::positiveInt(0, 'NewCommand::connectorId')->getMessage()
);
it('should throw an exception when graph template ID is < 1', function (): void {
new NewCommand(
name: new TrimmedString('command-name'),
commandLine: new TrimmedString('commandline'),
type: CommandType::Check,
graphTemplateId: 0
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::positiveInt(0, 'NewCommand::graphTemplateId')->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/Command/Infrastructure/API/AddCommand/AddCommandPresenterStub.php | centreon/tests/php/Core/Command/Infrastructure/API/AddCommand/AddCommandPresenterStub.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\Command\Infrastructure\API\AddCommand;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Command\Application\UseCase\AddCommand\AddCommandPresenterInterface;
use Core\Command\Application\UseCase\AddCommand\AddCommandResponse;
class AddCommandPresenterStub extends AbstractPresenter implements AddCommandPresenterInterface
{
public AddCommandResponse|ResponseStatusInterface $response;
public function presentResponse(ResponseStatusInterface|AddCommandResponse $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/Command/Infrastructure/API/FindCommands/FindCommandsPresenterStub.php | centreon/tests/php/Core/Command/Infrastructure/API/FindCommands/FindCommandsPresenterStub.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\Command\Infrastructure\API\FindCommands;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Command\Application\UseCase\FindCommands\FindCommandsPresenterInterface;
use Core\Command\Application\UseCase\FindCommands\FindCommandsResponse;
class FindCommandsPresenterStub extends AbstractPresenter implements FindCommandsPresenterInterface
{
public FindCommandsResponse|ResponseStatusInterface $response;
public function presentResponse(ResponseStatusInterface|FindCommandsResponse $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/Command/Infrastructure/Command/MigrateAllCommands/MigrateAllCommandsPresenterStub.php | centreon/tests/php/Core/Command/Infrastructure/Command/MigrateAllCommands/MigrateAllCommandsPresenterStub.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\Command\Infrastructure\Command\MigrateAllCommands;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Command\Application\UseCase\MigrateAllCommands\MigrateAllCommandsPresenterInterface;
use Core\Command\Application\UseCase\MigrateAllCommands\MigrateAllCommandsResponse;
class MigrateAllCommandsPresenterStub implements MigrateAllCommandsPresenterInterface
{
public ResponseStatusInterface|MigrateAllCommandsResponse $response;
public function presentResponse(MigrateAllCommandsResponse|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/Centreon/DependencyInjector.php | centreon/tests/php/Centreon/DependencyInjector.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon;
use ArrayAccess;
class DependencyInjector implements ArrayAccess
{
/** @var self */
protected static $instance;
/** @var array */
protected $container;
/**
* Get instance of the object
*
* @return self
*/
public static function getInstance(): self
{
if (! static::$instance instanceof DependencyInjector) {
static::$instance = new DependencyInjector();
}
return static::$instance;
}
/**
* Setter
*
* @param mixed $offset
* @param mixed $value
*/
public function offsetSet($offset, $value): void
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset): bool
{
return isset($this->container[$offset]);
}
/**
* @param mixed $offset
*/
public function offsetUnset($offset): void
{
unset($this->container[$offset]);
}
/**
* Getter
*
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset): mixed
{
return $this->container[$offset] ?? null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/AuthenticationControllerTest.php | centreon/tests/php/Centreon/Application/Controller/AuthenticationControllerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Application\Controller;
use Centreon\Application\Controller\AuthenticationController;
use Centreon\Domain\Authentication\Exception\AuthenticationException;
use Centreon\Domain\Authentication\UseCase\AuthenticateApi;
use Centreon\Domain\Authentication\UseCase\AuthenticateApiResponse;
use Centreon\Domain\Authentication\UseCase\Logout;
use Centreon\Domain\Contact\Contact;
use FOS\RestBundle\View\View;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Security\Infrastructure\Authentication\API\Model_2110\ApiAuthenticationFactory;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @package Tests\Centreon\Application\Controller
*/
class AuthenticationControllerTest extends TestCase
{
/** @var Contact */
protected $adminContact;
/** @var AuthenticateApi|\PHPUnit\Framework\MockObject\MockObject */
protected $authenticateApi;
/** @var Logout|\PHPUnit\Framework\MockObject\MockObject */
protected $logout;
/** @var ContainerInterface|\PHPUnit\Framework\MockObject\MockObject */
protected $container;
/** @var Request|\PHPUnit\Framework\MockObject\MockObject */
protected $request;
protected function setUp(): void
{
$timezone = new \DateTimeZone('Europe/Paris');
$this->adminContact = (new Contact())
->setId(1)
->setAlias('admin')
->setName('admin')
->setEmail('root@localhost')
->setAdmin(true)
->setTimezone($timezone);
$this->authenticateApi = $this->createMock(AuthenticateApi::class);
$this->logout = $this->createMock(Logout::class);
$this->container = $this->createMock(ContainerInterface::class);
$this->request = $this->createMock(Request::class);
}
/**
* test login
*/
public function testLogin(): void
{
$authenticationController = new AuthenticationController();
$authenticationController->setContainer($this->container);
$this->request
->expects($this->once())
->method('getContent')
->willReturn(json_encode([
'security' => [
'credentials' => [
'login' => 'admin',
'password' => 'centreon',
],
],
]));
$response = new AuthenticateApiResponse();
$response->setApiAuthentication(
$this->adminContact,
'token'
);
$view = $authenticationController->login($this->request, $this->authenticateApi, $response);
$this->assertEquals(
View::create(ApiAuthenticationFactory::createFromResponse($response)),
$view
);
}
/**
* test login with bad credentials
*/
public function testLoginFailed(): void
{
$authenticationController = new AuthenticationController();
$authenticationController->setContainer($this->container);
$this->request
->expects($this->once())
->method('getContent')
->willReturn(json_encode([
'security' => [
'credentials' => [
'login' => 'toto',
'password' => 'centreon',
],
],
]));
$response = new AuthenticateApiResponse();
$response->setApiAuthentication(
$this->adminContact,
'token'
);
$this->authenticateApi
->expects($this->once())
->method('execute')
->willThrowException(AuthenticationException::invalidCredentials());
$view = $authenticationController->login($this->request, $this->authenticateApi, $response);
$this->assertEquals(
View::create(
[
'code' => Response::HTTP_UNAUTHORIZED,
'message' => 'Authentication failed',
],
Response::HTTP_UNAUTHORIZED
),
$view
);
}
public function testLogout(): void
{
$authenticationController = new AuthenticationController();
$authenticationController->setContainer($this->container);
$this->request->headers = new HeaderBag([
'X-AUTH-TOKEN' => 'token',
]);
$view = $authenticationController->logout($this->request, $this->logout);
$this->assertEquals(
View::create([
'message' => 'Successful logout',
]),
$view
);
}
public function testLogoutFailed(): void
{
$authenticationController = new AuthenticationController();
$authenticationController->setContainer($this->container);
$this->request->headers = new HeaderBag();
$view = $authenticationController->logout($this->request, $this->logout);
$this->assertEquals(
View::create(
[
'code' => Response::HTTP_UNAUTHORIZED,
'message' => 'Authentication failed',
],
Response::HTTP_UNAUTHORIZED
),
$view
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/PlatformTopologyControllerTest.php | centreon/tests/php/Centreon/Application/Controller/PlatformTopologyControllerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Application\Controller;
use Centreon\Application\Controller\PlatformTopologyController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\PlatformTopology\Exception\PlatformTopologyException;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformTopologyServiceInterface;
use Centreon\Domain\PlatformTopology\Model\PlatformPending;
use Centreon\Domain\PlatformTopology\Model\PlatformRegistered;
use Centreon\Domain\PlatformTopology\Model\PlatformRelation;
use Centreon\Domain\PlatformTopology\PlatformTopologyService;
use Centreon\Infrastructure\PlatformTopology\Repository\Model\PlatformJsonGraph;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class PlatformTopologyControllerTest extends TestCase
{
protected $goodJsonPlatform;
protected $badJsonPlatform;
/** @var PlatformPending|null */
protected $platform;
/** @var Contact */
protected $adminContact;
/** @var PlatformRegistered */
protected $centralPlatform;
/** @var PlatformPending */
protected $pollerPlatform;
/** @var PlatformJsonGraph */
protected $centralJsonGraphFormat;
/** @var PlatformJsonGraph */
protected $pollerJsonGraphFormat;
/** @var PlatformTopologyService&MockObject */
protected $platformTopologyService;
protected $container;
protected $request;
protected function setUp(): void
{
$timezone = new \DateTimeZone('Europe/Paris');
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true)
->setTimezone($timezone);
$this->adminContact->addTopologyRule(Contact::ROLE_CONFIGURATION_MONITORING_SERVER_READ_WRITE);
$goodJsonPlatform = [
'name' => 'poller1',
'hostname' => 'localhost.localdomain',
'address' => '1.1.1.2',
'type' => 'poller',
'parent_address' => '1.1.1.1',
];
$this->goodJsonPlatform = json_encode($goodJsonPlatform);
$this->platform = (new PlatformPending())
->setName($goodJsonPlatform['name'])
->setRelation('normal')
->setHostname($goodJsonPlatform['hostname'])
->setAddress($goodJsonPlatform['address'])
->setType($goodJsonPlatform['type'])
->setParentAddress($goodJsonPlatform['parent_address']);
$this->centralPlatform = (new PlatformRegistered())
->setId(1)
->setName('Central')
->setHostname('localhost.localdomain')
->setType(PlatformRegistered::TYPE_CENTRAL)
->setAddress('192.168.1.1')
->setServerId(1)
->setRelation(PlatformRelation::NORMAL_RELATION);
$this->pollerPlatform = (new PlatformPending())
->setId(2)
->setName('Poller')
->setHostname('poller.poller1')
->setType(PlatformRegistered::TYPE_POLLER)
->setAddress('192.168.1.2')
->setParentAddress('192.168.1.1')
->setParentId(1)
->setServerId(2)
->setRelation(PlatformRelation::NORMAL_RELATION);
$this->centralJsonGraphFormat = new PlatformJsonGraph($this->centralPlatform);
$this->pollerJsonGraphFormat = new PlatformJsonGraph($this->pollerPlatform);
$this->badJsonPlatform = json_encode([
'unknown_property' => 'unknown',
]);
$this->platformTopologyService = $this->createMock(PlatformTopologyServiceInterface::class);
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$authorizationChecker->expects($this->once())
->method('isGranted')
->willReturn(true);
$token = $this->createMock(TokenInterface::class);
$token->expects($this->any())
->method('getUser')
->willReturn($this->adminContact);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage->expects($this->any())
->method('getToken')
->willReturn($token);
$this->container = $this->createMock(ContainerInterface::class);
$this->container->expects($this->any())
->method('has')
->willReturn(true);
$this->container->expects($this->any())
->method('get')
->willReturnOnConsecutiveCalls(
$authorizationChecker,
$tokenStorage,
new class () {
public function get(): string
{
return __DIR__ . '/../../../../../';
}
}
);
$this->request = $this->createMock(Request::class);
}
/**
* test addPlatformToTopology with bad json format
*/
public function testAddPlatformToTopologyBadJsonFormat(): void
{
$platformTopologyController = new PlatformTopologyController($this->platformTopologyService);
$platformTopologyController->setContainer($this->container);
$this->request->expects($this->once())
->method('getContent')
->willReturn('[}');
$this->expectException(PlatformTopologyException::class);
$this->expectExceptionMessage('Error when decoding sent data');
$this->expectExceptionCode(Response::HTTP_BAD_REQUEST);
$platformTopologyController->addPlatformToTopology($this->request);
}
/**
* test addPlatformToTopology with conflict
* @throws PlatformTopologyException
*/
public function testAddPlatformToTopologyConflict(): void
{
$platformTopologyController = new PlatformTopologyController($this->platformTopologyService);
$platformTopologyController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->goodJsonPlatform);
$this->platformTopologyService->expects($this->any())
->method('addPendingPlatformToTopology')
->will($this->throwException(new PlatformTopologyException('conflict')));
$view = $platformTopologyController->addPlatformToTopology($this->request);
$this->assertEquals(
$view,
View::create(['message' => 'conflict'], Response::HTTP_BAD_REQUEST)
);
}
/**
* test addPlatformToTopology with bad request
* @throws PlatformTopologyException
*/
public function testAddPlatformToTopologyBadRequest(): void
{
$platformTopologyController = new PlatformTopologyController($this->platformTopologyService);
$platformTopologyController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->goodJsonPlatform);
$this->platformTopologyService->expects($this->any())
->method('addPendingPlatformToTopology')
->will($this->throwException(new PlatformTopologyException('bad request')));
$view = $platformTopologyController->addPlatformToTopology($this->request);
$this->assertEquals(
$view,
View::create(['message' => 'bad request'], Response::HTTP_BAD_REQUEST)
);
}
/**
* test addPlatformToTopology which succeed
* @throws PlatformTopologyException
*/
public function testAddPlatformToTopologySuccess(): void
{
$platformTopologyController = new PlatformTopologyController($this->platformTopologyService);
$platformTopologyController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->goodJsonPlatform);
$view = $platformTopologyController->addPlatformToTopology($this->request);
$this->assertEquals(
$view,
View::create(null, Response::HTTP_CREATED)
);
}
public function testGetPlatformJsonGraph(): void
{
$platformTopologyController = new PlatformTopologyController($this->platformTopologyService);
$platformTopologyController->setContainer($this->container);
$completeTopology = [$this->centralPlatform, $this->pollerPlatform];
$nodes[$this->centralJsonGraphFormat->getId()] = $this->centralJsonGraphFormat;
$nodes[$this->pollerJsonGraphFormat->getId()] = $this->pollerJsonGraphFormat;
$this->platformTopologyService->expects($this->once())
->method('getPlatformTopology')
->willReturn($completeTopology);
$view = $platformTopologyController->getPlatformJsonGraph();
$context = (new Context())->setGroups(PlatformTopologyController::SERIALIZER_GROUP_JSON_GRAPH);
$this->assertEquals(
$view,
View::create(
[
'graph' => [
'label' => 'centreon-topology',
'metadata' => [
'version' => '1.0.0',
],
'nodes' => $nodes,
'edges' => [
[
'source' => '2',
'relation' => 'normal',
'target' => '1',
],
],
],
],
Response::HTTP_OK
)->setContext($context)
);
}
public function testDeletePlatformTopologySuccess(): void
{
$platformTopologyController = new PlatformTopologyController($this->platformTopologyService);
$platformTopologyController->setContainer($this->container);
$this->platformTopologyService->expects($this->once())
->method('isValidPlatform')
->willReturn(true);
$view = $platformTopologyController->deletePlatform($this->pollerPlatform->getId());
$this->assertEquals(
View::create(null, Response::HTTP_NO_CONTENT),
$view,
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/AbstractControllerTest.php | centreon/tests/php/Centreon/Application/Controller/AbstractControllerTest.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\Centreon\Application\Controller;
use Centreon\Application\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
beforeEach(function (): void {
$this->validateDataSentController = new class () extends AbstractController {
// We expose a public method to make the protected function testable.
public function testValidateDataSent(Request $request, string $jsonSchema): ?string
{
// Write the json schema in a temporary file
$jsonTempFile = tempnam(sys_get_temp_dir(), 'jsonSchema');
if ($jsonTempFile === false || file_put_contents($jsonTempFile, $jsonSchema) === false) {
throw new \Exception('Failed to create a temporary JSON schema file for the AbstractControllerTest');
}
try {
// Call of the protected method.
$this->validateDataSent($request, $jsonTempFile);
return null;
} catch (\InvalidArgumentException $ex) {
return $ex->getMessage();
}
}
};
});
// ────────────────────────────── FAILURES tests ──────────────────────────────
it(
'should NOT validate',
function (string $error, string $content, string $jsonSchema): void {
$request = $this->createMock(Request::class);
$request->method('getContent')->willReturn($content);
$return = $this->validateDataSentController->testValidateDataSent($request, $jsonSchema);
if ($return === null) {
$this->fail('Validated despite all expectations !!');
}
expect($return)->toContain($error);
}
)->with([
'JSON is an integer' => ['Error when decoding your sent data', '42', ''],
'JSON is a float' => ['Error when decoding your sent data', '1.23', ''],
'JSON is a string' => ['Error when decoding your sent data', '"foo"', ''],
'JSON is a boolean' => ['Error when decoding your sent data', 'false', ''],
'JSON is a null' => ['Error when decoding your sent data', 'null', ''],
'JSON is an emtpy array, expect an object' => [
'Array value found, but an object is required',
'[]',
<<<'JSON'
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object"
}
JSON,
],
'JSON is an emtpy object, expect an array' => [
'Object value found, but an array is required',
'{}',
<<<'JSON'
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": { "type": "object" }
}
JSON,
],
'JSON is an object containing an sub-object, expect an sub-array' => [
'[myProperty] Object value found, but an array is required',
'{"myProperty": {} }',
<<<'JSON'
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"myProperty": { "type": "array" }
}
}
JSON,
],
'JSON is an object containing an sub-array, expect an sub-object' => [
'[myProperty] Array value found, but an object is required',
'{"myProperty": [] }',
<<<'JSON'
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"myProperty": { "type": "object" }
}
}
JSON,
],
]);
// ────────────────────────────── SUCCESS tests ──────────────────────────────
it(
'should validate',
function (string $content, string $jsonSchema): void {
$request = $this->createMock(Request::class);
$request->method('getContent')->willReturn($content);
$return = $this->validateDataSentController->testValidateDataSent($request, $jsonSchema);
expect($return)->toBeNull();
}
)->with([
'JSON is an array of objects' => [
'[{}]',
<<<'JSON'
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": { "type": "object" }
}
JSON,
],
'JSON is an array of objects but empty' => [
'[]',
<<<'JSON'
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": { "type": "object" }
}
JSON,
],
'JSON is an empty object' => [
'{}',
<<<'JSON'
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object"
}
JSON,
],
'JSON is an object containing an sub-object' => [
'{"myProperty": [] }',
<<<'JSON'
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"myProperty": { "type": "array" }
}
}
JSON,
],
'JSON is an object containing an sub-array' => [
'{"myProperty": {} }',
<<<'JSON'
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"myProperty": { "type": "object" }
}
}
JSON,
],
]);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/Monitoring/TimelineControllerTest.php | centreon/tests/php/Centreon/Application/Controller/Monitoring/TimelineControllerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\Monitoring\TimelineController;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Centreon\Domain\Monitoring\ResourceStatus;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Monitoring\Timeline\Interfaces\TimelineServiceInterface;
use Centreon\Domain\Monitoring\Timeline\TimelineEvent;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class TimelineControllerTest extends TestCase
{
protected MockObject|ContactInterface $contact;
protected MockObject|UserInterface $user;
protected Host $host;
/** @var MockObject|Service */
protected $service;
/** @var MockObject|TimelineEvent */
protected $timelineEvent;
/** @var MockObject|MonitoringServiceInterface */
protected $monitoringService;
/** @var MockObject|TimelineServiceInterface */
protected $timelineService;
/** @var MockObject|ContainerInterface */
protected $container;
/** @var MockObject|RequestParametersInterface */
protected $requestParameters;
protected function setUp(): void
{
$timezone = new \DateTimeZone('Europe/Paris');
$this->contact = $this->createMock(ContactInterface::class);
$this->user = $this->createMock(UserInterface::class);
/*(new Contact())
->setId(1)
->setName('admin')
->setAdmin(true)
->setTimezone($timezone);*/
$this->host = (new Host())
->setId(1);
$this->service = (new Service())
->setId(1);
$this->service->setHost($this->host);
$resourceStatus = (new ResourceStatus())
->setCode(0)
->setName('UP')
->setSeverityCode(4);
$this->timelineEvent = (new TimelineEvent())
->setId(1)
->setType('event')
->setDate((new \Datetime())->setTimestamp(1581980400)->setTimezone($timezone))
->setContent('output')
->setStatus($resourceStatus)
->setTries(1);
$this->monitoringService = $this->createMock(MonitoringServiceInterface::class);
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->timelineService = $this->createMock(TimelineServiceInterface::class);
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$authorizationChecker->expects($this->once())
->method('isGranted')
->willReturn(true);
$token = $this->createMock(TokenInterface::class);
$token->expects($this->any())
->method('getUser')
->willReturn($this->user);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage->expects($this->any())
->method('getToken')
->willReturn($token);
$this->container = $this->createMock(ContainerInterface::class);
$this->container->expects($this->any())
->method('has')
->willReturn(true);
$this->container->expects($this->any())
->method('get')
->willReturnOnConsecutiveCalls(
$authorizationChecker,
$tokenStorage
);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
}
/**
* test getHostTimeline
*/
public function testGetHostTimeline(): void
{
$this->timelineService->expects($this->once())
->method('findTimelineEventsByHost')
->willReturn([$this->timelineEvent]);
$timelineController = new TimelineController($this->monitoringService, $this->timelineService, $this->contact);
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$timelineController->setContainer($this->container);
$view = $timelineController->getHostTimeline(1, $this->requestParameters);
$context = (new Context())
->setGroups(TimelineController::SERIALIZER_GROUPS_MAIN)
->enableMaxDepth();
$this->assertEquals(
$view,
View::create([
'result' => [$this->timelineEvent],
'meta' => [],
])->setContext($context)
);
}
/**
* test getServiceTimeline
*/
public function testGetServiceTimeline(): void
{
$this->monitoringService->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->timelineService->expects($this->once())
->method('findTimelineEventsByService')
->willReturn([$this->timelineEvent]);
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$timelineController = new TimelineController($this->monitoringService, $this->timelineService, $this->contact);
$timelineController->setContainer($this->container);
$view = $timelineController->getServiceTimeline(1, 1, $this->requestParameters);
$context = (new Context())
->setGroups(TimelineController::SERIALIZER_GROUPS_MAIN)
->enableMaxDepth();
$this->assertEquals(
$view,
View::create([
'result' => [$this->timelineEvent],
'meta' => [],
])->setContext($context)
);
}
public function testDownloadServiceTimeline(): void
{
$this->monitoringService
->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->requestParameters
->expects($this->once())
->method('setPage')
->with($this->equalTo(1));
$this->requestParameters
->expects($this->once())
->method('setLimit')
->with($this->equalTo(1000000000));
$this->timelineService->expects($this->once())
->method('findTimelineEventsByService')
->willReturn([$this->timelineEvent]);
$controller = new TimelineController($this->monitoringService, $this->timelineService, $this->contact);
// buffer output for streamed response
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
ob_start();
$controller->setContainer($this->container);
$response = $controller->downloadServiceTimeline(1, 1, $this->requestParameters);
$response->sendContent();
echo $response->getContent();
$actualContent = ob_get_contents();
ob_end_clean();
$this->assertInstanceOf(StreamedResponse::class, $response);
$this->assertSame('application/force-download', $response->headers->get('Content-Type'));
$this->assertSame('attachment; filename="export.csv"', $response->headers->get('content-disposition'));
$expectedContent = 'type;date;content;contact;status;tries' . PHP_EOL;
$expectedContent .= 'event;2020-02-18T00:00:00+01:00;output;;UP;1' . PHP_EOL;
$this->assertEquals($expectedContent, $actualContent);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/Monitoring/CommentControllerTest.php | centreon/tests/php/Centreon/Application/Controller/Monitoring/CommentControllerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\Monitoring\CommentController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Monitoring\Comment\CommentService;
use Centreon\Domain\Monitoring\MonitoringService;
use Centreon\Domain\Monitoring\Resource;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use FOS\RestBundle\View\View;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class CommentControllerTest extends TestCase
{
private const DECODING_ERROR_MESSAGE = 'Error when decoding your sent data';
private Contact $adminContact;
private Resource $hostResource;
private Resource $serviceResource;
private string $correctJsonComment;
private string $wrongJsonComment;
private string $hostCommentJson;
private string $serviceCommentJson;
private CommentService&MockObject $commentService;
private MonitoringService $monitoringService;
private ContainerInterface $container;
private Request&MockObject $request;
private ReadAccessGroupRepositoryInterface $readAccessGroupRepository;
protected function setUp(): void
{
$timezone = new \DateTimeZone('Europe/Paris');
$dateTime = new \DateTime('now');
$date = $dateTime->format(\DateTime::ATOM);
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true)
->setTimezone($timezone);
$correctJsonComment = [
'resources' => [
[
'type' => 'host',
'id' => 1,
'parent' => null,
'comment' => 'simple comment on a host resource',
'date' => null,
],
[
'type' => 'service',
'id' => 1,
'parent' => [
'id' => 1,
],
'comment' => 'simple comment on a service resource',
'date' => $date,
],
],
];
$hostCommentJson = [
'comment' => 'single comment on a service',
'date' => $date,
];
$serviceCommentJson = [
'comment' => 'single comment on a host',
'date' => $date,
];
$this->hostResource = (new Resource())
->setType($correctJsonComment['resources'][0]['type'])
->setId($correctJsonComment['resources'][0]['id']);
$this->serviceResource = (new Resource())
->setType($correctJsonComment['resources'][1]['type'])
->setId($correctJsonComment['resources'][1]['id'])
->setParent($this->hostResource);
$this->correctJsonComment = json_encode($correctJsonComment);
$this->serviceCommentJson = json_encode($serviceCommentJson);
$this->hostCommentJson = json_encode($hostCommentJson);
$this->wrongJsonComment = json_encode([
'unknown_property' => 'unknown',
]);
$this->commentService = $this->createMock(CommentService::class);
$this->monitoringService = $this->createMock(MonitoringService::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->readAccessGroupRepository->method('findByContact')->willReturn([]);
$this->readAccessGroupRepository->method('hasAccessToResources')->willReturn(true);
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$authorizationChecker->expects($this->once())
->method('isGranted')
->willReturn(true);
$token = $this->createMock(TokenInterface::class);
$token->expects($this->any())
->method('getUser')
->willReturn($this->adminContact);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage->expects($this->any())
->method('getToken')
->willReturn($token);
$this->container = $this->createMock(ContainerInterface::class);
$this->container->expects($this->any())
->method('has')
->willReturn(true);
$this->container->expects($this->any())
->method('get')
->willReturnOnConsecutiveCalls(
$authorizationChecker,
$tokenStorage,
new class () {
public function get()
{
return __DIR__ . '/../../../../../';
}
}
);
$this->request = $this->createMock(Request::class);
}
/**
* Testing wrongly formatted JSON POST data for addResourcesComment
*/
public function testaddResourcesCommentBadJsonFormat(): void
{
$commentController = new CommentController(
$this->commentService,
$this->monitoringService,
$this->readAccessGroupRepository
);
$commentController->setContainer($this->container);
$this->request->expects($this->once())
->method('getContent')
->willReturn('[}');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(self::DECODING_ERROR_MESSAGE);
$commentController->addResourcesComment($this->request);
}
/**
* Testing with wrong property added to the POST JSON for addResourcesComment
*/
public function testCommentResourcesBadJsonProperties(): void
{
$commentController = new CommentController(
$this->commentService,
$this->monitoringService,
$this->readAccessGroupRepository
);
$commentController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->wrongJsonComment);
$this->expectException(\InvalidArgumentException::class);
$commentController->addResourcesComment($this->request);
}
/**
* Testing with a correct JSON POST data and successfully adding a comment to a resource
*/
public function testAddResourcesCommentSuccess(): void
{
$this->commentService->expects($this->any())
->method('filterByContact')
->willReturn($this->commentService);
$commentController = new CommentController(
$this->commentService,
$this->monitoringService,
$this->readAccessGroupRepository
);
$commentController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->correctJsonComment);
$view = $commentController->addResourcesComment($this->request);
$this->assertEquals($view, View::create(null, Response::HTTP_NO_CONTENT));
}
/**
* Testing with wrongly formatted JSON POST data for addHostComment
*/
public function testAddHostCommentBadJsonFormat(): void
{
$commentController = new CommentController(
$this->commentService,
$this->monitoringService,
$this->readAccessGroupRepository
);
$commentController->setContainer($this->container);
$this->request->expects($this->once())
->method('getContent')
->willReturn('[}');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(self::DECODING_ERROR_MESSAGE);
$commentController->addHostComment($this->request, $this->hostResource->getId());
}
/**
* Testing with wrong property added to the POST JSON for addHostComment
*/
public function testAddHostCommentBadJsonProperties(): void
{
$commentController = new CommentController(
$this->commentService,
$this->monitoringService,
$this->readAccessGroupRepository
);
$commentController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->wrongJsonComment);
$this->expectException(\InvalidArgumentException::class);
$commentController->addHostComment($this->request, $this->hostResource->getId());
}
/**
* Testing with a correct JSON POST data and successfully adding a comment for a host resource
*/
public function testAddHostCommentSuccess(): void
{
$this->commentService->expects($this->any())
->method('filterByContact')
->willReturn($this->commentService);
$commentController = new CommentController(
$this->commentService,
$this->monitoringService,
$this->readAccessGroupRepository
);
$commentController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->hostCommentJson);
$view = $commentController->addHostComment($this->request, $this->hostResource->getId());
$this->assertEquals($view, View::create(null, Response::HTTP_NO_CONTENT));
}
/**
* Testing with wrongly formatted JSON POST data for addServiceComment
*/
public function testAddServiceCommentBadJsonFormat(): void
{
$commentController = new CommentController(
$this->commentService,
$this->monitoringService,
$this->readAccessGroupRepository
);
$commentController->setContainer($this->container);
$this->request->expects($this->once())
->method('getContent')
->willReturn('[}');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(self::DECODING_ERROR_MESSAGE);
$commentController->addServiceComment(
$this->request,
$this->serviceResource->getParent()->getId(),
$this->serviceResource->getId()
);
}
/**
* Testing with wrong property added to the POST JSON for addServiceComment
*/
public function testAddServiceCommentBadJsonProperties(): void
{
$commentController = new CommentController(
$this->commentService,
$this->monitoringService,
$this->readAccessGroupRepository
);
$commentController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->wrongJsonComment);
$this->expectException(\InvalidArgumentException::class);
$commentController->addServiceComment(
$this->request,
$this->serviceResource->getParent()->getId(),
$this->serviceResource->getId()
);
}
/**
* Testing with a correct JSON POST data and successfully adding comment for a service resource
*/
public function testAddServiceCommentSuccess(): void
{
$this->commentService->expects($this->any())
->method('filterByContact')
->willReturn($this->commentService);
$commentController = new CommentController(
$this->commentService,
$this->monitoringService,
$this->readAccessGroupRepository
);
$commentController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->serviceCommentJson);
$view = $commentController->addServiceComment(
$this->request,
$this->serviceResource->getParent()->getId(),
$this->serviceResource->getId()
);
$this->assertEquals($view, View::create(null, Response::HTTP_NO_CONTENT));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/Monitoring/MetricControllerTest.php | centreon/tests/php/Centreon/Application/Controller/Monitoring/MetricControllerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\Monitoring\MetricController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
use Centreon\Domain\Monitoring\Metric\Interfaces\MetricServiceInterface;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use FOS\RestBundle\View\View;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class MetricControllerTest extends TestCase
{
protected $adminContact;
protected $host;
protected $service;
protected $metrics;
protected $start;
protected $end;
protected $monitoringService;
protected $metricService;
protected $container;
protected $requestParameters;
protected array $normalizedPerformanceMetrics = [];
protected array $status = [];
protected function setUp(): void
{
$timezone = new \DateTimeZone('Europe/Paris');
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true)
->setTimezone($timezone);
$this->host = (new Host())
->setId(1);
$this->service = (new Service())
->setId(1);
$this->service->setHost($this->host);
$this->metrics = [
'global' => [
'start' => '1581980400',
'end' => '1582023600',
],
'metrics' => [],
'times' => [],
];
$this->normalizedPerformanceMetrics = [
'global' => [
'start' => (new \Datetime())->setTimestamp(1581980400)->setTimezone($timezone),
'end' => (new \Datetime())->setTimestamp(1582023600)->setTimezone($timezone),
],
'metrics' => [],
'times' => [],
];
$this->status = [
'critical' => [],
'wraning' => [],
'ok' => [],
'unknown' => [],
];
$this->start = new \DateTime('2020-02-18T00:00:00');
$this->end = new \DateTime('2020-02-18T12:00:00');
$this->metricService = $this->createMock(MetricServiceInterface::class);
$this->monitoringService = $this->createMock(MonitoringServiceInterface::class);
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$authorizationChecker->expects($this->once())
->method('isGranted')
->willReturn(true);
$token = $this->createMock(TokenInterface::class);
$token->expects($this->any())
->method('getUser')
->willReturn($this->adminContact);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage->expects($this->any())
->method('getToken')
->willReturn($token);
$this->container = $this->createMock(ContainerInterface::class);
$this->container->expects($this->any())
->method('has')
->willReturn(true);
$this->container->expects($this->any())
->method('get')
->willReturnOnConsecutiveCalls($authorizationChecker, $tokenStorage, $tokenStorage, $tokenStorage);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
}
/**
* test getServiceMetrics with not found host
*/
public function testGetServiceMetricsNotFoundHost(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn(null);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Host 1 not found');
$metricController->getServiceMetrics(1, 1, $this->start, $this->end);
}
/**
* test getServiceMetrics with not found service
*/
public function testGetServiceMetricsNotFoundService(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringService->expects($this->once())
->method('findOneService')
->willReturn(null);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Service 1 not found');
$metricController->getServiceMetrics(1, 1, $this->start, $this->end);
}
/**
* test getServiceMetrics which succeed
*/
public function testGetServiceMetricsSucceed(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringService->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->metricService->expects($this->once())
->method('filterByContact')
->willReturn($this->metricService);
$this->metricService->expects($this->once())
->method('findMetricsByService')
->willReturn($this->metrics);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$metrics = $metricController->getServiceMetrics(1, 1, $this->start, $this->end);
$this->assertEquals(
$metrics,
View::create($this->metrics, null, [])
);
}
/**
* test getServiceStatus with not found host
*/
public function testGetServiceStatusNotFoundHost(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn(null);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Host 1 not found');
$metricController->getServiceStatus(1, 1, $this->start, $this->end);
}
/**
* test getServiceStatus with not found service
*/
public function testGetServiceStatusNotFoundService(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringService->expects($this->once())
->method('findOneService')
->willReturn(null);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Service 1 not found');
$metricController->getServiceStatus(1, 1, $this->start, $this->end);
}
/**
* test getServiceStatus which succeed
*/
public function testGetServiceStatusSucceed(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringService->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->metricService->expects($this->once())
->method('filterByContact')
->willReturn($this->metricService);
$this->metricService->expects($this->once())
->method('findStatusByService')
->willReturn($this->status);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$status = $metricController->getServiceStatus(1, 1, $this->start, $this->end);
$this->assertEquals(
$status,
View::create($this->status, null, [])
);
}
/**
* test getServicePerformanceMetrics with not found host
*/
public function testGetServicePerformanceMetricsNotFoundHost(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn(null);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Host 1 not found');
$metricController->getServiceMetrics(1, 1, $this->start, $this->end);
}
/**
* test getServicePerformanceMetrics with not found service
*/
public function testGetServicePerformanceMetricsNotFoundService(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringService->expects($this->once())
->method('findOneService')
->willReturn(null);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Service 1 not found');
$metricController->getServicePerformanceMetrics($this->requestParameters, 1, 1);
}
/**
* test getServicePerformanceMetrics with wrong start date format
*/
public function testGetServicePerformanceMetricsWrongStartDate(): void
{
$this->requestParameters->expects($this->exactly(2))
->method('getExtraParameter')
->willReturnOnConsecutiveCalls('wrong format', '2020-02-18T12:00:00');
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(NotFoundHttpException::class);
$this->expectExceptionMessage('Invalid date given for parameter "start".');
$metricController->getServicePerformanceMetrics($this->requestParameters, 1, 1);
}
/**
* test getServicePerformanceMetrics with wrong end date format
*/
public function testGetServicePerformanceMetricsWrongEndDate(): void
{
$this->requestParameters->expects($this->exactly(2))
->method('getExtraParameter')
->willReturnOnConsecutiveCalls('2020-02-18T00:00:00', 'wrong format');
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(NotFoundHttpException::class);
$this->expectExceptionMessage('Invalid date given for parameter "end".');
$metricController->getServicePerformanceMetrics($this->requestParameters, 1, 1);
}
/**
* test getServicePerformanceMetrics with start date greater than end date
*/
public function testGetServicePerformanceMetricsWrongDateRange(): void
{
$this->requestParameters->expects($this->exactly(2))
->method('getExtraParameter')
->willReturnOnConsecutiveCalls('2020-02-18T12:00:00', '2020-02-18T00:00:00');
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(\RangeException::class);
$this->expectExceptionMessage('End date must be greater than start date.');
$metricController->getServicePerformanceMetrics($this->requestParameters, 1, 1);
}
/**
* test getServicePerformanceMetrics which succeed
*/
public function testGetServicePerformanceMetricsSucceed(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringService->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->metricService->expects($this->once())
->method('filterByContact')
->willReturn($this->metricService);
$this->metricService->expects($this->once())
->method('findMetricsByService')
->willReturn($this->metrics);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$metrics = $metricController->getServicePerformanceMetrics($this->requestParameters, 1, 1);
$this->assertEquals(
$metrics,
View::create($this->normalizedPerformanceMetrics, null, [])
);
}
/**
* test getServiceStatusMetrics with not found host
*/
public function testGetServiceStatusMetricsNotFoundHost(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn(null);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Host 1 not found');
$metricController->getServiceStatusMetrics($this->requestParameters, 1, 1);
}
/**
* test getServiceStatusMetrics with not found service
*/
public function testGetServiceStatusMetricsNotFoundService(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringService->expects($this->once())
->method('findOneService')
->willReturn(null);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Service 1 not found');
$metricController->getServiceStatusMetrics($this->requestParameters, 1, 1);
}
/**
* test getServiceStatusMetrics which succeed
*/
public function testGetServiceStatusMetricsSucceed(): void
{
$this->monitoringService->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringService->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->metricService->expects($this->once())
->method('filterByContact')
->willReturn($this->metricService);
$this->metricService->expects($this->once())
->method('findStatusByService')
->willReturn($this->status);
$metricController = new MetricController($this->metricService, $this->monitoringService);
$metricController->setContainer($this->container);
$status = $metricController->getServiceStatusMetrics($this->requestParameters, 1, 1);
$this->assertEquals(
$status,
View::create($this->status, null, [])
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/Monitoring/SubmitResultControllerTest.php | centreon/tests/php/Centreon/Application/Controller/Monitoring/SubmitResultControllerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Application\Controller\Monitoring;
use Centreon\Application\Controller\Monitoring\SubmitResultController;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Monitoring\Resource;
use Centreon\Domain\Monitoring\SubmitResult\SubmitResultService;
use FOS\RestBundle\View\View;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class SubmitResultControllerTest extends TestCase
{
private const DECODING_ERROR_MESSAGE = 'Error when decoding your sent data';
private Contact $adminContact;
private Resource $hostResource;
private Resource $serviceResource;
private string $correctJsonSubmitResult;
private string $wrongJsonSubmitResult;
private string $hostSubmitResultJson;
private string $serviceSubmitResultJson;
private SubmitResultService&MockObject $submitResultService;
private ContainerInterface $container;
private Request&MockObject $request;
protected function setUp(): void
{
$timezone = new \DateTimeZone('Europe/Paris');
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true)
->setTimezone($timezone);
$correctJsonSubmitResult = [
'resources' => [
[
'type' => 'host',
'id' => 1,
'parent' => null,
'status' => 2,
'output' => 'Host went down',
'performance_data' => 'ping: 0',
],
[
'type' => 'service',
'id' => 1,
'parent' => [
'id' => 1,
],
'status' => 2,
'output' => 'Service went critical',
'performance_data' => 'proc: 0',
],
],
];
$hostSubmitResultJson = [
'status' => 2,
'output' => 'Host went down',
'performance_data' => 'ping: 0',
];
$serviceSubmitResultJson = [
'status' => 2,
'output' => 'Service went critical',
'performance_data' => 'proc: 0',
];
$this->hostResource = (new Resource())
->setType($correctJsonSubmitResult['resources'][0]['type'])
->setId($correctJsonSubmitResult['resources'][0]['id']);
$this->serviceResource = (new Resource())
->setType($correctJsonSubmitResult['resources'][1]['type'])
->setId($correctJsonSubmitResult['resources'][1]['id'])
->setParent($this->hostResource);
$this->correctJsonSubmitResult = json_encode($correctJsonSubmitResult);
$this->serviceSubmitResultJson = json_encode($serviceSubmitResultJson);
$this->hostSubmitResultJson = json_encode($hostSubmitResultJson);
$this->wrongJsonSubmitResult = json_encode([
'unknown_property' => 'unknown',
]);
$this->submitResultService = $this->createMock(SubmitResultService::class);
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$authorizationChecker->expects($this->once())
->method('isGranted')
->willReturn(true);
$token = $this->createMock(TokenInterface::class);
$token->expects($this->any())
->method('getUser')
->willReturn($this->adminContact);
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage->expects($this->any())
->method('getToken')
->willReturn($token);
$this->container = $this->createMock(ContainerInterface::class);
$this->container->expects($this->any())
->method('has')
->willReturn(true);
$this->container->expects($this->any())
->method('get')
->willReturnOnConsecutiveCalls(
$authorizationChecker,
$tokenStorage,
new class () {
public function get()
{
return __DIR__ . '/../../../../../';
}
}
);
$this->request = $this->createMock(Request::class);
}
/**
* Testing wrongly formatted JSON POST data for submitResultResources
*/
public function testSubmitResultResourcesBadJsonFormat(): void
{
$submitResultController = new SubmitResultController($this->submitResultService);
$submitResultController->setContainer($this->container);
$this->request->expects($this->once())
->method('getContent')
->willReturn('[}');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(self::DECODING_ERROR_MESSAGE);
$submitResultController->submitResultResources($this->request);
}
/**
* Testing with wrong property added to the POST JSON for submitResultResources
*/
public function testSubmitResultResourcesBadJsonProperties(): void
{
$submitResultController = new SubmitResultController($this->submitResultService);
$submitResultController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->wrongJsonSubmitResult);
$this->expectException(\InvalidArgumentException::class);
$submitResultController->submitResultResources($this->request);
}
/**
* Testing with a correct JSON POST data and successful submit for submitResultResources
*/
public function testSubmitResultResourcesSuccess(): void
{
$this->submitResultService->expects($this->any())
->method('filterByContact')
->willReturn($this->submitResultService);
$submitResultController = new SubmitResultController($this->submitResultService);
$submitResultController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->correctJsonSubmitResult);
$view = $submitResultController->submitResultResources($this->request);
$this->assertEquals($view, View::create(null, Response::HTTP_NO_CONTENT));
}
/**
* Tesring with wrongly formatted JSON POST data for submitResultHost
*/
public function testSubmitResultHostBadJsonFormat(): void
{
$submitResultController = new SubmitResultController($this->submitResultService);
$submitResultController->setContainer($this->container);
$this->request->expects($this->once())
->method('getContent')
->willReturn('[}');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(self::DECODING_ERROR_MESSAGE);
$submitResultController->submitResultHost($this->request, $this->hostResource->getId());
}
/**
* Testing with wrong property added to the POST JSON for submitResultHost
*/
public function testSubmitResultHostBadJsonProperties(): void
{
$submitResultController = new SubmitResultController($this->submitResultService);
$submitResultController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->wrongJsonSubmitResult);
$this->expectException(\InvalidArgumentException::class);
// $this->expectExceptionMessage('[status] The property status is required');
$submitResultController->submitResultHost($this->request, $this->hostResource->getId());
}
/**
* Testing with a correct JSON POST data and successful submit for submitResultHost
*/
public function testSubmitResultHostSuccess(): void
{
$this->submitResultService->expects($this->any())
->method('filterByContact')
->willReturn($this->submitResultService);
$submitResultController = new SubmitResultController($this->submitResultService);
$submitResultController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->hostSubmitResultJson);
$view = $submitResultController->submitResultHost($this->request, $this->hostResource->getId());
$this->assertEquals($view, View::create(null, Response::HTTP_NO_CONTENT));
}
/**
* Tesring with wrongly formatted JSON POST data for submitResultService
*/
public function testSubmitResultServiceBadJsonFormat(): void
{
$submitResultController = new SubmitResultController($this->submitResultService);
$submitResultController->setContainer($this->container);
$this->request->expects($this->once())
->method('getContent')
->willReturn('[}');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(self::DECODING_ERROR_MESSAGE);
$submitResultController->submitResultService(
$this->request,
$this->serviceResource->getParent()->getId(),
$this->serviceResource->getId()
);
}
/**
* Testing with wrong property added to the POST JSON for submitResultService
*/
public function testSubmitResultServiceBadJsonProperties(): void
{
$submitResultController = new SubmitResultController($this->submitResultService);
$submitResultController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->wrongJsonSubmitResult);
$this->expectException(\InvalidArgumentException::class);
// $this->expectExceptionMessage('[status] The property status is required');
$submitResultController->submitResultService(
$this->request,
$this->serviceResource->getParent()->getId(),
$this->serviceResource->getId()
);
}
/**
* Testing with a correct JSON POST data and successful submit for submitResultService
*/
public function testSubmitResultServiceSuccess(): void
{
$this->submitResultService->expects($this->any())
->method('filterByContact')
->willReturn($this->submitResultService);
$submitResultController = new SubmitResultController($this->submitResultService);
$submitResultController->setContainer($this->container);
$this->request->expects($this->any())
->method('getContent')
->willReturn($this->serviceSubmitResultJson);
$view = $submitResultController->submitResultService(
$this->request,
$this->serviceResource->getParent()->getId(),
$this->serviceResource->getId()
);
$this->assertEquals($view, View::create(null, Response::HTTP_NO_CONTENT));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/CheckController/ResourcesTestCase.php | centreon/tests/php/Centreon/Application/Controller/CheckController/ResourcesTestCase.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\Centreon\Application\Controller\CheckController;
use Centreon\Application\Controller\CheckController;
use Centreon\Domain\Check\Check;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Entity\EntityValidator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use FOS\RestBundle\View\View;
use JMS\Serializer\Exception\ValidationFailedException;
abstract class ResourcesTestCase extends TestCase
{
/**
* @test
*/
public function adminPrivilegeIsRequiredForAction(): void
{
$this->assertAdminPrivilegeIsRequired();
}
/**
* @test
*/
public function adminShouldHaveCheckRule(): void
{
$this->assertAdminShouldHaveRole();
}
protected function getTestMethodArguments(): array
{
return [
$this->mockRequest(self::DEFAULT_REQUEST_CONTENT),
$this->mockEntityValidator(),
$this->mockSerializer([]),
];
}
protected function assertResourcesLoopsOverDeserializedElements(string $expectedServiceMethodName): void
{
$contact = $this->mockContact(isAdmin: true, expectedRole: Contact::ROLE_HOST_CHECK, hasRole: true);
$container = $this->mockContainer(
$this->mockAuthorizationChecker(isGranted: true),
$this->mockTokenStorage($this->mockToken($contact))
);
$check = new Check();
$service = $this->mockService();
$service->method($expectedServiceMethodName)->with($this->equalTo($check));
$readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$readAccessGroupRepository->method('hasAccessToResources')->willReturn(true);
$sut = new CheckController($service, $readAccessGroupRepository);
$sut->setContainer($container);
$checks = [$check];
$methodUnderTest = static::METHOD_UNDER_TEST;
$view = $sut->{$methodUnderTest}(
$this->mockRequest(self::DEFAULT_REQUEST_CONTENT),
$this->mockEntityValidator(),
$this->mockSerializer($checks)
);
$this->assertDateIsRecent($check->getCheckTime());
$this->assertInstanceOf(View::class, $view);
$this->assertNull($view->getStatusCode());
$this->assertNull($view->getData());
}
protected function assertResourceCheckValidatesChecks(EntityValidator $validator, array $checks): void
{
$this->expectException(ValidationFailedException::class);
$this->expectExceptionMessage('Validation failed with 1 error(s).');
$contact = $this->mockContact(isAdmin: true, expectedRole: Contact::ROLE_HOST_CHECK, hasRole: true);
$container = $this->mockContainer(
$this->mockAuthorizationChecker(isGranted: true),
$this->mockTokenStorage($this->mockToken($contact))
);
$readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$readAccessGroupRepository->method('hasAccessToResources')->willReturn(true);
$sut = new CheckController($this->mockService(), $readAccessGroupRepository);
$sut->setContainer($container);
$methodUnderTest = static::METHOD_UNDER_TEST;
$view = $sut->{$methodUnderTest}(
$this->mockRequest(static::DEFAULT_REQUEST_CONTENT),
$validator,
$this->mockSerializer($checks)
);
$this->assertInstanceOf(View::class, $view);
$this->assertNull($view->getStatusCode());
$this->assertNull($view->getData());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/CheckController/ServicesTest.php | centreon/tests/php/Centreon/Application/Controller/CheckController/ServicesTest.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\Centreon\Application\Controller\CheckController;
use Centreon\Domain\Check\Check;
use Centreon\Domain\Contact\Contact;
final class ServicesTest extends ResourcesTestCase
{
protected const METHOD_UNDER_TEST = 'checkServices';
protected const REQUIRED_ROLE_FOR_ADMIN = Contact::ROLE_SERVICE_CHECK;
/**
* @test
*/
public function checkServiceLoopsOverDeserializedElements(): void
{
$this->assertResourcesLoopsOverDeserializedElements('checkService');
}
/**
* @test
*/
public function checkServiceValidatesChecks(): void
{
$check = new Check();
$validator = $this->mockCheckValidator($check, Check::VALIDATION_GROUPS_SERVICE_CHECK, 1);
$this->assertResourceCheckValidatesChecks($validator, [$check]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/CheckController/TestCase.php | centreon/tests/php/Centreon/Application/Controller/CheckController/TestCase.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\Centreon\Application\Controller\CheckController;
use Centreon\Application\Controller\AbstractController;
use Centreon\Application\Controller\CheckController;
use Centreon\Domain\Check\Check;
use Centreon\Domain\Check\Interfaces\CheckServiceInterface;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Entity\EntityValidator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use DateInterval;
use DateTime;
use FOS\RestBundle\View\View;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\Exception\ValidationFailedException;
use JMS\Serializer\SerializerInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase as BaseTestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Validator\Constraints\GroupSequence;
use Symfony\Component\Validator\ConstraintViolationListInterface;
abstract class TestCase extends BaseTestCase
{
protected const METHOD_UNDER_TEST = '';
protected const REQUIRED_ROLE_FOR_ADMIN = Contact::ROLE_HOST_CHECK;
protected const DEFAULT_REQUEST_CONTENT = 'request content';
/**
* @return mixed[]
*/
abstract protected function getTestMethodArguments(): array;
protected function assertAdminPrivilegeIsRequired(): void
{
$this->expectException(AccessDeniedException::class);
$this->expectExceptionMessage(AbstractController::ROLE_API_REALTIME_EXCEPTION_MESSAGE);
$contact = $this->mockContact(isAdmin: false, expectedRole: Contact::ROLE_HOST_CHECK, hasRole: true);
$container = $this->mockContainer(
$this->mockAuthorizationChecker(isGranted: false),
$this->mockTokenStorage(
$this->mockToken($contact)
)
);
$sut = new CheckController($this->mockService(), $this->createMock(ReadAccessGroupRepositoryInterface::class));
$sut->setContainer($container);
call_user_func_array([$sut, static::METHOD_UNDER_TEST], $this->getTestMethodArguments());
}
protected function assertAdminShouldHaveRole(): void
{
$contact = $this->mockContact(isAdmin: false, expectedRole: static::REQUIRED_ROLE_FOR_ADMIN, hasRole: false);
$container = $this->mockContainer(
$this->mockAuthorizationChecker(isGranted: true),
$this->mockTokenStorage($this->mockToken($contact))
);
$sut = new CheckController($this->mockService(), $this->createMock(ReadAccessGroupRepositoryInterface::class));
$sut->setContainer($container);
$view = call_user_func_array([$sut, static::METHOD_UNDER_TEST], $this->getTestMethodArguments());
$this->assertInstanceOf(View::class, $view);
$this->assertSame(Response::HTTP_UNAUTHORIZED, $view->getStatusCode());
$this->assertNull($view->getData());
}
protected function assertResourcesLoopsOverDeserializedElements(string $expectedServiceMethodName): void
{
$contact = $this->mockContact(isAdmin: true, expectedRole: Contact::ROLE_HOST_CHECK, hasRole: true);
$container = $this->mockContainer(
$this->mockAuthorizationChecker(isGranted: true),
$this->mockTokenStorage($this->mockToken($contact))
);
$check = new Check();
$service = $this->mockService();
$service->method($expectedServiceMethodName)->with($this->equalTo($check));
$sut = new CheckController($service, $this->createMock(ReadAccessGroupRepositoryInterface::class));
$sut->setContainer($container);
$checks = [$check];
$view = call_user_func_array(
[$sut, static::METHOD_UNDER_TEST],
[
$this->mockRequest(self::DEFAULT_REQUEST_CONTENT),
$this->mockEntityValidator(),
$this->mockSerializer($checks),
]
);
$this->assertDateIsRecent($check->getCheckTime());
$this->assertInstanceOf(View::class, $view);
$this->assertNull($view->getStatusCode());
$this->assertNull($view->getData());
}
/**
* @param Check[] $checks
*/
protected function assertResourceCheckValidatesChecks(EntityValidator $validator, array $checks): void
{
$this->expectException(ValidationFailedException::class);
$this->expectExceptionMessage('Validation failed with 1 error(s).');
$contact = $this->mockContact(isAdmin: true, expectedRole: Contact::ROLE_HOST_CHECK, hasRole: true);
$container = $this->mockContainer(
$this->mockAuthorizationChecker(isGranted: true),
$this->mockTokenStorage($this->mockToken($contact))
);
$sut = new CheckController($this->mockService(), $this->createMock(ReadAccessGroupRepositoryInterface::class));
$sut->setContainer($container);
$view = call_user_func_array(
[$sut, static::METHOD_UNDER_TEST],
[
$this->mockRequest(static::DEFAULT_REQUEST_CONTENT),
$validator,
$this->mockSerializer($checks),
]
);
$this->assertInstanceOf(View::class, $view);
$this->assertNull($view->getStatusCode());
$this->assertNull($view->getData());
}
protected function mockContact(bool $isAdmin, string $expectedRole, bool $hasRole): Contact
{
$mock = $this->createMock(Contact::class);
$mock->method('isAdmin')
->willReturn($isAdmin);
$mock->method('hasRole')
->with($expectedRole)
->willReturn($hasRole);
return $mock;
}
protected function mockContainer(
AuthorizationCheckerInterface $authorizationChecker,
TokenStorageInterface $tokenStorage,
): ContainerInterface {
$mock = $this->createMock(ContainerInterface::class);
$mock
->method('has')
->willReturn(true);
$mock
->method('get')
->willReturnOnConsecutiveCalls(
$authorizationChecker,
$tokenStorage,
new class () {
public function get(): string
{
return __DIR__ . '/../../../../../../';
}
}
);
return $mock;
}
protected function mockRequest(mixed $content = ''): Request
{
$mock = $this->createMock(Request::class);
$mock->method('getContent')
->willReturn($content);
return $mock;
}
protected function mockEntityValidator(): EntityValidator|MockObject
{
return $this->createMock(EntityValidator::class);
}
/**
* @param Check[]|Check $deserializedObj
*/
protected function mockSerializer(array|Check $deserializedObj): SerializerInterface
{
$mock = $this->createMock(SerializerInterface::class);
$mock
->method('deserialize')
->with(
static::DEFAULT_REQUEST_CONTENT,
'array<' . Check::class . '>',
'json',
$this->isInstanceOf(DeserializationContext::class)
)
->willReturn($deserializedObj);
return $mock;
}
protected function mockService(): CheckServiceInterface|MockObject
{
return $this->createMock(CheckServiceInterface::class);
}
protected function mockAuthorizationChecker(bool $isGranted = true): AuthorizationCheckerInterface
{
$mock = $this->createMock(AuthorizationCheckerInterface::class);
$mock
->method('isGranted')
->willReturn($isGranted);
return $mock;
}
protected function mockTokenStorage(TokenInterface|null $token): TokenStorageInterface
{
$mock = $this->createMock(TokenStorageInterface::class);
$mock
->method('getToken')
->willReturn($token);
return $mock;
}
protected function mockToken(Contact $contact): TokenInterface
{
$mock = $this->createMock(TokenInterface::class);
$mock->expects($this->any())
->method('getUser')
->willReturn($contact);
return $mock;
}
/**
* @param string|GroupSequence|(string|GroupSequence)[]|null $groups
*/
protected function mockCheckValidator(Check $check, $groups = null, int $nbError = 0): EntityValidator
{
$constraint = $this->createMock(ConstraintViolationListInterface::class);
$constraint->method('count')->willReturn($nbError);
$validator = $this->mockEntityValidator();
$validator
->method('validate')
->with($this->equalTo($check), null, $groups)
->willReturn($constraint);
return $validator;
}
protected function assertDateIsRecent(DateTime $date): void
{
$timeSpan = new DateInterval('PT10S');
$lowerDate = new DateTime();
$lowerDate->sub($timeSpan);
$upperDate = new DateTime();
$upperDate->add($timeSpan);
$this->assertTrue($date > $lowerDate && $date < $upperDate);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/CheckController/HostsTest.php | centreon/tests/php/Centreon/Application/Controller/CheckController/HostsTest.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\Centreon\Application\Controller\CheckController;
use Centreon\Domain\Check\Check;
use Centreon\Domain\Contact\Contact;
final class HostsTest extends ResourcesTestCase
{
protected const METHOD_UNDER_TEST = 'checkHosts';
protected const REQUIRED_ROLE_FOR_ADMIN = Contact::ROLE_HOST_CHECK;
/**
* @test
*/
public function checkHostsLoopsOverDeserializedElements(): void
{
$this->assertResourcesLoopsOverDeserializedElements('checkHost');
}
/**
* @test
*/
public function checkHostsValidatesChecks(): void
{
$check = new Check();
$validator = $this->mockCheckValidator($check, Check::VALIDATION_GROUPS_HOST_CHECK, 1);
$this->assertResourceCheckValidatesChecks($validator, [$check]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Application/Controller/CheckController/HostTest.php | centreon/tests/php/Centreon/Application/Controller/CheckController/HostTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Centreon\Application\Controller\CheckController;
use Centreon\Application\Controller\CheckController;
use Centreon\Domain\Check\Check;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Entity\EntityValidator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use FOS\RestBundle\View\View;
use JMS\Serializer\Exception\ValidationFailedException;
final class HostTest extends ResourceTestCase
{
protected const METHOD_UNDER_TEST = 'checkHost';
protected const REQUIRED_ROLE_FOR_ADMIN = Contact::ROLE_HOST_CHECK;
/**
* @test
*/
public function exceptionIsThrownWhenValidationFails(): void
{
$this->expectException(ValidationFailedException::class);
$this->expectExceptionMessage('Validation failed with 1 error(s).');
$check = new Check();
$validator = $this->mockCheckValidator($check, Check::VALIDATION_GROUPS_HOST_CHECK, 1);
$this->executeMethodUnderTest($check, $validator);
}
/**
* @test
*/
public function checkHostValidatesChecks(): void
{
$check = new Check();
$validator = $this->mockCheckValidator($check, Check::VALIDATION_GROUPS_HOST_CHECK, 0);
$view = $this->executeMethodUnderTest($check, $validator);
$this->assertDateIsRecent($check->getCheckTime());
$this->assertEquals(1, $check->getResourceId());
$this->assertInstanceOf(View::class, $view);
$this->assertNull($view->getStatusCode());
$this->assertNull($view->getData());
}
protected function getTestMethodArguments(): array
{
return [
$this->mockRequest(self::DEFAULT_REQUEST_CONTENT),
$this->mockEntityValidator(),
$this->mockSerializer([]),
1,
];
}
private function executeMethodUnderTest(Check $check, EntityValidator $validator): View
{
$contact = $this->mockContact(isAdmin: true, expectedRole: Contact::ROLE_HOST_CHECK, hasRole: true);
$container = $this->mockContainer(
$this->mockAuthorizationChecker(isGranted: true),
$this->mockTokenStorage($this->mockToken($contact))
);
$service = $this->mockService();
$service->method('filterByContact')->with($this->equalTo($contact))->willReturn($service);
$service->method('checkHost')->with($this->equalTo($check));
$readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$sut = new CheckController($service, $readAccessGroupRepository);
$sut->setContainer($container);
$methodUnderTest = self::METHOD_UNDER_TEST;
return $sut->{$methodUnderTest}(
$this->mockRequest(self::DEFAULT_REQUEST_CONTENT),
$validator,
$this->mockSerializer($check),
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/Centreon/Application/Controller/CheckController/ServiceTest.php | centreon/tests/php/Centreon/Application/Controller/CheckController/ServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Centreon\Application\Controller\CheckController;
use Centreon\Application\Controller\CheckController;
use Centreon\Domain\Check\Check;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Entity\EntityValidator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use FOS\RestBundle\View\View;
use JMS\Serializer\Exception\ValidationFailedException;
final class ServiceTest extends ResourceTestCase
{
protected const METHOD_UNDER_TEST = 'checkService';
protected const REQUIRED_ROLE_FOR_ADMIN = Contact::ROLE_SERVICE_CHECK;
/**
* @test
*/
public function exceptionIsThrownWhenValidationFails(): void
{
$this->expectException(ValidationFailedException::class);
$this->expectExceptionMessage('Validation failed with 1 error(s).');
$check = new Check();
$validator = $this->mockCheckValidator($check, Check::VALIDATION_GROUPS_SERVICE_CHECK, 1);
$this->executeMethodUnderTest($check, $validator);
}
/**
* @test
*/
public function checkHostValidatesChecks(): void
{
$check = new Check();
$validator = $this->mockCheckValidator($check, Check::VALIDATION_GROUPS_SERVICE_CHECK, 0);
$view = $this->executeMethodUnderTest($check, $validator);
$this->assertDateIsRecent($check->getCheckTime());
$this->assertEquals(1, $check->getParentResourceId());
$this->assertEquals(2, $check->getResourceId());
$this->assertInstanceOf(View::class, $view);
$this->assertNull($view->getStatusCode());
$this->assertNull($view->getData());
}
protected function getTestMethodArguments(): array
{
return [
$this->mockRequest(self::DEFAULT_REQUEST_CONTENT),
$this->mockEntityValidator(),
$this->mockSerializer([]),
1,
2,
];
}
/**
* @param Check $check
* @param EntityValidator $validator
*/
private function executeMethodUnderTest(Check $check, EntityValidator $validator): View
{
$contact = $this->mockContact(isAdmin: true, expectedRole: Contact::ROLE_HOST_CHECK, hasRole: true);
$container = $this->mockContainer(
$this->mockAuthorizationChecker(isGranted: true),
$this->mockTokenStorage($this->mockToken($contact))
);
$service = $this->mockService();
$service->method('filterByContact')->with($this->equalTo($contact))->willReturn($service);
$service->method('checkHost')->with($this->equalTo($check));
$readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$sut = new CheckController($service, $readAccessGroupRepository);
$sut->setContainer($container);
$methodUnderTest = self::METHOD_UNDER_TEST;
return $sut->{$methodUnderTest}(
$this->mockRequest(self::DEFAULT_REQUEST_CONTENT),
$validator,
$this->mockSerializer($check),
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/Centreon/Application/Controller/CheckController/MetaServiceTest.php | centreon/tests/php/Centreon/Application/Controller/CheckController/MetaServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Centreon\Application\Controller\CheckController;
use Centreon\Application\Controller\CheckController;
use Centreon\Domain\Check\Check;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Entity\EntityValidator;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use FOS\RestBundle\View\View;
use JMS\Serializer\Exception\ValidationFailedException;
class MetaServiceTest extends ResourceTestCase
{
protected const METHOD_UNDER_TEST = 'checkMetaService';
protected const REQUIRED_ROLE_FOR_ADMIN = Contact::ROLE_SERVICE_CHECK;
/**
* @test
*/
public function exceptionIsThrownWhenValidationFails(): void
{
$this->expectException(ValidationFailedException::class);
$this->expectExceptionMessage('Validation failed with 1 error(s).');
$check = new Check();
$validator = $this->mockCheckValidator($check, Check::VALIDATION_GROUPS_META_SERVICE_CHECK, 1);
$this->executeMethodUnderTest($check, $validator);
}
/**
* @test
*/
public function checkMetaServiceValidatesChecks(): void
{
$check = new Check();
$validator = $this->mockCheckValidator($check, Check::VALIDATION_GROUPS_META_SERVICE_CHECK, 0);
$view = $this->executeMethodUnderTest($check, $validator);
$this->assertDateIsRecent($check->getCheckTime());
$this->assertEquals(1, $check->getResourceId());
$this->assertInstanceOf(View::class, $view);
$this->assertNull($view->getStatusCode());
$this->assertNull($view->getData());
}
protected function getTestMethodArguments(): array
{
return [
$this->mockRequest(self::DEFAULT_REQUEST_CONTENT),
$this->mockEntityValidator(),
$this->mockSerializer([]),
1,
];
}
private function executeMethodUnderTest(Check $check, EntityValidator $validator): View
{
$contact = $this->mockContact(isAdmin: true, expectedRole: Contact::ROLE_HOST_CHECK, hasRole: true);
$container = $this->mockContainer(
$this->mockAuthorizationChecker(isGranted: true),
$this->mockTokenStorage($this->mockToken($contact))
);
$service = $this->mockService();
$service->method('filterByContact')->with($this->equalTo($contact))->willReturn($service);
$service->method('checkMetaService')->with($this->equalTo($check));
$readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$sut = new CheckController($service, $readAccessGroupRepository);
$sut->setContainer($container);
$methodUnderTest = static::METHOD_UNDER_TEST;
return $sut->{$methodUnderTest}(
$this->mockRequest(self::DEFAULT_REQUEST_CONTENT),
$validator,
$this->mockSerializer($check),
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/Centreon/Application/Controller/CheckController/ResourceTestCase.php | centreon/tests/php/Centreon/Application/Controller/CheckController/ResourceTestCase.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\Centreon\Application\Controller\CheckController;
use Centreon\Domain\Check\Check;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\SerializerInterface;
abstract class ResourceTestCase extends TestCase
{
/**
* @test
*/
public function adminPrivilegeIsRequiredForAction(): void
{
$this->assertAdminPrivilegeIsRequired();
}
/**
* @test
*/
public function adminShouldHaveCheckRule(): void
{
$this->assertAdminShouldHaveRole();
}
protected function mockSerializer(array|Check $deserializedObj): SerializerInterface
{
$mock = $this->createMock(SerializerInterface::class);
$mock
->method('deserialize')
->with(
static::DEFAULT_REQUEST_CONTENT,
Check::class,
'json',
$this->isInstanceOf(DeserializationContext::class)
)
->willReturn($deserializedObj);
return $mock;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/VersionHelperTest.php | centreon/tests/php/Centreon/Domain/VersionHelperTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Domain;
use Centreon\Domain\VersionHelper;
use PHPUnit\Framework\TestCase;
class VersionHelperTest extends TestCase
{
public function testCompareWithPoint(): void
{
$this->assertFalse(VersionHelper::compare('1', '2', VersionHelper::EQUAL));
$this->assertTrue(VersionHelper::compare('1', '1.0', VersionHelper::EQUAL));
$this->assertTrue(VersionHelper::compare('1.2', '1.0', VersionHelper::GT));
$this->assertTrue(VersionHelper::compare('1.2', '1.0', VersionHelper::GE));
$this->assertTrue(VersionHelper::compare('1.2', '1.2', VersionHelper::GE));
$this->assertTrue(VersionHelper::compare('1.0', '2.0', VersionHelper::LT));
$this->assertTrue(VersionHelper::compare('1.2', '2.0', VersionHelper::LE));
$this->assertTrue(VersionHelper::compare('1.2', '2.0', VersionHelper::LE));
$this->assertTrue(VersionHelper::compare('1.1.0', '1.1', VersionHelper::EQUAL));
}
public function testRegularizeDepthVersionWithPoint(): void
{
$this->assertEquals('1.0.0', VersionHelper::regularizeDepthVersion('1', 2));
$this->assertEquals('2.1.0', VersionHelper::regularizeDepthVersion('2.1', 2));
$this->assertEquals('2.2', VersionHelper::regularizeDepthVersion('2.2', 1));
$this->assertEquals('9', VersionHelper::regularizeDepthVersion('9.8.5', 0));
$this->assertEquals('9.8', VersionHelper::regularizeDepthVersion('9.8.6', 1));
}
public function testCompareWithComma(): void
{
$this->assertFalse(VersionHelper::compare('1', '2', VersionHelper::EQUAL));
$this->assertTrue(VersionHelper::compare('1', '1,0', VersionHelper::EQUAL));
$this->assertTrue(VersionHelper::compare('1,2', '1,0', VersionHelper::GT));
$this->assertTrue(VersionHelper::compare('1,2', '1,0', VersionHelper::GE));
$this->assertTrue(VersionHelper::compare('1,2', '1,2', VersionHelper::GE));
$this->assertTrue(VersionHelper::compare('1,0', '2,0', VersionHelper::LT));
$this->assertTrue(VersionHelper::compare('1,2', '2,0', VersionHelper::LE));
$this->assertTrue(VersionHelper::compare('1,2', '2,0', VersionHelper::LE));
$this->assertTrue(VersionHelper::compare('1,1,0', '1,1', VersionHelper::EQUAL));
}
public function testRegularizeDepthVersionWithComma(): void
{
$this->assertEquals('1,0,0', VersionHelper::regularizeDepthVersion('1', 2, ','));
$this->assertEquals('2,1,0', VersionHelper::regularizeDepthVersion('2,1', 2, ','));
$this->assertEquals('2,2', VersionHelper::regularizeDepthVersion('2,2', 1, ','));
$this->assertEquals('9', VersionHelper::regularizeDepthVersion('9,8,5', 0, ','));
$this->assertEquals('9,8', VersionHelper::regularizeDepthVersion('9,8,6', 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/Centreon/Domain/Acknowledgement/AcknowledgementServiceTest.php | centreon/tests/php/Centreon/Domain/Acknowledgement/AcknowledgementServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Domain\Acknowledgement;
use Centreon\Domain\Acknowledgement\Acknowledgement;
use Centreon\Domain\Acknowledgement\AcknowledgementException;
use Centreon\Domain\Acknowledgement\AcknowledgementService;
use Centreon\Domain\Acknowledgement\Interfaces\AcknowledgementRepositoryInterface;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Engine\Interfaces\EngineServiceInterface;
use Centreon\Domain\Entity\EntityValidator;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface;
use Centreon\Domain\Monitoring\Service;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use JMS\Serializer\Exception\ValidationFailedException;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
class AcknowledgementServiceTest extends TestCase
{
protected $adminContact;
protected $aclContact;
protected $host;
protected $service;
protected $hostAcknowledgement;
protected $serviceAcknowledgement;
protected $acknowledgementRepository;
protected $accessGroupRepository;
protected $monitoringRepository;
protected $engineService;
protected $entityValidator;
protected $violationList;
protected function setUp(): void
{
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true);
$this->aclContact = (new Contact())
->setId(2)
->setName('contact')
->setAdmin(false);
$this->host = (new Host())
->setId(1);
$this->service = (new Service())
->setId(1);
$this->hostAcknowledgement = (new Acknowledgement())
->setId(1)
->setAuthorId(1)
->setComment('comment')
->setDeletionTime(null)
->setEntryTime(new \Datetime())
->setHostId(1)
->setPollerId(1)
->setResourceId(1)
->setParentResourceId(null)
->setNotifyContacts(true)
->setPersistentComment(true)
->setSticky(true)
->setState(0)
->setType(0);
$this->serviceAcknowledgement = (new Acknowledgement())
->setId(2)
->setAuthorId(1)
->setComment('comment')
->setDeletionTime(null)
->setEntryTime(new \Datetime())
->setHostId(1)
->setServiceId(1)
->setPollerId(1)
->setResourceId(1)
->setParentResourceId(1)
->setNotifyContacts(true)
->setPersistentComment(true)
->setSticky(true)
->setState(0)
->setType(1);
$this->acknowledgementRepository = $this->createMock(AcknowledgementRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->monitoringRepository = $this->createMock(MonitoringRepositoryInterface::class);
$this->engineService = $this->createMock(EngineServiceInterface::class);
$this->entityValidator = $this->createMock(EntityValidator::class);
$violation = new ConstraintViolation(
'wrong format',
'wrong format',
[],
$this->serviceAcknowledgement,
'propertyPath',
'InvalidValue'
);
$this->violationList = new ConstraintViolationList([$violation]);
}
/**
* test findOneAcknowledgement with admin user
*/
public function testFindOneAcknowledgementWithAdminUser(): void
{
$this->acknowledgementRepository->expects($this->once())
->method('findOneAcknowledgementForAdminUser')
->willReturn($this->hostAcknowledgement);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgementService->filterByContact($this->adminContact);
$acknowledgement = $acknowledgementService->findOneAcknowledgement(1);
$this->assertEquals($acknowledgement, $this->hostAcknowledgement);
}
/**
* test findOneAcknowledgement with acl user
*/
public function testFindOneAcknowledgementWithAclUser(): void
{
$this->acknowledgementRepository->expects($this->once())
->method('findOneAcknowledgementForNonAdminUser')
->willReturn($this->serviceAcknowledgement);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgementService->filterByContact($this->aclContact);
$acknowledgement = $acknowledgementService->findOneAcknowledgement(2);
$this->assertEquals($acknowledgement, $this->serviceAcknowledgement);
}
/**
* test findAcknowledgements with admin user
*/
public function testFindAcknowledgementsWithAdminUser(): void
{
$this->acknowledgementRepository->expects($this->once())
->method('findAcknowledgementsForAdminUser')
->willReturn([$this->hostAcknowledgement]);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgementService->filterByContact($this->adminContact);
$acknowledgement = $acknowledgementService->findAcknowledgements();
$this->assertEquals($acknowledgement, [$this->hostAcknowledgement]);
}
/**
* test findAcknowledgements with acl user
*/
public function testFindAcknowledgementsWithAclUser(): void
{
$this->acknowledgementRepository->expects($this->once())
->method('findAcknowledgementsForNonAdminUser')
->willReturn([$this->serviceAcknowledgement]);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgementService->filterByContact($this->aclContact);
$acknowledgement = $acknowledgementService->findAcknowledgements();
$this->assertEquals($acknowledgement, [$this->serviceAcknowledgement]);
}
/**
* test addHostAcknowledgement which is not valid (eg: missing hostId)
*/
public function testAddHostAcknowledgementNotValidated(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn($this->violationList);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(ValidationFailedException::class);
$acknowledgementService->addHostAcknowledgement($this->serviceAcknowledgement);
}
/**
* test addHostAcknowledgement with not found host
*/
public function testAddHostAcknowledgementNotFoundHost(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList([]));
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn(null);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(EntityNotFoundException::class);
$acknowledgementService->addHostAcknowledgement($this->hostAcknowledgement);
}
/**
* test addHostAcknowledgement which succeed
*/
public function testAddHostAcknowledgementWhichSucceed(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList([]));
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->engineService->expects($this->once())
->method('addHostAcknowledgement')
->willReturn(null);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgementService->addHostAcknowledgement($this->hostAcknowledgement);
}
/**
* test addServiceAcknowledgement which is not validated
*/
public function testAddServiceAcknowledgementNotValidated(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn($this->violationList);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(ValidationFailedException::class);
$acknowledgementService->addServiceAcknowledgement($this->serviceAcknowledgement);
}
/**
* test addServiceAcknowledgement with not found service
*/
public function testAddServiceAcknowledgementNotFoundService(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList([]));
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn(null);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(EntityNotFoundException::class);
$acknowledgementService->addServiceAcknowledgement($this->serviceAcknowledgement);
}
/**
* test addServiceAcknowledgement with not found host
*/
public function testAddServiceAcknowledgementNotFoundHost(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList([]));
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn(null);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(EntityNotFoundException::class);
$acknowledgementService->addServiceAcknowledgement($this->serviceAcknowledgement);
}
/**
* test addServiceAcknowledgement which succeed
*/
public function testAddServiceAcknowledgementWhichSucceed(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList([]));
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->engineService->expects($this->once())
->method('addServiceAcknowledgement')
->willReturn(null);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgementService->addServiceAcknowledgement($this->serviceAcknowledgement);
}
/**
* test findHostsAcknowledgements
*/
public function testFindHostsAcknowledgements(): void
{
$this->acknowledgementRepository->expects($this->once())
->method('findHostsAcknowledgements')
->willReturn([$this->hostAcknowledgement]);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgement = $acknowledgementService->findHostsAcknowledgements();
$this->assertEquals($acknowledgement, [$this->hostAcknowledgement]);
}
/**
* test findServicesAcknowledgements
*/
public function testFindServicesAcknowledgements(): void
{
$this->acknowledgementRepository->expects($this->once())
->method('findServicesAcknowledgements')
->willReturn([$this->serviceAcknowledgement]);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgement = $acknowledgementService->findServicesAcknowledgements();
$this->assertEquals($acknowledgement, [$this->serviceAcknowledgement]);
}
/**
* test findAcknowledgementsByHost
*/
public function testFindAcknowledgementsByHost(): void
{
$this->acknowledgementRepository->expects($this->once())
->method('findAcknowledgementsByHost')
->willReturn([$this->hostAcknowledgement]);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgement = $acknowledgementService->findAcknowledgementsByHost(1);
$this->assertEquals($acknowledgement, [$this->hostAcknowledgement]);
}
/**
* test findAcknowledgementsByService
*/
public function testFindAcknowledgementsByService(): void
{
$this->acknowledgementRepository->expects($this->once())
->method('findAcknowledgementsByService')
->willReturn([$this->serviceAcknowledgement]);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgement = $acknowledgementService->findAcknowledgementsByService(1, 1);
$this->assertEquals($acknowledgement, [$this->serviceAcknowledgement]);
}
/**
* test disacknowledgeHost with not found host
*/
public function testDisacknowledgeHostNotFoundHost(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn(null);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(EntityNotFoundException::class);
$acknowledgementService->disacknowledgeHost(1);
}
/**
* test disacknowledgeHost with not found acknowledgement
*/
public function testDisacknowledgeHostNotFoundAcknowledgement(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->acknowledgementRepository->expects($this->once())
->method('findLatestHostAcknowledgement')
->willReturn(null);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(AcknowledgementException::class);
$acknowledgementService->disacknowledgeHost(1);
}
/**
* test disacknowledgeHost which is already disacknowledge
*/
public function testDisacknowledgeHostAlreadyDisacknowledged(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$hostAcknowledgement = $this->hostAcknowledgement->setDeletionTime(new \DateTime());
$this->acknowledgementRepository->expects($this->once())
->method('findLatestHostAcknowledgement')
->willReturn($hostAcknowledgement);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(AcknowledgementException::class);
$acknowledgementService->disacknowledgeHost(1);
}
/**
* test disacknowledgeHost which succeed
*/
public function testDisacknowledgeHostSucceed(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->acknowledgementRepository->expects($this->once())
->method('findLatestHostAcknowledgement')
->willReturn($this->hostAcknowledgement);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgementService->disacknowledgeHost(1);
}
/**
* test disacknowledgeService with not found service
*/
public function testDisacknowledgeServiceNotFoundService(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneservice')
->willReturn(null);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(EntityNotFoundException::class);
$acknowledgementService->disacknowledgeService(1, 1);
}
/**
* test disacknowledgeService with not found acknowledgement
*/
public function testDisacknowledgeServiceNotFoundAcknowledgement(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->acknowledgementRepository->expects($this->once())
->method('findLatestServiceAcknowledgement')
->willReturn(null);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(AcknowledgementException::class);
$acknowledgementService->disacknowledgeService(1, 1);
}
/**
* test disacknowledgeService which is already disacknowledge
*/
public function testDisacknowledgeServiceAlreadyDisacknowledged(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$serviceAcknowledgement = $this->serviceAcknowledgement->setDeletionTime(new \DateTime());
$this->acknowledgementRepository->expects($this->once())
->method('findLatestServiceAcknowledgement')
->willReturn($serviceAcknowledgement);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$this->expectException(AcknowledgementException::class);
$acknowledgementService->disacknowledgeService(1, 1);
}
/**
* test disacknowledgeService which succeed
*/
public function testDisacknowledgeServiceSucceed(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->acknowledgementRepository->expects($this->once())
->method('findLatestServiceAcknowledgement')
->willReturn($this->hostAcknowledgement);
$acknowledgementService = new AcknowledgementService(
$this->acknowledgementRepository,
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$acknowledgementService->disacknowledgeService(1, 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/Centreon/Domain/PlatformTopology/PlatformTopologyServiceTest.php | centreon/tests/php/Centreon/Domain/PlatformTopology/PlatformTopologyServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Domain\PlatformTopology;
use Centreon\Domain\Broker\BrokerConfiguration;
use Centreon\Domain\Broker\Interfaces\BrokerRepositoryInterface;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Engine\EngineConfiguration;
use Centreon\Domain\Engine\EngineException;
use Centreon\Domain\Engine\Interfaces\EngineConfigurationServiceInterface;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\MonitoringServer\Exception\MonitoringServerException;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerServiceInterface;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\Platform\Interfaces\PlatformRepositoryInterface;
use Centreon\Domain\PlatformInformation\Exception\PlatformInformationException;
use Centreon\Domain\PlatformInformation\Interfaces\PlatformInformationServiceInterface;
use Centreon\Domain\PlatformTopology\Exception\PlatformTopologyException;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformTopologyRegisterRepositoryInterface;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformTopologyRepositoryExceptionInterface;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformTopologyRepositoryInterface;
use Centreon\Domain\PlatformTopology\Model\PlatformPending;
use Centreon\Domain\PlatformTopology\Model\PlatformRegistered;
use Centreon\Domain\PlatformTopology\PlatformTopologyService;
use Centreon\Domain\Proxy\Interfaces\ProxyServiceInterface;
use Centreon\Domain\RemoteServer\Interfaces\RemoteServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class PlatformTopologyServiceTest extends TestCase
{
/** @var Contact|null */
protected $adminContact;
/** @var PlatformPending|null */
protected $platform;
/** @var PlatformRegistered|null */
protected $registeredParent;
/** @var PlatformRepositoryInterface&MockObject */
protected $platformTopologyRepository;
/** @var HttpClientInterface|null */
protected $httpClient;
/** @var EngineConfiguration|null */
protected $engineConfiguration;
/** @var BrokerConfiguration */
protected $brokerConfiguration;
/** @var EngineConfigurationServiceInterface&MockObject */
protected $engineConfigurationService;
/** @var MonitoringServerServiceInterface&MockObject */
protected $monitoringServerService;
/** @var MonitoringServer */
protected $monitoringServer;
/** @var BrokerRepositoryInterface&MockObject */
protected $brokerRepository;
/** @var PlatformInformationServiceInterface&MockObject */
private $platformInformationService;
/** @var ProxyServiceInterface&MockObject */
private $proxyService;
/** @var PlatformTopologyRegisterRepositoryInterface&MockObject */
private $platformTopologyRegisterRepository;
/**
* Undocumented variable
*
* @var RemoteServerRepositoryInterface&MockObject
*/
private $remoteServerRepository;
/** @var ReadAccessGroupRepositoryInterface&MockObject */
private $readAccessGroupRepository;
/**
* initiate query data
*/
protected function setUp(): void
{
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true);
$this->platform = (new PlatformPending())
->setId(2)
->setName('poller1')
->setAddress('1.1.1.2')
->setType('poller')
->setParentAddress('1.1.1.1')
->setHostname('localhost.localdomain');
$this->registeredParent = (new PlatformRegistered())
->setName('Central')
->setAddress('1.1.1.1')
->setType('central')
->setId(1)
->setHostname('central.localdomain');
$this->engineConfiguration = (new EngineConfiguration())
->setId(1)
->setIllegalObjectNameCharacters('$!?')
->setMonitoringServerId(1)
->setName('Central');
$this->monitoringServer = (new MonitoringServer())
->setId(1)
->setName('Central');
$this->brokerConfiguration = (new BrokerConfiguration())
->setConfigurationKey('one_peer_retention_mode')
->setConfigurationValue('no');
$this->platformTopologyRepository = $this->createMock(PlatformTopologyRepositoryInterface::class);
$this->platformInformationService = $this->createMock(PlatformInformationServiceInterface::class);
$this->proxyService = $this->createMock(ProxyServiceInterface::class);
$this->httpClient = $this->createMock(HttpClientInterface::class);
$this->engineConfigurationService = $this->createMock(EngineConfigurationServiceInterface::class);
$this->monitoringServerService = $this->createMock(MonitoringServerServiceInterface::class);
$this->brokerRepository = $this->createMock(BrokerRepositoryInterface::class);
$this->platformTopologyRegisterRepository = $this->createMock(
PlatformTopologyRegisterRepositoryInterface::class
);
$this->remoteServerRepository = $this->createMock(RemoteServerRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
}
/**
* test addPendingPlatformToTopology with already existing platform
* @throws MonitoringServerException
* @throws EngineException
* @throws PlatformTopologyException
* @throws EntityNotFoundException
* @throws PlatformTopologyRepositoryExceptionInterface
* @throws PlatformInformationException
*/
public function testaddPendingPlatformToTopologyAlreadyExists(): void
{
$this->platformTopologyRepository
->expects($this->once())
->method('findPlatformByAddress')
->willReturn($this->platform);
$this->platformTopologyRepository
->expects($this->once())
->method('findPlatformByName')
->willReturn($this->platform);
$this->monitoringServerService
->expects($this->once())
->method('findLocalServer')
->willReturn($this->monitoringServer);
$this->engineConfigurationService
->expects($this->once())
->method('findEngineConfigurationByName')
->willReturn($this->engineConfiguration);
$platformTopologyService = new PlatformTopologyService(
$this->platformTopologyRepository,
$this->platformInformationService,
$this->proxyService,
$this->engineConfigurationService,
$this->monitoringServerService,
$this->brokerRepository,
$this->platformTopologyRegisterRepository,
$this->remoteServerRepository,
$this->readAccessGroupRepository,
);
$this->expectException(PlatformTopologyException::class);
$this->expectExceptionMessage("A platform using the name : 'poller1' or address : '1.1.1.2' already exists");
$platformTopologyService->addPendingPlatformToTopology($this->platform);
}
/**
* test addPendingPlatformToTopology with not found parent
* @throws MonitoringServerException
* @throws EngineException
* @throws PlatformTopologyException
* @throws EntityNotFoundException
* @throws PlatformInformationException
* @throws PlatformTopologyRepositoryExceptionInterface
*/
public function testaddPendingPlatformToTopologyNotFoundParent(): void
{
$this->platformTopologyRepository
->expects($this->any())
->method('findPlatformByAddress')
->willReturn(null);
$this->platformTopologyRepository
->expects($this->once())
->method('findPlatformByName')
->willReturn(null);
$this->platformTopologyRepository
->expects($this->any())
->method('findPlatformByAddress')
->willReturn(null);
$this->monitoringServerService
->expects($this->once())
->method('findLocalServer')
->willReturn($this->monitoringServer);
$this->engineConfigurationService
->expects($this->once())
->method('findEngineConfigurationByName')
->willReturn($this->engineConfiguration);
$platformTopologyService = new PlatformTopologyService(
$this->platformTopologyRepository,
$this->platformInformationService,
$this->proxyService,
$this->engineConfigurationService,
$this->monitoringServerService,
$this->brokerRepository,
$this->platformTopologyRegisterRepository,
$this->remoteServerRepository,
$this->readAccessGroupRepository,
);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage("No parent platform was found for : 'poller1'@'1.1.1.2'");
$platformTopologyService->addPendingPlatformToTopology($this->platform);
}
/**
* test addPendingPlatformToTopology which succeed
* @throws MonitoringServerException
* @throws EngineException
* @throws PlatformTopologyException
* @throws EntityNotFoundException
* @throws PlatformInformationException
* @throws PlatformTopologyRepositoryExceptionInterface
*/
/*
* @TODO refacto the test when MBI, MAP and failover
public function testaddPendingPlatformToTopologySuccess(): void
{
$this->platform->setParentId(1);
$this->platformTopologyRepository
->expects($this->any())
->method('findPlatformByAddress')
->willReturn(null);
$this->platformTopologyRepository
->expects($this->once())
->method('findPlatformByName')
->willReturn(null);
$this->platformTopologyRepository
->expects($this->any())
->method('findPlatformByAddress')
->willReturn($this->registeredParent);
$this->monitoringServerService
->expects($this->once())
->method('findLocalServer')
->willReturn($this->monitoringServer);
$this->engineConfigurationService
->expects($this->once())
->method('findEngineConfigurationByName')
->willReturn($this->engineConfiguration);
$platformTopologyService = new PlatformTopologyService(
$this->platformTopologyRepository,
$this->platformInformationService,
$this->proxyService,
$this->engineConfigurationService,
$this->monitoringServerService,
$this->brokerRepository,
$this->platformTopologyRegisterRepository,
$this->remoteServerRepository
);
$this->assertNull($platformTopologyService->addPendingPlatformToTopology($this->platform));
}*/
public function testGetPlatformTopologySuccess(): void
{
$this->platform
->setParentId(1)
->setServerId(2);
$this->registeredParent
->setServerId(1);
$this->brokerRepository
->expects($this->any())
->method('findByMonitoringServerAndParameterName')
->willReturn([$this->brokerConfiguration]);
$this->platformTopologyRepository
->expects($this->once())
->method('getPlatformTopology')
->willReturn([$this->platform, $this->registeredParent]);
$this->platformTopologyRepository
->expects($this->once())
->method('findPlatform')
->willReturn($this->registeredParent);
$platformTopologyService = new PlatformTopologyService(
$this->platformTopologyRepository,
$this->platformInformationService,
$this->proxyService,
$this->engineConfigurationService,
$this->monitoringServerService,
$this->brokerRepository,
$this->platformTopologyRegisterRepository,
$this->remoteServerRepository,
$this->readAccessGroupRepository,
);
$this->assertIsArray($platformTopologyService->getPlatformTopology());
}
public function testGetPlatformTopologyWithoutParentId(): void
{
$this->registeredParent
->setServerId(1);
$this->brokerRepository
->expects($this->any())
->method('findByMonitoringServerAndParameterName')
->willReturn([$this->brokerConfiguration]);
$this->platformTopologyRepository
->expects($this->once())
->method('getPlatformTopology')
->willReturn([$this->registeredParent]);
$platformTopologyService = new PlatformTopologyService(
$this->platformTopologyRepository,
$this->platformInformationService,
$this->proxyService,
$this->engineConfigurationService,
$this->monitoringServerService,
$this->brokerRepository,
$this->platformTopologyRegisterRepository,
$this->remoteServerRepository,
$this->readAccessGroupRepository,
);
/**
* Central Case
*/
$this->assertIsArray($platformTopologyService->getPlatformTopology());
}
public function testGetPlatformTopologyRelationSetting(): void
{
$this->registeredParent
->setServerId(1);
$this->platform
->setId(2)
->setParentId(1)
->setServerId(2);
$this->platformTopologyRepository
->expects($this->exactly(2))
->method('getPlatformTopology')
->willReturn([$this->registeredParent, $this->platform]);
$this->platformTopologyRepository
->expects($this->exactly(2))
->method('findPlatform')
->willReturn($this->registeredParent);
$brokerConfigurationPeerRetention = (new BrokerConfiguration())
->setConfigurationKey('one_peer_retention_mode')
->setConfigurationValue('yes');
$this->brokerRepository->expects($this->exactly(4))
->method('findByMonitoringServerAndParameterName')
->willReturnOnConsecutiveCalls(
[$this->brokerConfiguration],
[$this->brokerConfiguration],
[$brokerConfigurationPeerRetention],
[$brokerConfigurationPeerRetention]
);
$platformTopologyService = new PlatformTopologyService(
$this->platformTopologyRepository,
$this->platformInformationService,
$this->proxyService,
$this->engineConfigurationService,
$this->monitoringServerService,
$this->brokerRepository,
$this->platformTopologyRegisterRepository,
$this->remoteServerRepository,
$this->readAccessGroupRepository,
);
/**
* Normal Relation
*/
$completeTopology = $platformTopologyService->getPlatformTopology();
$centralRelation = $completeTopology[0]->getRelation();
$pollerRelation = $completeTopology[1]->getRelation();
$this->assertEquals(null, $centralRelation);
$this->assertEquals('normal', $pollerRelation->getRelation());
/**
* One Peer Retention Relation
*/
$completeTopology = $platformTopologyService->getPlatformTopology();
$centralRelation = $completeTopology[0]->getRelation();
$pollerRelation = $completeTopology[1]->getRelation();
$this->assertEquals(null, $centralRelation);
$this->assertEquals('peer_retention', $pollerRelation->getRelation());
}
public function testDeletePlatformTopologySuccess(): void
{
$this->platformTopologyRepository
->expects($this->once())
->method('findPlatform')
->willReturn($this->platform);
$platformTopologyService = new PlatformTopologyService(
$this->platformTopologyRepository,
$this->platformInformationService,
$this->proxyService,
$this->engineConfigurationService,
$this->monitoringServerService,
$this->brokerRepository,
$this->platformTopologyRegisterRepository,
$this->remoteServerRepository,
$this->readAccessGroupRepository,
);
$platformTopologyService->deletePlatformAndReallocateChildren(
$this->platform->getId()
);
}
public function testDeletePlatformTopologyWithBadId(): void
{
$this->platformTopologyRepository
->expects($this->once())
->method('findPlatform')
->willReturn(null);
$platformTopologyService = new PlatformTopologyService(
$this->platformTopologyRepository,
$this->platformInformationService,
$this->proxyService,
$this->engineConfigurationService,
$this->monitoringServerService,
$this->brokerRepository,
$this->platformTopologyRegisterRepository,
$this->remoteServerRepository,
$this->readAccessGroupRepository,
);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Platform not found');
$platformTopologyService->deletePlatformAndReallocateChildren($this->platform->getId());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/ConfigurationLoader/YamlConfigurationLoaderTest.php | centreon/tests/php/Centreon/Domain/ConfigurationLoader/YamlConfigurationLoaderTest.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 Centreon\Domain\ConfigurationLoader;
use PHPUnit\Framework\TestCase;
class YamlConfigurationLoaderTest extends TestCase
{
/**
* This test is designed to test the ability to load files and test include calls.
*/
public function testLoad(): void
{
$gcl = new YamlConfigurationLoader(__DIR__ . '/root_file.yaml');
$configuration = $gcl->load();
$this->assertArrayHasKey('name', $configuration);
$this->assertEquals($configuration['name'], 'text1');
$this->assertArrayHasKey('tab', $configuration);
$this->assertIsArray($configuration['tab']);
$this->assertArrayHasKey('key1', $configuration['tab']);
$this->assertEquals($configuration['tab']['key1'], 'value1');
$this->assertArrayHasKey('key2', $configuration['tab']);
$this->assertEquals($configuration['tab']['key2'], 'value2');
$this->assertArrayHasKey('child', $configuration);
$this->assertIsArray($configuration['child']);
$this->assertArrayHasKey('child_key', $configuration['child']);
$this->assertEquals($configuration['child']['child_key'], 'value_child_key');
$this->assertArrayHasKey('child_key2', $configuration['child']);
$this->assertIsArray($configuration['child']['child_key2']);
$this->assertArrayHasKey('loop', $configuration['child']['child_key2']);
$this->assertEquals($configuration['child']['child_key2']['loop'], 'no loop');
$this->assertArrayHasKey('extra', $configuration['child']['child_key2']);
$this->assertIsArray($configuration['child']['child_key2']['extra']);
$this->assertArrayHasKey(0, $configuration['child']['child_key2']['extra']);
$this->assertArrayHasKey(1, $configuration['child']['child_key2']['extra']);
}
/**
* This test is designed to detect a loop in file calls.
*/
public function testLoadWithLoop(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessageMatches("/^Loop detected in file.*child5\.yaml$/");
$gcl = new YamlConfigurationLoader(__DIR__ . '/root_file_with_loop.yaml');
$gcl->load();
}
// This test is designed to test the Exception
public function testFileNotFound(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessageMatches("/^The configuration file '.*no_file\.yaml' does not exists$/");
$gcl = new YamlConfigurationLoader(__DIR__ . '/no_file.yaml');
$gcl->load();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Filter/FilterServiceTest.php | centreon/tests/php/Centreon/Domain/Filter/FilterServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Domain\Filter;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Filter\Filter;
use Centreon\Domain\Filter\FilterCriteria;
use Centreon\Domain\Filter\FilterException;
use Centreon\Domain\Filter\FilterService;
use Centreon\Domain\Filter\Interfaces\FilterRepositoryInterface;
use Centreon\Domain\Monitoring\HostGroup;
use Centreon\Domain\Monitoring\HostGroup\Interfaces\HostGroupServiceInterface;
use Centreon\Domain\Monitoring\ServiceGroup\Interfaces\ServiceGroupServiceInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class FilterServiceTest extends TestCase
{
/** @var Contact|null */
protected $adminContact;
/** @var Filter|null */
protected $filter;
/** @var FilterRepositoryInterface&MockObject */
protected $filterRepository;
/** @var HostGroupServiceInterface&MockObject */
protected $hostGroupService;
/** @var ServiceGroupServiceInterface&MockObject */
protected $serviceGroupService;
protected function setUp(): void
{
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true);
$this->filter = (new Filter())
->setId(1)
->setName('filter1')
->setUserId(1)
->setPageName('events-view')
->setCriterias([
(new FilterCriteria())
->setName('host_groups')
->setType('multi_select')
->setValue([
[
'id' => 1,
'name' => 'linux',
],
])
->setObjectType('host_groups'),
(new FilterCriteria())
->setName('service_groups')
->setType('multi_select')
->setValue([
[
'id' => 1,
'name' => 'sg_ping',
],
])
->setObjectType('service_groups'),
(new FilterCriteria())
->setName('search')
->setType('text')
->setValue('my search'),
]);
$this->filterRepository = $this->createMock(FilterRepositoryInterface::class);
$this->hostGroupService = $this->createMock(HostGroupServiceInterface::class);
$this->serviceGroupService = $this->createMock(ServiceGroupServiceInterface::class);
}
/**
* test checkCriterias with renamed objects
*/
public function testCheckCriteriasRenamedObjects(): void
{
$renamedHostGroup = (new HostGroup())
->setId(1)
->setName('renamed_linux');
$this->hostGroupService->expects($this->once())
->method('filterByContact')
->willReturn($this->hostGroupService);
$this->hostGroupService->expects($this->once())
->method('findHostGroupsByNames')
->willReturn([$renamedHostGroup]);
$filterService = new FilterService(
$this->hostGroupService,
$this->serviceGroupService,
$this->filterRepository
);
$filterService->checkCriterias($this->filter->getCriterias());
$this->assertCount(
1,
$this->filter->getCriterias()[0]->getValue()
);
$this->assertEquals(
[
'id' => $renamedHostGroup->getId(),
'name' => $renamedHostGroup->getName(),
],
$this->filter->getCriterias()[0]->getValue()[0]
);
}
/**
* test checkCriterias with deleted objects
*/
public function testCheckCriteriasDeletedObjects(): void
{
$this->serviceGroupService->expects($this->once())
->method('filterByContact')
->willReturn($this->serviceGroupService);
$this->serviceGroupService->expects($this->once())
->method('findServiceGroupsByNames')
->willReturn([]);
$filterService = new FilterService(
$this->hostGroupService,
$this->serviceGroupService,
$this->filterRepository
);
$filterService->checkCriterias($this->filter->getCriterias());
$this->assertCount(
0,
$this->filter->getCriterias()[1]->getValue()
);
}
/**
* test update filter with name already in use
*/
public function testUpdateFilterNameExists(): void
{
$this->filterRepository->expects($this->once())
->method('findFilterByUserIdAndName')
->willReturn($this->filter);
$filterUpdate = (new Filter())
->setId(2)
->setName($this->filter->getName())
->setUserId($this->filter->getUserId())
->setPageName($this->filter->getPageName());
$filterService = new FilterService(
$this->hostGroupService,
$this->serviceGroupService,
$this->filterRepository
);
$this->expectException(FilterException::class);
$this->expectExceptionMessage('Filter name already used');
$filterService->updateFilter($filterUpdate);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/Model/MetaServiceConfigurationTest.php | centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/Model/MetaServiceConfigurationTest.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\Centreon\Domain\MetaServiceConfiguration\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfiguration;
use PHPUnit\Framework\TestCase;
/**
* This class is designed to test all setters of the MetaServiceConfiguration entity, especially those with exceptions.
*
* @package Tests\Centreon\Domain\MetaServiceConfiguration\Model
*/
class MetaServiceConfigurationTest extends TestCase
{
/**
* Too long name test
*/
public function testNameTooShortException(): void
{
$name = str_repeat('.', MetaServiceConfiguration::MIN_NAME_LENGTH - 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$name,
strlen($name),
MetaServiceConfiguration::MIN_NAME_LENGTH,
'MetaServiceConfiguration::name'
)->getMessage()
);
new MetaServiceConfiguration($name, 'average', 1);
}
/**
* Too long name test
*/
public function testNameTooLongException(): void
{
$name = str_repeat('.', MetaServiceConfiguration::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
strlen($name),
MetaServiceConfiguration::MAX_NAME_LENGTH,
'MetaServiceConfiguration::name'
)->getMessage()
);
new MetaServiceConfiguration($name, 'average', 1);
}
/**
* Too long output test
*/
public function testOutputTooLongException(): void
{
$output = str_repeat('.', MetaServiceConfiguration::MAX_OUTPUT_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$output,
strlen($output),
MetaServiceConfiguration::MAX_OUTPUT_LENGTH,
'MetaServiceConfiguration::output'
)->getMessage()
);
(new MetaServiceConfiguration('name', 'average', 1))->setOutput($output);
}
/**
* Too long regexp test
*/
public function testRegexpStringTooLong(): void
{
$regexpString = str_repeat('.', MetaServiceConfiguration::MAX_REGEXP_STRING_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$regexpString,
strlen($regexpString),
MetaServiceConfiguration::MAX_REGEXP_STRING_LENGTH,
'MetaServiceConfiguration::regexpString'
)->getMessage()
);
(new MetaServiceConfiguration('name', 'average', 1))->setRegexpString($regexpString);
}
/**
* Too long warning test
*/
public function testWarningTooLong(): void
{
$warning = str_repeat('.', MetaServiceConfiguration::MAX_WARNING_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$warning,
strlen($warning),
MetaServiceConfiguration::MAX_WARNING_LENGTH,
'MetaServiceConfiguration::warning'
)->getMessage()
);
(new MetaServiceConfiguration('name', 'average', 1))->setWarning($warning);
}
/**
* Too long warning test
*/
public function testCriticalTooLong(): void
{
$critical = str_repeat('.', MetaServiceConfiguration::MAX_CRITICAL_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$critical,
strlen($critical),
MetaServiceConfiguration::MAX_CRITICAL_LENGTH,
'MetaServiceConfiguration::critical'
)->getMessage()
);
(new MetaServiceConfiguration('name', 'average', 1))->setCritical($critical);
}
/**
* Too long metric test
*/
public function testMetricTooLong(): void
{
$metric = str_repeat('.', MetaServiceConfiguration::MAX_METRIC_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$metric,
strlen($metric),
MetaServiceConfiguration::MAX_METRIC_LENGTH,
'MetaServiceConfiguration::metric'
)->getMessage()
);
(new MetaServiceConfiguration('name', 'average', 1))->setMetric($metric);
}
/**
* Not supported calculation type
*/
public function testNotSupportedCalculationType(): void
{
$calculationType = 'calculationType';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
sprintf(_('Calculation method provided not supported (%s)'), $calculationType)
);
new MetaServiceConfiguration('name', $calculationType, 1);
}
/**
* Not supported calculation type
*/
public function testNotSupportedDataSourceType(): void
{
$dataSourceType = 'dataSourceType';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
sprintf(_('Data source type provided not supported (%s)'), $dataSourceType)
);
(new MetaServiceConfiguration('name', 'average', 1))->setDataSourceType($dataSourceType);
}
/**
* @throws \Assert\AssertionFailedException
* @return MetaServiceConfiguration
*/
public static function createEntity(): MetaServiceConfiguration
{
return (new MetaServiceConfiguration('name', 'average', 1))
->setId(1)
->setOutput('output')
->setDataSourceType('gauge')
->setMetaSelectMode(1)
->setRegexpString(null)
->setWarning('10')
->setCritical('20')
->setMetric(null)
->setActivated(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/Centreon/Domain/MetaServiceConfiguration/UseCase/V21/FindOneMetaServiceConfigurationTest.php | centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/UseCase/V21/FindOneMetaServiceConfigurationTest.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\Centreon\Domain\MetaServiceConfiguration\UseCase\V21;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\MetaServiceConfiguration\MetaServiceConfigurationService;
use Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfiguration;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindOneMetaServiceConfiguration;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfigurationTest;
/**
* @package Tests\Centreon\Domain\MetaServiceConfiguration\UseCase\V21
*/
class FindOneMetaServiceConfigurationTest extends TestCase
{
private MetaServiceConfigurationService&MockObject $metaServiceConfigurationService;
private MetaServiceConfiguration $metaServiceConfiguration;
private ContactInterface&MockObject $contact;
protected function setUp(): void
{
$this->metaServiceConfigurationService = $this->createMock(MetaServiceConfigurationService::class);
$this->metaServiceConfiguration = MetaServiceConfigurationTest::createEntity();
$this->contact = $this->createMock(ContactInterface::class);
}
/**
* Test as admin user
*/
public function testExecuteAsAdmin(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->metaServiceConfigurationService
->expects($this->once())
->method('findWithoutAcl')
->willReturn($this->metaServiceConfiguration);
$findMetaServiceConfigurations = new FindOneMetaServiceConfiguration(
$this->metaServiceConfigurationService,
$this->contact
);
$response = $findMetaServiceConfigurations->execute($this->metaServiceConfiguration->getId());
$metaServiceConfigurationResponse = $response->getMetaServiceConfiguration();
/**
* Only testing the ID here and not everything as this part is already tested in other test case
*/
$this->assertEquals($this->metaServiceConfiguration->getId(), $metaServiceConfigurationResponse['id']);
}
/**
* Test as non admin user
*/
public function testExecuteAsNonAdmin(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->metaServiceConfigurationService
->expects($this->once())
->method('findWithAcl')
->willReturn($this->metaServiceConfiguration);
$findMetaServiceConfigurations = new FindOneMetaServiceConfiguration(
$this->metaServiceConfigurationService,
$this->contact
);
$response = $findMetaServiceConfigurations->execute($this->metaServiceConfiguration->getId());
$metaServiceConfigurationResponse = $response->getMetaServiceConfiguration();
/**
* Only testing the ID here and not everything as this part is already tested in other test case
*/
$this->assertEquals($this->metaServiceConfiguration->getId(), $metaServiceConfigurationResponse['id']);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/UseCase/V21/FindMetaServicesConfigurationsResponseTest.php | centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/UseCase/V21/FindMetaServicesConfigurationsResponseTest.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\Centreon\Domain\MetaServiceConfiguration\UseCase\V21;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindMetaServicesConfigurationsResponse;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfigurationTest;
/**
* @package Tests\Centreon\Domain\MetaServiceConfiguration\UseCase\V21
*/
class FindMetaServicesConfigurationsResponseTest extends TestCase
{
/**
* We test the transformation of an empty response into an array.
*/
public function testEmptyResponse(): void
{
$response = new FindMetaServicesConfigurationsResponse();
$metaServicesConfigurations = $response->getMetaServicesConfigurations();
$this->assertCount(0, $metaServicesConfigurations);
}
/**
* We test the transformation of an entity into an array.
*/
public function testNotEmptyResponse(): void
{
$metaServiceConfiguration = MetaServiceConfigurationTest::createEntity();
$response = new FindMetaServicesConfigurationsResponse();
$response->setMetaServicesConfigurations([$metaServiceConfiguration]);
$metaServiceConfigurations = $response->getMetaServicesConfigurations();
$this->assertCount(1, $metaServiceConfigurations);
$this->assertEquals($metaServiceConfiguration->getId(), $metaServiceConfigurations[0]['id']);
$this->assertEquals($metaServiceConfiguration->getName(), $metaServiceConfigurations[0]['name']);
$this->assertEquals($metaServiceConfiguration->getOutput(), $metaServiceConfigurations[0]['meta_display']);
$this->assertEquals(
$metaServiceConfiguration->getDataSourceType(),
$metaServiceConfigurations[0]['data_source_type']
);
$this->assertEquals(
$metaServiceConfiguration->getCalculationType(),
$metaServiceConfigurations[0]['calcul_type']
);
$this->assertEquals(
$metaServiceConfiguration->getMetaSelectMode(),
$metaServiceConfigurations[0]['meta_select_mode']
);
$this->assertEquals($metaServiceConfiguration->getMetric(), $metaServiceConfigurations[0]['metric']);
$this->assertEquals($metaServiceConfiguration->getWarning(), $metaServiceConfigurations[0]['warning']);
$this->assertEquals($metaServiceConfiguration->isActivated(), $metaServiceConfigurations[0]['is_activated']);
$this->assertEquals($metaServiceConfiguration->getCritical(), $metaServiceConfigurations[0]['critical']);
$this->assertEquals($metaServiceConfiguration->getRegexpString(), $metaServiceConfigurations[0]['regexp_str']);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/UseCase/V21/FindOneMetaServiceConfigurationResponseTest.php | centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/UseCase/V21/FindOneMetaServiceConfigurationResponseTest.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\Centreon\Domain\MetaServiceConfiguration\UseCase\V21;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindOneMetaServiceConfigurationResponse;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfigurationTest;
/**
* @package Tests\Centreon\Domain\MetaServiceConfiguration\UseCase\V21
*/
class FindOneMetaServiceConfigurationResponseTest extends TestCase
{
/**
* We test the transformation of an entity into an array.
*/
public function testNotEmptyResponse(): void
{
$metaServiceConfiguration = MetaServiceConfigurationTest::createEntity();
$response = new FindOneMetaServiceConfigurationResponse();
$response->setMetaServiceConfiguration($metaServiceConfiguration);
$metaServiceConfigurationResponse = $response->getMetaServiceConfiguration();
$this->assertEquals($metaServiceConfiguration->getId(), $metaServiceConfigurationResponse['id']);
$this->assertEquals($metaServiceConfiguration->getName(), $metaServiceConfigurationResponse['name']);
$this->assertEquals($metaServiceConfiguration->getOutput(), $metaServiceConfigurationResponse['meta_display']);
$this->assertEquals(
$metaServiceConfiguration->getDataSourceType(),
$metaServiceConfigurationResponse['data_source_type']
);
$this->assertEquals(
$metaServiceConfiguration->getCalculationType(),
$metaServiceConfigurationResponse['calcul_type']
);
$this->assertEquals(
$metaServiceConfiguration->getMetaSelectMode(),
$metaServiceConfigurationResponse['meta_select_mode']
);
$this->assertEquals($metaServiceConfiguration->getMetric(), $metaServiceConfigurationResponse['metric']);
$this->assertEquals($metaServiceConfiguration->getWarning(), $metaServiceConfigurationResponse['warning']);
$this->assertEquals(
$metaServiceConfiguration->isActivated(),
$metaServiceConfigurationResponse['is_activated']
);
$this->assertEquals($metaServiceConfiguration->getCritical(), $metaServiceConfigurationResponse['critical']);
$this->assertEquals(
$metaServiceConfiguration->getRegexpString(),
$metaServiceConfigurationResponse['regexp_str']
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/UseCase/V21/FindMetaServicesConfigurationsTest.php | centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/UseCase/V21/FindMetaServicesConfigurationsTest.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\Centreon\Domain\MetaServiceConfiguration\UseCase\V21;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\MetaServiceConfiguration\MetaServiceConfigurationService;
use Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfiguration;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindMetaServicesConfigurations;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfigurationTest;
/**
* @package Tests\Centreon\Domain\MetaServiceConfiguration\UseCase\V21
*/
class FindMetaServicesConfigurationsTest extends TestCase
{
private MetaServiceConfigurationService&\PHPUnit\Framework\MockObject\MockObject $metaServiceConfigurationService;
private MetaServiceConfiguration $metaServiceConfiguration;
private ReadAccessGroupRepositoryInterface $accessGroupRepository;
private ContactInterface&\PHPUnit\Framework\MockObject\MockObject $contact;
protected function setUp(): void
{
$this->metaServiceConfigurationService = $this->createMock(MetaServiceConfigurationService::class);
$this->metaServiceConfiguration = MetaServiceConfigurationTest::createEntity();
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
}
/**
* Test as admin user
*/
public function testExecuteAsAdmin(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->metaServiceConfigurationService
->expects($this->once())
->method('findAllWithoutAcl')
->willReturn([$this->metaServiceConfiguration]);
$findMetaServiceConfigurations = new FindMetaServicesConfigurations(
$this->metaServiceConfigurationService,
$this->contact,
$this->accessGroupRepository,
false
);
$response = $findMetaServiceConfigurations->execute();
$this->assertCount(1, $response->getMetaServicesConfigurations());
}
/**
* Test as non admin user
*/
public function testExecuteAsNonAdmin(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->metaServiceConfigurationService
->expects($this->once())
->method('findAllWithAcl')
->willReturn([$this->metaServiceConfiguration]);
$findMetaServiceConfigurations = new FindMetaServicesConfigurations(
$this->metaServiceConfigurationService,
$this->contact,
$this->accessGroupRepository,
false
);
$response = $findMetaServiceConfigurations->execute();
$this->assertCount(1, $response->getMetaServicesConfigurations());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/Exception/MetaServiceConfigurationExceptionTest.php | centreon/tests/php/Centreon/Domain/MetaServiceConfiguration/Exception/MetaServiceConfigurationExceptionTest.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\Centreon\Domain\MetaServiceConfiguration\Exception;
use Centreon\Domain\MetaServiceConfiguration\Exception\MetaServiceConfigurationException;
use PHPUnit\Framework\TestCase;
/**
* @package Tests\Centreon\Domain\HostConfiguration\Exceptions
*/
class MetaServiceConfigurationExceptionTest extends TestCase
{
/**
* Tests the arguments of the static method findM.
*/
public function testFindMetaServicesConfigurations(): void
{
$previousMessage1 = 'Error message 1';
$errorMessage = 'Error when searching for the meta services configurations';
$exception = MetaServiceConfigurationException::findMetaServicesConfigurations(
new \Exception($previousMessage1)
);
self::assertEquals(sprintf($errorMessage), $exception->getMessage());
self::assertNotNull($exception->getPrevious());
self::assertEquals($previousMessage1, $exception->getPrevious()->getMessage());
}
/**
* Tests the arguments of the static method findOneMetaServiceConfiguration.
*/
public function testFindOneMetaServiceConfiguration(): void
{
$previousMessage1 = 'Error message 1';
$errorMessage = 'Error when searching for the meta service configuration (%s)';
$exception = MetaServiceConfigurationException::findOneMetaServiceConfiguration(
new \Exception($previousMessage1),
1
);
self::assertEquals(sprintf($errorMessage, 1), $exception->getMessage());
self::assertNotNull($exception->getPrevious());
self::assertEquals($previousMessage1, $exception->getPrevious()->getMessage());
}
/**
* Tests the arguments of the static method findOneMetaServiceConfigurationNotFound.
*/
public function testFindOneMetaServiceConfigurationNotFound(): void
{
$errorMessage = 'Meta service configuration (%s) not found';
$exception = MetaServiceConfigurationException::findOneMetaServiceConfigurationNotFound(1);
self::assertEquals(sprintf($errorMessage, 1), $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/Centreon/Domain/Authentication/UseCase/AuthenticateApiTest.php | centreon/tests/php/Centreon/Domain/Authentication/UseCase/AuthenticateApiTest.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\Centreon\Domain\Authentication\UseCase;
use Centreon\Domain\Authentication\Exception\AuthenticationException;
use Centreon\Domain\Authentication\UseCase\AuthenticateApi;
use Centreon\Domain\Authentication\UseCase\AuthenticateApiRequest;
use Centreon\Domain\Authentication\UseCase\AuthenticateApiResponse;
use Centreon\Domain\Contact\Contact;
use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface;
use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface;
use Core\Security\Authentication\Application\Repository\WriteTokenRepositoryInterface;
use Core\Security\Authentication\Application\UseCase\Login\LoginRequest;
use Core\Security\Authentication\Domain\Model\NewProviderToken;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
use Core\Security\ProviderConfiguration\Domain\Model\Provider;
use PHPUnit\Framework\TestCase;
use Security\Domain\Authentication\Exceptions\ProviderException;
/**
* @package Tests\Centreon\Domain\Authentication\UseCase
*/
class AuthenticateApiTest extends TestCase
{
/** @var ProviderAuthenticationFactoryInterface&\PHPUnit\Framework\MockObject\MockObject */
private ProviderAuthenticationFactoryInterface $providerFactory;
/** @var WriteTokenRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */
private WriteTokenRepositoryInterface $writeTokenRepository;
/** @var NewProviderToken */
private NewProviderToken $providerToken;
/** @var Contact */
private Contact $contact;
/** @var Configuration&\PHPUnit\Framework\MockObject\MockObject */
private Configuration $configuration;
/** @var ProviderAuthenticationInterface&\PHPUnit\Framework\MockObject\MockObject */
private ProviderAuthenticationInterface $providerAuthentication;
protected function setUp(): void
{
$this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class);
$this->providerAuthentication = $this->createMock(ProviderAuthenticationInterface::class);
$this->configuration = $this->createMock(Configuration::class);
$this->providerToken = $this->createMock(NewProviderToken::class);
$this->writeTokenRepository = $this->createMock(WriteTokenRepositoryInterface::class);
$this->contact = (new Contact())
->setId(1)
->setName('contact_name1')
->setAlias('contact_alias1')
->setEmail('root@localhost')
->setAdmin(true);
}
/**
* test execute when local provider is not found
*/
public function testExecuteLocalProviderNotFound(): void
{
$authenticateApi = $this->createAuthenticationAPI();
$authenticateApiRequest = new AuthenticateApiRequest('admin', 'centreon');
$authenticateApiResponse = new AuthenticateApiResponse();
$this->providerFactory
->expects($this->once())
->method('create')
->with(Provider::LOCAL)
->willThrowException(ProviderException::providerConfigurationNotFound(Provider::LOCAL));
$this->expectException(ProviderException::class);
$this->expectExceptionMessage('Provider configuration (local) not found');
$authenticateApi->execute($authenticateApiRequest, $authenticateApiResponse);
}
/**
* test execute when user is not authenticated by provider
*/
public function testExecuteUserNotAuthenticated(): void
{
$authenticateApi = $this->createAuthenticationAPI();
$authenticateApiRequest = new AuthenticateApiRequest('admin', 'centreon');
$authenticateApiResponse = new AuthenticateApiResponse();
$this->providerFactory
->expects($this->once())
->method('create')
->with(Provider::LOCAL)
->willReturn($this->providerAuthentication);
$this->providerAuthentication
->expects($this->once())
->method('authenticateOrFail')
->with(LoginRequest::createForLocal('admin', 'centreon'))
->willThrowException(AuthenticationException::invalidCredentials());
$this->expectException(AuthenticationException::class);
$this->expectExceptionMessage('Invalid Credentials');
$authenticateApi->execute($authenticateApiRequest, $authenticateApiResponse);
}
/**
* test execute when user is not found
*/
public function testExecuteUserNotFound(): void
{
$authenticateApi = $this->createAuthenticationAPI();
$authenticateApiRequest = new AuthenticateApiRequest('admin', 'centreon');
$authenticateApiResponse = new AuthenticateApiResponse();
$this->providerFactory
->expects($this->once())
->method('create')
->with(Provider::LOCAL)
->willReturn($this->providerAuthentication);
$this->providerAuthentication
->expects($this->once())
->method('authenticateOrFail')
->with(LoginRequest::createForLocal('admin', 'centreon'));
$this->providerAuthentication
->expects($this->once())
->method('getAuthenticatedUser')
->willReturn(null);
$this->expectException(AuthenticationException::class);
$this->expectExceptionMessage('User cannot be retrieved from the provider');
$authenticateApi->execute($authenticateApiRequest, $authenticateApiResponse);
}
/**
* test execute when tokens cannot be created
*/
public function testExecuteCannotCreateTokens(): void
{
$authenticateApi = $this->createAuthenticationAPI();
$authenticateApiRequest = new AuthenticateApiRequest('admin', 'centreon');
$authenticateApiResponse = new AuthenticateApiResponse();
$this->providerFactory
->expects($this->once())
->method('create')
->with(Provider::LOCAL)
->willReturn($this->providerAuthentication);
$this->providerAuthentication
->expects($this->once())
->method('authenticateOrFail')
->with(LoginRequest::createForLocal('admin', 'centreon'));
$this->providerAuthentication
->expects($this->once())
->method('getAuthenticatedUser')
->willReturn($this->contact);
$this->providerAuthentication
->expects($this->once())
->method('getConfiguration')
->willReturn($this->configuration);
$this->providerAuthentication
->expects($this->once())
->method('getProviderToken')
->willReturn($this->providerToken);
$authenticateApi->execute($authenticateApiRequest, $authenticateApiResponse);
}
/**
* test execute succeed
*/
public function testExecuteSucceed(): void
{
$authenticateApi = $this->createAuthenticationAPI();
$authenticateApiRequest = new AuthenticateApiRequest('admin', 'centreon');
$authenticateApiResponse = new AuthenticateApiResponse();
$this->providerFactory
->expects($this->once())
->method('create')
->with(Provider::LOCAL)
->willReturn($this->providerAuthentication);
$this->providerAuthentication
->expects($this->once())
->method('authenticateOrFail')
->with(LoginRequest::createForLocal('admin', 'centreon'));
$this->providerAuthentication
->expects($this->once())
->method('getAuthenticatedUser')
->willReturn($this->contact);
$this->providerAuthentication
->expects($this->once())
->method('getConfiguration')
->willReturn($this->configuration);
$this->providerAuthentication
->expects($this->once())
->method('getProviderToken')
->willReturn($this->providerToken);
$authenticateApi->execute($authenticateApiRequest, $authenticateApiResponse);
$this->assertEqualsCanonicalizing(
[
'id' => 1,
'name' => 'contact_name1',
'alias' => 'contact_alias1',
'email' => 'root@localhost',
'is_admin' => true,
],
$authenticateApiResponse->getApiAuthentication()['contact']
);
$this->assertIsString($authenticateApiResponse->getApiAuthentication()['security']['token']);
}
/**
* @return AuthenticateApi
*/
private function createAuthenticationAPI(): AuthenticateApi
{
return new AuthenticateApi(
$this->writeTokenRepository,
$this->providerFactory
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Authentication/UseCase/LogoutTest.php | centreon/tests/php/Centreon/Domain/Authentication/UseCase/LogoutTest.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\Centreon\Domain\Authentication\UseCase;
use Centreon\Domain\Authentication\UseCase\Logout;
use Centreon\Domain\Authentication\UseCase\LogoutRequest;
use PHPUnit\Framework\TestCase;
use Security\Domain\Authentication\Interfaces\AuthenticationRepositoryInterface;
/**
* @package Tests\Centreon\Domain\Authentication\UseCase
*/
class LogoutTest extends TestCase
{
/** @var AuthenticationRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject */
private $authenticationRepository;
protected function setUp(): void
{
$this->authenticationRepository = $this->createMock(AuthenticationRepositoryInterface::class);
}
/**
* test execute
*/
public function testExecute(): void
{
$logout = new Logout($this->authenticationRepository);
$logoutRequest = new LogoutRequest('abc123');
$this->authenticationRepository
->expects($this->once())
->method('deleteSecurityToken')
->with('abc123');
$logout->execute($logoutRequest);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Common/AssertionTest.php | centreon/tests/php/Centreon/Domain/Common/AssertionTest.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\Centreon\Domain\Common;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Centreon\Domain\Common\Assertion\AssertionException;
$propertyPath = 'Class::property';
// ────────────────────────────── FAILURES tests ──────────────────────────────
$failDataProvider = [
'maxLength("oooX", 3)' => [
fn () => Assertion::maxLength('oooX', 3, $propertyPath),
AssertionException::maxLength('oooX', 4, 3, $propertyPath)->getMessage(),
AssertionException::INVALID_MAX_LENGTH,
],
'maxLength("utf8: éà", 7)' => [
fn () => Assertion::maxLength('utf8: éà', 7, $propertyPath),
AssertionException::maxLength('utf8: éà', 8, 7, $propertyPath)->getMessage(),
AssertionException::INVALID_MAX_LENGTH,
],
'minLength("", 1)' => [
fn () => Assertion::minLength('', 1, $propertyPath),
AssertionException::minLength('', 0, 1, $propertyPath)->getMessage(),
AssertionException::INVALID_MIN_LENGTH,
],
'minLength("utf8: éà", 9)' => [
fn () => Assertion::minLength('utf8: éà', 9, $propertyPath),
AssertionException::minLength('utf8: éà', 8, 9, $propertyPath)->getMessage(),
AssertionException::INVALID_MIN_LENGTH,
],
'email("not-an-email")' => [
fn () => Assertion::email('not-an-email', $propertyPath),
AssertionException::email('not-an-email', $propertyPath)->getMessage(),
AssertionException::INVALID_EMAIL,
],
'positiveInt(0)' => [
fn () => Assertion::positiveInt(0, $propertyPath),
AssertionException::positiveInt(0, $propertyPath)->getMessage(),
AssertionException::INVALID_MIN,
],
'min(0, 1)' => [
fn () => Assertion::min(0, 1, $propertyPath),
AssertionException::min(0, 1, $propertyPath)->getMessage(),
AssertionException::INVALID_MIN,
],
'max(43, 42)' => [
fn () => Assertion::max(43, 42, $propertyPath),
AssertionException::max(43, 42, $propertyPath)->getMessage(),
AssertionException::INVALID_MAX,
],
'greaterOrEqualThan(41, 42)' => [
fn () => Assertion::greaterOrEqualThan(41, 42, $propertyPath),
AssertionException::greaterOrEqualThan(41, 42, $propertyPath)->getMessage(),
AssertionException::INVALID_GREATER_OR_EQUAL,
],
'notEmpty(NULL)' => [
fn () => Assertion::notEmpty(null, $propertyPath),
AssertionException::notEmpty($propertyPath)->getMessage(),
AssertionException::VALUE_EMPTY,
],
'notEmpty(false)' => [
fn () => Assertion::notEmpty(false, $propertyPath),
AssertionException::notEmpty($propertyPath)->getMessage(),
AssertionException::VALUE_EMPTY,
],
'notEmpty(0)' => [
fn () => Assertion::notEmpty(0, $propertyPath),
AssertionException::notEmpty($propertyPath)->getMessage(),
AssertionException::VALUE_EMPTY,
],
'notEmpty(0.0)' => [
fn () => Assertion::notEmpty(0.0, $propertyPath),
AssertionException::notEmpty($propertyPath)->getMessage(),
AssertionException::VALUE_EMPTY,
],
'notEmpty("")' => [
fn () => Assertion::notEmpty('', $propertyPath),
AssertionException::notEmpty($propertyPath)->getMessage(),
AssertionException::VALUE_EMPTY,
],
'notEmpty("0")' => [
fn () => Assertion::notEmpty('0', $propertyPath),
AssertionException::notEmpty($propertyPath)->getMessage(),
AssertionException::VALUE_EMPTY,
],
'notEmpty([])' => [
fn () => Assertion::notEmpty([], $propertyPath),
AssertionException::notEmpty($propertyPath)->getMessage(),
AssertionException::VALUE_EMPTY,
],
'notEmptyString(NULL)' => [
fn () => Assertion::notEmptyString(null, $propertyPath),
AssertionException::notEmptyString($propertyPath)->getMessage(),
AssertionException::VALUE_EMPTY,
],
'notEmptyString("")' => [
fn () => Assertion::notEmptyString('', $propertyPath),
AssertionException::notEmptyString($propertyPath)->getMessage(),
AssertionException::VALUE_EMPTY,
],
'notNull(NULL)' => [
fn () => Assertion::notNull(null, $propertyPath),
AssertionException::notNull($propertyPath)->getMessage(),
AssertionException::VALUE_NULL,
],
'inArray(2, [1, "a", NULL])' => [
fn () => Assertion::inArray(2, [1, 'a', null], $propertyPath),
AssertionException::inArray(2, [1, 'a', null], $propertyPath)->getMessage(),
AssertionException::INVALID_CHOICE,
],
'range(0.9, 1.0, 2)' => [
fn () => Assertion::range(0.9, 1.0, 2, $propertyPath),
AssertionException::range(0.9, 1.0, 2, $propertyPath)->getMessage(),
AssertionException::INVALID_RANGE,
],
'range(2.1, 1.0, 2)' => [
fn () => Assertion::range(2.1, 1.0, 2, $propertyPath),
AssertionException::range(2.1, 1.0, 2, $propertyPath)->getMessage(),
AssertionException::INVALID_RANGE,
],
'regex("abc123", "/^\d+$/")' => [
fn () => Assertion::regex('abc123', '/^\d+$/', $propertyPath),
AssertionException::matchRegex('abc123', '/^\d+$/', $propertyPath)->getMessage(),
AssertionException::INVALID_REGEX,
],
'regex(1234, "/^\d+$/")' => [
fn () => Assertion::regex(1234, '/^\d+$/', $propertyPath),
AssertionException::matchRegex('1234', '/^\d+$/', $propertyPath)->getMessage(),
AssertionException::INVALID_REGEX,
],
'ipOrDomain("")' => [
fn () => Assertion::ipOrDomain('', $propertyPath),
AssertionException::ipOrDomain('', $propertyPath)->getMessage(),
AssertionException::INVALID_IP_OR_DOMAIN,
],
'ipOrDomain("not:valid")' => [
fn () => Assertion::ipOrDomain('not:valid', $propertyPath),
AssertionException::ipOrDomain('not:valid', $propertyPath)->getMessage(),
AssertionException::INVALID_IP_OR_DOMAIN,
],
'ipAddress("any-hostname")' => [
fn () => Assertion::ipAddress('any-hostname', $propertyPath),
AssertionException::ipAddressNotValid('any-hostname', $propertyPath)->getMessage(),
AssertionException::INVALID_IP,
],
'ipAddress(1234)' => [
fn () => Assertion::ipAddress(1234, $propertyPath),
AssertionException::ipAddressNotValid('1234', $propertyPath)->getMessage(),
AssertionException::INVALID_IP,
],
'maxDate(new DateTime("2023-02-08 16:00:01"), new DateTime("2023-02-08 16:00:00"))' => [
fn () => Assertion::maxDate(
new \DateTime('2023-02-08 16:00:01'),
new \DateTime('2023-02-08 16:00:00'),
$propertyPath
),
AssertionException::maxDate(
new \DateTime('2023-02-08 16:00:01'),
new \DateTime('2023-02-08 16:00:00'),
$propertyPath
)->getMessage(),
AssertionException::INVALID_MAX_DATE,
],
"isInstanceOf('test', Exception:class)" => [
fn () => Assertion::isInstanceOf('test', \Exception::class, $propertyPath),
AssertionException::badInstanceOfObject(gettype('test'), \Exception::class, $propertyPath)->getMessage(),
AssertionException::INVALID_INSTANCE_OF,
],
'jsonString("not:valid")' => [
fn () => Assertion::jsonString('not:valid', $propertyPath),
AssertionException::invalidJsonString($propertyPath)->getMessage(),
AssertionException::INVALID_JSON_STRING,
],
'jsonString("")' => [
fn () => Assertion::jsonString('', $propertyPath),
AssertionException::invalidJsonString($propertyPath)->getMessage(),
AssertionException::INVALID_JSON_STRING,
],
'arrayJsonEncodable("malformed utf8 : ..")' => [
fn () => Assertion::jsonEncodable("malformed utf8 :\xd8\x3d", $propertyPath),
AssertionException::notJsonEncodable($propertyPath)->getMessage(),
AssertionException::INVALID_ARRAY_JSON_ENCODABLE,
],
'arrayJsonEncodable("too long")' => [
fn () => Assertion::jsonEncodable('too long', $propertyPath, 5),
AssertionException::maxLength('<JSON>', 10, 5, $propertyPath)->getMessage(),
AssertionException::INVALID_MAX_LENGTH,
],
"unauthorisedCharacters('new bad string!', '!&#@')" => [
fn () => Assertion::unauthorizedCharacters('new bad string!', '!&#@', $propertyPath),
AssertionException::unauthorizedCharacters('new bad string!', '!', $propertyPath)->getMessage(),
AssertionException::INVALID_CHARACTERS,
],
];
// We use a custom data provider with a loop to avoid pest from auto-evaluating the closure from the dataset.
foreach ($failDataProvider as $name => [$failAssertion, $failMessage, $failCode]) {
it(
'should throw an exception for ' . $name . ' (' . rand(1, 10000) . ')',
function () use ($propertyPath, $failAssertion, $failMessage, $failCode): void {
try {
$failAssertion();
$this->fail('This SHALL NOT pass.');
} catch (AssertionFailedException $e) {
// expected class + message + propertyPath + code
expect($e->getMessage())->toBe($failMessage)
->and($e->getPropertyPath())->toBe($propertyPath)
->and($e->getCode())->toBe($failCode);
} catch (\Throwable) {
$this->fail('This SHALL NOT pass.');
}
}
);
}
// ────────────────────────────── SUCCESS tests ──────────────────────────────
$successDataProvider = [
'maxLength("ooo", 3)' => [
fn () => Assertion::maxLength('ooo', 3, $propertyPath),
],
'maxLength("utf8: éà", 8)' => [
fn () => Assertion::maxLength('utf8: éà', 8, $propertyPath),
],
'minLength("o", 1)' => [
fn () => Assertion::minLength('o', 1, $propertyPath),
],
'minLength("utf8: éà", 8)' => [
fn () => Assertion::minLength('utf8: éà', 8, $propertyPath),
],
'email("ok@centreon.com")' => [
fn () => Assertion::email('ok@centreon.com', $propertyPath),
],
'positiveInt(1)' => [
fn () => Assertion::positiveInt(1, $propertyPath),
],
'min(1, 1)' => [
fn () => Assertion::min(1, 1, $propertyPath),
],
'max(42, 42)' => [
fn () => Assertion::max(42, 42, $propertyPath),
],
'greaterOrEqualThan(42, 42)' => [
fn () => Assertion::greaterOrEqualThan(42, 42, $propertyPath),
],
'notEmpty(true)' => [
fn () => Assertion::notEmpty(true, $propertyPath),
],
'notEmpty(1)' => [
fn () => Assertion::notEmpty(1, $propertyPath),
],
'notEmpty(1.5)' => [
fn () => Assertion::notEmpty(1, $propertyPath),
],
'notEmpty("abc")' => [
fn () => Assertion::notEmpty('abc', $propertyPath),
],
'notEmpty([42])' => [
fn () => Assertion::notEmpty([42], $propertyPath),
],
'notEmptyString("0")' => [
fn () => Assertion::notEmptyString('0', $propertyPath),
],
'notEmptyString("abc")' => [
fn () => Assertion::notEmptyString('abc', $propertyPath),
],
'notNull(0)' => [
fn () => Assertion::notNull(0, $propertyPath),
],
'notNull(0.0)' => [
fn () => Assertion::notNull(0.0, $propertyPath),
],
'notNull("")' => [
fn () => Assertion::notNull('', $propertyPath),
],
'notNull([])' => [
fn () => Assertion::notNull([], $propertyPath),
],
'inArray(NULL, [1, "a", NULL])' => [
fn () => Assertion::inArray(null, [1, 'a', null], $propertyPath),
],
'range(1.1, 1.0, 2)' => [
fn () => Assertion::range(1.1, 1.0, 2, $propertyPath),
],
'range(1, 1.0, 2)' => [
fn () => Assertion::range(1, 1.0, 2, $propertyPath),
],
'range(2, 1.0, 2)' => [
fn () => Assertion::range(2, 1.0, 2, $propertyPath),
],
'range(2.0, 1.0, 2)' => [
fn () => Assertion::range(2.0, 1.0, 2, $propertyPath),
],
'regex("1234", "/^\d+$/")' => [
fn () => Assertion::regex('1234', '/^\d+$/', $propertyPath),
],
'ipOrDomain("1.2.3.4")' => [
fn () => Assertion::ipOrDomain('1.2.3.4', $propertyPath),
],
'ipOrDomain("any-hostname")' => [
fn () => Assertion::ipOrDomain('any-hostname', $propertyPath),
],
'ipAddress("2.3.4.5")' => [
fn () => Assertion::ipAddress('2.3.4.5', $propertyPath),
],
'maxDate(new DateTime("2023-02-08 16:00:00"), new DateTime("2023-02-08 16:00:00"))' => [
fn () => Assertion::maxDate(
new \DateTime('2023-02-08 16:00:00'),
new \DateTime('2023-02-08 16:00:00'),
$propertyPath
),
],
"isInstanceOf(new \Exception(), \Throwable::class)" => [
fn () => Assertion::isInstanceOf(new \Exception(), \Throwable::class, $propertyPath),
],
"jsonString('{}')" => [
fn () => Assertion::jsonString('{}', $propertyPath),
],
"jsonString('[]')" => [
fn () => Assertion::jsonString('[]', $propertyPath),
],
"jsonString('42')" => [
fn () => Assertion::jsonString('42', $propertyPath),
],
"jsonString('42.42')" => [
fn () => Assertion::jsonString('42', $propertyPath),
],
"jsonString('null')" => [
fn () => Assertion::jsonString('null', $propertyPath),
],
"jsonString('false')" => [
fn () => Assertion::jsonString('false', $propertyPath),
],
"jsonString('true')" => [
fn () => Assertion::jsonString('true', $propertyPath),
],
"jsonString('\"foo\"')" => [
fn () => Assertion::jsonString('"foo"', $propertyPath),
],
'arrayJsonEncodable([1,2,3])' => [
fn () => Assertion::jsonEncodable([1, 2, 3], $propertyPath),
],
'arrayJsonEncodable("foo")' => [
fn () => Assertion::jsonEncodable('foo', $propertyPath),
],
"unauthorisedCharacters('new bad string!', '&#@')" => [
fn () => Assertion::unauthorizedCharacters('new bad string!', '&#@', $propertyPath),
],
"unauthorisedCharacters('new bad string!&#@', '')" => [
fn () => Assertion::unauthorizedCharacters('new bad string!&#@', '', $propertyPath),
],
];
// We use a custom data provider with a loop to avoid pest from auto-evaluating the closure from the dataset.
foreach ($successDataProvider as $name => [$successAssertion]) {
it(
'should not throw an exception for ' . $name . ' (' . rand(1, 10000) . ')',
function () use ($successAssertion): void {
try {
$successAssertion();
expect(true)->toBeTrue();
} catch (\Throwable) {
$this->fail('This SHALL NOT fail.');
}
}
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/HostConfiguration/Model/HostSeverityTest.php | centreon/tests/php/Centreon/Domain/HostConfiguration/Model/HostSeverityTest.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\Centreon\Domain\HostConfiguration\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\HostConfiguration\Model\HostSeverity;
use Centreon\Domain\Media\Model\Image;
use PHPUnit\Framework\TestCase;
/**
* This class is designed to test all setters of the HostSeverity entity, especially those with exceptions.
*
* @package Tests\Centreon\Domain\HostConfiguration\Model
*/
class HostSeverityTest extends TestCase
{
/** @var Image define the image that should be associated with this severity */
protected $icon;
protected function setUp(): void
{
$this->icon = (new Image())->setId(1)->setName('my icon')->setPath('/');
}
/**
* Too long name test
* @throws \Assert\AssertionFailedException
*/
public function testNameTooLongException(): void
{
$name = str_repeat('.', HostSeverity::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
strlen($name),
HostSeverity::MAX_NAME_LENGTH,
'HostSeverity::name'
)->getMessage()
);
new HostSeverity($name, 'alias', 42, $this->icon);
}
/**
* Too short name test
* @throws \Assert\AssertionFailedException
*/
public function testNameTooShortException(): void
{
$name = str_repeat('.', HostSeverity::MIN_NAME_LENGTH - 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$name,
strlen($name),
HostSeverity::MIN_NAME_LENGTH,
'HostSeverity::name'
)->getMessage()
);
new HostSeverity($name, 'alias', 42, $this->icon);
}
/**
* Too long alias test
* @throws \Assert\AssertionFailedException
*/
public function testAliasTooLongException(): void
{
$alias = str_repeat('.', HostSeverity::MAX_ALIAS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$alias,
strlen($alias),
HostSeverity::MAX_ALIAS_LENGTH,
'HostSeverity::alias'
)->getMessage()
);
new HostSeverity('name', $alias, 42, $this->icon);
}
/**
* Too short alias test
* @throws \Assert\AssertionFailedException
*/
public function testAliasTooShortException(): void
{
$alias = str_repeat('.', HostSeverity::MIN_ALIAS_LENGTH - 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$alias,
strlen($alias),
HostSeverity::MIN_ALIAS_LENGTH,
'HostSeverity::alias'
)->getMessage()
);
new HostSeverity('name', $alias, 42, $this->icon);
}
/**
* Too long level test
* @throws \Assert\AssertionFailedException
*/
public function testLevelTooLongException(): void
{
$level = HostSeverity::MAX_LEVEL_NUMBER + 1;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::max(
$level,
HostSeverity::MAX_LEVEL_NUMBER,
'HostSeverity::level'
)->getMessage()
);
new HostSeverity('name', 'alias', $level, $this->icon);
}
/**
* Too short rrd test
*/
public function testLevelTooShortException(): void
{
$level = HostSeverity::MIN_LEVEL_NUMBER - 1;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::min(
$level,
HostSeverity::MIN_LEVEL_NUMBER,
'HostSeverity::level'
)->getMessage()
);
new HostSeverity('name', 'alias', $level, $this->icon);
}
/**
* Too long comments test
* @throws \Assert\AssertionFailedException
*/
public function testCommentsTooLongException(): void
{
$comments = str_repeat('.', HostSeverity::MAX_COMMENTS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$comments,
strlen($comments),
HostSeverity::MAX_COMMENTS_LENGTH,
'HostSeverity::comments'
)->getMessage()
);
(new HostSeverity('name', 'alias', 42, $this->icon))->setComments($comments);
}
/**
* IsActivated property test
*/
public function testIsActivatedProperty(): void
{
$hostSeverity = new HostSeverity('name', 'alias', 42, $this->icon);
$this->assertTrue($hostSeverity->isActivated());
$hostSeverity->setActivated(false);
$this->assertFalse($hostSeverity->isActivated());
}
/**
* Id property test
*/
public function testIdProperty(): void
{
$newHostId = 1;
$hostSeverity = new HostSeverity('name', 'alias', 42, $this->icon);
$hostSeverity->setId($newHostId);
$this->assertEquals($newHostId, $hostSeverity->getId());
}
/**
* @throws \Assert\AssertionFailedException
* @return HostSeverity
*/
public static function createEntity(): HostSeverity
{
$icon = (new Image())->setId(1)->setName('my icon')->setPath('/');
return (new HostSeverity('Severity', 'Alias severity', 42, $icon))
->setId(10)
->setActivated(true)
->setComments('blablabla');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/HostConfiguration/Model/HostTemplateTest.php | centreon/tests/php/Centreon/Domain/HostConfiguration/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\Centreon\Domain\HostConfiguration\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\HostConfiguration\Exception\HostTemplateArgumentException;
use Centreon\Domain\HostConfiguration\Model\HostTemplate;
use Centreon\Domain\Media\Model\Image;
use PHPUnit\Framework\TestCase;
/**
* This class is designed to test all setters of the HostTemplate entity, especially those with exceptions.
*
* @package Tests\Centreon\Domain\HostConfiguration\Model
*/
class HostTemplateTest extends TestCase
{
/**
* Test the notification options
*/
public function testBadNotificationOptionException(): void
{
$optionsValueToTest = (
HostTemplate::NOTIFICATION_OPTION_DOWN
| HostTemplate::NOTIFICATION_OPTION_UNREACHABLE
| HostTemplate::NOTIFICATION_OPTION_RECOVERY
| HostTemplate::NOTIFICATION_OPTION_FLAPPING
| HostTemplate::NOTIFICATION_OPTION_DOWNTIME_SCHEDULED
) + 1;
$this->expectException(HostTemplateArgumentException::class);
$this->expectExceptionMessage(
HostTemplateArgumentException::badNotificationOptions($optionsValueToTest)->getMessage()
);
$hostTemplate = new HostTemplate();
$hostTemplate->setNotificationOptions($optionsValueToTest);
}
/**
* Test the stalking options
*/
public function testBadStalkingOptionException(): void
{
$optionsValueToTest = (
HostTemplate::STALKING_OPTION_UP
| HostTemplate::STALKING_OPTION_DOWN
| HostTemplate::STALKING_OPTION_UNREACHABLE
) + 1;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
HostTemplateArgumentException::badStalkingOptions($optionsValueToTest)->getMessage()
);
$hostTemplate = new HostTemplate();
$hostTemplate->setStalkingOptions($optionsValueToTest);
}
/**
* Too long name test
*/
public function testNameTooLongException(): void
{
$name = str_repeat('.', HostTemplate::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
strlen($name),
HostTemplate::MAX_NAME_LENGTH,
'HostTemplate::name'
)->getMessage()
);
(new HostTemplate())->setName($name);
}
/**
* Too long alias test
*/
public function testAliasTooLongException(): void
{
$alias = str_repeat('.', HostTemplate::MAX_ALIAS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$alias,
strlen($alias),
HostTemplate::MAX_ALIAS_LENGTH,
'HostTemplate::alias'
)->getMessage()
);
(new HostTemplate())->setAlias($alias);
}
/**
* Too long display name test
*/
public function testDisplayNameTooLongException(): void
{
$displayName = str_repeat('.', HostTemplate::MAX_DISPLAY_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$displayName,
strlen($displayName),
HostTemplate::MAX_DISPLAY_NAME_LENGTH,
'HostTemplate::displayName'
)->getMessage()
);
(new HostTemplate())->setDisplayName($displayName);
}
/**
* Too long address test
*/
public function testAddressTooLongException(): void
{
$address = str_repeat('.', HostTemplate::MAX_ADDRESS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$address,
strlen($address),
HostTemplate::MAX_ADDRESS_LENGTH,
'HostTemplate::address'
)->getMessage()
);
(new HostTemplate())->setAddress($address);
}
/**
* Too long comments test
*/
public function testCommentTooLongException(): void
{
$comments = str_repeat('.', HostTemplate::MAX_COMMENTS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$comments,
strlen($comments),
HostTemplate::MAX_COMMENTS_LENGTH,
'HostTemplate::comment'
)->getMessage()
);
(new HostTemplate())->setComment($comments);
}
/**
* Test the bad active checks status
*/
public function testBadActiveChecksException(): void
{
$badActiveChecksStatus = 128;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
HostTemplateArgumentException::badActiveChecksStatus($badActiveChecksStatus)->getMessage()
);
(new HostTemplate())->setActiveChecksStatus($badActiveChecksStatus);
}
/**
* Test the bad passive checks status
*/
public function testBadPassiveChecksException(): void
{
$badPassiveChecksStatus = 128;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
HostTemplateArgumentException::badPassiveChecksStatus($badPassiveChecksStatus)->getMessage()
);
(new HostTemplate())->setPassiveChecksStatus($badPassiveChecksStatus);
}
/**
* Test the max check attemps
*/
public function testBadMaxCheckAttempts(): void
{
$maxCheckAttempts = HostTemplate::MIN_CHECK_ATTEMPS - 1;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::min(
HostTemplate::MIN_CHECK_ATTEMPS - 1,
HostTemplate::MIN_CHECK_ATTEMPS,
'HostTemplate::maxCheckAttempts'
)->getMessage()
);
(new HostTemplate())->setMaxCheckAttempts($maxCheckAttempts);
}
/**
* Test the check interval
*/
public function testBadCheckInterval(): void
{
$checkInterval = HostTemplate::MIN_CHECK_INTERVAL - 1;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::min(
HostTemplate::MIN_CHECK_INTERVAL - 1,
HostTemplate::MIN_CHECK_INTERVAL,
'HostTemplate::checkInterval'
)->getMessage()
);
(new HostTemplate())->setCheckInterval($checkInterval);
}
/**
* Test the retry check interval
*/
public function testBadRetryCheckInterval(): void
{
$retryCheckInterval = HostTemplate::MIN_RETRY_CHECK_INTERVAL - 1;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::min(
HostTemplate::MIN_RETRY_CHECK_INTERVAL - 1,
HostTemplate::MIN_RETRY_CHECK_INTERVAL,
'HostTemplate::retryCheckInterval'
)->getMessage()
);
(new HostTemplate())->setRetryCheckInterval($retryCheckInterval);
}
/**
* Test the notification interval
*/
public function testBadNotificationInterval(): void
{
$notificationInterval = HostTemplate::MIN_NOTIFICATION_INTERVAL - 1;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::greaterOrEqualThan(
HostTemplate::MIN_NOTIFICATION_INTERVAL - 1,
HostTemplate::MIN_NOTIFICATION_INTERVAL,
'HostTemplate::notificationInterval'
)->getMessage()
);
(new HostTemplate())->setNotificationInterval($notificationInterval);
}
/**
* Test the first notification delay
*/
public function testBadFirstNotificationDelay(): void
{
$firstNotificationDelay = HostTemplate::MIN_FIRST_NOTIFICATION_DELAY - 1;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::greaterOrEqualThan(
HostTemplate::MIN_FIRST_NOTIFICATION_DELAY - 1,
HostTemplate::MIN_FIRST_NOTIFICATION_DELAY,
'HostTemplate::firstNotificationDelay'
)->getMessage()
);
(new HostTemplate())->setFirstNotificationDelay($firstNotificationDelay);
}
/**
* Test the recovery notification delay
*/
public function testBadRecoveryNotificationDelay(): void
{
$recoveryNotificationDelay = HostTemplate::MIN_RECOVERY_NOTIFICATION_DELAY - 1;
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::greaterOrEqualThan(
HostTemplate::MIN_RECOVERY_NOTIFICATION_DELAY - 1,
HostTemplate::MIN_RECOVERY_NOTIFICATION_DELAY,
'HostTemplate::recoveryNotificationDelay'
)->getMessage()
);
(new HostTemplate())->setRecoveryNotificationDelay($recoveryNotificationDelay);
}
/**
* Test the snmp community
*/
public function testBadSnmpCommunity(): void
{
$snmpCommunity = str_repeat('.', HostTemplate::MAX_SNMP_COMMUNITY_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$snmpCommunity,
strlen($snmpCommunity),
HostTemplate::MAX_SNMP_COMMUNITY_LENGTH,
'HostTemplate::snmpCommunity'
)->getMessage()
);
(new HostTemplate())->setSnmpCommunity($snmpCommunity);
}
/**
* Test the snmp version
*/
public function testBadSnmpVersion(): void
{
$snmpVersion = '4';
$hostTemplate = new HostTemplate();
$hostTemplate->setSnmpVersion($snmpVersion);
$this->assertNull($hostTemplate->getSnmpVersion());
}
/**
* Test the alternative icon text
*/
public function testBadAlternativeIconText(): void
{
$alternativeText = str_repeat('.', HostTemplate::MAX_ALTERNATIF_ICON_TEXT + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$alternativeText,
strlen($alternativeText),
HostTemplate::MAX_ALTERNATIF_ICON_TEXT,
'HostTemplate::alternativeIcon'
)->getMessage()
);
(new HostTemplate())->setAlternativeIcon($alternativeText);
}
/**
* Test the url notes
*/
public function testBadUrlNotes(): void
{
$urlNotes = str_repeat('.', HostTemplate::MAX_URL_NOTES + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$urlNotes,
strlen($urlNotes),
HostTemplate::MAX_URL_NOTES,
'HostTemplate::urlNotes'
)->getMessage()
);
(new HostTemplate())->setUrlNotes($urlNotes);
}
/**
* Test the action url
*/
public function testBadActionUrl(): void
{
$actionUrl = str_repeat('.', HostTemplate::MAX_ACTION_URL + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$actionUrl,
strlen($actionUrl),
HostTemplate::MAX_ACTION_URL,
'HostTemplate::actionUrl'
)->getMessage()
);
(new HostTemplate())->setActionUrl($actionUrl);
}
/**
* Test the notes
*/
public function testBadNotes(): void
{
$notes = str_repeat('.', HostTemplate::MAX_NOTES + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$notes,
strlen($notes),
HostTemplate::MAX_NOTES,
'HostTemplate::notes'
)->getMessage()
);
(new HostTemplate())->setNotes($notes);
}
/**
* Test the parentIds
*/
public function testParentIds(): void
{
$hostTemplate = new HostTemplate();
$hostTemplate->setParentIds(['a', 2, 'c', 7]);
$this->assertCount(2, $hostTemplate->getParentIds());
$this->assertEquals([2, 7], $hostTemplate->getParentIds());
}
/**
* @throws \Assert\AssertionFailedException
* @return HostTemplate
*/
public static function createEntity(): HostTemplate
{
return (new HostTemplate())
->setId(10)
->setName('OS-Linux-SNMP-custom')
->setAlias('Template to check Linux server using SNMP protocol')
->setActivated(true)
->setLocked(false)
->setActiveChecksStatus(HostTemplate::STATUS_DEFAULT)
->setPassiveChecksStatus(HostTemplate::STATUS_DEFAULT)
->setNotificationsStatus(HostTemplate::STATUS_DEFAULT)
->setNotificationOptions(
HostTemplate::NOTIFICATION_OPTION_DOWN
| HostTemplate::NOTIFICATION_OPTION_UNREACHABLE
| HostTemplate::NOTIFICATION_OPTION_RECOVERY
| HostTemplate::NOTIFICATION_OPTION_FLAPPING
| HostTemplate::NOTIFICATION_OPTION_DOWNTIME_SCHEDULED
)
->setIcon((new Image())->setId(1)->setName('my icon')->setPath('/'))
->setStatusMapImage((new Image())->setId(2)->setName('my status map image')->setPath('/'))
->setParentIds([9]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/HostConfiguration/Model/HostGroupTest.php | centreon/tests/php/Centreon/Domain/HostConfiguration/Model/HostGroupTest.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\Centreon\Domain\HostConfiguration\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\HostConfiguration\Model\HostGroup;
use Centreon\Domain\Media\Model\Image;
use PHPUnit\Framework\TestCase;
/**
* This class is designed to test all setters of the HostGroup entity, especially those with exceptions.
*
* @package Tests\Centreon\Domain\HostConfiguration\Model
*/
class HostGroupTest extends TestCase
{
/**
* Too long name test
*/
public function testNameTooLongException(): void
{
$name = str_repeat('.', HostGroup::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
strlen($name),
HostGroup::MAX_NAME_LENGTH,
'HostGroup::name'
)->getMessage()
);
(new HostGroup('hg-name'))->setName($name);
}
/**
* Too long alias test
*/
public function testAliasTooLongException(): void
{
$alias = str_repeat('.', HostGroup::MAX_ALIAS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$alias,
strlen($alias),
HostGroup::MAX_ALIAS_LENGTH,
'HostGroup::alias'
)->getMessage()
);
(new HostGroup('hg-name'))->setAlias($alias);
}
/**
* Too long comments test
*/
public function testCommentTooLongException(): void
{
$comments = str_repeat('.', HostGroup::MAX_COMMENTS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$comments,
strlen($comments),
HostGroup::MAX_COMMENTS_LENGTH,
'HostGroup::comment'
)->getMessage()
);
(new HostGroup('hg-name'))->setComment($comments);
}
/**
* Too long geo coords test
*/
public function testGeoCoordsTooLongException(): void
{
$geoCoords = str_repeat('.', HostGroup::MAX_GEO_COORDS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$geoCoords,
strlen($geoCoords),
HostGroup::MAX_GEO_COORDS_LENGTH,
'HostGroup::geoCoords'
)->getMessage()
);
(new HostGroup('hg-name'))->setGeoCoords($geoCoords);
}
/**
* @throws \Assert\AssertionFailedException
* @return HostGroup
*/
public static function createEntity(): HostGroup
{
return (new HostGroup('hg-name'))
->setId(10)
->setName('hg-name')
->setAlias('host group name')
->setActivated(true)
->setIcon((new Image())->setId(1)->setName('my icon')->setPath('/'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/HostConfiguration/Model/HostCategoryTest.php | centreon/tests/php/Centreon/Domain/HostConfiguration/Model/HostCategoryTest.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\Centreon\Domain\HostConfiguration\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\HostConfiguration\Model\HostCategory;
use PHPUnit\Framework\TestCase;
/**
* This class is designed to test all setters of the HostCategory entity, especially those with exceptions.
*
* @package Tests\Centreon\Domain\HostConfiguration\Model
*/
class HostCategoryTest extends TestCase
{
/**
* Too long name test
*/
public function testNameTooShortException(): void
{
$name = str_repeat('.', HostCategory::MIN_NAME_LENGTH - 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$name,
strlen($name),
HostCategory::MIN_NAME_LENGTH,
'HostCategory::name'
)->getMessage()
);
new HostCategory($name, 'alias');
}
/**
* Too long name test
*/
public function testNameTooLongException(): void
{
$name = str_repeat('.', HostCategory::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
strlen($name),
HostCategory::MAX_NAME_LENGTH,
'HostCategory::name'
)->getMessage()
);
new HostCategory($name, 'alias');
}
/**
* Too short alias test
*/
public function testAliasTooShortException(): void
{
$alias = str_repeat('.', HostCategory::MIN_ALIAS_LENGTH - 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$alias,
strlen($alias),
HostCategory::MIN_ALIAS_LENGTH,
'HostCategory::alias'
)->getMessage()
);
new HostCategory('name', $alias);
}
/**
* Too long alias test
*/
public function testAliasTooLongException(): void
{
$alias = str_repeat('.', HostCategory::MAX_ALIAS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$alias,
strlen($alias),
HostCategory::MAX_ALIAS_LENGTH,
'HostCategory::alias'
)->getMessage()
);
new HostCategory('name', $alias);
}
/**
* Too long comments test
*/
public function testCommentsTooLongException(): void
{
$comments = str_repeat('.', HostCategory::MAX_COMMENTS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$comments,
strlen($comments),
HostCategory::MAX_COMMENTS_LENGTH,
'HostCategory::comments'
)->getMessage()
);
(new HostCategory('name', 'alias'))->setComments($comments);
}
/**
* IsActivated property test
*/
public function testIsActivatedProperty(): void
{
$hostCategory = new HostCategory('name', 'alias');
$this->assertTrue($hostCategory->isActivated());
$hostCategory->setActivated(false);
$this->assertFalse($hostCategory->isActivated());
}
/**
* Id property test
*/
public function testIdProperty(): void
{
$newHostId = 1;
$hostCategory = new HostCategory('name', 'alias');
$this->assertNull($hostCategory->getId());
$hostCategory->setId($newHostId);
$this->assertEquals($newHostId, $hostCategory->getId());
}
/**
* @throws \Assert\AssertionFailedException
* @return HostCategory
*/
public static function createEntity(): HostCategory
{
return (new HostCategory('name', 'alias'))
->setId(10)
->setName('Category')
->setAlias('Alias category')
->setActivated(true)
->setComments('blablabla');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/HostConfiguration/Exceptions/HostCategoryExceptionTest.php | centreon/tests/php/Centreon/Domain/HostConfiguration/Exceptions/HostCategoryExceptionTest.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\Centreon\Domain\HostConfiguration\Exceptions;
use Centreon\Domain\HostConfiguration\Exception\HostCategoryException;
use PHPUnit\Framework\TestCase;
/**
* @package Tests\Centreon\Domain\HostConfiguration\Exceptions
*/
class HostCategoryExceptionTest extends TestCase
{
/**
* Tests the arguments of the static method findHostCategoryException.
*/
public function testFindHostCategoryException(): void
{
$previousMessage1 = 'Error message 1';
$previousMessage2 = 'Error message 2';
$errorMessage = 'Error when searching for the host category (%s)';
$exception = HostCategoryException::findHostCategoryException(
new \Exception($previousMessage1),
['id' => 999]
);
self::assertEquals(sprintf($errorMessage, 999), $exception->getMessage());
self::assertNotNull($exception->getPrevious());
self::assertEquals($previousMessage1, $exception->getPrevious()->getMessage());
$exception = HostCategoryException::findHostCategoryException(
new \Exception($previousMessage2),
['name' => 'test name']
);
self::assertEquals(sprintf($errorMessage, 'test name'), $exception->getMessage());
self::assertNotNull($exception->getPrevious());
self::assertEquals($previousMessage2, $exception->getPrevious()->getMessage());
}
/**
* Tests the arguments of the static method notFoundException.
*/
public function testNotFoundException(): void
{
$previousMessage1 = 'Error message 1';
$previousMessage2 = 'Error message 2';
$errorMessage = 'Host category (%s) not found';
$exception = HostCategoryException::notFoundException(
['id' => 999],
new \Exception($previousMessage1),
);
self::assertEquals(sprintf($errorMessage, 999), $exception->getMessage());
self::assertNotNull($exception->getPrevious());
self::assertEquals($previousMessage1, $exception->getPrevious()->getMessage());
$exception = HostCategoryException::notFoundException(
['name' => 'test name'],
new \Exception($previousMessage2)
);
self::assertEquals(sprintf($errorMessage, 'test name'), $exception->getMessage());
self::assertNotNull($exception->getPrevious());
self::assertEquals($previousMessage2, $exception->getPrevious()->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/Centreon/Domain/MonitoringServer/MonitoringServerServiceTest.php | centreon/tests/php/Centreon/Domain/MonitoringServer/MonitoringServerServiceTest.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\Centreon\Domain\MonitoringServer;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\MonitoringServer\Exception\MonitoringServerException;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerRepositoryInterface;
use Centreon\Domain\MonitoringServer\MonitoringServerService;
use Core\MonitoringServer\Model\MonitoringServer;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
beforeEach(function (): void {
$this->user = $this->createMock(ContactInterface::class);
$this->monitoringServerRepository = $this->createMock(MonitoringServerRepositoryInterface::class);
$this->readAccessGroupsRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->monitoringServerService = new MonitoringServerService(
$this->monitoringServerRepository,
$this->readAccessGroupsRepository,
$this->user
);
$this->central = new MonitoringServer(1, 'Central');
$this->poller = new MonitoringServer(2, 'Poller');
$this->monitoringServers = [$this->central, $this->poller];
});
it(
'should throw an AccessDeniedException when the non-admin user does not have access to Monitoring Servers configuration page.',
function (): void {
$this->user
->expects($this->exactly(2))
->method('hasTopologyRole')
->willReturn(false);
$this->monitoringServerService->findServers();
}
)->throws(AccessDeniedException::class, 'You are not allowed to access this resource');
it('should throw a MonitoringServerException when an unhandled error is occured.', function (): void {
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$accessGroup = new AccessGroup(2, 'nonAdmin', 'nonAdmin');
$this->readAccessGroupsRepository
->expects($this->once())
->method('findByContact')
->willReturn([$accessGroup]);
$this->monitoringServerRepository
->expects($this->once())
->method('findServersWithRequestParametersAndAccessGroups')
->with([$accessGroup])
->willThrowException(new \Exception());
$this->monitoringServerService->findServers();
})->throws(MonitoringServerException::class, 'Error when searching for monitoring servers');
it('should return an array of monitoring servers when executed by an admin user.', function (): void {
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->monitoringServerRepository
->expects($this->once())
->method('findServersWithRequestParameters')
->willReturn($this->monitoringServers);
$monitoringServers = $this->monitoringServerService->findServers();
expect($monitoringServers)->toBeArray();
foreach ($monitoringServers as $index => $monitoringServer) {
expect($monitoringServer->getId())
->toBe($this->monitoringServers[$index]->getId());
expect($monitoringServer->getName())
->toBe($this->monitoringServers[$index]->getName());
}
});
it('should return an array of monitoring servers when executed by a non-admin user.', function (): void {
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->monitoringServerRepository
->expects($this->once())
->method('findServersWithRequestParametersAndAccessGroups')
->willReturn([$this->poller]);
$monitoringServers = $this->monitoringServerService->findServers();
expect($monitoringServers)->toBeArray();
foreach ($monitoringServers as $monitoringServer) {
expect($monitoringServer->getId())
->toBe($this->poller->getId());
expect($monitoringServer->getName())
->toBe($this->poller->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/Centreon/Domain/MonitoringServer/Model/RealTimeMonitoringServerTest.php | centreon/tests/php/Centreon/Domain/MonitoringServer/Model/RealTimeMonitoringServerTest.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\Centreon\Domain\MonitoringServer\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\MonitoringServer\Model\RealTimeMonitoringServer;
use DateTime;
use PHPUnit\Framework\TestCase;
/**
* This class is designed to test all setters of the RealTimeMonitoringServer entity, especially those with exceptions.
*
* @package Tests\Centreon\Domain\MonitoringServer\Model
*/
class RealTimeMonitoringServerTest extends TestCase
{
/**
* Too long name test
*/
public function testNameTooShortException(): void
{
$name = str_repeat('.', RealTimeMonitoringServer::MIN_NAME_LENGTH - 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$name,
strlen($name),
RealTimeMonitoringServer::MIN_NAME_LENGTH,
'RealTimeMonitoringServer::name'
)->getMessage()
);
new RealTimeMonitoringServer(1, $name);
}
/**
* Too long name test
*/
public function testNameTooLongException(): void
{
$name = str_repeat('.', RealTimeMonitoringServer::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
strlen($name),
RealTimeMonitoringServer::MAX_NAME_LENGTH,
'RealTimeMonitoringServer::name'
)->getMessage()
);
new RealTimeMonitoringServer(1, $name);
}
/**
* Too long address test
*/
public function testAddressTooLongException(): void
{
$address = str_repeat('.', RealTimeMonitoringServer::MAX_ADDRESS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$address,
strlen($address),
RealTimeMonitoringServer::MAX_ADDRESS_LENGTH,
'RealTimeMonitoringServer::address'
)->getMessage()
);
(new RealTimeMonitoringServer(1, 'Central'))
->setAddress($address);
}
/**
* Too long version test
*/
public function testVersionTooLongException(): void
{
$version = str_repeat('.', RealTimeMonitoringServer::MAX_VERSION_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$version,
strlen($version),
RealTimeMonitoringServer::MAX_VERSION_LENGTH,
'RealTimeMonitoringServer::version'
)->getMessage()
);
(new RealTimeMonitoringServer(1, 'Central'))
->setVersion($version);
}
/**
* Too long address test
*/
public function testDescriptionTooLongException(): void
{
$description = str_repeat('.', RealTimeMonitoringServer::MAX_DESCRIPTION_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$description,
strlen($description),
RealTimeMonitoringServer::MAX_DESCRIPTION_LENGTH,
'RealTimeMonitoringServer::description'
)->getMessage()
);
(new RealTimeMonitoringServer(1, 'Central'))
->setDescription($description);
}
/**
* isRunning property test
*/
public function testIsRunningProperty(): void
{
$realTimeMonitoringServer = new RealTimeMonitoringServer(1, 'Central');
$this->assertFalse($realTimeMonitoringServer->isRunning());
$realTimeMonitoringServer->setRunning(true);
$this->assertTrue($realTimeMonitoringServer->isRunning());
}
/**
* @throws \Assert\AssertionFailedException
* @return RealTimeMonitoringServer
*/
public static function createEntity(): RealTimeMonitoringServer
{
return (new RealTimeMonitoringServer(1, 'Central'))
->setDescription('Monitoring Server description')
->setLastAlive((new DateTime())->getTimestamp())
->setVersion('99.99.99')
->setAddress('0.0.0.0')
->setRunning(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/Centreon/Domain/MonitoringServer/UseCase/GenerateConfigurationTest.php | centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/GenerateConfigurationTest.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\Centreon\Domain\MonitoringServer\UseCase;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\MonitoringServer\Exception\ConfigurationMonitoringServerException;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerConfigurationRepositoryInterface;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerRepositoryInterface;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\MonitoringServer\UseCase\GenerateConfiguration;
use Centreon\Domain\Repository\RepositoryException;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class GenerateConfigurationTest extends TestCase
{
/** @var MonitoringServerRepositoryInterface&MockObject */
private $monitoringServerRepository;
/** @var MonitoringServerConfigurationRepositoryInterface&MockObject */
private $monitoringServerConfigurationRepository;
/** @var ReadAccessGroupRepositoryInterface&MockObject */
private $readAccessGroupsRepository;
/** @var ContactInterface&MockObject */
private $user;
/** @var AccessGroup&MockObject */
private $accessGroup;
/** @var MonitoringServer */
private $monitoringServer;
protected function setUp(): void
{
$this->monitoringServerRepository = $this->createMock(MonitoringServerRepositoryInterface::class);
$this->monitoringServerConfigurationRepository
= $this->createMock(MonitoringServerConfigurationRepositoryInterface::class);
$this->readAccessGroupsRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->accessGroup = (new AccessGroup(2, 'nonAdmin', 'nonAdmin'));
$this->monitoringServer = (new MonitoringServer())->setId(1);
}
public function testErrorRetrievingMonitoringServerException(): void
{
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->monitoringServerRepository
->expects($this->once())
->method('findServer')
->willReturn(null);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage(
ConfigurationMonitoringServerException::notFound($this->monitoringServer->getId())->getMessage()
);
$useCase = new GenerateConfiguration(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupsRepository,
$this->user
);
$useCase->execute($this->monitoringServer->getId());
}
public function testErrorOnGeneration(): void
{
$repositoryException = new RepositoryException('Test exception message');
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->monitoringServerRepository
->expects($this->once())
->method('findServer')
->willReturn($this->monitoringServer);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('generateConfiguration')
->willThrowException($repositoryException);
$useCase = new GenerateConfiguration(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupsRepository,
$this->user
);
$this->expectException(ConfigurationMonitoringServerException::class);
$this->expectExceptionMessage(ConfigurationMonitoringServerException::errorOnGeneration(
$this->monitoringServer->getId(),
$repositoryException->getMessage()
)->getMessage());
$useCase->execute($this->monitoringServer->getId());
}
public function testSuccessAsAdminUser(): void
{
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->monitoringServerRepository
->expects($this->once())
->method('findServer')
->willReturn($this->monitoringServer);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('generateConfiguration')
->with($this->monitoringServer->getId());
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('moveExportFiles')
->with($this->monitoringServer->getId());
$useCase = new GenerateConfiguration(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupsRepository,
$this->user
);
$useCase->execute($this->monitoringServer->getId());
}
public function testSuccessAsNonAdminUser(): void
{
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupsRepository
->expects($this->once())
->method('findByContact')
->willReturn([$this->accessGroup]);
$this->monitoringServerRepository
->expects($this->once())
->method('findByIdAndAccessGroups')
->willReturn($this->monitoringServer);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('generateConfiguration')
->with($this->monitoringServer->getId());
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('moveExportFiles')
->with($this->monitoringServer->getId());
$useCase = new GenerateConfiguration(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupsRepository,
$this->user
);
$useCase->execute($this->monitoringServer->getId());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/FindRealTimeMonitoringServersResponseTest.php | centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/FindRealTimeMonitoringServersResponseTest.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\Centreon\Domain\MonitoringServer\UseCase;
use Centreon\Domain\MonitoringServer\UseCase\RealTimeMonitoringServer\FindRealTimeMonitoringServersResponse;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\MonitoringServer\Model\RealTimeMonitoringServerTest;
/**
* @package Tests\Centreon\Domain\MonitoringServer\UseCase
*/
class FindRealTimeMonitoringServersResponseTest extends TestCase
{
/**
* We test the transformation of an empty response into an array.
*/
public function testEmptyResponse(): void
{
$response = new FindRealTimeMonitoringServersResponse();
$realTimeMonitoringServers = $response->getRealTimeMonitoringServers();
$this->assertCount(0, $realTimeMonitoringServers);
}
/**
* We test the transformation of an entity into an array.
*/
public function testNotEmptyResponse(): void
{
$realTimeMonitoringServer = RealTimeMonitoringServerTest::createEntity();
$response = new FindRealTimeMonitoringServersResponse();
$response->setRealTimeMonitoringServers([$realTimeMonitoringServer]);
$realTimeMonitoringServers = $response->getRealTimeMonitoringServers();
$this->assertCount(1, $realTimeMonitoringServers);
$this->assertEquals($realTimeMonitoringServer->getId(), $realTimeMonitoringServers[0]['id']);
$this->assertEquals($realTimeMonitoringServer->getName(), $realTimeMonitoringServers[0]['name']);
$this->assertEquals($realTimeMonitoringServer->getDescription(), $realTimeMonitoringServers[0]['description']);
$this->assertEquals($realTimeMonitoringServer->getVersion(), $realTimeMonitoringServers[0]['version']);
$this->assertEquals($realTimeMonitoringServer->isRunning(), $realTimeMonitoringServers[0]['is_running']);
$this->assertEquals($realTimeMonitoringServer->getLastAlive(), $realTimeMonitoringServers[0]['last_alive']);
$this->assertEquals($realTimeMonitoringServer->getAddress(), $realTimeMonitoringServers[0]['address']);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/ReloadAllConfigurationsTest.php | centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/ReloadAllConfigurationsTest.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\Centreon\Domain\MonitoringServer\UseCase;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\MonitoringServer\Exception\ConfigurationMonitoringServerException;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerConfigurationRepositoryInterface;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerRepositoryInterface;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\MonitoringServer\UseCase\ReloadAllConfigurations;
use Centreon\Domain\Repository\RepositoryException;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class ReloadAllConfigurationsTest extends TestCase
{
/** @var MonitoringServerRepositoryInterface&MockObject */
private $monitoringServerRepository;
/** @var MonitoringServerConfigurationRepositoryInterface&MockObject */
private $monitoringServerConfigurationRepository;
/** @var ReadAccessGroupRepositoryInterface&MockObject */
private $readAccessGroupRepository;
/** @var ContactInterface&MockObject */
private $contact;
protected function setUp(): void
{
$this->monitoringServerRepository = $this->createMock(MonitoringServerRepositoryInterface::class);
$this->monitoringServerConfigurationRepository
= $this->createMock(MonitoringServerConfigurationRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
}
public function testErrorRetrievingMonitoringServersException(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$exception = new \Exception();
$this->monitoringServerRepository
->expects($this->once())
->method('findServersWithoutRequestParameters')
->willThrowException($exception);
$this->expectException(ConfigurationMonitoringServerException::class);
$this->expectExceptionMessage(
ConfigurationMonitoringServerException::errorRetrievingMonitoringServers($exception)->getMessage()
);
$useCase = new ReloadAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$useCase->execute();
}
public function testErrorAccessDeniedexception(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(false);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$exception = new AccessDeniedException(
'Insufficient rights (required: ROLE_CONFIGURATION_MONITORING_SERVER_READ or ROLE_CONFIGURATION_MONITORING_SERVER_READ_WRITE)'
);
$this->expectException(AccessDeniedException::class);
$this->expectExceptionMessage($exception->getMessage());
$useCase = new ReloadAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$useCase->execute();
}
public function testErrorOnReload(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$monitoringServers = [
(new MonitoringServer())->setId(1),
];
$repositoryException = new RepositoryException('Test exception message');
$this->monitoringServerRepository
->expects($this->once())
->method('findServersWithoutRequestParameters')
->willReturn($monitoringServers);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('reloadConfiguration')
->willThrowException($repositoryException);
$useCase = new ReloadAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$this->expectException(ConfigurationMonitoringServerException::class);
$this->expectExceptionMessage(
ConfigurationMonitoringServerException::errorOnReload(
$monitoringServers[0]->getId(),
$repositoryException->getMessage()
)->getMessage()
);
$useCase->execute();
}
public function testSuccess(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$monitoringServer = (new MonitoringServer())->setId(1);
$monitoringServers = [$monitoringServer];
$this->monitoringServerRepository
->expects($this->once())
->method('findServersWithoutRequestParameters')
->willReturn($monitoringServers);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('reloadConfiguration')
->with($monitoringServer->getId());
$useCase = new ReloadAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$useCase->execute();
}
public function testSuccessNonAdmin(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$monitoringServer = (new MonitoringServer())->setId(1);
$monitoringServers = [$monitoringServer];
$this->monitoringServerRepository
->expects($this->once())
->method('findAllServersWithAccessGroups')
->willReturn($monitoringServers);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('reloadConfiguration')
->with($monitoringServer->getId());
$useCase = new ReloadAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$useCase->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/GenerateAllConfigurationsTest.php | centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/GenerateAllConfigurationsTest.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\Centreon\Domain\MonitoringServer\UseCase;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\MonitoringServer\Exception\ConfigurationMonitoringServerException;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerConfigurationRepositoryInterface;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerRepositoryInterface;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\MonitoringServer\UseCase\GenerateAllConfigurations;
use Centreon\Domain\Repository\RepositoryException;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class GenerateAllConfigurationsTest extends TestCase
{
/** @var MonitoringServerRepositoryInterface&MockObject */
private $monitoringServerRepository;
/** @var MonitoringServerConfigurationRepositoryInterface&MockObject */
private $monitoringServerConfigurationRepository;
/** @var ReadAccessGroupRepositoryInterface&MockObject */
private $readAccessGroupRepository;
/** @var ContactInterface&MockObject */
private $contact;
protected function setUp(): void
{
$this->monitoringServerRepository = $this->createMock(MonitoringServerRepositoryInterface::class);
$this->monitoringServerConfigurationRepository
= $this->createMock(MonitoringServerConfigurationRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
}
public function testErrorRetrievingMonitoringServersException(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$exception = new \Exception();
$this->monitoringServerRepository
->expects($this->once())
->method('findServersWithoutRequestParameters')
->willThrowException($exception);
$this->expectException(ConfigurationMonitoringServerException::class);
$this->expectExceptionMessage(
ConfigurationMonitoringServerException::errorRetrievingMonitoringServers($exception)->getMessage()
);
$useCase = new GenerateAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$useCase->execute();
}
public function testErrorAccessDeniedException(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(false);
$exception = new AccessDeniedException(
'Insufficient rights (required: ROLE_CONFIGURATION_MONITORING_SERVER_READ or ROLE_CONFIGURATION_MONITORING_SERVER_READ_WRITE)'
);
$this->expectException(AccessDeniedException::class);
$this->expectExceptionMessage(
$exception->getMessage()
);
$useCase = new GenerateAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$useCase->execute();
}
public function testErrorOnGeneration(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$monitoringServers = [
(new MonitoringServer())->setId(1),
];
$repositoryException = new RepositoryException('Test exception message');
$this->monitoringServerRepository
->expects($this->once())
->method('findServersWithoutRequestParameters')
->willReturn($monitoringServers);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('generateConfiguration')
->willThrowException($repositoryException);
$useCase = new GenerateAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$this->expectException(ConfigurationMonitoringServerException::class);
$this->expectExceptionMessage(ConfigurationMonitoringServerException::errorOnGeneration(
$monitoringServers[0]->getId(),
$repositoryException->getMessage()
)->getMessage());
$useCase->execute();
}
public function testSuccess(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$monitoringServer = (new MonitoringServer())->setId(1);
$monitoringServers = [$monitoringServer];
$this->monitoringServerRepository
->expects($this->once())
->method('findServersWithoutRequestParameters')
->willReturn($monitoringServers);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('generateConfiguration')
->with($monitoringServer->getId());
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('moveExportFiles')
->with($monitoringServer->getId());
$useCase = new GenerateAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$useCase->execute();
}
public function testSuccessNonAdmin(): void
{
$this->contact
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->contact
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$monitoringServer = (new MonitoringServer())->setId(1);
$monitoringServers = [$monitoringServer];
$this->monitoringServerRepository
->expects($this->once())
->method('findAllServersWithAccessGroups')
->willReturn($monitoringServers);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('generateConfiguration')
->with($monitoringServer->getId());
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('moveExportFiles')
->with($monitoringServer->getId());
$useCase = new GenerateAllConfigurations(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->contact
);
$useCase->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/FindRealTimeMonitoringServersTest.php | centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/FindRealTimeMonitoringServersTest.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\Centreon\Domain\MonitoringServer\UseCase;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\MonitoringServer\Model\RealTimeMonitoringServer;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\MonitoringServer\UseCase\RealTimeMonitoringServer\FindRealTimeMonitoringServers;
use Centreon\Infrastructure\MonitoringServer\Repository\RealTimeMonitoringServerRepositoryRDB;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\MonitoringServer\Model\RealTimeMonitoringServerTest;
/**
* @package Tests\Centreon\Domain\MonitoringServer\UseCase
*/
class FindRealTimeMonitoringServersTest extends TestCase
{
private RealTimeMonitoringServerRepositoryRDB&MockObject $realTimeMonitoringServerRepository;
private RealTimeMonitoringServer $realTimeMonitoringServer;
private MonitoringServer $monitoringServer;
private ContactInterface|MockObject $contact;
protected function setUp(): void
{
$this->realTimeMonitoringServerRepository = $this->createMock(RealTimeMonitoringServerRepositoryRDB::class);
$this->realTimeMonitoringServer = RealTimeMonitoringServerTest::createEntity();
$this->monitoringServer = (new MonitoringServer())->setId(1);
$this->contact = $this->createMock(ContactInterface::class);
}
/**
* Test as admin user
*/
public function testExecuteAsAdmin(): void
{
$this->realTimeMonitoringServerRepository
->expects($this->once())
->method('findAll')
->willReturn([$this->realTimeMonitoringServer]);
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->with(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)
->willReturn(true);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$findRealTimeMonitoringServers = new FindRealTimeMonitoringServers(
$this->realTimeMonitoringServerRepository,
$this->contact
);
$response = $findRealTimeMonitoringServers->execute();
$this->assertCount(1, $response->getRealTimeMonitoringServers());
}
/**
* Test as non admin user
*/
public function testExecuteAsNonAdmin(): void
{
$this->realTimeMonitoringServerRepository
->expects($this->once())
->method('findAllowedMonitoringServers')
->willReturn([$this->monitoringServer]);
$this->realTimeMonitoringServerRepository
->expects($this->once())
->method('findByIds')
->willReturn([$this->realTimeMonitoringServer]);
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->with(Contact::ROLE_MONITORING_RESOURCES_STATUS_RW)
->willReturn(true);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$findRealTimeMonitoringServers = new FindRealTimeMonitoringServers(
$this->realTimeMonitoringServerRepository,
$this->contact
);
$response = $findRealTimeMonitoringServers->execute();
$this->assertCount(1, $response->getRealTimeMonitoringServers());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/ReloadConfigurationTest.php | centreon/tests/php/Centreon/Domain/MonitoringServer/UseCase/ReloadConfigurationTest.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\Centreon\Domain\MonitoringServer\UseCase;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\MonitoringServer\Exception\ConfigurationMonitoringServerException;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerConfigurationRepositoryInterface;
use Centreon\Domain\MonitoringServer\Interfaces\MonitoringServerRepositoryInterface;
use Centreon\Domain\MonitoringServer\MonitoringServer;
use Centreon\Domain\MonitoringServer\UseCase\ReloadConfiguration;
use Centreon\Domain\Repository\RepositoryException;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class ReloadConfigurationTest extends TestCase
{
/** @var MonitoringServerRepositoryInterface&MockObject */
private $monitoringServerRepository;
/** @var MonitoringServerConfigurationRepositoryInterface&MockObject */
private $monitoringServerConfigurationRepository;
/** @var ReadAccessGroupRepositoryInterface&MockObject */
private $readAccessGroupRepository;
/** @var ContactInterface&MockObject */
private $user;
/** @var MonitoringServer */
private $monitoringServer;
protected function setUp(): void
{
$this->monitoringServerRepository = $this->createMock(MonitoringServerRepositoryInterface::class);
$this->monitoringServerConfigurationRepository
= $this->createMock(MonitoringServerConfigurationRepositoryInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->monitoringServer = (new MonitoringServer())->setId(1);
}
public function testErrorRetrievingMonitoringServerException(): void
{
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->monitoringServerRepository
->expects($this->any())
->method('findServer')
->willReturn(null);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage(
ConfigurationMonitoringServerException::notFound($this->monitoringServer->getId())->getMessage()
);
$useCase = new ReloadConfiguration(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->user
);
$useCase->execute($this->monitoringServer->getId());
}
public function testErrorOnReload(): void
{
$repositoryException = new RepositoryException('Test exception message');
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->monitoringServerRepository
->expects($this->any())
->method('findServer')
->willReturn($this->monitoringServer);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('reloadConfiguration')
->willThrowException($repositoryException);
$useCase = new ReloadConfiguration(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->user
);
$this->expectException(ConfigurationMonitoringServerException::class);
$this->expectExceptionMessage(ConfigurationMonitoringServerException::errorOnReload(
$this->monitoringServer->getId(),
$repositoryException->getMessage()
)->getMessage());
$useCase->execute($this->monitoringServer->getId());
}
public function testSuccess(): void
{
$this->user
->expects($this->any())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->monitoringServerRepository
->expects($this->once())
->method('findServer')
->willReturn($this->monitoringServer);
$this->monitoringServerConfigurationRepository
->expects($this->once())
->method('reloadConfiguration')
->with($this->monitoringServer->getId());
$useCase = new ReloadConfiguration(
$this->monitoringServerRepository,
$this->monitoringServerConfigurationRepository,
$this->readAccessGroupRepository,
$this->user
);
$useCase->execute($this->monitoringServer->getId());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Check/CheckServiceTest.php | centreon/tests/php/Centreon/Domain/Check/CheckServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Domain\Check;
use Centreon\Domain\Check\Check;
use Centreon\Domain\Check\CheckService;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Engine\Interfaces\EngineServiceInterface;
use Centreon\Domain\Entity\EntityValidator;
use Centreon\Domain\Exception\EntityNotFoundException;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface;
use Centreon\Domain\Monitoring\Resource;
use Centreon\Domain\Monitoring\Service;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use JMS\Serializer\Exception\ValidationFailedException;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
class CheckServiceTest extends TestCase
{
protected $adminContact;
protected $aclContact;
protected $host;
protected $service;
protected $check;
protected $hostCheck;
protected $serviceCheck;
protected $hostResource;
protected $serviceResource;
protected $monitoringRepository;
protected $engineService;
protected $entityValidator;
protected $violationList;
protected $accessGroupRepository;
protected function setUp(): void
{
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true);
$this->aclContact = (new Contact())
->setId(2)
->setName('contact')
->setAdmin(false);
$this->host = (new Host())
->setId(1);
$this->service = (new Service())
->setId(1);
$this->hostResource = (new Resource())
->setType('host')
->setId(1);
$this->serviceResource = (new Resource())
->setType('service')
->setId(1)
->setParent($this->hostResource);
$this->check = (new Check())
->setCheckTime(new \DateTime());
$this->hostCheck = (new Check())
->setResourceId(1);
$this->serviceCheck = (new Check())
->setResourceId(1)
->setParentResourceId(1);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->monitoringRepository = $this->createMock(MonitoringRepositoryInterface::class);
$this->engineService = $this->createMock(EngineServiceInterface::class);
$this->entityValidator = $this->createMock(EntityValidator::class);
$violation = new ConstraintViolation(
'wrong format',
'wrong format',
[],
$this->serviceCheck,
'propertyPath',
'InvalidValue'
);
$this->violationList = new ConstraintViolationList([$violation]);
}
/**
* test checkHost with not well formated check
*/
public function testCheckHostNotValidatedCheck(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn($this->violationList);
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$this->expectException(ValidationFailedException::class);
$this->expectExceptionMessage('Validation failed with 1 error(s).');
$checkService->checkHost($this->hostCheck);
}
/**
* test checkHost with not found host
*/
public function testCheckHostNotFoundHost(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList());
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn(null);
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Host not found');
$checkService->checkHost($this->hostCheck);
}
/**
* test checkHost which succeed
*/
public function testCheckHostSucceed(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList());
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->engineService->expects($this->once())
->method('scheduleHostCheck');
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$checkService->checkHost($this->hostCheck);
}
/**
* test checkService with not well formated check
*/
public function testCheckServiceNotValidatedCheck(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn($this->violationList);
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$this->expectException(ValidationFailedException::class);
$this->expectExceptionMessage('Validation failed with 1 error(s).');
$checkService->checkService($this->serviceCheck);
}
/**
* test checkService with not found host
*/
public function testCheckServiceNotFoundHost(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList());
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn(null);
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Host not found');
$checkService->checkService($this->serviceCheck);
}
/**
* test checkService with not found host
*/
public function testCheckServiceNotFoundService(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList());
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn(null);
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Service not found');
$checkService->checkService($this->serviceCheck);
}
/**
* test checkService which succeed
*/
public function testCheckServiceSucceed(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList());
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->engineService->expects($this->once())
->method('scheduleServiceCheck');
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$checkService->checkService($this->serviceCheck);
}
/**
* test checkResource with host not found
*/
public function testCheckResourceHostNotFound(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn(null);
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Host 1 not found');
$checkService->checkResource($this->check, $this->hostResource);
}
/**
* test checkResource with service not found
*/
public function testCheckResourceServiceNotFound(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn(null);
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$this->expectException(EntityNotFoundException::class);
$this->expectExceptionMessage('Service 1 (parent: 1) not found');
$checkService->checkResource($this->check, $this->serviceResource);
}
/**
* test checkResource on host which succeed
*/
public function testCheckResourceHostSucceed(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->engineService->expects($this->once())
->method('scheduleHostCheck');
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$checkService->checkResource($this->check, $this->hostResource);
}
/**
* test checkResource on service which succeed
*/
public function testCheckResourceServiceSucceed(): void
{
$this->monitoringRepository->expects($this->once())
->method('findOneHost')
->willReturn($this->host);
$this->monitoringRepository->expects($this->once())
->method('findOneService')
->willReturn($this->service);
$this->engineService->expects($this->once())
->method('scheduleServiceCheck');
$checkService = new CheckService(
$this->accessGroupRepository,
$this->monitoringRepository,
$this->engineService,
$this->entityValidator
);
$checkService->filterByContact($this->adminContact);
$checkService->checkResource($this->check, $this->serviceResource);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Monitoring/MonitoringServiceTest.php | centreon/tests/php/Centreon/Domain/Monitoring/MonitoringServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Domain\Monitoring;
use Centreon\Domain\HostConfiguration\Interfaces\HostConfigurationServiceInterface;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\HostGroup;
use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface;
use Centreon\Domain\Monitoring\MonitoringService;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Monitoring\ServiceGroup;
use Centreon\Domain\ServiceConfiguration\Interfaces\ServiceConfigurationServiceInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class MonitoringServiceTest extends TestCase
{
private MonitoringRepositoryInterface&MockObject $monitoringRepository;
private ReadAccessGroupRepositoryInterface&MockObject $accessGroupRepository;
private ServiceConfigurationServiceInterface&MockObject $serviceConfiguration;
private HostConfigurationServiceInterface&MockObject $hostConfiguration;
protected function setUp(): void
{
$this->monitoringRepository = $this->createMock(MonitoringRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->serviceConfiguration = $this->createMock(ServiceConfigurationServiceInterface::class);
$this->hostConfiguration = $this->createMock(HostConfigurationServiceInterface::class);
}
/**
* @throws \Exception
*/
public function testFindServices(): void
{
$service = (new Service())
->setId(1)
->setDisplayName('test');
$this->monitoringRepository->expects(self::any())
->method('findServices')
->willReturn([$service]); // values returned for the all next tests
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
$servicesFound = $monitoringService->findServices();
$this->assertCount(
1,
$servicesFound,
"Error, this method must relay the 'findServices' method of the monitoring repository"
);
}
/**
* @throws \Exception
*/
public function testFindServicesByHost(): void
{
$service = (new Service())
->setId(1)
->setDisplayName('test');
$hostId = 1;
$this->monitoringRepository->expects(self::any())
->method('findServicesByHostWithRequestParameters')
->with($hostId)
->willReturn([$service]); // values returned for the all next tests
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
$servicesFound = $monitoringService->findServicesByHost($hostId);
$this->assertCount(
1,
$servicesFound,
"Error, this method must relay the 'findServicesByHost' method of the monitoring repository"
);
}
/**
* @throws \Exception
*/
public function testFindHosts(): void
{
$service = (new Service())
->setId(1)
->setDisplayName('test');
$host = (new Host())
->setId(1)
->setDisplayName('test');
$this->monitoringRepository->expects(self::any())
->method('findHosts')
->willReturn([$host]); // values returned for the all next tests
$this->monitoringRepository->expects(self::any())
->method('findServicesByHosts')
->with([$host->getId()])
->willReturn([$host->getId() => [$service]]); // values returned for the all next tests
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
/**
* @var Host[] $hostsFound
*/
$hostsFound = $monitoringService->findHosts(true);
$this->assertCount(
1,
$hostsFound,
'Error, the number of hosts is not equal to the number given by the '
. "'findHosts' method of the monitoring repository"
);
$this->assertEquals($hostsFound[0]->getId(), $host->getId());
$this->assertCount(
1,
$hostsFound[0]->getServices(),
'Error, the service of the first host does not match the one given by the '
. "'findServicesOnMultipleHosts' method of the monitoring repository"
);
$this->assertEquals($hostsFound[0]->getServices()[0]->getId(), $service->getId());
}
/**
* @throws \Exception
*/
public function testFindServiceGroups(): void
{
$service = (new Service())
->setId(1)
->setDisplayName('test');
$host = (new Host())
->setId(2)
->setDisplayName('test');
$host->addService($service);
$serviceGroup = (new ServiceGroup())
->setId(3)
->setHosts([$host]);
$this->monitoringRepository->expects(self::any())
->method('findServiceGroups')
->willReturn([$serviceGroup]); // values returned for the all next tests
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
/**
* @var ServiceGroup[] $servicesGroupsFound
*/
$servicesGroupsFound = $monitoringService->findServiceGroups();
$this->assertCount(
1,
$servicesGroupsFound,
"Error, this method must relay the 'findServiceGroups' method of the monitoring repository"
);
$this->assertEquals($serviceGroup->getId(), $servicesGroupsFound[0]->getId());
$this->assertEquals($host->getId(), $serviceGroup->getHosts()[0]->getId());
$this->assertEquals($service->getId(), $serviceGroup->getHosts()[0]->getServices()[0]->getId());
}
/**
* @throws \Exception
*/
public function testFindOneService(): void
{
$service = (new Service())
->setId(1)
->setDisplayName('test');
$host = (new Host())
->setId(1)
->setDisplayName('test');
$this->monitoringRepository->expects(self::any())
->method('findOneService')
->with($host->getId(), $service->getId())
->willReturn($service); // values returned for the all next tests
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
$oneService = $monitoringService->findOneService($host->getId(), $service->getId());
$this->assertNotNull($oneService);
$this->assertEquals(
$oneService->getId(),
$service->getId(),
"Error, this method must relay the 'findOneService' method of the monitoring repository"
);
}
/**
* @throws \Exception
*/
public function testFindOneHost(): void
{
$service = (new Service())
->setId(1)
->setDisplayName('test');
$host = (new Host())
->setId(1)
->setDisplayName('test');
$host->addService($service);
$this->monitoringRepository->expects(self::any())
->method('findOneHost')
->with($host->getId())
->willReturn($host, null);
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
$hostFound = $monitoringService->findOneHost($host->getId());
$this->assertNotNull($hostFound);
$this->assertEquals($host->getId(), $hostFound->getId());
$this->assertEquals($host->getServices()[0]->getId(), $service->getId());
$hostFound = $monitoringService->findOneHost($host->getId());
$this->assertNull($hostFound);
}
/**
* @throws \Exception
*/
public function testFindHostGroups(): void
{
$service = (new Service())
->setId(3)
->setDisplayName('test');
$host = (new Host())
->setId(2)
->setDisplayName('test');
$host->addService($service);
$hostGroup = (new HostGroup())
->setId(1)
->addHost($host);
$this->monitoringRepository->expects(self::any())
->method('findHostGroups')
->willReturn([$hostGroup]);
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
/**
* @var HostGroup[] $hostsGroupsFound
*/
$hostsGroupsFound = $monitoringService->findHostGroups();
$this->assertCount(
1,
$hostsGroupsFound,
"Error, this method must relay the 'findHostGroups' method of the monitoring repository"
);
$this->assertEquals($hostsGroupsFound[0]->getId(), $hostGroup->getId());
$this->assertEquals($hostsGroupsFound[0]->getHosts()[0]->getId(), $host->getId());
$this->assertEquals($hostsGroupsFound[0]->getHosts()[0]->getServices()[0]->getId(), $service->getId());
}
/**
* @throws \Exception
*/
public function testIsHostExist(): void
{
$host = (new Host())
->setId(1)
->setDisplayName('test');
$this->monitoringRepository->expects(self::any())
->method('findOneHost')
->with($host->getId())
->willReturn($host, null);
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
// First test when the 'findOneHost' returns one host
$isHostExist = $monitoringService->isHostExists($host->getId());
$this->assertTrue($isHostExist);
// Second test when the 'findOneHost' returns null
$isHostExist = $monitoringService->isHostExists($host->getId());
$this->assertfalse($isHostExist);
}
/**
* @throws \Exception
*/
public function testIsServiceExist(): void
{
$host = (new Host())
->setId(1)
->setDisplayName('test');
$service = (new Service())
->setId(1)
->setHost($host);
$this->monitoringRepository->expects(self::any())
->method('findOneService')
->with($host->getId(), $service->getId())
->willReturn($service, null);
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
$exists = $monitoringService->isServiceExists($host->getId(), $service->getId());
$this->assertTrue($exists);
}
/**
* @throws \Exception
*/
public function testFindServiceGroupsByHostAndService(): void
{
$service = (new Service())
->setId(1)
->setDisplayName('test');
$host = (new Host())
->setId(2)
->setDisplayName('test');
$host->addService($service);
$serviceGroup = (new ServiceGroup())
->setId(3)
->setHosts([$host]);
$this->monitoringRepository->expects(self::any())
->method('findServiceGroupsByHostAndService')
->with($host->getId(), $service->getId())
->willReturn([$serviceGroup]); // values returned for the all next tests
$monitoringService = new MonitoringService(
$this->monitoringRepository,
$this->accessGroupRepository,
$this->serviceConfiguration,
$this->hostConfiguration,
);
/**
* @var ServiceGroup[] $servicesGroupsFound
*/
$servicesGroupsFound = $monitoringService->findServiceGroupsByHostAndService($host->getId(), $service->getId());
$this->assertCount(
1,
$servicesGroupsFound,
"Error, this method must relay the 'findServiceGroupsByHostAndService' method of the monitoring repository"
);
$this->assertEquals($serviceGroup->getId(), $servicesGroupsFound[0]->getId());
$this->assertEquals($host->getId(), $serviceGroup->getHosts()[0]->getId());
$this->assertEquals($service->getId(), $serviceGroup->getHosts()[0]->getServices()[0]->getId());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Monitoring/CommandLineTraitTest.php | centreon/tests/php/Centreon/Domain/Monitoring/CommandLineTraitTest.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\Centreon\Domain\Monitoring;
use Centreon\Domain\HostConfiguration\HostMacro;
use Centreon\Domain\Monitoring\CommandLineTrait;
use Centreon\Domain\Monitoring\Exception\MonitoringServiceException;
use Centreon\Domain\ServiceConfiguration\ServiceMacro;
use PHPUnit\Framework\TestCase;
class CommandLineTraitTest extends TestCase
{
use CommandLineTrait;
/** @var HostMacro */
private $hostMacroWithoutSpace;
/** @var HostMacro */
private $hostMacroWithSpace;
/** @var ServiceMacro */
private $serviceMacroWithoutSpace;
/** @var ServiceMacro */
private $serviceMacroWithSpace;
/** @var string */
private $configurationCommand;
/** @var string */
private $replacementValue;
protected function setUp(): void
{
$this->hostMacroWithoutSpace = (new HostMacro())->setName('$_HOSTWITHOUTSPACE$')->setValue('value1');
$this->hostMacroWithSpace = (new HostMacro())->setName('$_HOSTWITHSPACE$')->setValue('value 2');
$this->serviceMacroWithoutSpace = (new ServiceMacro())->setName('$_SERVICEWITHOUTSPACE$')->setValue('value1');
$this->serviceMacroWithSpace = (new ServiceMacro())->setName('$_SERVICEWITHSPACE$')->setValue('value 2');
$this->configurationCommand = '$USER1$/plugin.pl --a="' . $this->hostMacroWithoutSpace->getName() . '" '
. $this->serviceMacroWithoutSpace->getName() . ' '
. '-b "' . $this->hostMacroWithSpace->getName() . '" '
. $this->serviceMacroWithSpace->getName() . ' -f $_SERVICEEXTRAOPTIONS$';
$this->replacementValue = '*****';
}
/**
* Test built command line which does not contain any password
*
* @return void
*/
public function testBuildCommandLineFromConfigurationWithoutPassword(): void
{
$macros = [
$this->hostMacroWithoutSpace,
$this->hostMacroWithSpace,
$this->serviceMacroWithoutSpace,
$this->serviceMacroWithSpace,
];
$monitoringCommand = '/centreon/plugins/plugin.pl --a="' . $this->hostMacroWithoutSpace->getValue() . '" '
. $this->serviceMacroWithoutSpace->getValue() . ' '
. '-b "' . $this->hostMacroWithSpace->getValue() . '" '
. $this->serviceMacroWithSpace->getValue() . ' -f extra options';
$result = $this->buildCommandLineFromConfiguration(
$this->configurationCommand,
$monitoringCommand,
$macros,
$this->replacementValue
);
$this->assertEquals($monitoringCommand, $result);
}
/**
* Test built command line which contains host & service macros password
*
* @return void
*/
public function testBuildCommandLineFromConfigurationWithPasswords(): void
{
$this->hostMacroWithoutSpace->setPassword(true);
$this->hostMacroWithSpace->setPassword(true);
$this->serviceMacroWithoutSpace->setPassword(true);
$this->serviceMacroWithSpace->setPassword(true);
$macros = [
$this->hostMacroWithoutSpace,
$this->hostMacroWithSpace,
$this->serviceMacroWithoutSpace,
$this->serviceMacroWithSpace,
];
$monitoringCommand = '/centreon/plugins/plugin.pl --a="' . $this->replacementValue . '" '
. $this->replacementValue . ' '
. '-b "' . $this->replacementValue . '" '
. $this->replacementValue . ' -f extra options';
$result = $this->buildCommandLineFromConfiguration(
$this->configurationCommand,
$monitoringCommand,
$macros,
$this->replacementValue
);
$this->assertEquals($monitoringCommand, $result);
}
/**
* Test built command line which contains service macros password which are glued
* it cannot be parsed so it should throw an exception
*
* @return void
*/
public function testBuildCommandLineFromConfigurationWithGluedPasswords(): void
{
$this->hostMacroWithoutSpace->setPassword(true);
$this->hostMacroWithSpace->setPassword(true);
$this->serviceMacroWithoutSpace->setPassword(true);
$this->serviceMacroWithSpace->setPassword(true);
$serviceMacroExtraOptions = (new ServiceMacro())
->setName('$_SERVICEEXTRAOPTIONS$')
->setValue('password')
->setPassword(true);
$serviceMacroExtraOptions2 = (new ServiceMacro())
->setName('$_SERVICEEXTRAOPTIONS2$')
->setValue('password2')
->setPassword(true);
// end of configuration command : $_SERVICEEXTRAOPTIONS$$_SERVICEEXTRAOPTIONS2$
$this->configurationCommand .= '$_SERVICEEXTRAOPTIONS2$';
$macros = [
$this->hostMacroWithoutSpace,
$this->hostMacroWithSpace,
$this->serviceMacroWithoutSpace,
$this->serviceMacroWithSpace,
$serviceMacroExtraOptions,
$serviceMacroExtraOptions2,
];
$monitoringCommand = '/centreon/plugins/plugin.pl --a="' . $this->replacementValue . '" '
. $this->replacementValue . ' '
. '-b "' . $this->replacementValue . '" '
. $this->replacementValue . ' -f extra options';
$this->expectException(MonitoringServiceException::class);
$this->expectExceptionMessage('Macro passwords cannot be detected');
$this->buildCommandLineFromConfiguration(
$this->configurationCommand,
$monitoringCommand,
$macros,
$this->replacementValue
);
}
/**
* Test built host command line which contains service macros which can be replaced and applied spaces
*
* @return void
*/
public function testBuildCommandLineFromConfigurationWithSpaceSeparatedValues(): void
{
$configurationCommand = '$CENTREONPLUGINS$/centreon_linux_snmp.pl --plugin=os::linux::snmp::plugin '
. '--mode=time --hostname=$HOSTADDRESS$ --snmp-version="$_HOSTSNMPVERSION$" '
. '--snmp-community="$_HOSTSNMPCOMMUNITY$" $_HOSTSNMPEXTRAOPTIONS$ '
. '--ntp-hostname="$_SERVICENTPADDR$" --ntp-port="$_SERVICENTPPORT$" '
. '--warning-offset="$_SERVICEWARNING$" --critical-offset="$_SERVICECRITICAL$" '
. '--timezone="$_SERVICETIMEZONE$" $_SERVICEEXTRAOPTIONS$ $_HOSTSNMPEXTRAOPTIONS_2$';
$macros = [
(new HostMacro())
->setName('$_HOSTSNMPEXTRAOPTIONS$')
->setValue('test_host_snmp_extra'),
(new HostMacro())
->setName('$_HOSTSNMPEXTRAOPTIONS_2$')
->setValue('test_host_snmp_extra_2 extra texte')
->setPassword(true),
];
$monitoringCommand = '/usr/lib/centreon/plugins//centreon_linux_snmp.pl --plugin=os::linux::snmp::plugin '
. '--mode=time --hostname=localhost --snmp-version="2c" '
. '--snmp-community="public" test_host_snmp_extra '
. '--ntp-hostname="" --ntp-port="" '
. '--warning-offset="" --critical-offset="" '
. '--timezone="" test_host_snmp_extra_2 extra texte';
// $_SERVICEEXTRAOPTIONS$ $_HOSTSNMPEXTRAOPTIONS_2$ will be converted as " test_host_snmp_extra_2 extra texte"
// then, pattern cannot detect which word is from $_SERVICEEXTRAOPTIONS$ or $_HOSTSNMPEXTRAOPTIONS_2$
$this->expectException(MonitoringServiceException::class);
$this->expectExceptionMessage('Macro passwords cannot be detected');
$this->buildCommandLineFromConfiguration(
$configurationCommand,
$monitoringCommand,
$macros,
$this->replacementValue
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Monitoring/MetaService/Model/MetaServiceMetricTest.php | centreon/tests/php/Centreon/Domain/Monitoring/MetaService/Model/MetaServiceMetricTest.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\Centreon\Domain\Monitoring\MetaService\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Monitoring\MetaService\Model\MetaServiceMetric;
use Centreon\Domain\Monitoring\Resource;
use PHPUnit\Framework\TestCase;
/**
* This class is designed to test all setters of the MetaServiceMetric entity, especially those with exceptions.
*
* @package Tests\Centreon\Domain\Monitoring\MetaService\Model
*/
class MetaServiceMetricTest extends TestCase
{
/**
* Too short name test
*/
public function testNameTooShortException(): void
{
$name = str_repeat('.', MetaServiceMetric::MIN_METRIC_NAME_LENGTH - 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$name,
strlen($name),
MetaServiceMetric::MIN_METRIC_NAME_LENGTH,
'MetaServiceMetric::name'
)->getMessage()
);
new MetaServiceMetric($name);
}
/**
* Too long name test
*/
public function testNameTooLongException(): void
{
$name = str_repeat('.', MetaServiceMetric::MAX_METRIC_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
strlen($name),
MetaServiceMetric::MAX_METRIC_NAME_LENGTH,
'MetaServiceMetric::name'
)->getMessage()
);
new MetaServiceMetric($name);
}
/**
* Too long metric unit name test
*/
public function testMetricUnitNameTooLongException(): void
{
$unitName = str_repeat('.', MetaServiceMetric::MAX_METRIC_UNIT_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$unitName,
strlen($unitName),
MetaServiceMetric::MAX_METRIC_UNIT_NAME_LENGTH,
'MetaServiceMetric::unit'
)->getMessage()
);
(new MetaServiceMetric('metric_name'))->setUnit($unitName);
}
/**
* @throws \Assert\AssertionFailedException
* @return MetaServiceMetric
*/
public static function createMetaServiceMetricEntity(): MetaServiceMetric
{
return (new MetaServiceMetric('rta'))
->setId(10)
->setUnit('ms')
->setValue(0.5);
}
/**
* @throws \Assert\AssertionFailedException
* @return resource
*/
public static function createResourceEntity(): Resource
{
$parentResource = (new Resource())
->setId(1)
->setName('Centreon-Central');
return (new Resource())
->setId(1)
->setName('Ping')
->setParent($parentResource);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Monitoring/MetaService/UseCase/V21/MetaServiceMetric/FindMetaServiceMetricsResponseTest.php | centreon/tests/php/Centreon/Domain/Monitoring/MetaService/UseCase/V21/MetaServiceMetric/FindMetaServiceMetricsResponseTest.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\Centreon\Domain\Monitoring\MetaService\UseCase\V21\MetaServiceMetric;
use Centreon\Domain\Monitoring\MetaService\UseCase\V21\MetaServiceMetric\FindMetaServiceMetricsResponse;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\Monitoring\MetaService\Model\MetaServiceMetricTest;
/**
* @package Tests\Centreon\Domain\Monitoring\MetaService\UseCase\V21\MetaServiceMetric
*/
class FindMetaServiceMetricsResponseTest extends TestCase
{
/**
* We test the transformation of an empty response into an array.
*/
public function testEmptyResponse(): void
{
$response = new FindMetaServiceMetricsResponse();
$metaServiceMetrics = $response->getMetaServiceMetrics();
$this->assertCount(0, $metaServiceMetrics);
}
/**
* We test the transformation of an entity into an array.
*/
public function testNotEmptyResponse(): void
{
$metaServiceMetric = MetaServiceMetricTest::createMetaServiceMetricEntity();
$metaServiceMetric->setResource(MetaServiceMetricTest::createResourceEntity());
$response = new FindMetaServiceMetricsResponse();
$response->setMetaServiceMetrics([$metaServiceMetric]);
$metaServiceMetrics = $response->getMetaServiceMetrics();
$this->assertCount(1, $metaServiceMetrics);
$this->assertEquals($metaServiceMetric->getId(), $metaServiceMetrics[0]['id']);
$this->assertEquals($metaServiceMetric->getName(), $metaServiceMetrics[0]['name']);
$this->assertEquals($metaServiceMetric->getValue(), $metaServiceMetrics[0]['value']);
$this->assertEquals($metaServiceMetric->getUnit(), $metaServiceMetrics[0]['unit']);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Monitoring/MetaService/UseCase/V21/MetaServiceMetric/FindMetaServiceMetricsTest.php | centreon/tests/php/Centreon/Domain/Monitoring/MetaService/UseCase/V21/MetaServiceMetric/FindMetaServiceMetricsTest.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\Centreon\Domain\Monitoring\MetaService\UseCase\V21\MetaServiceMetric;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Monitoring\MetaService\MetaServiceMetricService;
use Centreon\Domain\Monitoring\MetaService\UseCase\V21\MetaServiceMetric\FindMetaServiceMetrics;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\Monitoring\MetaService\Model\MetaServiceMetricTest;
/**
* @package Tests\Centreon\Domain\MetaServiceConfiguration\UseCase\V21
*/
class FindMetaServiceMetricsTest extends TestCase
{
/** @var MetaServiceMetricService&\PHPUnit\Framework\MockObject\MockObject */
private $metaServiceMetricService;
/** @var \Centreon\Domain\Monitoring\MetaService\Model\MetaServiceMetric */
private $metaServiceMetric;
protected function setUp(): void
{
$this->metaServiceMetricService = $this->createMock(MetaServiceMetricService::class);
$this->metaServiceMetric = MetaServiceMetricTest::createMetaServiceMetricEntity();
$this->metaServiceMetric->setResource(MetaServiceMetricTest::createResourceEntity());
}
/**
* Test as admin user
*/
public function testExecuteAsAdmin(): void
{
$this->metaServiceMetricService
->expects($this->once())
->method('findWithoutAcl')
->willReturn([$this->metaServiceMetric]);
$contact = new Contact();
$contact->setAdmin(true);
$findMetaServiceMetrics = new FindMetaServiceMetrics($this->metaServiceMetricService, $contact);
$response = $findMetaServiceMetrics->execute(1);
$this->assertCount(1, $response->getMetaServiceMetrics());
}
/**
* Test as non admin user
*/
public function testExecuteAsNonAdmin(): void
{
$this->metaServiceMetricService
->expects($this->once())
->method('findWithAcl')
->willReturn([$this->metaServiceMetric]);
$contact = new Contact();
$contact->setAdmin(false);
$findMetaServiceMetrics = new FindMetaServiceMetrics($this->metaServiceMetricService, $contact);
$response = $findMetaServiceMetrics->execute(1);
$this->assertCount(1, $response->getMetaServiceMetrics());
}
/**
* @return FindMetaServiceMetrics
*/
private function createMetaServiceMetricUseCase(): FindMetaServiceMetrics
{
$contact = new Contact();
$contact->setAdmin(true);
return new FindMetaServiceMetrics($this->metaServiceMetricService, $contact);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Monitoring/MetaService/Exceptions/MetaServiceMetricExceptionTest.php | centreon/tests/php/Centreon/Domain/Monitoring/MetaService/Exceptions/MetaServiceMetricExceptionTest.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\Centreon\Domain\Monitoring\MetaService\Exceptions;
use Centreon\Domain\Monitoring\MetaService\Exception\MetaServiceMetricException;
use PHPUnit\Framework\TestCase;
/**
* @package Tests\Centreon\Domain\Monitoring\MetaService\Exceptions
*/
class MetaServiceMetricExceptionTest extends TestCase
{
/**
* Tests the arguments of the static method findMetaServiceMetricsException.
*/
public function testFindMetaServiceMetricsException(): void
{
$previousMessage1 = 'Error message 1';
$errorMessageMetaServiceMetricsError = 'Error when searching for the meta service (%d) metrics';
$exception = MetaServiceMetricException::findMetaServiceMetricsException(
new \Exception($previousMessage1),
999
);
self::assertEquals(sprintf($errorMessageMetaServiceMetricsError, 999), $exception->getMessage());
self::assertNotNull($exception->getPrevious());
self::assertEquals($previousMessage1, $exception->getPrevious()->getMessage());
}
/**
* Tests the arguments of the static method findMetaServiceException.
*/
public function testFindMetaServiceException(): void
{
$errorMessageMetaServiceNotFound = 'Meta service with ID %d not found';
$exception = MetaServiceMetricException::findMetaServiceException(
999
);
self::assertEquals(sprintf($errorMessageMetaServiceNotFound, 999), $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/Centreon/Domain/Monitoring/Metric/MetricServiceTest.php | centreon/tests/php/Centreon/Domain/Monitoring/Metric/MetricServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Domain\Monitoring\Metric;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface;
use Centreon\Domain\Monitoring\Metric\Interfaces\MetricRepositoryInterface;
use Centreon\Domain\Monitoring\Metric\MetricService;
use Centreon\Domain\Monitoring\Service;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use PHPUnit\Framework\TestCase;
class MetricServiceTest extends TestCase
{
protected $adminContact;
protected $aclContact;
protected $host;
protected $service;
protected $metrics;
protected $start;
protected $end;
protected $monitoringRepository;
protected $metricRepository;
protected $accessGroupRepository;
protected array $status = [];
protected function setUp(): void
{
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true);
$this->host = (new Host())
->setId(1);
$this->service = (new Service())
->setId(1);
$this->service->setHost($this->host);
$this->metrics = [
'global' => [],
'metrics' => [],
'times' => [],
];
$this->status = [
'critical' => [],
'wraning' => [],
'ok' => [],
'unknown' => [],
];
$this->start = new \DateTime('2020-02-18T00:00:00');
$this->end = new \DateTime('2020-02-18T12:00:00');
$this->metricRepository = $this->createMock(MetricRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->monitoringRepository = $this->createMock(MonitoringRepositoryInterface::class);
}
/**
* test findMetricsByService with admin user
*/
public function testFindMetricsByService(): void
{
$this->metricRepository->expects($this->once())
->method('findMetricsByService')
->willReturn($this->metrics);
$metricService = new MetricService(
$this->monitoringRepository,
$this->metricRepository,
$this->accessGroupRepository
);
$metricService->filterByContact($this->adminContact);
$metrics = $metricService->findMetricsByService($this->service, $this->start, $this->end);
$this->assertEquals($metrics, $this->metrics);
}
/**
* test findStatusByService with admin user
*/
public function testFindStatusByService(): void
{
$this->metricRepository->expects($this->once())
->method('findStatusByService')
->willReturn($this->status);
$metricService = new MetricService(
$this->monitoringRepository,
$this->metricRepository,
$this->accessGroupRepository
);
$metricService->filterByContact($this->adminContact);
$status = $metricService->findStatusByService($this->service, $this->start, $this->end);
$this->assertEquals($status, $this->status);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/PlatformInformation/Model/PlatformInformationTest.php | centreon/tests/php/Centreon/Domain/PlatformInformation/Model/PlatformInformationTest.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\Centreon\Domain\PlatformInformation\Model;
use Centreon\Domain\PlatformInformation\Exception\PlatformInformationException;
use Centreon\Domain\PlatformInformation\Model\PlatformInformation;
use PHPUnit\Framework\TestCase;
class PlatformInformationTest extends TestCase
{
/**
* Invalid Information apiPort Test.
*
* @return void
*/
public function testInvalidApiPortException(): void
{
$port = 0;
$this->expectException(PlatformInformationException::class);
$this->expectExceptionMessage(
"Central platform's API data is not consistent. Please check the 'Remote Access' form."
);
(new PlatformInformation(true))->setApiPort($port);
}
/**
* Invalid Information apiPath Test.
*
* @return void
*/
public function testInvalidApiPathException(): void
{
$path = '';
$this->expectException(PlatformInformationException::class);
$this->expectExceptionMessage(
"Central platform's API data is not consistent. Please check the 'Remote Access' form."
);
(new PlatformInformation(true))->setApiPath($path);
}
/**
* Create Platform Information for a Central.
*
* @return PlatformInformation
*/
public static function createEntityForCentralInformation(): PlatformInformation
{
return new PlatformInformation(false);
}
/**
* Create Platform Information for a Remote.
*
* @return PlatformInformation
*/
public static function createEntityForRemoteInformation(): PlatformInformation
{
return (new PlatformInformation(true))
->setCentralServerAddress('1.1.1.10')
->setApiUsername('admin')
->setApiCredentials('centreon')
->setApiScheme('http')
->setApiPort(80)
->setApiPath('centreon')
->setApiPeerValidation(false);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/PlatformInformation/Model/InformationFactoryTest.php | centreon/tests/php/Centreon/Domain/PlatformInformation/Model/InformationFactoryTest.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\Centreon\Domain\PlatformInformation\Model;
use Centreon\Domain\PlatformInformation\Model\Information;
use Centreon\Domain\PlatformInformation\Model\InformationFactory;
use PHPUnit\Framework\TestCase;
class InformationFactoryTest extends TestCase
{
/** @var array<Information> */
private $information;
/** @var array<string,mixed> */
private $informationRequest;
protected function setUp(): void
{
$this->information = InformationTest::createEntities();
$this->informationRequest = [
'isRemote' => true,
'centralServerAddress' => '1.1.1.10',
'apiUsername' => 'admin',
'apiCredentials' => 'centreon',
'apiScheme' => 'http',
'apiPort' => 80,
'apiPath' => 'centreon',
'peerValidation' => false,
];
}
/**
* Test the Information instances are correctly created from a request body.
*/
public function testCreateFromRequest(): void
{
$information = InformationFactory::createFromDto($this->informationRequest);
$this->assertCount(count($information), $this->informationRequest);
foreach ($information as $informationObject) {
$this->assertEquals(
$this->informationRequest[$informationObject->getKey()],
$informationObject->getValue()
);
}
$this->assertEquals($this->information, $information);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/PlatformInformation/Model/InformationTest.php | centreon/tests/php/Centreon/Domain/PlatformInformation/Model/InformationTest.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\Centreon\Domain\PlatformInformation\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\PlatformInformation\Model\Information;
use PHPUnit\Framework\TestCase;
class InformationTest extends TestCase
{
/**
* Too long Key Test.
*/
public function testKeyTooLongException(): void
{
$key = str_repeat('.', Information::MAX_KEY_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$key,
strlen($key),
Information::MAX_KEY_LENGTH,
'Information::key'
)->getMessage()
);
(new Information())->setKey($key);
}
/**
* Too Short Key Test.
*/
public function testKeyTooShortException(): void
{
$key = str_repeat('.', Information::MIN_KEY_LENGTH - 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$key,
strlen($key),
Information::MIN_KEY_LENGTH,
'Information::key'
)->getMessage()
);
(new Information())->setKey($key);
}
/**
* Too long Value Test.
*/
public function testValueTooLongException(): void
{
$value = str_repeat('.', Information::MAX_VALUE_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$value,
strlen($value),
Information::MAX_VALUE_LENGTH,
'Information::value'
)->getMessage()
);
(new Information())->setValue($value);
}
/**
* Too long Value Test.
*/
public function testValueTooShortException(): void
{
$value = str_repeat('.', Information::MIN_VALUE_LENGTH - 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::minLength(
$value,
strlen($value),
Information::MIN_VALUE_LENGTH,
'Information::value'
)->getMessage()
);
(new Information())->setValue($value);
}
/**
* @throws \Assert\AssertionFailedException
* @return array<Information>
*/
public static function createEntities(): array
{
$request = [
'isRemote' => true,
'centralServerAddress' => '1.1.1.10',
'apiUsername' => 'admin',
'apiCredentials' => 'centreon',
'apiScheme' => 'http',
'apiPort' => 80,
'apiPath' => 'centreon',
'peerValidation' => false,
];
$information = [];
foreach ($request as $key => $value) {
$newInformation = (new Information())
->setKey($key)
->setValue($value);
$information[] = $newInformation;
}
return $information;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/PlatformInformation/Model/PlatformInformationFactoryTest.php | centreon/tests/php/Centreon/Domain/PlatformInformation/Model/PlatformInformationFactoryTest.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\Centreon\Domain\PlatformInformation\Model;
use Centreon\Domain\PlatformInformation\Model\PlatformInformation;
use Centreon\Domain\PlatformInformation\Model\PlatformInformationFactory;
use PHPUnit\Framework\TestCase;
class PlatformInformationFactoryTest extends TestCase
{
/** @var PlatformInformation */
private $centralPlatformInformationStub;
/** @var PlatformInformation */
private $remotePlatformInformationStub;
/** @var array<string,mixed> */
private $remoteRequest;
/** @var array<string,bool> */
private $centralRequest;
private $platformInformationFactory;
protected function setUp(): void
{
$this->centralPlatformInformationStub = PlatformInformationTest::createEntityForCentralInformation();
$this->remotePlatformInformationStub = PlatformInformationTest::createEntityForRemoteInformation();
$this->remoteRequest = [
'isRemote' => true,
'centralServerAddress' => '1.1.1.10',
'apiUsername' => 'admin',
'apiCredentials' => 'centreon',
'apiScheme' => 'http',
'apiPort' => 80,
'apiPath' => 'centreon',
'peerValidation' => false,
];
$this->centralRequest = [
'isRemote' => false,
];
$this->platformInformationFactory = new PlatformInformationFactory(
'encryptionF0rT3st'
);
}
public function testCreateRemotePlatformInformation(): void
{
$remotePlatformInformation = $this->platformInformationFactory->createRemoteInformation($this->remoteRequest);
$this->assertEquals($this->remotePlatformInformationStub->isRemote(), $remotePlatformInformation->isRemote());
$this->assertEquals(
$this->remotePlatformInformationStub->getCentralServerAddress(),
$remotePlatformInformation->getCentralServerAddress()
);
$this->assertEquals(
$this->remotePlatformInformationStub->getApiUsername(),
$remotePlatformInformation->getApiUsername()
);
$this->assertEquals(
$this->remotePlatformInformationStub->getApiCredentials(),
$remotePlatformInformation->getApiCredentials()
);
$this->assertEquals(
$this->remotePlatformInformationStub->getApiScheme(),
$remotePlatformInformation->getApiScheme()
);
$this->assertEquals(
$this->remotePlatformInformationStub->getApiPort(),
$remotePlatformInformation->getApiPort()
);
$this->assertEquals(
$this->remotePlatformInformationStub->getApiPath(),
$remotePlatformInformation->getApiPath()
);
$this->assertEquals(
$this->remotePlatformInformationStub->hasApiPeerValidation(),
$remotePlatformInformation->hasApiPeerValidation()
);
}
public function testCreateCentralPlatformInformation(): void
{
$centralPlatformInformation = $this->platformInformationFactory->createCentralInformation(
$this->centralRequest
);
$this->assertEquals($this->centralPlatformInformationStub->isRemote(), $centralPlatformInformation->isRemote());
$this->assertEquals(
$this->centralPlatformInformationStub->getCentralServerAddress(),
$centralPlatformInformation->getCentralServerAddress()
);
$this->assertEquals(
$this->centralPlatformInformationStub->getApiUsername(),
$centralPlatformInformation->getApiUsername()
);
$this->assertEquals(
$this->centralPlatformInformationStub->getApiCredentials(),
$centralPlatformInformation->getApiCredentials()
);
$this->assertEquals(
$this->centralPlatformInformationStub->getApiScheme(),
$centralPlatformInformation->getApiScheme()
);
$this->assertEquals(
$this->centralPlatformInformationStub->getApiPort(),
$centralPlatformInformation->getApiPort()
);
$this->assertEquals(
$this->centralPlatformInformationStub->getApiPath(),
$centralPlatformInformation->getApiPath()
);
$this->assertEquals(
$this->centralPlatformInformationStub->hasApiPeerValidation(),
$centralPlatformInformation->hasApiPeerValidation()
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/PlatformInformation/UseCase/UpdatePartiallyPlatformInformationTest.php | centreon/tests/php/Centreon/Domain/PlatformInformation/UseCase/UpdatePartiallyPlatformInformationTest.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\Centreon\Domain\PlatformInformation\UseCase;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\PlatformInformation\Interfaces\PlatformInformationReadRepositoryInterface;
use Centreon\Domain\PlatformInformation\Interfaces\PlatformInformationWriteRepositoryInterface;
use Centreon\Domain\PlatformInformation\Model\PlatformInformation;
use Centreon\Domain\PlatformInformation\UseCase\V20\UpdatePartiallyPlatformInformation;
use Centreon\Domain\PlatformTopology\Interfaces\PlatformTopologyServiceInterface;
use Centreon\Domain\Proxy\Interfaces\ProxyServiceInterface;
use Centreon\Domain\RemoteServer\Interfaces\RemoteServerServiceInterface;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\PlatformInformation\Model\PlatformInformationTest;
class UpdatePartiallyPlatformInformationTest extends TestCase
{
/** @var PlatformInformationReadRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject */
private $readRepository;
/** @var PlatformInformationWriteRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject */
private $writeRepository;
/** @var PlatformInformation */
private $centralInformation;
/** @var PlatformInformation */
private $remoteInformation;
/** @var ProxyServiceInterface|\PHPUnit\Framework\MockObject\MockObject */
private $proxyService;
/** @var RemoteServerServiceInterface|\PHPUnit\Framework\MockObject\MockObject */
private $remoteServerService;
/** @var PlatformTopologyServiceInterface|\PHPUnit\Framework\MockObject\MockObject */
private $platformTopologyService;
/** @var ContactInterface|\PHPUnit\Framework\MockObject\MockObject */
private $user;
/** @var array<string,bool> */
private $centralInformationRequest;
/** @var array<string, mixed> */
private $remoteInformationRequest;
protected function setUp(): void
{
$this->readRepository = $this->createMock(PlatformInformationReadRepositoryInterface::class);
$this->writeRepository = $this->createMock(PlatformInformationWriteRepositoryInterface::class);
$this->proxyService = $this->createMock(ProxyServiceInterface::class);
$this->remoteServerService = $this->createMock(RemoteServerServiceInterface::class);
$this->platformTopologyService = $this->createMock(PlatformTopologyServiceInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->centralInformation = PlatformInformationTest::createEntityForCentralInformation();
$this->remoteInformation = PlatformInformationTest::createEntityForRemoteInformation();
$this->centralInformationRequest = ['isRemote' => false];
$this->remoteInformationRequest = [
'isRemote' => true,
'centralServerAddress' => '1.1.1.10',
'apiUsername' => 'admin',
'apiCredentials' => 'centreon',
'apiScheme' => 'http',
'apiPort' => 80,
'apiPath' => 'centreon',
'peerValidation' => false,
];
}
/**
* Test that the use case will call the central to remote conversion method
*
* @return void
*/
public function testExecuteUpdateToRemote(): void
{
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readRepository
->expects($this->any())
->method('findPlatformInformation')
->willReturn($this->centralInformation);
$updatePartiallyPlatformInformation = $this->createUpdatePartiallyPlatformUseCase();
$this->remoteServerService->expects($this->once())->method('convertCentralToRemote');
$updatePartiallyPlatformInformation->execute($this->remoteInformationRequest);
}
/**
* Test that the use case will call the remote to central conversion method
*
* @return void
*/
public function testExecuteUpdateToCentral(): void
{
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readRepository->expects($this->any())
->method('findPlatformInformation')
->willReturn($this->remoteInformation);
$updatePartiallyPlatformInformation = $this->createUpdatePartiallyPlatformUseCase();
$this->remoteServerService->expects($this->once())->method('convertRemoteToCentral');
$updatePartiallyPlatformInformation->execute($this->centralInformationRequest);
}
/**
* @return UpdatePartiallyPlatformInformation
*/
private function createUpdatePartiallyPlatformUseCase(): UpdatePartiallyPlatformInformation
{
$useCase = new UpdatePartiallyPlatformInformation(
$this->writeRepository,
$this->readRepository,
$this->proxyService,
$this->remoteServerService,
$this->platformTopologyService,
$this->user
);
$useCase->setEncryptionFirstKey('encryptionF0rT3st');
return $useCase;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Gorgone/CommandServiceTest.php | centreon/tests/php/Centreon/Domain/Gorgone/CommandServiceTest.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\Centreon\Domain\Gorgone;
use Centreon\Domain\Gorgone\Command\Thumbprint;
use Centreon\Domain\Gorgone\GorgoneService;
use Centreon\Domain\Gorgone\Interfaces\CommandRepositoryInterface;
use Centreon\Domain\Gorgone\Interfaces\ResponseInterface;
use Centreon\Domain\Gorgone\Interfaces\ResponseRepositoryInterface;
use Centreon\Domain\Gorgone\Response;
use PHPUnit\Framework\TestCase;
class CommandServiceTest extends TestCase
{
public function testSendCommand(): void
{
$mockThumprint = '6pX4rBssjlEV1YBHwLFRPyfRE_MvdwTKY5wsBq48cRw';
$mockToken = '86ca0747484d947';
$firstGorgoneResponse = file_get_contents(__DIR__ . '/first_gorgone_response.json');
$secondGorgoneResponse = file_get_contents(__DIR__ . '/second_gorgone_response.json');
$thumbprintCommand = new Thumbprint(2);
$commandRepository = $this
->getMockBuilder(CommandRepositoryInterface::class)
->disableOriginalConstructor()
->getMock();
$commandRepository->expects(self::any())
->method('send')
->willReturn($mockToken); // values returned for the all next tests
$responseRepository = $this
->getMockBuilder(ResponseRepositoryInterface::class)
->disableOriginalConstructor()
->getMock();
$responseRepository->expects($this->exactly(2))
->method('getResponse')
->willReturnOnConsecutiveCalls(
$firstGorgoneResponse,
$secondGorgoneResponse
);
$service = new GorgoneService($responseRepository, $commandRepository);
Response::setRepository($responseRepository);
/** @var ResponseInterface $gorgoneResponse */
$gorgoneResponse = $service->send($thumbprintCommand);
do {
$lastResponse = $gorgoneResponse->getLastActionLog();
} while ($lastResponse == null || $lastResponse->getCode() === ResponseInterface::STATUS_BEGIN);
$this->assertEquals($lastResponse->getToken(), $mockToken);
$data = json_decode($lastResponse->getData(), true);
$this->assertEquals($data['data']['thumbprint'], $mockThumprint);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Engine/EngineServiceTest.php | centreon/tests/php/Centreon/Domain/Engine/EngineServiceTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Domain\Engine;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Engine\EngineService;
use Centreon\Domain\Engine\Interfaces\EngineConfigurationRepositoryInterface;
use Centreon\Domain\Engine\Interfaces\EngineRepositoryInterface;
use Centreon\Domain\Engine\Interfaces\EngineServiceInterface;
use Centreon\Domain\Entity\EntityValidator;
use Centreon\Domain\Monitoring\Comment\Comment;
use Centreon\Domain\Monitoring\Host;
use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Monitoring\SubmitResult\SubmitResult;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolationList;
class EngineServiceTest extends TestCase
{
protected $engineRepository;
protected $entityValidator;
protected $host;
protected $service;
protected $hostResult;
protected $serviceResult;
protected $adminContact;
protected $engineService;
protected $commandHeaderRegex;
protected $monitoringRepository;
protected $engineConfigurationService;
protected $hostComment;
protected $serviceComment;
protected function setUp(): void
{
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true)
->setAlias('adminAlias');
$this->host = (new Host())
->setId(1)
->setName('host-test')
->setPollerId(1);
$this->service = (new Service())
->setId(1)
->setDescription('service-test')
->setHost($this->host);
$this->hostResult = (new SubmitResult($this->host->getId(), 2))
->setOutput('Host went down')
->setPerformanceData('ping: 0');
$this->serviceResult = (new SubmitResult($this->service->getId(), 2))
->setParentResourceId($this->service->getHost()->getId())
->setOutput('Service went critical')
->setPerformanceData('ping: 0');
$this->hostComment = (new Comment($this->host->getID(), 'Simple host comment'))
->setDate(new \DateTime('now'));
$this->serviceComment = (new Comment($this->service->getID(), 'Simple service comment'))
->setDate(new \DateTime('now'));
/**
* commandHeader should look like 'EXTERNALCMD:<pollerid>:[timestamp] '
*/
$this->commandHeaderRegex = 'EXTERNALCMD\:'
. $this->host->getPollerId() . '\:\[\d+\] ';
$this->engineRepository = $this->createMock(EngineRepositoryInterface::class);
$this->engineConfigurationService = $this->createMock(EngineConfigurationRepositoryInterface::class);
$this->engineService = $this->createMock(EngineServiceInterface::class);
$this->entityValidator = $this->createMock(EntityValidator::class);
$this->monitoringRepository = $this->createMock(MonitoringRepositoryInterface::class);
}
/**
* Testing the addHostComment EngineService function in a nominal case.
*/
public function testAddHostComment(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList());
/**
* Creating the command to check that the code
* will send the same to the sendExternalCommand
* repository function
*/
$command = sprintf(
'ADD_HOST_COMMENT;%s;1;%s;%s',
$this->host->getName(),
$this->adminContact->getAlias(),
$this->hostComment->getComment()
);
$this->engineRepository->expects($this->once())
->method('sendExternalCommand')
->with(
$this->matchesRegularExpression(
'/^' . $this->commandHeaderRegex . str_replace('|', '\|', $command) . '$/'
)
);
$engineService = new EngineService(
$this->engineRepository,
$this->engineConfigurationService,
$this->entityValidator
);
$engineService->filterByContact($this->adminContact);
$engineService->addHostComment($this->hostComment, $this->host);
}
/**
* Testing the addServiceComment EngineService function in a nominal case.
*/
public function testServiceComment(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList());
/**
* Creating the command to check that the code
* will send the same to the sendExternalCommand
* repository function
*/
$command = sprintf(
'ADD_SVC_COMMENT;%s;%s;1;%s;%s',
$this->host->getName(),
$this->service->getDescription(),
$this->adminContact->getAlias(),
$this->serviceComment->getComment()
);
$this->engineRepository->expects($this->once())
->method('sendExternalCommand')
->with(
$this->matchesRegularExpression(
'/^' . $this->commandHeaderRegex . str_replace('|', '\|', $command) . '$/'
)
);
$engineService = new EngineService(
$this->engineRepository,
$this->engineConfigurationService,
$this->entityValidator
);
$engineService->filterByContact($this->adminContact);
$engineService->addServiceComment($this->serviceComment, $this->service);
}
/**
* Testing the submitHostResult EngineService function in a nominal case.
*/
public function testSubmitHostResult(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList());
/**
* Creating the command to check that the code
* will send the same to the sendExternalCommand
* repository function
*/
$command = sprintf(
'%s;%s;%d;%s|%s',
'PROCESS_HOST_CHECK_RESULT',
$this->host->getName(),
$this->hostResult->getStatus(),
$this->hostResult->getOutput(),
$this->hostResult->getPerformanceData()
);
$this->engineRepository->expects($this->once())
->method('sendExternalCommand')
->with(
$this->matchesRegularExpression(
'/^' . $this->commandHeaderRegex . str_replace('|', '\|', $command) . '$/'
)
);
$engineService = new EngineService(
$this->engineRepository,
$this->engineConfigurationService,
$this->entityValidator
);
$engineService->filterByContact($this->adminContact);
$engineService->submitHostResult($this->hostResult, $this->host);
}
/**
* Testing the submitServiceResult EngineService function in a nominal case.
*/
public function testSubmitServiceResult(): void
{
$this->entityValidator->expects($this->once())
->method('validate')
->willReturn(new ConstraintViolationList());
/**
* Creating the command to check that the code
* will send the same to the sendExternalCommand
* repository function
*/
$command = sprintf(
'%s;%s;%s;%d;%s|%s',
'PROCESS_SERVICE_CHECK_RESULT',
$this->service->getHost()->getName(),
$this->service->getDescription(),
$this->serviceResult->getStatus(),
$this->serviceResult->getOutput(),
$this->serviceResult->getPerformanceData()
);
$this->engineRepository->expects($this->once())
->method('sendExternalCommand')
->with(
$this->matchesRegularExpression(
'/^' . $this->commandHeaderRegex . str_replace('|', '\|', $command) . '$/'
)
);
$engineService = new EngineService(
$this->engineRepository,
$this->engineConfigurationService,
$this->entityValidator
);
$engineService->filterByContact($this->adminContact);
$engineService->submitServiceResult($this->serviceResult, $this->service);
}
/**
* Testing the disacknowledgeHost EngineService method in a nominal case.
*/
public function testDisacknowledgeHost(): void
{
/**
* Creating the command to check that the code
* will send the same to the sendExternalCommand
* repository function
*/
$command = sprintf(
'%s;%s',
'REMOVE_HOST_ACKNOWLEDGEMENT',
$this->host->getName()
);
$this->engineRepository->expects($this->once())
->method('sendExternalCommand')
->with($this->matchesRegularExpression('/^' . $this->commandHeaderRegex . $command . '$/'));
$engineService = new EngineService(
$this->engineRepository,
$this->engineConfigurationService,
$this->entityValidator
);
$engineService->filterByContact($this->adminContact);
$engineService->disacknowledgeHost($this->host);
}
/**
* Testing the disacknowledgeService EngineService method in a nominal case.
*/
public function testDisacknowledgeService(): void
{
/**
* Creating the command to check that the code
* will send the same to the sendExternalCommand
* repository function
*/
$command = sprintf(
'%s;%s;%s',
'REMOVE_SVC_ACKNOWLEDGEMENT',
$this->service->getHost()->getName(),
$this->service->getDescription()
);
$this->engineRepository->expects($this->once())
->method('sendExternalCommand')
->with($this->matchesRegularExpression('/^' . $this->commandHeaderRegex . $command . '$/'));
$engineService = new EngineService(
$this->engineRepository,
$this->engineConfigurationService,
$this->entityValidator
);
$engineService->filterByContact($this->adminContact);
$engineService->disacknowledgeService($this->service);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Media/Model/ImageTest.php | centreon/tests/php/Centreon/Domain/Media/Model/ImageTest.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\Centreon\Domain\Media\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Media\Model\Image;
use PHPUnit\Framework\TestCase;
class ImageTest extends TestCase
{
/**
* Test the name
*/
public function testBadNameException(): void
{
$name = str_repeat('.', Image::MAX_NAME_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$name,
strlen($name),
Image::MAX_NAME_LENGTH,
'Image::name'
)->getMessage()
);
(new Image())->setName($name);
}
/**
* Test the path
*/
public function testBadPathException(): void
{
$path = str_repeat('.', Image::MAX_PATH_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$path,
strlen($path),
Image::MAX_PATH_LENGTH,
'Image::path'
)->getMessage()
);
(new Image())->setPath($path);
}
/**
* Test the comments
*/
public function testBadCommentsException(): void
{
$comment = str_repeat('.', Image::MAX_COMMENTS_LENGTH + 1);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(
AssertionException::maxLength(
$comment,
strlen($comment),
Image::MAX_COMMENTS_LENGTH,
'Image::comment'
)->getMessage()
);
(new Image())->setComment($comment);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Log/LoggerTraitTest.php | centreon/tests/php/Centreon/Domain/Log/LoggerTraitTest.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\Centreon\Domain\Log;
use LogicException;
beforeEach(function (): void {
$this->logFilePath = __DIR__ . '/log';
$this->logFileName = 'test.log';
$this->logPathFileName = $this->logFilePath . '/test.log';
if (! file_exists($this->logFilePath)) {
mkdir($this->logFilePath);
}
$this->logger = new LoggerStub($this->logPathFileName);
});
afterEach(function (): void {
if (file_exists($this->logPathFileName)) {
expect(unlink($this->logPathFileName))->toBeTrue();
$successDeleteFile = rmdir($this->logFilePath);
expect($successDeleteFile)->toBeTrue();
}
});
it('test a log with debug level without context without exception', function (): void {
$this->logger->debug('debug_message');
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.DEBUG: debug_message {"custom":null,"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with debug level with a context without exception', function (): void {
$this->logger->debug('debug_message', ['contact' => 1, 'name' => 'John Doe', 'is_admin' => true]);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.DEBUG: debug_message {"custom":{"contact":1,"name":"John Doe","is_admin":true},"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with info level without context without exception', function (): void {
$this->logger->info('info_message');
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.INFO: info_message {"custom":null,"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with info level with a context without exception', function (): void {
$this->logger->info('info_message', ['contact' => 1, 'name' => 'John Doe', 'is_admin' => true]);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.INFO: info_message {"custom":{"contact":1,"name":"John Doe","is_admin":true},"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with notice level without context without exception', function (): void {
$this->logger->notice('notice_message');
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.NOTICE: notice_message {"custom":null,"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with notice level with a context without exception', function (): void {
$this->logger->notice('notice_message', ['contact' => 1, 'name' => 'John Doe', 'is_admin' => true]);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.NOTICE: notice_message {"custom":{"contact":1,"name":"John Doe","is_admin":true},"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with warning level without context without exception', function (): void {
$this->logger->warning('warning_message');
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.WARNING: warning_message {"custom":null,"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with warning level with a context without exception', function (): void {
$this->logger->warning('warning_message', ['contact' => 1, 'name' => 'John Doe', 'is_admin' => true]);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.WARNING: warning_message {"custom":{"contact":1,"name":"John Doe","is_admin":true},"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with error level without context without exception', function (): void {
$this->logger->error('error_message');
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.ERROR: error_message {"custom":null,"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with error level with a context without exception', function (): void {
$this->logger->error('error_message', ['contact' => 1, 'name' => 'John Doe', 'is_admin' => true]);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.ERROR: error_message {"custom":{"contact":1,"name":"John Doe","is_admin":true},"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with critical level without context without exception', function (): void {
$this->logger->critical('critical_message');
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.CRITICAL: critical_message {"custom":null,"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with critical level with a context without exception', function (): void {
$this->logger->critical('critical_message', ['contact' => 1, 'name' => 'John Doe', 'is_admin' => true]);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.CRITICAL: critical_message {"custom":{"contact":1,"name":"John Doe","is_admin":true},"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with alert level without context without exception', function (): void {
$this->logger->alert('alert_message');
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.ALERT: alert_message {"custom":null,"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with alert level with a context without exception', function (): void {
$this->logger->alert('alert_message', ['contact' => 1, 'name' => 'John Doe', 'is_admin' => true]);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.ALERT: alert_message {"custom":{"contact":1,"name":"John Doe","is_admin":true},"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with emergency level without context without exception', function (): void {
$this->logger->emergency('emergency_message');
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.EMERGENCY: emergency_message {"custom":null,"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with emergency level with a context without exception', function (): void {
$this->logger->emergency('emergency_message', ['contact' => 1, 'name' => 'John Doe', 'is_admin' => true]);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.EMERGENCY: emergency_message {"custom":{"contact":1,"name":"John Doe","is_admin":true},"exception":null,"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
it('test a log with exception', function (): void {
$this->logger->error(
'error_message',
[
'contact' => 1,
'name' => 'John Doe',
'is_admin' => true,
'exception' => new LogicException('exception_message', 99),
]
);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'test_logger.ERROR: error_message {"custom":{"contact":1,"name":"John Doe","is_admin":true},"exception":"[object] (LogicException(code: 99): exception_message at ' . __FILE__ . ':' . (__LINE__ - 6) . ')","default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Log/LoggerStub.php | centreon/tests/php/Centreon/Domain/Log/LoggerStub.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\Centreon\Domain\Log;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\ContactForDebug;
use Centreon\Domain\Log\LoggerTrait;
use Mockery;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
/**
* Class
*
* @class LoggerStub
* @package Tests\Centreon\Domain\Log
*/
class LoggerStub implements LoggerInterface
{
use LoggerTrait {
emergency as traitEmergency;
alert as traitAlert;
critical as traitCritical;
error as traitError;
warning as traitWarning;
notice as traitNotice;
info as traitInfo;
debug as traitDebug;
log as traitLog;
}
/** @var Logger */
private Logger $monolog;
/** @var string */
private string $logPathFileName;
/**
* LoggerStub constructor
*
* @param string $logPathFileName
*/
public function __construct(string $logPathFileName)
{
$this->monolog = new Logger('test_logger');
$this->monolog->pushHandler(new StreamHandler($logPathFileName));
$this->setLogger($this->monolog);
$this->loggerContact = Mockery::mock(ContactInterface::class);
$this->loggerContactForDebug = Mockery::mock(ContactForDebug::class);
$this->loggerContactForDebug->shouldReceive('isValidForContact')->andReturnTrue();
}
/**
* Factory
*
* @param string $logPathFileName
*
* @return LoggerInterface
*/
public static function create(string $logPathFileName): LoggerInterface
{
return new self($logPathFileName);
}
/**
* @inheritDoc
*/
public function emergency(string|\Stringable $message, array $context = []): void
{
$this->traitEmergency($message, $context);
}
/**
* @inheritDoc
*/
public function alert(string|\Stringable $message, array $context = []): void
{
$this->traitAlert($message, $context);
}
/**
* @inheritDoc
*/
public function critical(string|\Stringable $message, array $context = []): void
{
$this->traitCritical($message, $context);
}
/**
* @inheritDoc
*/
public function error(string|\Stringable $message, array $context = []): void
{
$this->traitError($message, $context);
}
/**
* @inheritDoc
*/
public function warning(string|\Stringable $message, array $context = []): void
{
$this->traitWarning($message, $context);
}
/**
* @inheritDoc
*/
public function notice(string|\Stringable $message, array $context = []): void
{
$this->traitNotice($message, $context);
}
/**
* @inheritDoc
*/
public function info(string|\Stringable $message, array $context = []): void
{
$this->traitInfo($message, $context);
}
/**
* @inheritDoc
*/
public function debug(string|\Stringable $message, array $context = []): void
{
$this->traitDebug($message, $context);
}
/**
* @inheritDoc
*/
public function log($level, string|\Stringable $message, array $context = []): void
{
$this->traitLog($level, $message, $context);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Domain/Proxy/ProxyTest.php | centreon/tests/php/Centreon/Domain/Proxy/ProxyTest.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\Centreon\Domain\Proxy;
use Centreon\Domain\Proxy\Proxy;
use PHPUnit\Framework\TestCase;
class ProxyTest extends TestCase
{
public function testSettingProxyWithEmptyUrl(): void
{
$proxy = new Proxy();
$proxy->setUrl('');
$this->assertNull($proxy->getUrl());
$proxy->setUrl(null);
$this->assertNull($proxy->getUrl());
}
public function testSettingProxyWithNonEmptyUrl(): void
{
$proxy = new Proxy();
$proxy->setUrl('centreon.com');
$this->assertEquals('centreon.com', $proxy->getUrl());
}
public function testSettingProxyWithEmptyUser(): void
{
$proxy = new Proxy();
$proxy->setUser('');
$this->assertNull($proxy->getUser());
$proxy->setUser(null);
$this->assertNull($proxy->getUser());
}
public function testSettingProxyWithNonEmptyUser(): void
{
$proxy = new Proxy();
$proxy->setUser('admin');
$this->assertEquals('admin', $proxy->getUser());
}
public function testSettingProxyWithEmptyPassword(): void
{
$proxy = new Proxy();
$proxy->setPassword('');
$this->assertEmpty($proxy->getPassword());
$proxy->setPassword(null);
$this->assertNull($proxy->getPassword());
}
public function testSettingProxyWithNonEmptyPassword(): void
{
$proxy = new Proxy();
$proxy->setPassword('my password');
$this->assertEquals('my password', $proxy->getPassword());
}
public function testSettingProxyWithNotAllowedProtocol(): void
{
$protocol = 'http://badprotocol';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(sprintf(_('Protocol %s is not allowed'), $protocol));
$proxy = new Proxy();
$proxy->setProtocol($protocol);
}
public function testSettingProxyWithAllowedProtocol(): void
{
$proxy = new Proxy();
$proxy->setProtocol(Proxy::PROTOCOL_CONNECT);
$this->assertEquals(Proxy::PROTOCOL_CONNECT, $proxy->getProtocol());
$proxy = new Proxy();
$proxy->setProtocol(Proxy::PROTOCOL_HTTPS);
$this->assertEquals(Proxy::PROTOCOL_HTTPS, $proxy->getProtocol());
$proxy = new Proxy();
$proxy->setProtocol(Proxy::PROTOCOL_HTTP);
$this->assertEquals(Proxy::PROTOCOL_HTTP, $proxy->getProtocol());
}
public function testSettingProxyWithNegativePort(): void
{
$proxy = new Proxy();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The port can only be between 0 and 65535 inclusive');
$proxy->setPort(-1);
}
public function testSettingProxyWithOutOfRangePort(): void
{
$proxy = new Proxy();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The port can only be between 0 and 65535 inclusive');
$proxy->setPort(65536);
}
public function testProxySerialization(): void
{
// Serialization to test: <<procotol>>://<<user>>:<<password>>@<<url>>:<<port>>
$proxy = new Proxy();
$proxy->setProtocol(Proxy::PROTOCOL_HTTPS);
$proxy->setUser('user');
$proxy->setPassword('password');
$proxy->setUrl('centreon.com');
$proxy->setPort(10);
$this->assertEquals('https://user:password@centreon.com:10', (string) $proxy);
// Serialization to test: <<procotol>>://<<user>>:<<password>>@<<url>>
$proxy = new Proxy();
$proxy->setProtocol(Proxy::PROTOCOL_HTTPS);
$proxy->setUser('user');
$proxy->setPassword('password');
$proxy->setUrl('centreon.com');
$this->assertEquals('https://user:password@centreon.com', (string) $proxy);
// Serialization to test: <<procotol>>://<<url>>:<<port>>
$proxy = new Proxy();
$proxy->setProtocol(Proxy::PROTOCOL_HTTPS);
$proxy->setPassword('password'); // Without user value the password should not be taken into account
$proxy->setUrl('centreon.com');
$proxy->setPort(10);
$this->assertEquals('https://centreon.com:10', (string) $proxy);
// Serialization to test: <<procotol>>://<<url>>
$proxy = new Proxy();
$proxy->setProtocol(Proxy::PROTOCOL_HTTPS);
$proxy->setUrl('centreon.com');
$this->assertEquals('https://centreon.com', (string) $proxy);
// Serialization when nothing is defined
$proxy = new Proxy();
$proxy->setProtocol(Proxy::PROTOCOL_HTTPS);
$this->assertEquals('', (string) $proxy);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Infrastructure/DatabaseConnectionTest.php | centreon/tests/php/Centreon/Infrastructure/DatabaseConnectionTest.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\Centreon\Infrastructure;
use Adaptation\Database\Connection\Collection\BatchInsertParameters;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\Model\ConnectionConfig;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Adaptation\Database\ExpressionBuilder\Adapter\Dbal\DbalExpressionBuilderAdapter;
use Adaptation\Database\ExpressionBuilder\ExpressionBuilderInterface;
use Adaptation\Database\QueryBuilder\Adapter\Dbal\DbalQueryBuilderAdapter;
use Adaptation\Database\QueryBuilder\QueryBuilderInterface;
use Centreon\Infrastructure\DatabaseConnection;
/**
* @param string $nameEnvVar
*
* @return string|null
*/
function getEnvironmentVariable(string $nameEnvVar): ?string
{
$envVarValue = getenv($nameEnvVar, true) ?: getenv($nameEnvVar);
return (is_string($envVarValue) && ! empty($envVarValue)) ? $envVarValue : null;
}
$dbHost = getEnvironmentVariable('MYSQL_HOST');
$dbUser = getEnvironmentVariable('MYSQL_USER');
$dbPassword = getEnvironmentVariable('MYSQL_PASSWORD');
$dbConfigCentreon = null;
if (! is_null($dbHost) && ! is_null($dbUser) && ! is_null($dbPassword)) {
$dbConfigCentreon = new ConnectionConfig(
host: $dbHost,
user: $dbUser,
password: $dbPassword,
databaseNameConfiguration: 'centreon',
databaseNameRealTime: 'centreon_storage',
port: 3306
);
}
/**
* @param ConnectionConfig $connectionConfig
*
* @return bool
*/
function hasConnectionDb(ConnectionConfig $connectionConfig): bool
{
try {
new \PDO(
$connectionConfig->getMysqlDsn(),
$connectionConfig->getUser(),
$connectionConfig->getPassword(),
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
);
return true;
} catch (\PDOException $exception) {
return false;
}
}
// ************************************** With centreon database connection *******************************************
if (! is_null($dbConfigCentreon) && hasConnectionDb($dbConfigCentreon)) {
it(
'DatabaseConnection constructor',
function () use ($dbConfigCentreon): void {
$db = new DatabaseConnection($dbConfigCentreon);
expect($db)->toBeInstanceOf(DatabaseConnection::class);
$stmt = $db->prepare('select database()');
$stmt->execute();
$dbName = $stmt->fetchColumn();
expect($dbName)->toBe('centreon')
->and($db->getAttribute(\PDO::ATTR_STATEMENT_CLASS)[0])->toBe(\PDOStatement::class);
}
);
it(
'DatabaseConnection::createFromConfig factory"',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
expect($db)->toBeInstanceOf(DatabaseConnection::class);
$stmt = $db->prepare('select database()');
$stmt->execute();
$dbName = $stmt->fetchColumn();
expect($dbName)->toBe('centreon')
->and($db->getAttribute(\PDO::ATTR_STATEMENT_CLASS)[0])->toBe(\PDOStatement::class);
}
);
it(
'create query builder with success',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryBuilder = $db->createQueryBuilder();
expect($queryBuilder)
->toBeInstanceOf(QueryBuilderInterface::class)
->toBeInstanceOf(DbalQueryBuilderAdapter::class);
}
);
it(
'create expression builder with success',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$expressionBuilder = $db->createExpressionBuilder();
expect($expressionBuilder)
->toBeInstanceOf(ExpressionBuilderInterface::class)
->toBeInstanceOf(DbalExpressionBuilderAdapter::class);
}
);
it(
'switch to database',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->switchToDb('centreon_storage');
expect($db->getDatabaseName())->toBe('centreon_storage');
$db->switchToDb('centreon');
expect($db->getDatabaseName())->toBe('centreon');
}
);
it(
'get connection config',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$connectionConfig = $db->getConnectionConfig();
expect($connectionConfig)->toBeInstanceOf(ConnectionConfig::class)
->and($connectionConfig->getHost())->toBe($dbConfigCentreon->getHost())
->and($connectionConfig->getUser())->toBe($dbConfigCentreon->getUser())
->and($connectionConfig->getPassword())->toBe($dbConfigCentreon->getPassword())
->and($connectionConfig->getDatabaseNameConfiguration())->toBe($dbConfigCentreon->getDatabaseNameConfiguration())
->and($connectionConfig->getPort())->toBe($dbConfigCentreon->getPort());
}
);
it(
'get the database name of the current connection',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$dbName = $db->getDatabaseName();
expect($dbName)->toBe('centreon');
}
);
it('get native connection', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$pdo = $db->getNativeConnection();
expect($pdo)->toBeInstanceOf(\PDO::class);
});
it('get last insert id', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$insert = $db->exec(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($insert)->toBeInt()->toBe(1);
$lastInsertId = $db->getLastInsertId();
expect($lastInsertId)->toBeString()->toBe('110');
// clean up the database
$delete = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($delete)->toBeInt()->toBe(1);
});
it('is connected', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
expect($db->isConnected())->toBeTrue();
});
it('quote string', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$quotedString = $db->quote('foo');
expect($quotedString)->toBeString()->toBe("'foo'");
});
// --------------------------------------- CUD METHODS -----------------------------------------
// -- executeStatement()
it(
'execute statement with a correct query without query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$inserted = $db->executeStatement(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($inserted)->toBeInt()->toBe(1);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1);
}
);
it(
'execute statement with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $db->executeStatement(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1);
}
);
it(
'execute statement with a correct query with query parameters with ":" before keys',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int(':id', 110),
QueryParameter::string(':name', 'foo_name'),
QueryParameter::string(':alias', 'foo_alias'),
]
);
$inserted = $db->executeStatement(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1);
}
);
it('execute statement with a SELECT query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->executeStatement('SELECT * FROM contact');
})->throws(ConnectionException::class);
it('execute statement with an empty query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->executeStatement('');
})->throws(ConnectionException::class);
it(
'execute statement with an incorrect query',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->executeStatement('foo');
}
)->throws(ConnectionException::class);
it(
'execute statement with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
]
);
$db->executeStatement(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
}
)->throws(ConnectionException::class);
// -- insert()
it(
'insert with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $db->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1);
}
);
it('insert with a SELECT query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->insert(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('contact_id', 110)])
);
})->throws(ConnectionException::class);
it('insert with an empty query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->insert('', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it('insert with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->insert('foo', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it(
'insert with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
]
);
$db->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
}
)->throws(ConnectionException::class);
// -- batchInsert()
it(
'batch insert with a correct query with batch query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$batchQueryParameters = BatchInsertParameters::create([
QueryParameters::create([
QueryParameter::int('contact_id', 110),
QueryParameter::string('contact_name', 'foo_name'),
QueryParameter::string('contact_alias', 'foo_alias'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 111),
QueryParameter::string('contact_name', 'bar_name'),
QueryParameter::string('contact_alias', 'bar_alias'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 112),
QueryParameter::string('contact_name', 'baz_name'),
QueryParameter::string('contact_alias', 'baz_alias'),
]),
]);
$inserted = $db->batchInsert(
'contact',
['contact_id', 'contact_name', 'contact_alias'],
$batchQueryParameters
);
expect($inserted)->toBeInt()->toBe(3);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id IN (110,111,112)');
expect($deleted)->toBeInt()->toBe(3);
}
);
it(
'batch insert with a correct query with empty batch query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->batchInsert(
'contact',
['contact_id', 'contact_name', 'contact_alias'],
BatchInsertParameters::create([])
);
}
)->throws(ConnectionException::class);
it(
'batch insert with an incorrect batch query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$batchQueryParameters = BatchInsertParameters::create([
QueryParameters::create([
QueryParameter::int('contact_id', 110),
QueryParameter::string('contact_name', 'foo_name'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 111),
QueryParameter::string('contact_name', 'bar_name'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 112),
QueryParameter::string('contact_name', 'baz_name'),
]),
]);
$db->batchInsert(
'contact',
['contact_id', 'contact_name', 'contact_alias'],
$batchQueryParameters
);
}
)->throws(ConnectionException::class);
// -- update()
it(
'update with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$inserted = $db->executeStatement(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($inserted)->toBeInt()->toBe(1);
$queryParameters = QueryParameters::create(
[
QueryParameter::string('name', 'bar_name'),
QueryParameter::string('alias', 'bar_alias'),
QueryParameter::int('id', 110),
]
);
$updated = $db->update(
'UPDATE contact SET contact_name = :name, contact_alias = :alias WHERE contact_id = :id',
$queryParameters
);
expect($updated)->toBeInt()->toBe(1);
// clean up the database
$delete = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($delete)->toBeInt()->toBe(1);
}
);
it('update with a SELECT query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->update(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('contact_id', 110)])
);
})->throws(ConnectionException::class);
it('update with an empty query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->update('', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it('update with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->update('foo', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it(
'update with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::string('name', 'bar_name'),
QueryParameter::string('alias', 'bar_alias'),
]
);
$db->update(
'UPDATE contact SET contact_name = :name, contact_alias = :alias WHERE contact_id = :id',
$queryParameters
);
}
)->throws(ConnectionException::class);
// -- delete()
it(
'delete with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$inserted = $db->executeStatement(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($inserted)->toBeInt()->toBe(1);
$queryParameters = QueryParameters::create([QueryParameter::int('id', 110)]);
$deleted = $db->delete('DELETE FROM contact WHERE contact_id = :id', $queryParameters);
expect($deleted)->toBeInt()->toBe(1);
}
);
it('delete with a SELECT query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->delete(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('contact_id', 110)])
);
})->throws(ConnectionException::class);
it('delete with an empty query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->delete('', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it('delete with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->delete('foo', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
})->throws(ConnectionException::class);
it(
'delete with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$db->delete(
'DELETE FROM contact WHERE contact_id = :id AND contact_name = :name AND contact_alias = :alias',
$queryParameters
);
}
)->throws(ConnectionException::class);
// ---------------------------------------- FETCH METHODS ----------------------------------------------
// -- fetchNumeric()
it(
'fetchNumeric with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchNumeric(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBe(1);
}
);
it('fetchNumeric with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchNumeric(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBe(1);
});
it('fetchNumeric with a CUD query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchNumeric(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
})->throws(ConnectionException::class);
it('fetchNumeric with an empty query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchNumeric('', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it('fetchNumeric with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchNumeric('foo', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it(
'fetchNumeric with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchNumeric(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::string('name', 'foo_name')])
);
}
)->throws(ConnectionException::class);
// -- fetchAssociative()
it(
'fetchAssociative with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($contact)->toBeArray()
->and($contact['contact_id'])->toBe(1);
}
);
it('fetchAssociative with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($contact)->toBeArray()
->and($contact['contact_id'])->toBe(1);
});
it('fetchAssociative with a CUD query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchAssociative(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
})->throws(ConnectionException::class);
it('fetchAssociative with an empty query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchAssociative('', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it('fetchAssociative with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchAssociative('foo', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it(
'fetchAssociative with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::string('name', 'foo_name')])
);
}
)->throws(ConnectionException::class);
// -- fetchOne()
it(
'fetchOne with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$alias = $db->fetchOne(
'SELECT contact_alias FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($alias)->toBeString()->toBe('admin');
}
);
it('fetchOne with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$alias = $db->fetchOne(
'SELECT contact_alias FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($alias)->toBeString()->toBe('admin');
});
it('fetchOne with a CUD query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchOne(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
})->throws(ConnectionException::class);
it('fetchOne with an empty query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchOne('', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it('fetchOne with an incorrect query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchOne('foo', QueryParameters::create([QueryParameter::int('id', 1)]));
})->throws(ConnectionException::class);
it(
'fetchOne with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchOne(
'SELECT contact_alias FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::string('name', 'foo_name')])
);
}
)->throws(ConnectionException::class);
// -- fetchFirstColumn()
it(
'fetchFirstColumn with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchFirstColumn(
'SELECT contact_id FROM contact ORDER BY :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBeInt()->toBe(1);
}
);
it('fetchFirstColumn with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchFirstColumn(
'SELECT contact_id FROM contact ORDER BY :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBeInt()->toBe(1);
});
it(
'fetchFirstColumn with a correct query with query parameters and another column',
function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$contact = $db->fetchFirstColumn('SELECT contact_alias FROM contact ORDER BY contact_id');
expect($contact)->toBeArray()
->and($contact[0])->toBeString()->toBe('admin');
}
);
it('fetchFirstColumn with a CUD query', function () use ($dbConfigCentreon): void {
$db = DatabaseConnection::createFromConfig(connectionConfig: $dbConfigCentreon);
$db->fetchFirstColumn(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
})->throws(ConnectionException::class);
it('fetchFirstColumn with an empty query', function () use ($dbConfigCentreon): void {
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Infrastructure/MetaServiceConfiguration/Repository/Model/MetaServiceConfigurationFactoryRdbTest.php | centreon/tests/php/Centreon/Infrastructure/MetaServiceConfiguration/Repository/Model/MetaServiceConfigurationFactoryRdbTest.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\Centreon\Infrastructure\MetaServiceConfiguration\Repository\Model;
use Centreon\Infrastructure\MetaServiceConfiguration\Repository\Model\MetaServiceConfigurationFactoryRdb;
use PHPUnit\Framework\TestCase;
/**
* @package Tests\Centreon\Infrastructure\MetaServiceConfiguration\Repository\Model
*/
class MetaServiceConfigurationFactoryRdbTest extends TestCase
{
/** @var array<string, string|int> */
private $rdbData;
protected function setUp(): void
{
$this->rdbData = [
'meta_id' => 1,
'meta_name' => 'meta-test',
'calculation_type' => 'average',
'data_source_type' => 'gauge',
'meta_activate' => '1',
'meta_display' => 'META: %s',
'metric' => 'rta',
'warning' => '5',
'critical' => '10',
'regexp_str' => '%Ping%',
'meta_select_mode' => 1,
];
}
/**
* Tests the of the good creation of the MetaServiceConfiguration entity
* We test all properties.
*/
public function testAllPropertiesOnCreate(): void
{
$metaServiceConfiguration = MetaServiceConfigurationFactoryRdb::create($this->rdbData);
$this->assertEquals($this->rdbData['meta_id'], $metaServiceConfiguration->getId());
$this->assertEquals($this->rdbData['meta_name'], $metaServiceConfiguration->getName());
$this->assertEquals($this->rdbData['calculation_type'], $metaServiceConfiguration->getCalculationType());
$this->assertEquals($this->rdbData['data_source_type'], $metaServiceConfiguration->getDataSourceType());
$this->assertEquals($this->rdbData['meta_display'], $metaServiceConfiguration->getOutput());
$this->assertEquals($this->rdbData['metric'], $metaServiceConfiguration->getMetric());
$this->assertEquals($this->rdbData['warning'], $metaServiceConfiguration->getWarning());
$this->assertEquals($this->rdbData['critical'], $metaServiceConfiguration->getCritical());
$this->assertEquals($this->rdbData['regexp_str'], $metaServiceConfiguration->getRegexpString());
$this->assertEquals((bool) $this->rdbData['meta_activate'], $metaServiceConfiguration->isActivated());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Infrastructure/MetaServiceConfiguration/API/Model/MetaServiceConfigurationV2110FactoryTest.php | centreon/tests/php/Centreon/Infrastructure/MetaServiceConfiguration/API/Model/MetaServiceConfigurationV2110FactoryTest.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\Centreon\Infrastructure\MetaServiceConfiguration\API\Model;
use Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfiguration;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindMetaServicesConfigurationsResponse;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindOneMetaServiceConfigurationResponse;
use Centreon\Infrastructure\MetaServiceConfiguration\API\Model\MetaServiceConfigurationV2110Factory;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfigurationTest;
/**
* @package Tests\Centreon\Infrastructure\MetaServiceConfiguration\API\Model
*/
class MetaServiceConfigurationV2110FactoryTest extends TestCase
{
/** @var MetaServiceConfiguration */
private $metaServiceConfiguration;
protected function setUp(): void
{
$this->metaServiceConfiguration = MetaServiceConfigurationTest::createEntity();
}
/**
* We check the format sent for the API request (v21.10) using the factory
*/
public function testCreateAllFromResponse(): void
{
$response = new FindMetaServicesConfigurationsResponse();
$response->setMetaServicesConfigurations([$this->metaServiceConfiguration]);
$metaServiceConfigurationV21 = MetaServiceConfigurationV2110Factory::createAllFromResponse($response);
$metaServiceConfiguration = $response->getMetaServicesConfigurations()[0];
$this->assertEquals($metaServiceConfiguration['id'], $metaServiceConfigurationV21[0]->id);
$this->assertEquals($metaServiceConfiguration['name'], $metaServiceConfigurationV21[0]->name);
$this->assertEquals($metaServiceConfiguration['meta_display'], $metaServiceConfigurationV21[0]->output);
$this->assertEquals(
$metaServiceConfiguration['data_source_type'],
$metaServiceConfigurationV21[0]->dataSourceType
);
$this->assertEquals($metaServiceConfiguration['regexp_str'], $metaServiceConfigurationV21[0]->regexpString);
$this->assertEquals($metaServiceConfiguration['warning'], $metaServiceConfigurationV21[0]->warning);
$this->assertEquals($metaServiceConfiguration['critical'], $metaServiceConfigurationV21[0]->critical);
$this->assertEquals(
$metaServiceConfiguration['meta_select_mode'],
$metaServiceConfigurationV21[0]->metaSelectMode
);
$this->assertEquals($metaServiceConfiguration['is_activated'], $metaServiceConfigurationV21[0]->isActivated);
}
/**
* We check the format sent for the API request (v21.10) using the factory
*/
public function testCreateFromResponse(): void
{
$response = new FindOneMetaServiceConfigurationResponse();
$response->setMetaServiceConfiguration($this->metaServiceConfiguration);
$metaServiceConfigurationV21 = MetaServiceConfigurationV2110Factory::createOneFromResponse($response);
$metaServiceConfiguration = $response->getMetaServiceConfiguration();
$this->assertEquals($metaServiceConfiguration['id'], $metaServiceConfigurationV21->id);
$this->assertEquals($metaServiceConfiguration['name'], $metaServiceConfigurationV21->name);
$this->assertEquals($metaServiceConfiguration['meta_display'], $metaServiceConfigurationV21->output);
$this->assertEquals(
$metaServiceConfiguration['data_source_type'],
$metaServiceConfigurationV21->dataSourceType
);
$this->assertEquals($metaServiceConfiguration['regexp_str'], $metaServiceConfigurationV21->regexpString);
$this->assertEquals($metaServiceConfiguration['warning'], $metaServiceConfigurationV21->warning);
$this->assertEquals($metaServiceConfiguration['critical'], $metaServiceConfigurationV21->critical);
$this->assertEquals(
$metaServiceConfiguration['meta_select_mode'],
$metaServiceConfigurationV21->metaSelectMode
);
$this->assertEquals($metaServiceConfiguration['is_activated'], $metaServiceConfigurationV21->isActivated);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Infrastructure/HostConfiguration/Model/HostTemplateFactoryRdbTest.php | centreon/tests/php/Centreon/Infrastructure/HostConfiguration/Model/HostTemplateFactoryRdbTest.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\Centreon\Infrastructure\HostConfiguration\Model;
use Centreon\Domain\HostConfiguration\Exception\HostTemplateFactoryException;
use Centreon\Domain\HostConfiguration\Model\HostTemplate;
use Centreon\Infrastructure\HostConfiguration\Repository\Model\HostTemplateFactoryRdb;
use PHPUnit\Framework\TestCase;
/**
* @package Tests\Centreon\Infrastructure\HostConfiguration\Model
*/
class HostTemplateFactoryRdbTest extends TestCase
{
private const ALL_NOTIFICATION_OPTIONS
= HostTemplate::NOTIFICATION_OPTION_DOWN
| HostTemplate::NOTIFICATION_OPTION_UNREACHABLE
| HostTemplate::NOTIFICATION_OPTION_RECOVERY
| HostTemplate::NOTIFICATION_OPTION_FLAPPING
| HostTemplate::NOTIFICATION_OPTION_DOWNTIME_SCHEDULED;
private const ALL_STALKING_OPTIONS
= HostTemplate::STALKING_OPTION_UP
| HostTemplate::STALKING_OPTION_DOWN
| HostTemplate::STALKING_OPTION_UNREACHABLE;
/** @var array<string, string|int> */
private $rdbData;
protected function setUp(): void
{
$this->rdbData = [
'host_id' => 10,
'host_name' => 'Template name',
'host_alias' => 'Template alias',
'host_address' => 'address',
'display_name' => 'Template display name',
'host_max_check_attempts' => 1,
'host_check_interval' => 2,
'host_retry_check_interval' => 1,
'host_active_checks_enabled' => 2,
'host_passive_checks_enabled' => 1,
'host_notification_interval' => 1,
'host_recovery_notification_delay' => 1,
'host_notification_options' => 'd,u,r,f,s',
'host_notifications_enabled' => 2,
'host_first_notification_delay' => 1,
'host_stalking_options' => 'o,d,u',
'host_snmp_community' => 'community',
'host_snmp_version' => '1',
'host_comment' => 'comment',
'host_locked' => 0,
'host_activate' => 1,
'ehi_notes' => 'notes',
'ehi_notes_url' => 'notes url',
'ehi_action_url' => 'action url',
'parents' => '5,6',
];
}
/**
* Tests the of the good creation of the HostTemplate entity.<br>
* We test all properties.
*
* @throws HostTemplateFactoryException
*/
public function testAllPropertiesOnCreate(): void
{
$hostTemplate = HostTemplateFactoryRdb::create($this->rdbData);
$this->assertEquals($this->rdbData['host_id'], $hostTemplate->getId());
$this->assertEquals($this->rdbData['host_name'], $hostTemplate->getName());
$this->assertEquals($this->rdbData['host_alias'], $hostTemplate->getAlias());
$this->assertEquals($this->rdbData['host_address'], $hostTemplate->getAddress());
$this->assertEquals($this->rdbData['display_name'], $hostTemplate->getDisplayName());
$this->assertEquals($this->rdbData['host_max_check_attempts'], $hostTemplate->getMaxCheckAttempts());
$this->assertEquals($this->rdbData['host_check_interval'], $hostTemplate->getCheckInterval());
$this->assertEquals($this->rdbData['host_retry_check_interval'], $hostTemplate->getRetryCheckInterval());
$this->assertEquals(
$this->rdbData['host_active_checks_enabled'],
$hostTemplate->getActiveChecksStatus() === HostTemplate::STATUS_DEFAULT
);
$this->assertEquals(
$this->rdbData['host_passive_checks_enabled'],
$hostTemplate->getPassiveChecksStatus() === HostTemplate::STATUS_ENABLE
);
$this->assertEquals($this->rdbData['host_notification_interval'], $hostTemplate->getNotificationInterval());
$this->assertEquals(
$this->rdbData['host_recovery_notification_delay'],
$hostTemplate->getRecoveryNotificationDelay()
);
$this->assertEquals(
self::ALL_NOTIFICATION_OPTIONS,
$hostTemplate->getNotificationOptions(),
'The notification options of the HostTemplate are not set correctly.'
);
$this->assertEquals(
$this->rdbData['host_notifications_enabled'],
$hostTemplate->getNotificationsStatus() === (HostTemplate::STATUS_DEFAULT)
);
$this->assertEquals(
$this->rdbData['host_first_notification_delay'],
$hostTemplate->getFirstNotificationDelay()
);
$this->assertEquals(
self::ALL_STALKING_OPTIONS,
$hostTemplate->getStalkingOptions(),
'The stalking options of the HostTemplate are not set correctly.'
);
$this->assertEquals($this->rdbData['host_snmp_community'], $hostTemplate->getSnmpCommunity());
$this->assertEquals($this->rdbData['host_snmp_version'], $hostTemplate->getSnmpVersion());
$this->assertEquals((bool) $this->rdbData['host_locked'], $hostTemplate->isLocked());
$this->assertEquals((bool) $this->rdbData['host_activate'], $hostTemplate->isActivated());
$this->assertEquals($this->rdbData['ehi_notes'], $hostTemplate->getNotes());
$this->assertEquals($this->rdbData['ehi_notes_url'], $hostTemplate->getUrlNotes());
$this->assertEquals($this->rdbData['ehi_action_url'], $hostTemplate->getActionUrl());
$this->assertEquals($this->rdbData['parents'], implode(',', $hostTemplate->getParentIds()));
}
/**
* We are testing a bad notification option.
*
* @throws HostTemplateFactoryException
*/
public function testBadNotificationOptions(): void
{
$this->rdbData['host_notification_options'] = 'd,u,c,r,f,s,x';
$this->expectException(HostTemplateFactoryException::class);
$this->expectExceptionMessage(HostTemplateFactoryException::notificationOptionsNotAllowed('c,x')->getMessage());
HostTemplateFactoryRdb::create($this->rdbData);
}
/**
* We are testing a bad stalking option.
*
* @throws HostTemplateFactoryException
*/
public function testBadStalkingOptions(): void
{
$this->rdbData['host_stalking_options'] = 'o,c,d,u,x';
$this->expectException(HostTemplateFactoryException::class);
$this->expectExceptionMessage(HostTemplateFactoryException::stalkingOptionsNotAllowed('c,x')->getMessage());
HostTemplateFactoryRdb::create($this->rdbData);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Infrastructure/HostConfiguration/Repository/Model/HostGroupFactoryRdbTest.php | centreon/tests/php/Centreon/Infrastructure/HostConfiguration/Repository/Model/HostGroupFactoryRdbTest.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\Centreon\Infrastructure\HostConfiguration\Repository\Model;
use Centreon\Infrastructure\HostConfiguration\Repository\Model\HostGroupFactoryRdb;
use PHPUnit\Framework\TestCase;
/**
* @package Tests\Centreon\Infrastructure\HostConfiguration\Repository\Model
*/
class HostGroupFactoryRdbTest extends TestCase
{
/** @var array<string, string|int> */
private $rdbData;
protected function setUp(): void
{
$this->rdbData = [
'hg_id' => 10,
'hg_name' => 'hg name',
'hg_alias' => 'hg alias',
'geo_coords' => '2;4',
'hg_comment' => 'comment',
'hg_activate' => '1',
];
}
/**
* Tests the of the good creation of the hostGroup entity.<br>
* We test all properties.
*
* @throws \Assert\AssertionFailedException
*/
public function testAllPropertiesOnCreate(): void
{
$hostGroup = HostGroupFactoryRdb::create($this->rdbData);
$this->assertEquals($this->rdbData['hg_id'], $hostGroup->getId());
$this->assertEquals($this->rdbData['hg_name'], $hostGroup->getName());
$this->assertEquals($this->rdbData['hg_alias'], $hostGroup->getAlias());
$this->assertEquals($this->rdbData['geo_coords'], $hostGroup->getGeoCoords());
$this->assertEquals($this->rdbData['hg_comment'], $hostGroup->getComment());
$this->assertEquals((bool) $this->rdbData['hg_activate'], $hostGroup->isActivated());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Centreon/Infrastructure/RequestParameters/SqlRequestParametersTranslatorTest.php | centreon/tests/php/Centreon/Infrastructure/RequestParameters/SqlRequestParametersTranslatorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Centreon\Infrastructure\RequestParameters;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use PHPUnit\Framework\TestCase;
class SqlRequestParametersTranslatorTest extends TestCase
{
protected $requestParameters;
protected function setUp(): void
{
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
}
/**
* test translatePaginationToSql first page
*/
public function testTranslatePaginationToSqlFirstPage(): void
{
$this->requestParameters->expects($this->once())
->method('getPage')
->willReturn(1);
$this->requestParameters->expects($this->exactly(2))
->method('getLimit')
->willReturn(10);
$sqlRequestParametersTranslator = new SqlRequestParametersTranslator($this->requestParameters);
$pagination = $sqlRequestParametersTranslator->translatePaginationToSql();
$this->assertEquals(' LIMIT 0, 10', $pagination);
}
/**
* test translatePaginationToSql second page
*/
public function testTranslatePaginationToSqlSecondPage(): void
{
$this->requestParameters->expects($this->once())
->method('getPage')
->willReturn(2);
$this->requestParameters->expects($this->exactly(2))
->method('getLimit')
->willReturn(10);
$sqlRequestParametersTranslator = new SqlRequestParametersTranslator($this->requestParameters);
$pagination = $sqlRequestParametersTranslator->translatePaginationToSql();
$this->assertEquals(' LIMIT 10, 10', $pagination);
}
/**
* test translateSearchParameterToSql with matching concordance array
*/
public function testTranslateSearchParameterToSqlWithMatchingConcordanceArray(): void
{
$this->requestParameters->expects($this->once())
->method('getSearch')
->willReturn([
'$or' => [
'host.name' => ['$rg' => 'host1'],
'host.description' => ['$rg' => 'host1'],
],
]);
$sqlRequestParametersTranslator = new SqlRequestParametersTranslator($this->requestParameters);
$sqlRequestParametersTranslator->setConcordanceArray([
'host.name' => 'h.name',
'host.description' => 'h.description',
]);
$search = $sqlRequestParametersTranslator->translateSearchParameterToSql();
$this->assertEquals(
' WHERE (h.name REGEXP :value_1 OR h.description REGEXP :value_2)',
$search
);
}
/**
* test translateSearchParameterToSql with wrong concordance array and strict mode with exception
*/
public function testTranslateSearchParameterToSqlWithWrongConcordanceArrayAndStrictModeException(): void
{
$this->requestParameters->expects($this->once())
->method('getSearch')
->willReturn([
'$or' => [
'host.name' => ['$rg' => 'host1'],
'host.description' => ['$rg' => 'host1'],
],
]);
$this->requestParameters->expects($this->exactly(2))
->method('getConcordanceStrictMode')
->willReturn(RequestParameters::CONCORDANCE_MODE_STRICT);
$this->requestParameters->expects($this->once())
->method('getConcordanceErrorMode')
->willReturn(RequestParameters::CONCORDANCE_ERRMODE_EXCEPTION);
$sqlRequestParametersTranslator = new SqlRequestParametersTranslator($this->requestParameters);
$sqlRequestParametersTranslator->setConcordanceArray([
'host.name' => 'h.name',
'host.alias' => 'h.description',
]);
$this->expectException(RequestParametersTranslatorException::class);
$this->expectExceptionMessage('The parameter host.description is not allowed');
$sqlRequestParametersTranslator->translateSearchParameterToSql();
}
/**
* test translateSearchParameterToSql with wrong concordance array and strict mode in silent mode
*/
public function testTranslateSearchParameterToSqlWithWrongConcordanceArrayAndStrictModeSilent(): void
{
$this->requestParameters->expects($this->once())
->method('getSearch')
->willReturn([
'$or' => [
'host.name' => ['$rg' => 'host1'],
'host.description' => ['$rg' => 'host1'],
],
]);
$this->requestParameters->expects($this->exactly(2))
->method('getConcordanceStrictMode')
->willReturn(RequestParameters::CONCORDANCE_MODE_STRICT);
$this->requestParameters->expects($this->once())
->method('getConcordanceErrorMode')
->willReturn(RequestParameters::CONCORDANCE_ERRMODE_SILENT);
$sqlRequestParametersTranslator = new SqlRequestParametersTranslator($this->requestParameters);
$sqlRequestParametersTranslator->setConcordanceArray([
'host.name' => 'h.name',
'host.alias' => 'h.description',
]);
$search = $sqlRequestParametersTranslator->translateSearchParameterToSql();
$this->assertEquals(
' WHERE (h.name REGEXP :value_1)',
$search
);
}
/**
* test translateSearchParameterToSql with normalizers
*/
public function testTranslateSearchParametersWithNormalizers(): void
{
$this->requestParameters->expects($this->once())
->method('getSearch')
->willReturn([
'$and' => [
'event.type' => ['$eq' => 'comment'],
'event.date' => ['$ge' => '2020-01-31T03:54:12+01:00'],
],
]);
$sqlRequestParametersTranslator = new SqlRequestParametersTranslator($this->requestParameters);
$sqlRequestParametersTranslator->setConcordanceArray([
'event.type' => 'e.type',
'event.date' => 'e.date',
]);
$sqlRequestParametersTranslator->addNormalizer(
'event.date',
new class () implements NormalizerInterface {
public function normalize($valueToNormalize)
{
return (new \Datetime($valueToNormalize))->getTimestamp();
}
}
);
$search = $sqlRequestParametersTranslator->translateSearchParameterToSql();
$this->assertEquals(
' WHERE (e.type = :value_1 AND e.date >= :value_2)',
$search
);
$this->assertEquals(
[
':value_1' => [\PDO::PARAM_STR => 'comment'],
':value_2' => [\PDO::PARAM_INT => 1580439252],
],
$sqlRequestParametersTranslator->getSearchValues()
);
}
/**
* test translateSortParameterToSql
*/
public function testTranslateSortParameterToSql(): void
{
$this->requestParameters->expects($this->once())
->method('getSort')
->willReturn([
'host.name' => 'ASC',
'host.alias' => 'DESC',
]);
$this->requestParameters->expects($this->exactly(1))
->method('getPage')
->willReturn(1);
$this->requestParameters->expects($this->exactly(2))
->method('getLimit')
->willReturn(10);
$sqlRequestParametersTranslator = new SqlRequestParametersTranslator($this->requestParameters);
$sqlRequestParametersTranslator->setConcordanceArray([
'host.name' => 'h.name',
'host.alias' => 'h.description',
]);
$this->assertEquals(
' LIMIT 0, 10',
$sqlRequestParametersTranslator->translatePaginationToSql()
);
$this->assertEquals(
' ORDER BY h.name IS NULL, h.name ASC, h.description IS NULL, h.description DESC',
$sqlRequestParametersTranslator->translateSortParameterToSql()
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Security/TokenAPIAuthenticatorTest.php | centreon/tests/php/Security/TokenAPIAuthenticatorTest.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\Security;
use Centreon\Domain\Contact\Interfaces\ContactRepositoryInterface;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Security\Domain\Authentication\Interfaces\AuthenticationRepositoryInterface;
use Security\Domain\Authentication\Model\LocalProvider;
use Security\TokenAPIAuthenticator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class TokenAPIAuthenticatorTest extends TestCase
{
private AuthenticationRepositoryInterface|MockObject $authenticationRepository;
private ContactRepositoryInterface|MockObject $contactRepository;
private LocalProvider $localProvider;
private ReadTokenRepositoryInterface $readTokenRepository;
private TokenAPIAuthenticator $authenticator;
public function setUp(): void
{
$this->authenticationRepository = $this->createMock(AuthenticationRepositoryInterface::class);
$this->contactRepository = $this->createMock(ContactRepositoryInterface::class);
$this->localProvider = $this->createMock(LocalProvider::class);
$this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class);
$this->authenticator = new TokenAPIAuthenticator(
$this->authenticationRepository,
$this->contactRepository,
$this->localProvider,
$this->readTokenRepository,
);
}
public function testStart(): void
{
$request = new Request();
$this->assertEquals(
new JsonResponse(
[
'message' => 'Authentication Required',
],
Response::HTTP_UNAUTHORIZED
),
$this->authenticator->start($request)
);
}
public function testSupports(): void
{
$request = new Request();
$request->headers->set('X-AUTH-TOKEN', 'my_token');
$this->assertTrue($this->authenticator->supports($request));
}
public function testNotSupports(): void
{
$request = new Request();
$this->assertFalse($this->authenticator->supports($request));
}
public function testOnAuthenticationFailure(): void
{
$request = new Request();
$exception = new AuthenticationException();
$this->assertEquals(
new JsonResponse(
[
'message' => 'An authentication exception occurred.',
],
Response::HTTP_UNAUTHORIZED
),
$this->authenticator->onAuthenticationFailure($request, $exception)
);
}
public function testOnAuthenticationSuccess(): void
{
$request = new Request();
$token = $this->createMock(TokenInterface::class);
$this->assertNull(
$this->authenticator->onAuthenticationSuccess($request, $token, 'local')
);
}
public function testAuthenticateSuccess(): void
{
$request = new Request();
$request->headers->set('X-AUTH-TOKEN', 'my_token');
$this->assertInstanceOf(
SelfValidatingPassport::class,
$this->authenticator->authenticate($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/Security/SessionAPIAuthenticatorTest.php | centreon/tests/php/Security/SessionAPIAuthenticatorTest.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\Security;
use Centreon\Domain\Contact\Interfaces\ContactRepositoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Security\Domain\Authentication\Interfaces\AuthenticationServiceInterface;
use Security\SessionAPIAuthenticator;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class SessionAPIAuthenticatorTest extends TestCase
{
/** @var AuthenticationServiceInterface|MockObject */
private $authenticationService;
/** @var ContactRepositoryInterface|MockObject */
private $contactRepository;
/**
* @var MockObject|Request
*/
private Request|MockObject $request;
/**
* @var MockObject|SessionInterface
*/
private SessionInterface|MockObject $session;
public function setUp(): void
{
$this->authenticationService = $this->createMock(AuthenticationServiceInterface::class);
$this->contactRepository = $this->createMock(ContactRepositoryInterface::class);
$this->request = $this->createMock(Request::class);
$this->session = $this->createMock(SessionInterface::class);
$this->session
->method('getId')
->willReturn(uniqid());
$this->request
->method('getSession')
->willReturn($this->session);
$this->request->headers = new HeaderBag();
}
public function testSupports(): void
{
$authenticator = new SessionAPIAuthenticator(
$this->authenticationService,
$this->contactRepository,
);
$this->request->headers->set('Cookie', 'centreon_session=my_session_id');
$this->assertTrue($authenticator->supports($this->request));
}
public function testNotSupports(): void
{
$authenticator = new SessionAPIAuthenticator(
$this->authenticationService,
$this->contactRepository,
);
$request = new Request();
$this->assertFalse($authenticator->supports($request));
}
public function testOnAuthenticationFailure(): void
{
$authenticator = new SessionAPIAuthenticator(
$this->authenticationService,
$this->contactRepository,
);
$request = new Request();
$exception = new AuthenticationException();
$this->assertEquals(
new JsonResponse(
[
'message' => 'An authentication exception occurred.',
],
Response::HTTP_UNAUTHORIZED
),
$authenticator->onAuthenticationFailure($request, $exception)
);
}
public function testAuthenticateSuccess(): void
{
$authenticator = new SessionAPIAuthenticator(
$this->authenticationService,
$this->contactRepository,
);
$this->assertInstanceOf(
SelfValidatingPassport::class,
$authenticator->authenticate($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/Security/EncryptionTest.php | centreon/tests/php/Security/EncryptionTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Security;
use PHPUnit\Framework\TestCase;
use Security\Encryption;
/**
* Class
*
* @class EncryptionTest
* @package Tests\Security
*/
class EncryptionTest extends TestCase
{
/** @var string */
private $firstKey;
/** @var string */
private $secondKey;
/** @var string */
private $falseKey;
public function setUp(): void
{
parent::setUp(); // TODO: Change the autogenerated stub
$this->falseKey = 'o3usvAMHw1lmTvvmlXIIpJPJEpuCEJLPVkbAaJEshz2FadxQqq7Ifiey8A/EM8OEWEcDdlb5oRCI3ZNDSBDcyQ==';
$this->firstKey = 'UTgsISjmvIKH28VVPh165Hqwse5CdvIMnG2K31nOieRL9NuQ6VRsXbE7Jb2KUTYtWNBoc+vyLgPzPCtB4F6GDw==';
$this->secondKey = '6iqKFqOUUD8mFncNtSqQPw7cgFypQ9O9H7qH17Z6Qd1zsGH0NmJdDwk2GI4/yqmOFnJqC5RKeUGKz55Xx/+mOg==';
}
public function testCryptDecrypt(): void
{
$messageToEncrypt = 'my secret message';
$encryption = (new Encryption())
->setFirstKey($this->firstKey)
->setSecondKey($this->secondKey);
$encrypedMessage = $encryption->crypt($messageToEncrypt);
$decryptedMessage = $encryption->decrypt($encrypedMessage);
$this->assertEquals($messageToEncrypt, $decryptedMessage);
$encryption->setSecondKey($this->falseKey); // False second secret key
$falseDecryptedMessage = $encryption->decrypt($encrypedMessage);
$this->assertNull($falseDecryptedMessage);
$encryption
->setFirstKey($this->falseKey) // False first secret key
->setSecondKey($this->secondKey);
$falseDecryptedMessage = $encryption->decrypt($encrypedMessage);
$this->assertNull($falseDecryptedMessage);
}
public function testExceptionOnFirstKeyWhileEncryption(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('First key not defined');
$encryption = (new Encryption())
->setSecondKey($this->secondKey);
// The data to be encrypted is not important
$encryption->crypt($this->falseKey);
}
public function testExceptionOnSecondKeyWhileEncryption(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Second key not defined');
$encryption = (new Encryption())
->setFirstKey($this->secondKey);
// The data to be encrypted is not important
$encryption->crypt($this->falseKey);
}
public function testWarningOnBadHashAlgorithmWhileEncryption(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('openssl_cipher_iv_length(): Unknown cipher algorithm');
set_error_handler(function ($errNo, $errStr, ...$args): void {
throw new \Exception($errStr);
restore_error_handler();
});
$encryption = (new Encryption('bad-algorithm'))
->setFirstKey($this->secondKey)
->setSecondKey($this->secondKey);
// The data to be encrypted is not important
$encryption->crypt($this->falseKey);
}
public function testWarningOnBadHashMethodWhileEncryption(): void
{
$this->expectException(\ValueError::class);
$this->expectExceptionMessage(
'hash_hmac(): Argument #1 ($algo) must be a valid cryptographic hashing algorithm'
);
$encryption = (new Encryption('aes-256-cbc', 'bad-hash'))
->setFirstKey($this->secondKey)
->setSecondKey($this->secondKey);
// The data to be encrypted is not important
$encryption->crypt($this->falseKey);
}
public function testExceptionOnFirstKeyWhileDecryption(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('First key not defined');
$encryption = (new Encryption())
->setSecondKey($this->firstKey);
// The data to be decrypted is not important
$encryption->decrypt($this->falseKey);
}
public function testExceptionOnSecondKeyWhileDecryption(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Second key not defined');
$encryption = (new Encryption())
->setFirstKey($this->firstKey);
// The data to be decrypted is not important
$encryption->decrypt($this->falseKey);
}
public function testWarningOnBadHashAlgorithmWhileDecryption(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('openssl_cipher_iv_length(): Unknown cipher algorithm');
set_error_handler(function ($errNo, $errStr, ...$args): void {
throw new \Exception($errStr);
restore_error_handler();
});
$encryption = (new Encryption('bad-algorithm'))
->setFirstKey($this->secondKey)
->setSecondKey($this->secondKey);
// The data to be decrypted is not important
$encryption->decrypt('456');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Security/Domain/Authentication/AuthenticationServiceTest.php | centreon/tests/php/Security/Domain/Authentication/AuthenticationServiceTest.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\Security\Domain\Authentication;
use Centreon\Domain\Authentication\Exception\AuthenticationException;
use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface;
use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface;
use Core\Security\Authentication\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Authentication\Domain\Model\AuthenticationTokens;
use Core\Security\Authentication\Domain\Model\ProviderToken;
use Core\Security\ProviderConfiguration\Application\Repository\ReadConfigurationRepositoryInterface;
use PHPUnit\Framework\TestCase;
use Security\Domain\Authentication\AuthenticationService;
use Security\Domain\Authentication\Exceptions\ProviderException;
use Security\Domain\Authentication\Interfaces\AuthenticationRepositoryInterface;
use Security\Domain\Authentication\Interfaces\SessionRepositoryInterface;
/**
* @package Tests\Security\Domain\Authentication
*/
class AuthenticationServiceTest extends TestCase
{
/** @var AuthenticationRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject */
private $authenticationRepository;
/** @var SessionRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject */
private $sessionRepository;
/** @var ProviderAuthenticationInterface|\PHPUnit\Framework\MockObject\MockObject */
private $provider;
/** @var AuthenticationTokens|\PHPUnit\Framework\MockObject\MockObject */
private $authenticationTokens;
/** @var ProviderToken|\PHPUnit\Framework\MockObject\MockObject */
private $providerToken;
/** @var ProviderToken|\PHPUnit\Framework\MockObject\MockObject */
private $refreshToken;
/** @var ReadConfigurationRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject */
private $readConfigurationFactory;
/** @var ProviderAuthenticationFactoryInterface|\PHPUnit\Framework\MockObject\MockObject */
private $providerFactory;
/** @var ReadTokenRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject */
private $readTokenRepository;
protected function setUp(): void
{
$this->authenticationRepository = $this->createMock(AuthenticationRepositoryInterface::class);
$this->sessionRepository = $this->createMock(SessionRepositoryInterface::class);
$this->provider = $this->createMock(ProviderAuthenticationInterface::class);
$this->authenticationTokens = $this->createMock(AuthenticationTokens::class);
$this->providerToken = $this->createMock(ProviderToken::class);
$this->refreshToken = $this->createMock(ProviderToken::class);
$this->readConfigurationFactory = $this->createMock(ReadConfigurationRepositoryInterface::class);
$this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class);
$this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class);
}
/**
* test isValidToken when authentication tokens are not found
*/
public function testIsValidTokenTokensNotFound(): void
{
$authenticationService = $this->createAuthenticationService();
$this->readTokenRepository
->expects($this->once())
->method('findAuthenticationTokensByToken')
->with('abc123')
->willReturn(null);
$isValid = $authenticationService->isValidToken('abc123');
$this->assertEquals(false, $isValid);
}
/**
* test isValidToken when provider is not found
*/
public function testIsValidTokenProviderNotFound(): void
{
$authenticationService = $this->createAuthenticationService();
$this->readTokenRepository
->expects($this->once())
->method('findAuthenticationTokensByToken')
->with('abc123')
->willReturn($this->authenticationTokens);
$this->providerFactory
->expects($this->once())
->method('create')
->willThrowException(ProviderException::providerNotFound());
$isValid = $authenticationService->isValidToken('abc123');
$this->assertEquals(false, $isValid);
}
/**
* test isValidToken when session has expired
*/
public function testIsValidTokenSessionExpired(): void
{
$authenticationService = $this->createAuthenticationService();
$this->readTokenRepository
->expects($this->once())
->method('findAuthenticationTokensByToken')
->with('abc123')
->willReturn($this->authenticationTokens);
$this->providerFactory
->expects($this->once())
->method('create')
->willReturn($this->provider);
$this->authenticationTokens
->expects($this->once())
->method('getProviderToken')
->willReturn($this->providerToken);
$this->providerToken
->expects($this->once())
->method('isExpired')
->willReturn(true);
$this->provider
->expects($this->once())
->method('canRefreshToken')
->willReturn(false);
$isValid = $authenticationService->isValidToken('abc123');
$this->assertEquals(false, $isValid);
}
/**
* test isValidToken when error happened on refresh token
*/
public function testIsValidTokenErrorWhileRefreshToken(): void
{
$authenticationService = $this->createAuthenticationService();
$this->readTokenRepository
->expects($this->once())
->method('findAuthenticationTokensByToken')
->with('abc123')
->willReturn($this->authenticationTokens);
$this->providerFactory
->expects($this->once())
->method('create')
->willReturn($this->provider);
$this->authenticationTokens
->expects($this->once())
->method('getProviderToken')
->willReturn($this->providerToken);
$this->authenticationTokens
->expects($this->any())
->method('getProviderRefreshToken')
->willReturn($this->refreshToken);
$this->providerToken
->expects($this->once())
->method('isExpired')
->willReturn(true);
$this->refreshToken
->expects($this->once())
->method('isExpired')
->willReturn(false);
$this->provider
->expects($this->once())
->method('canRefreshToken')
->willReturn(true);
$this->provider
->expects($this->once())
->method('refreshToken')
->willReturn(null);
$isValid = $authenticationService->isValidToken('abc123');
$this->assertEquals(false, $isValid);
}
/**
* test isValidToken when token is valid
*/
public function testIsValidTokenValid(): void
{
$authenticationService = $this->createAuthenticationService();
$this->readTokenRepository
->expects($this->once())
->method('findAuthenticationTokensByToken')
->with('abc123')
->willReturn($this->authenticationTokens);
$this->providerFactory
->expects($this->once())
->method('create')
->willReturn($this->provider);
$this->providerToken
->expects($this->once())
->method('isExpired')
->willReturn(false);
$this->authenticationTokens
->expects($this->once())
->method('getProviderToken')
->willReturn($this->providerToken);
$isValid = $authenticationService->isValidToken('abc123');
$this->assertEquals(true, $isValid);
}
/**
* test deleteSession on failure
*/
public function testDeleteSessionFailed(): void
{
$authenticationService = $this->createAuthenticationService();
$this->authenticationRepository
->expects($this->once())
->method('deleteSecurityToken')
->with('abc123');
$this->sessionRepository
->expects($this->once())
->method('deleteSession')
->willThrowException(new \Exception());
$this->expectException(AuthenticationException::class);
$this->expectExceptionMessage('Error while deleting session');
$authenticationService->deleteSession('abc123');
}
/**
* test deleteSession on success
*/
public function testDeleteSessionSucceed(): void
{
$authenticationService = $this->createAuthenticationService();
$this->authenticationRepository
->expects($this->once())
->method('deleteSecurityToken')
->with('abc123');
$this->sessionRepository
->expects($this->once())
->method('deleteSession')
->with('abc123');
$authenticationService->deleteSession('abc123');
}
/**
* test findAuthenticationTokensByToken on failure
*/
public function testFindAuthenticationTokensByTokenFailed(): void
{
$authenticationService = $this->createAuthenticationService();
$this->readTokenRepository
->expects($this->once())
->method('findAuthenticationTokensByToken')
->with('abc123')
->willThrowException(new \Exception());
$this->expectException(AuthenticationException::class);
$this->expectExceptionMessage('Error while searching authentication tokens');
$authenticationService->findAuthenticationTokensByToken('abc123');
}
/**
* test findAuthenticationTokensByToken on success
*/
public function testFindAuthenticationTokensByTokenSucceed(): void
{
$authenticationService = $this->createAuthenticationService();
$this->readTokenRepository
->expects($this->once())
->method('findAuthenticationTokensByToken')
->with('abc123');
$authenticationService->findAuthenticationTokensByToken('abc123');
}
/**
* test updateAuthenticationTokens on failure
*/
public function testUpdateAuthenticationTokensFailed(): void
{
$authenticationService = $this->createAuthenticationService();
$this->authenticationRepository
->expects($this->once())
->method('updateAuthenticationTokens')
->with($this->authenticationTokens)
->willThrowException(new \Exception());
$this->expectException(AuthenticationException::class);
$this->expectExceptionMessage('Error while updating authentication tokens');
$authenticationService->updateAuthenticationTokens($this->authenticationTokens);
}
/**
* test updateAuthenticationTokens on success
*/
public function testUpdateAuthenticationTokensSucceed(): void
{
$authenticationService = $this->createAuthenticationService();
$this->authenticationRepository
->expects($this->once())
->method('updateAuthenticationTokens')
->with($this->authenticationTokens);
$authenticationService->updateAuthenticationTokens($this->authenticationTokens);
}
/**
* @return AuthenticationService
*/
private function createAuthenticationService(): AuthenticationService
{
return new AuthenticationService(
$this->authenticationRepository,
$this->sessionRepository,
$this->readConfigurationFactory,
$this->providerFactory,
$this->readTokenRepository
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Security/Infrastructure/Authentication/Repository/Model/ProviderConfigurationFactoryRdbTest.php | centreon/tests/php/Security/Infrastructure/Authentication/Repository/Model/ProviderConfigurationFactoryRdbTest.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\Security\Infrastructure\Authentication\Repository\Model;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
use PHPUnit\Framework\TestCase;
use Security\Infrastructure\Repository\Model\ProviderConfigurationFactoryRdb;
/**
* @package Tests\Security\Infrastructure\Authentication\API\Model_2110
*/
class ProviderConfigurationFactoryRdbTest extends TestCase
{
/** @var array<string,int|string|bool> */
private $dbData;
protected function setUp(): void
{
$this->dbData = [
'id' => 1,
'type' => 'local',
'name' => 'local',
'is_active' => true,
'is_forced' => true,
'custom_configuration' => '{}',
];
}
/**
* Tests model is properly created
*/
public function testCreateWithAllProperties(): void
{
$providerConfiguration = ProviderConfigurationFactoryRdb::create($this->dbData);
$this->assertInstanceOf(Configuration::class, $providerConfiguration);
$this->assertEquals($this->dbData['id'], $providerConfiguration->getId());
$this->assertEquals($this->dbData['type'], $providerConfiguration->getType());
$this->assertEquals($this->dbData['name'], $providerConfiguration->getName());
$this->assertEquals($this->dbData['is_active'], $providerConfiguration->isActive());
$this->assertEquals($this->dbData['is_forced'], $providerConfiguration->isForced());
}
/**
* Tests model is properly created
*/
public function testCreateFromResponseWithMissingProperty(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage("Missing mandatory parameter: 'is_forced'");
$dbData = array_slice($this->dbData, 0, 4, true);
ProviderConfigurationFactoryRdb::create($dbData);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/www/class/CentreonDBTest.php | centreon/tests/php/www/class/CentreonDBTest.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\www\class;
use Adaptation\Database\Connection\Collection\BatchInsertParameters;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\Model\ConnectionConfig;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Adaptation\Database\ExpressionBuilder\Adapter\Dbal\DbalExpressionBuilderAdapter;
use Adaptation\Database\ExpressionBuilder\ExpressionBuilderInterface;
use Adaptation\Database\QueryBuilder\Adapter\Dbal\DbalQueryBuilderAdapter;
use Adaptation\Database\QueryBuilder\QueryBuilderInterface;
use CentreonDB;
use CentreonDbException;
use CentreonDBStatement;
use PDO;
use PDOStatement;
/**
* @param string $nameEnvVar
*
* @return string|null
*/
function getEnvironmentVariable(string $nameEnvVar): ?string
{
$envVarValue = getenv($nameEnvVar, true) ?: getenv($nameEnvVar);
return (is_string($envVarValue) && ! empty($envVarValue)) ? $envVarValue : null;
}
$dbHost = getEnvironmentVariable('MYSQL_HOST');
$dbUser = getEnvironmentVariable('MYSQL_USER');
$dbPassword = getEnvironmentVariable('MYSQL_PASSWORD');
$dbConfigCentreon = null;
$dbConfigCentreonStorage = null;
if (! is_null($dbHost) && ! is_null($dbUser) && ! is_null($dbPassword)) {
$dbConfigCentreon = new ConnectionConfig(
host: $dbHost,
user: $dbUser,
password: $dbPassword,
databaseNameConfiguration: 'centreon',
databaseNameRealTime: 'centreon_storage',
port: 3306
);
$dbConfigCentreonStorage = new ConnectionConfig(
host: $dbHost,
user: $dbUser,
password: $dbPassword,
databaseNameConfiguration: 'centreon_storage',
databaseNameRealTime: 'centreon_storage',
port: 3306
);
}
/**
* @param ConnectionConfig $connectionConfig
*
* @return bool
*/
function hasConnectionDb(ConnectionConfig $connectionConfig): bool
{
try {
new PDO(
$connectionConfig->getMysqlDsn(),
$connectionConfig->getUser(),
$connectionConfig->getPassword(),
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
return true;
} catch (\PDOException $e) {
return false;
}
}
// ************************************** With centreon database connection *******************************************
if (! is_null($dbConfigCentreon) && hasConnectionDb($dbConfigCentreon)) {
it(
'connect to centreon database with CentreonDB constructor',
function () use ($dbConfigCentreon): void {
$db = new CentreonDB(dbLabel: CentreonDB::LABEL_DB_CONFIGURATION, connectionConfig: $dbConfigCentreon);
expect($db)->toBeInstanceOf(CentreonDB::class);
$stmt = $db->prepare('select database()');
$stmt->execute();
$dbName = $stmt->fetchColumn();
expect($dbName)->toBe('centreon')
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it(
'connect to centreon database with CentreonDB::connectToCentreonDb factory',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
expect($db)->toBeInstanceOf(CentreonDB::class);
$stmt = $db->prepare('select database()');
$stmt->execute();
$dbName = $stmt->fetchColumn();
expect($dbName)->toBe('centreon')
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it(
'CentreonDB::createFromConfig factory with centreon database',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::createFromConfig($dbConfigCentreon);
expect($db)->toBeInstanceOf(CentreonDB::class);
/** @var CentreonDB $db */
$stmt = $db->prepare('select database()');
$stmt->execute();
$dbName = $stmt->fetchColumn();
expect($dbName)->toBe('centreon')
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it(
'create query builder with success',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$queryBuilder = $db->createQueryBuilder();
expect($queryBuilder)
->toBeInstanceOf(QueryBuilderInterface::class)
->toBeInstanceOf(DbalQueryBuilderAdapter::class);
}
);
it(
'create expression builder with success',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$expressionBuilder = $db->createExpressionBuilder();
expect($expressionBuilder)
->toBeInstanceOf(ExpressionBuilderInterface::class)
->toBeInstanceOf(DbalExpressionBuilderAdapter::class);
}
);
it(
'get connection config',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$connectionConfig = $db->getConnectionConfig();
expect($connectionConfig)->toBeInstanceOf(ConnectionConfig::class)
->and($connectionConfig->getHost())->toBe($dbConfigCentreon->getHost())
->and($connectionConfig->getUser())->toBe($dbConfigCentreon->getUser())
->and($connectionConfig->getPassword())->toBe($dbConfigCentreon->getPassword())
->and($connectionConfig->getDatabaseNameConfiguration())->toBe($dbConfigCentreon->getDatabaseNameConfiguration())
->and($connectionConfig->getPort())->toBe($dbConfigCentreon->getPort());
}
);
it('get the database name of the current connection', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$dbName = $db->getDatabaseName();
expect($dbName)->toBe('centreon');
});
it('get native connection', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
/** @var PDO $pdo */
$pdo = $db->getNativeConnection();
expect($pdo)->toBeInstanceOf(PDO::class);
});
it('get last insert id', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$insert = $db->exec(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($insert)->toBeInt()->toBe(1);
$lastInsertId = $db->getLastInsertId();
expect($lastInsertId)->toBeString()->toBe('110');
// clean up the database
$delete = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($delete)->toBeInt()->toBe(1);
});
it('is connected', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
expect($db->isConnected())->toBeTrue();
});
it('quote string', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$quotedString = $db->quote('foo');
expect($quotedString)->toBeString()->toBe("'foo'");
});
// --------------------------------------- CUD METHODS -----------------------------------------
// -- executeStatement()
it(
'execute statement with a correct query without query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$inserted = $db->executeStatement(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($inserted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it(
'execute statement with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $db->executeStatement(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it(
'execute statement with a correct query with query parameters with ":" before keys',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int(':id', 110),
QueryParameter::string(':name', 'foo_name'),
QueryParameter::string(':alias', 'foo_alias'),
]
);
$inserted = $db->executeStatement(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it('execute statement with a SELECT query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->executeStatement('SELECT * FROM contact');
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('execute statement with an empty query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->executeStatement('');
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('execute statement with an incorrect query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->executeStatement('foo');
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it(
'execute statement with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
]
);
$db->executeStatement(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
)->throws(ConnectionException::class);
// -- insert()
it(
'insert with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $db->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($deleted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it('insert with a SELECT query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->insert(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('contact_id', 110)])
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('insert with an empty query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->insert('', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('insert with an incorrect query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->insert('foo', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it(
'insert with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
]
);
$db->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
)->throws(ConnectionException::class);
// -- batchInsert()
it(
'batch insert with a correct query with batch query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$batchQueryParameters = BatchInsertParameters::create([
QueryParameters::create([
QueryParameter::int('contact_id', 110),
QueryParameter::string('contact_name', 'foo_name'),
QueryParameter::string('contact_alias', 'foo_alias'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 111),
QueryParameter::string('contact_name', 'bar_name'),
QueryParameter::string('contact_alias', 'bar_alias'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 112),
QueryParameter::string('contact_name', 'baz_name'),
QueryParameter::string('contact_alias', 'baz_alias'),
]),
]);
$inserted = $db->batchInsert(
'contact',
['contact_id', 'contact_name', 'contact_alias'],
$batchQueryParameters
);
expect($inserted)->toBeInt()->toBe(3)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
// clean up the database
$deleted = $db->exec('DELETE FROM contact WHERE contact_id IN (110,111,112)');
expect($deleted)->toBeInt()->toBe(3)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it(
'batch insert with a correct query with empty batch query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->batchInsert(
'contact',
['contact_id', 'contact_name', 'contact_alias'],
BatchInsertParameters::create([])
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
)->throws(ConnectionException::class);
it(
'batch insert with an incorrect batch query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$batchQueryParameters = BatchInsertParameters::create([
QueryParameters::create([
QueryParameter::int('contact_id', 110),
QueryParameter::string('contact_name', 'foo_name'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 111),
QueryParameter::string('contact_name', 'bar_name'),
]),
QueryParameters::create([
QueryParameter::int('contact_id', 112),
QueryParameter::string('contact_name', 'baz_name'),
]),
]);
$db->batchInsert(
'contact',
['contact_id', 'contact_name', 'contact_alias'],
$batchQueryParameters
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
)->throws(ConnectionException::class);
// -- update()
it(
'update with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$inserted = $db->executeStatement(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($inserted)->toBeInt()->toBe(1);
$queryParameters = QueryParameters::create(
[
QueryParameter::string('name', 'bar_name'),
QueryParameter::string('alias', 'bar_alias'),
QueryParameter::int('id', 110),
]
);
$updated = $db->update(
'UPDATE contact SET contact_name = :name, contact_alias = :alias WHERE contact_id = :id',
$queryParameters
);
expect($updated)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
// clean up the database
$delete = $db->exec('DELETE FROM contact WHERE contact_id = 110');
expect($delete)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it('update with a SELECT query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->update(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('contact_id', 110)])
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('update with an empty query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->update('', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('update with an incorrect query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->update('foo', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it(
'update with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::string('name', 'bar_name'),
QueryParameter::string('alias', 'bar_alias'),
]
);
$db->update(
'UPDATE contact SET contact_name = :name, contact_alias = :alias WHERE contact_id = :id',
$queryParameters
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
)->throws(ConnectionException::class);
// -- delete()
it(
'delete with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$inserted = $db->executeStatement(
"INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(110, 'foo_name', 'foo_alias')"
);
expect($inserted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
$queryParameters = QueryParameters::create([QueryParameter::int('id', 110)]);
$deleted = $db->delete('DELETE FROM contact WHERE contact_id = :id', $queryParameters);
expect($deleted)->toBeInt()->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it('delete with a SELECT query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->delete(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('contact_id', 110)])
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('delete with an empty query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->delete('', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('delete with an incorrect query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->delete('foo', QueryParameters::create([QueryParameter::int('contact_id', 110)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it(
'delete with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$queryParameters = QueryParameters::create(
[
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$db->delete(
'DELETE FROM contact WHERE contact_id = :id AND contact_name = :name AND contact_alias = :alias',
$queryParameters
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
)->throws(ConnectionException::class);
// ---------------------------------------- FETCH METHODS ----------------------------------------------
// -- fetchNumeric()
it(
'fetchNumeric with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$contact = $db->fetchNumeric(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it('fetchNumeric with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$contact = $db->fetchNumeric(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($contact)->toBeArray()
->and($contact[0])->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
});
it('fetchNumeric with a CUD query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->fetchNumeric(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('fetchNumeric with an empty query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->fetchNumeric('', QueryParameters::create([QueryParameter::int('id', 1)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('fetchNumeric with an incorrect query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->fetchNumeric('foo', QueryParameters::create([QueryParameter::int('id', 1)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it(
'fetchNumeric with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->fetchNumeric(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::string('name', 'foo_name')])
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
)->throws(ConnectionException::class);
// -- fetchAssociative()
it(
'fetchAssociative with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$contact = $db->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($contact)->toBeArray()
->and($contact['contact_id'])->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
);
it('fetchAssociative with a correct query with query parameters with ":" before keys', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$contact = $db->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int(':id', 1)])
);
expect($contact)->toBeArray()
->and($contact['contact_id'])->toBe(1)
->and($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
});
it('fetchAssociative with a CUD query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->fetchAssociative(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('fetchAssociative with an empty query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->fetchAssociative('', QueryParameters::create([QueryParameter::int('id', 1)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it('fetchAssociative with an incorrect query', function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->fetchAssociative('foo', QueryParameters::create([QueryParameter::int('id', 1)]));
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
})->throws(ConnectionException::class);
it(
'fetchAssociative with an incorrect query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$db->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::string('name', 'foo_name')])
);
expect($db->getAttribute(PDO::ATTR_STATEMENT_CLASS)[0])->toBe(CentreonDBStatement::class);
}
)->throws(ConnectionException::class);
// -- fetchOne()
it(
'fetchOne with a correct query with query parameters',
function () use ($dbConfigCentreon): void {
$db = CentreonDB::connectToCentreonDb($dbConfigCentreon);
$alias = $db->fetchOne(
'SELECT contact_alias FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 1)])
);
expect($alias)->toBeString()->toBe('admin')
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/www/class/CentreonLogTest.php | centreon/tests/php/www/class/CentreonLogTest.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
*
*/
/*
* Example :
* [2024-08-08T12:20:05+02:00] ERROR : Error while getting widget preferences for the host monitoring custom view |
* {"custom":{"widget_id":1},"exception":{"exception_type":"Exception","file":"/usr/share/centreon/
* www/widgets/host-monitoring/src/index.php","line":97,"code":0,"message":"test message","previous":null},"default":
* {"request_infos":{"uri":"/centreon/widgets/host-monitoring/src/index.php?widgetId=1&page=0","http_method":"GET","server":"localhost"}}
*/
beforeEach(function (): void {
if (! file_exists(__DIR__ . '/log')) {
mkdir(__DIR__ . '/log');
}
$this->centreonLogTest = new stdClass();
$this->centreonLogTest->date = (new DateTime())->format('Y-m-d\T');
$this->centreonLogTest->pathToLogTest = __DIR__ . '/log';
$this->centreonLogTest->loggerTest = new CentreonLog(
customLogFiles: [99 => 'custom.log'],
pathLogFile: $this->centreonLogTest->pathToLogTest
);
});
afterEach(function (): void {
if (file_exists($this->centreonLogTest->pathToLogTest)) {
$files = glob($this->centreonLogTest->pathToLogTest);
foreach ($files as $file) {
if (is_file($file)) {
expect(unlink($file))->toBeTrue();
}
}
$successDeleteFile = rmdir($this->centreonLogTest->pathToLogTest);
expect($successDeleteFile)->toBeTrue();
}
});
it('test contructor arguments of CentreonLog', function (): void {
$loggerTest = new CentreonLog([99 => 'custom.log'], __DIR__ . '/log');
expect($loggerTest->getLogFileHandler())->toEqual(
[
CentreonLog::TYPE_LOGIN => __DIR__ . '/log/login.log',
CentreonLog::TYPE_SQL => __DIR__ . '/log/sql-error.log',
CentreonLog::TYPE_LDAP => __DIR__ . '/log/ldap.log',
CentreonLog::TYPE_UPGRADE => __DIR__ . '/log/upgrade.log',
CentreonLog::TYPE_PLUGIN_PACK_MANAGER => __DIR__ . '/log/plugin-pack-manager.log',
CentreonLog::TYPE_BUSINESS_LOG => __DIR__ . '/log/centreon-web.log',
99 => __DIR__ . '/log/custom.log',
]
);
});
it('test changing the path of an existing log', function (): void {
$loggerTest = new CentreonLog();
$loggerTest->setPathLogFile('/user/test')
->pushLogFileHandler(CentreonLog::TYPE_LOGIN, 'login.log')
->pushLogFileHandler(CentreonLog::TYPE_SQL, 'sql.log')
->pushLogFileHandler(CentreonLog::TYPE_LDAP, 'ldap.log')
->pushLogFileHandler(CentreonLog::TYPE_UPGRADE, 'upgrade.log')
->pushLogFileHandler(CentreonLog::TYPE_PLUGIN_PACK_MANAGER, 'plugin.log')
->pushLogFileHandler(CentreonLog::TYPE_BUSINESS_LOG, 'centreon-web.log');
expect($loggerTest->getLogFileHandler())->toEqual(
[
CentreonLog::TYPE_LOGIN => '/user/test/login.log',
CentreonLog::TYPE_SQL => '/user/test/sql.log',
CentreonLog::TYPE_LDAP => '/user/test/ldap.log',
CentreonLog::TYPE_UPGRADE => '/user/test/upgrade.log',
CentreonLog::TYPE_PLUGIN_PACK_MANAGER => '/user/test/plugin.log',
CentreonLog::TYPE_BUSINESS_LOG => '/user/test/centreon-web.log',
]
);
});
it('test adding custom log', function (): void {
$loggerTest = new CentreonLog();
$loggerTest->setPathLogFile('/user/test')
->pushLogFileHandler(99, 'custom.log');
expect($loggerTest->getLogFileHandler())->toHaveKey(99, '/user/test/custom.log');
});
it('test log file handler is correct', function (): void {
expect($this->centreonLogTest->loggerTest->getLogFileHandler())->toEqual(
[
CentreonLog::TYPE_LOGIN => __DIR__ . '/log/login.log',
CentreonLog::TYPE_SQL => __DIR__ . '/log/sql-error.log',
CentreonLog::TYPE_LDAP => __DIR__ . '/log/ldap.log',
CentreonLog::TYPE_UPGRADE => __DIR__ . '/log/upgrade.log',
CentreonLog::TYPE_PLUGIN_PACK_MANAGER => __DIR__ . '/log/plugin-pack-manager.log',
99 => __DIR__ . '/log/custom.log',
CentreonLog::TYPE_BUSINESS_LOG => __DIR__ . '/log/centreon-web.log',
]
);
});
it('test writing the log to the login file', function (): void {
$logfile = $this->centreonLogTest->pathToLogTest . '/login.log';
$this->centreonLogTest->loggerTest
->log(CentreonLog::TYPE_LOGIN, CentreonLog::LEVEL_ERROR, 'login_message');
testContentLogWithoutContext(
'error',
$logfile,
$this->centreonLogTest->date,
'login_message',
(__LINE__ - 6)
);
});
it('test writing the log to the sql file', function (): void {
$logfile = $this->centreonLogTest->pathToLogTest . '/sql-error.log';
$this->centreonLogTest->loggerTest
->log(CentreonLog::TYPE_SQL, CentreonLog::LEVEL_ERROR, 'sql_message');
testContentLogWithoutContext(
'error',
$logfile,
$this->centreonLogTest->date,
'sql_message',
(__LINE__ - 6)
);
});
it('test writing the log to the ldap file', function (): void {
$logfile = $this->centreonLogTest->pathToLogTest . '/ldap.log';
$this->centreonLogTest->loggerTest
->log(CentreonLog::TYPE_LDAP, CentreonLog::LEVEL_ERROR, 'ldap_message');
testContentLogWithoutContext(
'error',
$logfile,
$this->centreonLogTest->date,
'ldap_message',
(__LINE__ - 6)
);
});
it('test writing the log to the upgrade file', function (): void {
$logfile = $this->centreonLogTest->pathToLogTest . '/upgrade.log';
$this->centreonLogTest->loggerTest
->log(CentreonLog::TYPE_UPGRADE, CentreonLog::LEVEL_ERROR, 'upgrade_message');
testContentLogWithoutContext(
'error',
$logfile,
$this->centreonLogTest->date,
'upgrade_message',
(__LINE__ - 6)
);
});
it('test writing the log to the plugin pack manager file', function (): void {
$logfile = $this->centreonLogTest->pathToLogTest . '/plugin-pack-manager.log';
$this->centreonLogTest->loggerTest
->log(CentreonLog::TYPE_PLUGIN_PACK_MANAGER, CentreonLog::LEVEL_ERROR, 'plugin_message');
testContentLogWithoutContext(
'error',
$logfile,
$this->centreonLogTest->date,
'plugin_message',
(__LINE__ - 6)
);
});
it('test writing the log to the custom log file', function (): void {
$logfile = $this->centreonLogTest->pathToLogTest . '/custom.log';
$this->centreonLogTest->loggerTest->log(99, CentreonLog::LEVEL_ERROR, 'custom_message');
testContentLogWithoutContext(
'error',
$logfile,
$this->centreonLogTest->date,
'custom_message',
(__LINE__ - 6)
);
});
it('test writing logs with all levels', function (): void {
$logfile = $this->centreonLogTest->pathToLogTest . '/login.log';
$this->centreonLogTest->loggerTest->notice(CentreonLog::TYPE_LOGIN, 'login_message');
testContentLogWithoutContext(
'notice',
$logfile,
$this->centreonLogTest->date,
'login_message',
(__LINE__ - 6)
);
$this->centreonLogTest->loggerTest->info(CentreonLog::TYPE_LOGIN, 'login_message');
testContentLogWithoutContext(
'info',
$logfile,
$this->centreonLogTest->date,
'login_message',
(__LINE__ - 6)
);
$this->centreonLogTest->loggerTest->warning(CentreonLog::TYPE_LOGIN, 'login_message');
testContentLogWithoutContext(
'warning',
$logfile,
$this->centreonLogTest->date,
'login_message',
(__LINE__ - 6)
);
$this->centreonLogTest->loggerTest->error(CentreonLog::TYPE_LOGIN, 'login_message');
testContentLogWithoutContext(
'error',
$logfile,
$this->centreonLogTest->date,
'login_message',
(__LINE__ - 6)
);
$this->centreonLogTest->loggerTest->critical(CentreonLog::TYPE_LOGIN, 'login_message');
testContentLogWithoutContext(
'critical',
$logfile,
$this->centreonLogTest->date,
'login_message',
(__LINE__ - 6)
);
$this->centreonLogTest->loggerTest->alert(CentreonLog::TYPE_LOGIN, 'login_message');
testContentLogWithoutContext(
'alert',
$logfile,
$this->centreonLogTest->date,
'login_message',
(__LINE__ - 6)
);
$this->centreonLogTest->loggerTest->emergency(CentreonLog::TYPE_LOGIN, 'login_message');
testContentLogWithoutContext(
'emergency',
$logfile,
$this->centreonLogTest->date,
'login_message',
(__LINE__ - 6)
);
});
it('test writing logs with a custom context', function (): void {
$logfile = $this->centreonLogTest->pathToLogTest . '/login.log';
$this->centreonLogTest->loggerTest
->notice(CentreonLog::TYPE_LOGIN, 'login_message', ['custom_value1' => 'foo', 'custom_value2' => 'bar']);
expect(file_exists($logfile))->toBeTrue();
$contentLog = file_get_contents($logfile);
expect($contentLog)->toBeString()->toContain(
"[{$this->centreonLogTest->date}",
'] NOTICE : login_message | {"custom":{"custom_value1":"foo","custom_value2":"bar"},"exception":null,"default":'
. '{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
$successDeleteFile = unlink($logfile);
expect($successDeleteFile)->toBeTrue();
});
it('test writing logs with a custom context and an exception', function (): void {
try {
throw new RuntimeException('test_message_exception', 99);
} catch (RuntimeException $e) {
$logfile = $this->centreonLogTest->pathToLogTest . '/login.log';
$this->centreonLogTest->loggerTest
->notice(CentreonLog::TYPE_LOGIN, 'login_message', ['custom_value1' => 'foo'], $e);
expect(file_exists($logfile))->toBeTrue();
$contentLog = file_get_contents($logfile);
expect($contentLog)->toBeString()->toContain(
sprintf(
'] NOTICE : login_message | {"custom":{"custom_value1":"foo"},"exception":{"exceptions":'
. '[{"type":"%s","message":"%s","file":"%s","line":%s,"code":%s,"class":"%s","method":"%s"}],'
. '"traces":[{"',
'RuntimeException',
'test_message_exception',
$e->getFile(),
$e->getLine(),
99,
'P\\\\Tests\\\\php\\\\www\\\\class\\\\CentreonLogTest',
'{closure}'
),
'"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
$successDeleteFile = unlink($logfile);
expect($successDeleteFile)->toBeTrue();
}
});
it('test writing logs with a custom context and a native exception with a previous (native exception)', function (): void {
try {
$previous = new LogicException('test_message_exception_previous', 98);
throw new RuntimeException('test_message_exception', 99, $previous);
} catch (RuntimeException $e) {
$logfile = $this->centreonLogTest->pathToLogTest . '/login.log';
$this->centreonLogTest->loggerTest
->notice(CentreonLog::TYPE_LOGIN, 'login_message', ['custom_value1' => 'foo'], $e);
expect(file_exists($logfile))->toBeTrue();
$contentLog = file_get_contents($logfile);
expect($contentLog)->toBeString()->toContain(
sprintf(
'] NOTICE : login_message | {"custom":{"custom_value1":"foo"},'
. '"exception":{"exceptions":[{"type":"%s","message":"%s","file":"%s","line":%s,"code":%s,"class":"%s","method":"%s"},'
. '{"type":"%s","message":"%s","file":"%s","line":%s,"code":%s,"class":"%s","method":"%s"}],'
. '"traces":[{"',
'RuntimeException',
'test_message_exception',
$e->getFile(),
$e->getLine(),
99,
'P\\\\Tests\\\\php\\\\www\\\\class\\\\CentreonLogTest',
'{closure}',
'LogicException',
'test_message_exception_previous',
$e->getPrevious()->getFile(),
$e->getPrevious()->getLine(),
98,
'P\\\\Tests\\\\php\\\\www\\\\class\\\\CentreonLogTest',
'{closure}'
),
'"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}',
);
$successDeleteFile = unlink($logfile);
expect($successDeleteFile)->toBeTrue();
}
});
it('test writing logs with a custom context and an exception (BusinessLogicException with context) with a previous exception (native exception)', function (): void {
try {
$previous = new LogicException('test_message_exception_previous', 99);
throw new CentreonDbException('test_message_exception', ['contact' => 1], $previous);
} catch (CentreonDbException $e) {
$logfile = $this->centreonLogTest->pathToLogTest . '/login.log';
$this->centreonLogTest->loggerTest
->notice(CentreonLog::TYPE_LOGIN, 'login_message', ['custom_value1' => 'foo'], $e);
expect(file_exists($logfile))->toBeTrue();
$contentLog = file_get_contents($logfile);
expect($contentLog)->toBeString()->toContain(
sprintf(
'] NOTICE : login_message | {"custom":{"custom_value1":"foo","from_exception":[{"contact":1}]},'
. '"exception":{"exceptions":[{"type":"%s","message":"%s","file":"%s","line":%s,"code":%s,"class":"%s","method":"%s"},'
. '{"type":"%s","message":"%s","file":"%s","line":%s,"code":%s,"class":"%s","method":"%s"}],'
. '"traces":[{"',
'CentreonDbException',
'test_message_exception',
$e->getFile(),
$e->getLine(),
1,
'P\\\\Tests\\\\php\\\\www\\\\class\\\\CentreonLogTest',
'{closure}',
'LogicException',
'test_message_exception_previous',
$e->getPrevious()->getFile(),
$e->getPrevious()->getLine(),
99,
'P\\\\Tests\\\\php\\\\www\\\\class\\\\CentreonLogTest',
'{closure}'
),
'"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}',
);
$successDeleteFile = unlink($logfile);
expect($successDeleteFile)->toBeTrue();
}
});
it('test writing logs with a custom context and an exception (BusinessLogicException with context) with a previous exception (BusinessLogicException with context) which have a native exception as previous', function (): void {
try {
$nativePrevious = new LogicException('test_message_native_exception_previous', 99);
$previous = new CentreonDbException('test_message_exception_previous', ['id' => 1, 'name' => 'John', 'age' => 48], $nativePrevious);
throw new StatisticException('test_message_exception', ['X' => 100.36, 'Y' => 888, 'graph' => true], $previous);
} catch (StatisticException $e) {
$logfile = $this->centreonLogTest->pathToLogTest . '/login.log';
$this->centreonLogTest->loggerTest
->notice(CentreonLog::TYPE_LOGIN, 'login_message', ['custom_value1' => 'foo', 'custom_value2' => 'bar'], $e);
expect(file_exists($logfile))->toBeTrue();
$contentLog = file_get_contents($logfile);
expect($contentLog)->toBeString()->toContain(
sprintf(
'] NOTICE : login_message | {"custom":{"custom_value1":"foo","custom_value2":"bar","from_exception":'
. '[{"X":100.36,"Y":888,"graph":true},{"id":1,"name":"John","age":48}]},'
. '"exception":{"exceptions":[{"type":"%s","message":"%s","file":"%s","line":%s,"code":%s,"class":"%s","method":"%s"},'
. '{"type":"%s","message":"%s","file":"%s","line":%s,"code":%s,"class":"%s","method":"%s"},'
. '{"type":"%s","message":"%s","file":"%s","line":%s,"code":%s,"class":"%s","method":"%s"}],'
. '"traces":[{"',
'StatisticException',
'test_message_exception',
$e->getFile(),
$e->getLine(),
0,
'P\\\\Tests\\\\php\\\\www\\\\class\\\\CentreonLogTest',
'{closure}',
'CentreonDbException',
'test_message_exception_previous',
$e->getPrevious()->getFile(),
$e->getPrevious()->getLine(),
1,
'P\\\\Tests\\\\php\\\\www\\\\class\\\\CentreonLogTest',
'{closure}',
'LogicException',
'test_message_native_exception_previous',
$e->getPrevious()->getPrevious()->getFile(),
$e->getPrevious()->getPrevious()->getLine(),
99,
'P\\\\Tests\\\\php\\\\www\\\\class\\\\CentreonLogTest',
'{closure}'
),
'"default":{"request_infos":{"uri":null,"http_method":null,"server":null}}',
);
$successDeleteFile = unlink($logfile);
expect($successDeleteFile)->toBeTrue();
}
});
/**
* @param string $level
* @param string $logfile
* @param string $date
* @param string $message
* @param int $line
*
* @return void
*/
function testContentLogWithoutContext(
string $level,
string $logfile,
string $date,
string $message,
int $line,
): void {
expect(file_exists($logfile))->toBeTrue();
$contentLog = file_get_contents($logfile);
expect($contentLog)->toBeString()->toContain(
"[{$date}",
'] ' . strtoupper($level) . ' : ' . $message . ' | {"custom":null,"exception":null,"default":'
. '{"request_infos":{"uri":null,"http_method":null,"server":null}}}'
);
$successDeleteFile = unlink($logfile);
expect($successDeleteFile)->toBeTrue();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/www/class/service/HtmlSanitizerTest.php | centreon/tests/php/www/class/service/HtmlSanitizerTest.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
*
*/
it('test factory used for HtmlSanitizer', function (): void {
$string = 'I am a <div><span>king</span></div>';
$htmlSanitizer = HtmlSanitizer::createFromString($string);
expect($htmlSanitizer)->toBeInstanceOf(HtmlSanitizer::class)
->and($htmlSanitizer->getString())->toBeString()
->and($htmlSanitizer->getString())->toEqual($string);
});
it('test sanitize of a string with html by HtmlSanitizer', function (): void {
$string = 'I am a <div><span>king</span></div>';
$stringTest = 'I am a <div><span>king</span></div>';
$htmlSanitizer = HtmlSanitizer::createFromString($string)->sanitize();
expect($htmlSanitizer->getString())->toBeString()
->and($htmlSanitizer->getString())->toEqual($stringTest);
});
it('test remove html tags of a string with html by HtmlSanitizer', function (): void {
$string = 'I am a <div><span>king</span></div>';
$stringTest = 'I am a king';
$htmlSanitizer = HtmlSanitizer::createFromString($string)->removeTags();
expect($htmlSanitizer->getString())->toBeString()
->and($htmlSanitizer->getString())->toEqual($stringTest);
});
it('test remove html tags of a string with html without remove allowed tags by HtmlSanitizer', function (): void {
$string = 'I am a <div><span>king</span></div>';
$stringTest = 'I am a <span>king</span>';
$htmlSanitizer = HtmlSanitizer::createFromString($string)->removeTags(['span']);
expect($htmlSanitizer->getString())->toBeString()
->and($htmlSanitizer->getString())->toEqual($stringTest);
});
it('test remove html tags of a string with html without remove several allowed tags by HtmlSanitizer', function (): void {
$string = 'I am a <div><span><i>king</i></span></div>';
$stringTest = 'I am a <span><i>king</i></span>';
$htmlSanitizer = HtmlSanitizer::createFromString($string)->removeTags(['span', 'i']);
expect($htmlSanitizer->getString())->toBeString()
->and($htmlSanitizer->getString())->toEqual($stringTest);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/www/install/functionsTest.php | centreon/tests/php/www/install/functionsTest.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\Www\Install\Steps;
$fileInstallFunctions = __DIR__ . '/../../../../www/install/functions.php';
// patch to fix an error when we run pest tests because install folder is deleted after installation in container
if (file_exists($fileInstallFunctions)) {
require_once __DIR__ . '/../../../../www/install/functions.php';
it('generates random password with lowercase, uppercase, number and special character', function (): void {
$password = generatePassword();
expect($password)->toHaveLength(12)
->and($password)->toMatch('/[0-9]+/')
->and($password)->toMatch('/[a-z]+/')
->and($password)->toMatch('/[A-Z]+/')
->and($password)->toMatch('/[@$!%*?&]+/');
});
} else {
it("tests of /www/install/functions.php skiped because install folder doesn't exist");
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/GPL_LIB/smarty-plugins/compiler.pagination.php | centreon/GPL_LIB/smarty-plugins/compiler.pagination.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
*
*/
/**
* This plugin is a wrapper around the legacy commonly included file `include/common/pagination.php`
* which displays a pagination bar in the legacy pages before + after the tables.
*
* Usage: <pre>
* {pagination}
* </pre>
*/
class Smarty_Compiler_Pagination extends Smarty_Internal_CompileBase
{
/**
* @param array<mixed> $args
* @param Smarty_Internal_TemplateCompilerBase $compiler
*
* @return string
*/
public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler): string
{
return "<?php include('./include/common/pagination.php'); ?>";
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/GPL_LIB/smarty-plugins/compiler.displaysvg.php | centreon/GPL_LIB/smarty-plugins/compiler.displaysvg.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
*
*/
/**
* This plugin is a wrapper around the function {@see displaySvg()}
* which cannot be called directly from the templates.
*
* Usage: <pre>
* {displaysvg svgPath='SVG-PATH' color='#COLOR' height=200.0 width=300.0}
* </pre>
*/
class Smarty_Compiler_Displaysvg extends Smarty_Internal_CompileBase
{
/**
* @param array<array{ svgPath?: string, color?: string, height?: string, width?: string }> $args
* @param Smarty_Internal_TemplateCompilerBase $compiler
*
* @return string
*/
public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler): string
{
$svgPath = var_export($this->getArg($args, 'svgPath'), true);
$color = var_export($this->getArg($args, 'color'), true);
$height = var_export((float) $this->getArg($args, 'height'), true);
$width = var_export((float) $this->getArg($args, 'width'), true);
return "<?php displaySvg({$svgPath}, {$color}, {$height}, {$width}); ?>";
}
/**
* @param array<array<string, string>> $args
* @param string $name
*
* @return string
*/
private function getArg(array $args, string $name): string
{
foreach ($args as $arg) {
if (isset($arg[$name])) {
return preg_match('#^"(.*)"$#', $arg[$name], $matches)
|| preg_match('#^\'(.*)\'$#', $arg[$name], $matches)
? $matches[1] : $arg[$name];
}
}
throw new Exception("Missing {$name} argument");
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/GPL_LIB/smarty-plugins/function.eval.php | centreon/GPL_LIB/smarty-plugins/function.eval.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
*
*/
/**
* Smarty eval function.
*
* @param array $params
* @param Smarty $smarty
*
* @throws SmartyException
*
* @return false|string|void
*/
function smarty_function_eval($params, &$smarty)
{
if (! isset($params['var'])) {
$smarty->trigger_error("eval: missing 'var' parameter");
return;
}
if ($params['var'] === '') {
return;
}
return $smarty->fetch('eval:' . $params['var']);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/GPL_LIB/smarty-plugins/SmartyBC.php | centreon/GPL_LIB/smarty-plugins/SmartyBC.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
*
*/
/**
* This class is a pure copy/paste from the Smarty v3 codebase.
*
* It was deprecated in v3, but removed in v4, then we needed to reintroduce it to avoid
* breaking the legacy everywhere.
*
* This class was created by smarty in september 2011 : we need to get rid of it asap !
*
* "BC" stands for "Backward Compatibility".
*
* @see Smarty_Compiler_Php
*/
class SmartyBC extends Smarty
{
/** @var array<callable-string> */
private const SMARTY_V3_DEPRECATED_PHP_MODIFIERS = [
'count',
'sizeof',
'in_array',
'is_array',
'time',
'urlencode',
'rawurlencode',
'json_encode',
'strtotime',
'number_format',
];
/**
* Forbidden tags in Smarty templates.
*/
private const FORBIDDEN_TAGS = ['extends'];
/**
* Smarty 2 BC.
*
* @var string
*/
public $_version = self::SMARTY_VERSION;
/**
* This is an array of directories where trusted php scripts reside.
*
* @var array
*/
public $trusted_dir = [];
/**
* SmartyBC constructor
*
* @throws SmartyException
*/
public function __construct()
{
parent::__construct();
// Check if forbidden tags like 'extends' are used in templates, if yes a SmartyException is thrown.
$this->registerFilter('pre', [$this, 'checkForbiddenTags']);
// We need to explicitly define these plugins to avoid breaking a future smarty upgrade.
foreach (self::SMARTY_V3_DEPRECATED_PHP_MODIFIERS as $phpFunction) {
$this->registerPlugin(self::PLUGIN_MODIFIER, $phpFunction, $phpFunction);
}
}
/**
* Factory
*
* @param string|null $pathTemplate
* @param string|null $subDirTemplate
*
* @return SmartyBC
* @throws SmartyException
*/
public static function createSmartyTemplate(?string $pathTemplate = null, ?string $subDirTemplate = null): SmartyBC
{
try {
$template = new \SmartyBC();
$template->setTemplateDir($pathTemplate . ($subDirTemplate ?? ''));
$template->setCompileDir(__DIR__ . '/../SmartyCache/compile');
$template->setConfigDir(__DIR__ . '/../SmartyCache/config');
$template->setCacheDir(__DIR__ . '/../SmartyCache/cache');
$template->addPluginsDir(__DIR__ . '/../smarty-plugins');
$template->loadPlugin('smarty_function_eval');
$template->setForceCompile(true);
$template->setAutoLiteral(false);
$template->allow_ambiguous_resources = true;
return $template;
} catch (SmartyException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
"Smarty error while initializing smarty template : {$e->getMessage()}",
['path_template' => $pathTemplate, 'sub_directory_template' => $subDirTemplate],
$e
);
throw new SmartyException("Smarty error while initializing smarty template : {$e->getMessage()}");
}
}
/**
* wrapper for assign_by_ref.
*
* @param string $tpl_var the template variable name
* @param mixed &$value the referenced value to assign
*/
public function assign_by_ref($tpl_var, &$value): void
{
$this->assignByRef($tpl_var, $value);
}
/**
* wrapper for append_by_ref.
*
* @param string $tpl_var the template variable name
* @param mixed &$value the referenced value to append
* @param bool $merge flag if array elements shall be merged
*/
public function append_by_ref($tpl_var, &$value, $merge = false): void
{
$this->appendByRef($tpl_var, $value, $merge);
}
/**
* clear the given assigned template variable.
*
* @param string $tpl_var the template variable to clear
*/
public function clear_assign($tpl_var): void
{
$this->clearAssign($tpl_var);
}
/**
* Registers custom function to be used in templates.
*
* @param string $function the name of the template function
* @param string $function_impl the name of the PHP function to register
* @param bool $cacheable
* @param mixed $cache_attrs
*
* @throws SmartyException
*/
public function register_function($function, $function_impl, $cacheable = true, $cache_attrs = null): void
{
$this->registerPlugin('function', $function, $function_impl, $cacheable, $cache_attrs);
}
/**
* Unregister custom function.
*
* @param string $function name of template function
*/
public function unregister_function($function): void
{
$this->unregisterPlugin('function', $function);
}
/**
* Registers object to be used in templates.
*
* @param string $object name of template object
* @param object $object_impl the referenced PHP object to register
* @param array $allowed list of allowed methods (empty = all)
* @param bool $smarty_args smarty argument format, else traditional
* @param array $block_methods list of methods that are block format
*
* @throws SmartyException
*
* @internal param array $block_functs list of methods that are block format
*/
public function register_object(
$object,
$object_impl,
$allowed = [],
$smarty_args = true,
$block_methods = []
): void {
$allowed = (array) $allowed;
$smarty_args = (bool) $smarty_args;
$this->registerObject($object, $object_impl, $allowed, $smarty_args, $block_methods);
}
/**
* Unregister object.
*
* @param string $object name of template object
*/
public function unregister_object($object): void
{
$this->unregisterObject($object);
}
/**
* Registers block function to be used in templates.
*
* @param string $block name of template block
* @param string $block_impl PHP function to register
* @param bool $cacheable
* @param mixed $cache_attrs
*
* @throws SmartyException
*/
public function register_block($block, $block_impl, $cacheable = true, $cache_attrs = null): void
{
$this->registerPlugin('block', $block, $block_impl, $cacheable, $cache_attrs);
}
/**
* Unregister block function.
*
* @param string $block name of template function
*/
public function unregister_block($block): void
{
$this->unregisterPlugin('block', $block);
}
/**
* Registers compiler function.
*
* @param string $function name of template function
* @param string $function_impl name of PHP function to register
* @param bool $cacheable
*
* @throws SmartyException
*/
public function register_compiler_function($function, $function_impl, $cacheable = true): void
{
$this->registerPlugin('compiler', $function, $function_impl, $cacheable);
}
/**
* Unregister compiler function.
*
* @param string $function name of template function
*/
public function unregister_compiler_function($function): void
{
$this->unregisterPlugin('compiler', $function);
}
/**
* Registers modifier to be used in templates.
*
* @param string $modifier name of template modifier
* @param string $modifier_impl name of PHP function to register
*
* @throws SmartyException
*/
public function register_modifier($modifier, $modifier_impl): void
{
$this->registerPlugin('modifier', $modifier, $modifier_impl);
}
/**
* Unregister modifier.
*
* @param string $modifier name of template modifier
*/
public function unregister_modifier($modifier): void
{
$this->unregisterPlugin('modifier', $modifier);
}
/**
* Registers a resource to fetch a template.
*
* @param string $type name of resource
* @param array $functions array of functions to handle resource
*/
public function register_resource($type, $functions): void
{
$this->registerResource($type, $functions);
}
/**
* Unregister a resource.
*
* @param string $type name of resource
*/
public function unregister_resource($type): void
{
$this->unregisterResource($type);
}
/**
* Registers a prefilter function to apply
* to a template before compiling.
*
* @param callable $function
*
* @throws SmartyException
*/
public function register_prefilter($function): void
{
$this->registerFilter('pre', $function);
}
/**
* Unregister a prefilter function.
*
* @param callable $function
*/
public function unregister_prefilter($function): void
{
$this->unregisterFilter('pre', $function);
}
/**
* Registers a postfilter function to apply
* to a compiled template after compilation.
*
* @param callable $function
*
* @throws SmartyException
*/
public function register_postfilter($function): void
{
$this->registerFilter('post', $function);
}
/**
* Unregister a postfilter function.
*
* @param callable $function
*/
public function unregister_postfilter($function): void
{
$this->unregisterFilter('post', $function);
}
/**
* Registers an output filter function to apply
* to a template output.
*
* @param callable $function
*
* @throws SmartyException
*/
public function register_outputfilter($function): void
{
$this->registerFilter('output', $function);
}
/**
* Unregister an outputfilter function.
*
* @param callable $function
*/
public function unregister_outputfilter($function): void
{
$this->unregisterFilter('output', $function);
}
/**
* load a filter of specified type and name.
*
* @param string $type filter type
* @param string $name filter name
*
* @throws SmartyException
*/
public function load_filter($type, $name): void
{
$this->loadFilter($type, $name);
}
/**
* clear cached content for the given template and cache id.
*
* @param string $tpl_file name of template file
* @param string $cache_id name of cache_id
* @param string $compile_id name of compile_id
* @param string $exp_time expiration time
*
* @return bool
*/
public function clear_cache($tpl_file = null, $cache_id = null, $compile_id = null, $exp_time = null)
{
return $this->clearCache($tpl_file, $cache_id, $compile_id, $exp_time);
}
/**
* clear the entire contents of cache (all templates).
*
* @param string $exp_time expire time
*
* @return bool
*/
public function clear_all_cache($exp_time = null)
{
return $this->clearCache(null, null, null, $exp_time);
}
/**
* test to see if valid cache exists for this template.
*
* @param string $tpl_file name of template file
* @param string $cache_id
* @param string $compile_id
*
* @return bool
* @throws SmartyException
*
* @throws \Exception
*/
public function is_cached($tpl_file, $cache_id = null, $compile_id = null)
{
return $this->isCached($tpl_file, $cache_id, $compile_id);
}
/**
* clear all the assigned template variables.
*/
public function clear_all_assign(): void
{
$this->clearAllAssign();
}
/**
* clears compiled version of specified template resource,
* or all compiled template files if one is not specified.
* This function is for advanced use only, not normally needed.
*
* @param string $tpl_file
* @param string $compile_id
* @param string $exp_time
*
* @return bool results of {@link smarty_core_rm_auto()}
*/
public function clear_compiled_tpl($tpl_file = null, $compile_id = null, $exp_time = null)
{
return $this->clearCompiledTemplate($tpl_file, $compile_id, $exp_time);
}
/**
* Checks whether requested template exists.
*
* @param string $tpl_file
*
* @return bool
* @throws SmartyException
*
*/
public function template_exists($tpl_file)
{
return $this->templateExists($tpl_file);
}
/**
* Returns an array containing template variables.
*
* @param string $name
*
* @return array
*/
public function get_template_vars($name = null)
{
return $this->getTemplateVars($name);
}
/**
* Returns an array containing config variables.
*
* @param string $name
*
* @return array
*/
public function get_config_vars($name = null)
{
return $this->getConfigVars($name);
}
/**
* load configuration values.
*
* @param string $file
* @param string $section
* @param string $scope
*/
public function config_load($file, $section = null, $scope = 'global'): void
{
$this->ConfigLoad($file, $section, $scope);
}
/**
* return a reference to a registered object.
*
* @param string $name
*
* @return object
*/
public function get_registered_object($name)
{
return $this->getRegisteredObject($name);
}
/**
* clear configuration values.
*
* @param string $var
*/
public function clear_config($var = null): void
{
$this->clearConfig($var);
}
/**
* trigger Smarty error.
*
* @param string $error_msg
* @param int $error_type
*/
public function trigger_error($error_msg, $error_type = E_USER_WARNING): void
{
trigger_error("Smarty error: {$error_msg}", $error_type);
}
/**
* Display a Smarty template.
* Error handling is done here to avoid breaking the legacy.
* If an error occurs, a generic error message is displayed using the following template :
* www/include/common/templates/error.ihtml.
*
* @param string|null $template
* @param string|null $cache_id
* @param string|null $compile_id
* @param object|null $parent
*
* @return void
*/
public function display($template = null, $cache_id = null, $compile_id = null, $parent = null): void
{
try {
parent::display($template, $cache_id, $compile_id, $parent);
} catch (Throwable $e) {
CentreonLog::create()->critical(
CentreonLog::TYPE_BUSINESS_LOG,
"An error occurred while displaying the following template {$template} : {$e->getMessage()}",
['template_name' => $template, 'error_message' => $e->getMessage()],
$e
);
try {
$smartyErrorTpl = new Smarty();
$error = "An unexpected error occurred. Please try again later or contact your administrator.";
$smartyErrorTpl->assign('error', $error);
$smartyErrorTpl->display(__DIR__ . '/../../www/include/common/templates/error.ihtml');
} catch (Throwable $e) {
CentreonLog::create()->critical(
CentreonLog::TYPE_BUSINESS_LOG,
"An error occurred while displaying the error template : {$e->getMessage()}",
['error_message' => $e->getMessage()],
$e
);
}
}
}
/**
* Check if forbidden tags are used in templates. If yes, a SmartyException is thrown.
* Forbidden tags are defined in the $forbiddenTags array.
*
* @param string $source
*
* @return string
* @throws SmartyException
*/
public function checkForbiddenTags(string $source): string
{
foreach (self::FORBIDDEN_TAGS as $tag) {
if (preg_match('/\{' . $tag . '\b.*?}/', $source)) {
throw new SmartyException("The '{{$tag}}' tag is forbidden in templates.");
}
}
return $source;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/cron/downtimeManager.php | centreon/cron/downtimeManager.php | #!@PHP_BIN@
<?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
*
*/
define('_DELAY_', '600'); // Default 10 minutes
require_once realpath(__DIR__ . '/../config/centreon.config.php');
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonDowntime.Broker.class.php';
$unix_time = time();
$ext_cmd_add['host'] = ['[%u] SCHEDULE_HOST_DOWNTIME;%s;%u;%u;%u;0;%u;Downtime cycle;[Downtime cycle #%u]', '[%u] SCHEDULE_HOST_SVC_DOWNTIME;%s;%u;%u;%u;0;%u;Downtime cycle;[Downtime cycle #%u]'];
$ext_cmd_del['host'] = ['[%u] DEL_HOST_DOWNTIME;%u'];
$ext_cmd_add['svc'] = ['[%u] SCHEDULE_SVC_DOWNTIME;%s;%s;%u;%u;%u;0;%u;Downtime cycle;[Downtime cycle #%u]'];
$ext_cmd_del['svc'] = ['[%u] DEL_SVC_DOWNTIME;%u'];
// Connector to centreon DB
$pearDB = new CentreonDB();
$downtimeObj = new CentreonDowntimeBroker($pearDB, _CENTREON_VARLIB_);
// Get approaching downtimes
$downtimes = $downtimeObj->getApproachingDowntimes(_DELAY_);
foreach ($downtimes as $downtime) {
$isScheduled = $downtimeObj->isScheduled($downtime);
if (! $isScheduled && $downtime['dt_activate'] == '1') {
$downtimeObj->insertCache($downtime);
if ($downtime['service_id'] != '') {
foreach ($ext_cmd_add['svc'] as $cmd) {
$cmd = sprintf(
$cmd,
$unix_time,
$downtime['host_name'],
$downtime['service_description'],
$downtime['start_timestamp'],
$downtime['end_timestamp'],
$downtime['fixed'],
$downtime['duration'],
$downtime['dt_id']
);
$downtimeObj->setCommand($downtime['host_id'], $cmd);
}
} else {
foreach ($ext_cmd_add['host'] as $cmd) {
$cmd = sprintf(
$cmd,
$unix_time,
$downtime['host_name'],
$downtime['start_timestamp'],
$downtime['end_timestamp'],
$downtime['fixed'],
$downtime['duration'],
$downtime['dt_id']
);
$downtimeObj->setCommand($downtime['host_id'], $cmd);
}
}
} elseif ($isScheduled && $downtime['dt_activate'] == '0') {
if ($downtime['service_id'] != '') {
foreach ($ext_cmd_del['svc'] as $cmd) {
$cmd = sprintf(
$cmd,
$unix_time,
$downtime['dt_id']
);
$downtimeObj->setCommand($downtime['host_id'], $cmd);
}
} else {
foreach ($ext_cmd_del['host'] as $cmd) {
$cmd = sprintf(
$cmd,
$unix_time,
$downtime['dt_id']
);
$downtimeObj->setCommand($downtime['host_id'], $cmd);
}
}
}
}
// Send the external commands
$downtimeObj->sendCommands();
// Purge downtime cache
$downtimeObj->purgeCache();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/cron/centAcl.php | centreon/cron/centAcl.php | #!@PHP_BIN@
<?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
*
*/
require_once realpath(__DIR__ . '/../config/centreon.config.php');
include_once _CENTREON_PATH_ . '/cron/centAcl-Func.php';
include_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
include_once _CENTREON_PATH_ . '/www/class/centreonLDAP.class.php';
include_once _CENTREON_PATH_ . '/www/class/centreonMeta.class.php';
include_once _CENTREON_PATH_ . '/www/class/centreonContactgroup.class.php';
include_once _CENTREON_PATH_ . '/www/class/centreonLog.class.php';
$centreonDbName = $conf_centreon['db'];
$centreonLog = new CentreonLog();
// Define the period between two update in second for LDAP user/contactgroup
define('LDAP_UPDATE_PERIOD', 3600);
/**
* CentAcl script
*/
$nbProc = exec('ps -o args -p $(pidof -o $$ -o $PPID -o %PPID -x php || echo 1000000) | grep -c ' . __FILE__);
if ((int) $nbProc > 0) {
programExit('More than one centAcl.php process is currently running. Going to exit...');
}
ini_set('max_execution_time', 0);
try {
// Init values
$debug = 0;
// Init DB connections
$pearDB = new CentreonDB();
$pearDBO = new CentreonDB('centstorage');
$metaObj = new CentreonMeta($pearDB);
$cgObj = new CentreonContactgroup($pearDB);
// checking the state of the Cron
$data = getCentAclRunningState();
$beginTime = time();
if (empty($data)) {
try {
// at first run (eg: after the install), data may be missing.
$pearDB->query(
"INSERT INTO `cron_operation` (`name`, `system`, `activate`) VALUES ('centAcl.php', '1', '1')"
);
} catch (PDOException $e) {
programExit("Error can't insert centAcl values in the `cron_operation` table.");
}
$data = getCentAclRunningState();
$appId = (int) $data['id'] ?? 0;
$is_running = 0;
} else {
$is_running = $data['running'];
$appId = (int) $data['id'];
}
// Lock in MySQL (ie: by setting the `running` value to 1)
if ($is_running == 0) {
putALock($appId);
} else {
if ($nbProc <= 1) {
$errorMessage = 'According to DB another instance of centAcl.php is already running and I found '
. $nbProc . " process...\n";
$errorMessage .= 'Correcting the state in the DB, by setting the `running` value to 0 for id = ' . $appId;
removeLock($appId);
} else {
$errorMessage = 'centAcl marked as running. Exiting...';
}
programExit($errorMessage);
}
/**
* Sync ACL with LDAP's contactgroup
* If the LDAP is enabled and the last check is greater than the update period
*
* @TODO : Synchronize LDAP with contacts data in background to avoid it at login
*/
$ldapEnable = '0';
$ldapLastUpdate = 0;
$queryOptions = "SELECT `key`, `value` FROM `options` WHERE `key` IN ('ldap_auth_enable', 'ldap_last_acl_update')";
$res = $pearDB->query($queryOptions);
while ($row = $res->fetch()) {
switch ($row['key']) {
case 'ldap_auth_enable':
$ldapEnable = $row['value'];
break;
case 'ldap_last_acl_update':
$ldapLastUpdate = $row['value'];
break;
}
}
if ($ldapEnable === '1' && $ldapLastUpdate < (time() - LDAP_UPDATE_PERIOD)) {
$cgObj->syncWithLdap();
}
/**
* Check expected contact data sync on login with the LDAP, depending on last sync time and own sync interval
*/
$pearDB->beginTransaction();
try {
$ldapConf = $pearDB->query(
"SELECT auth.ar_id, auth.ar_sync_base_date, info.ari_value AS `interval`
FROM auth_ressource auth
INNER JOIN auth_ressource_info info ON auth.ar_id = info.ar_id
WHERE auth.ar_enable = '1' AND info.ari_name = 'ldap_sync_interval'"
);
$updateSyncTime = $pearDB->prepare(
'UPDATE auth_ressource SET ar_sync_base_date = :currentTime
WHERE ar_id = :arId'
);
$currentTime = time();
while ($ldapRow = $ldapConf->fetch()) {
if ($currentTime > ($ldapRow['ar_sync_base_date'] + 3600 * $ldapRow['interval'])) {
$updateSyncTime->bindValue(':currentTime', $currentTime, PDO::PARAM_INT);
$updateSyncTime->bindValue(':arId', (int) $ldapRow['ar_id'], PDO::PARAM_INT);
$updateSyncTime->execute();
}
}
$pearDB->commit();
} catch (PDOException $e) {
$pearDB->rollBack();
programExit("Error when updating LDAP's reference date for next synchronization");
}
/**
* Remove data from old groups (deleted groups)
*/
$aclGroupToDelete = 'SELECT DISTINCT acl_group_id
FROM `' . $centreonDbName . "`.acl_groups WHERE acl_group_activate = '1'";
$aclGroupToDelete2 = 'SELECT DISTINCT acl_group_id FROM `' . $centreonDbName . '`.acl_res_group_relations';
$pearDBO->beginTransaction();
try {
$pearDBO->query('DELETE FROM centreon_acl WHERE group_id NOT IN (' . $aclGroupToDelete . ')');
$pearDBO->query('DELETE FROM centreon_acl WHERE group_id NOT IN (' . $aclGroupToDelete2 . ')');
$pearDBO->commit();
} catch (PDOException $e) {
$pearDBO->rollBack();
$centreonLog->insertLog(
2,
'CentACL CRON: failed to delete old groups relations'
);
}
/**
* Check if some ACL groups have global options selected for
* contacts or contact groups
*/
$request = <<<'SQL'
SELECT
acl_group_id,
all_contacts,
all_contact_groups
FROM acl_groups
WHERE acl_group_activate = '1'
AND (all_contacts != 0 OR all_contact_groups != 0)
SQL;
$statement = $pearDB->query($request);
while ($record = $statement->fetch(PDO::FETCH_ASSOC)) {
$accessGroupId = $record['acl_group_id'];
if ($record['all_contacts']) {
// Find all contacts that are not already linked to the access group
$contactIds = getContactsNotLinkedToAclGroup($accessGroupId);
$pearDB->beginTransaction();
try {
linkContactsToAccessGroup(
accessGroupId: $accessGroupId,
contactIds: $contactIds
);
$pearDB->commit();
} catch (Throwable $exception) {
$pearDB->rollBack();
$centreonLog->insertLog(
2,
'CentACL CRON: failed to add new contacts to access group ' . $accessGroupId
);
}
}
if ($record['all_contact_groups']) {
// Find all contact groups that are not already linked to the access group
$contactGroupIds = getContactGroupsNotLinkedToAclGroup($accessGroupId);
$pearDB->beginTransaction();
try {
linkContactGroupsToAccessGroup(
accessGroupId: $accessGroupId,
contactGroupIds: $contactGroupIds
);
$pearDB->commit();
} catch (Throwable $exception) {
$pearDB->rollBack();
$centreonLog->insertLog(
2,
'CentACL CRON: failed to add new contact groups to access group ' . $accessGroupId
);
}
}
}
/**
* Check if some ACL have global options selected for
* all the resources
*/
$res = $pearDB->query(
"SELECT acl_res_id, all_hosts, all_hostgroups, all_servicegroups
FROM acl_resources WHERE acl_res_activate = '1'
AND (all_hosts IS NOT NULL OR all_hostgroups IS NOT NULL OR all_servicegroups IS NOT NULL)"
);
while ($row = $res->fetch()) {
// manage acl_resources.changed flag
$aclResourcesUpdated = false;
/**
* Add Hosts
*/
if ($row['all_hosts']) {
$pearDB->beginTransaction();
try {
$res1 = $pearDB->prepare(
"SELECT host_id FROM host WHERE host_id NOT IN (SELECT DISTINCT host_host_id
FROM acl_resources_host_relations WHERE acl_res_id = :aclResId)
AND host_register = '1'"
);
$res1->bindValue(':aclResId', $row['acl_res_id'], PDO::PARAM_INT);
$res1->execute();
if ($res1->rowCount()) {
// set acl_resources.changed flag to 1
$aclResourcesUpdated = true;
}
while ($rowData = $res1->fetch()) {
$stmt = $pearDB->prepare(
'INSERT INTO acl_resources_host_relations (host_host_id, acl_res_id)
VALUES (:hostId, :aclResId)'
);
$stmt->bindValue(':hostId', $rowData['host_id'], PDO::PARAM_INT);
$stmt->bindValue(':aclResId', $row['acl_res_id'], PDO::PARAM_INT);
$stmt->execute();
}
$pearDB->commit();
$res1->closeCursor();
} catch (PDOException $e) {
$pearDB->rollBack();
$centreonLog->insertLog(
2,
'CentACL CRON: failed to add new host'
);
}
}
/**
* Add Hostgroups
*/
if ($row['all_hostgroups']) {
$pearDB->beginTransaction();
try {
$res1 = $pearDB->prepare(
'SELECT hg_id FROM hostgroup
WHERE hg_id NOT IN (
SELECT DISTINCT hg_hg_id FROM acl_resources_hg_relations
WHERE acl_res_id = :aclResId)'
);
$res1->bindValue(':aclResId', $row['acl_res_id'], PDO::PARAM_INT);
$res1->execute();
if ($res1->rowCount()) {
// set acl_resources.changed flag to 1
$aclResourcesUpdated = true;
}
while ($rowData = $res1->fetch()) {
$stmt = $pearDB->prepare(
'INSERT INTO acl_resources_hg_relations (hg_hg_id, acl_res_id)
VALUES (:hgId, :aclResId)'
);
$stmt->bindValue(':hgId', $rowData['hg_id'], PDO::PARAM_INT);
$stmt->bindValue(':aclResId', $row['acl_res_id'], PDO::PARAM_INT);
$stmt->execute();
}
$pearDB->commit();
$res1->closeCursor();
} catch (PDOException $e) {
$pearDB->rollBack();
$centreonLog->insertLog(
2,
'CentACL CRON: failed to add new hostgroups'
);
}
}
/**
* Add Servicesgroups
*/
$pearDB->beginTransaction();
try {
if ($row['all_servicegroups']) {
$res1 = $pearDB->prepare(
'SELECT sg_id FROM servicegroup
WHERE sg_id NOT IN (
SELECT DISTINCT sg_id FROM acl_resources_sg_relations
WHERE acl_res_id = :aclResId)'
);
$res1->bindValue(':aclResId', $row['acl_res_id'], PDO::PARAM_INT);
$res1->execute();
if ($res1->rowCount()) {
// set acl_resources.changed flag to 1
$aclResourcesUpdated = true;
}
while ($rowData = $res1->fetch()) {
$stmt = $pearDB->prepare(
'INSERT INTO acl_resources_sg_relations (sg_id, acl_res_id)
VALUES (:sgId, :aclResId)'
);
$stmt->bindValue(':sgId', $rowData['sg_id'], PDO::PARAM_INT);
$stmt->bindValue(':aclResId', $row['acl_res_id'], PDO::PARAM_INT);
$stmt->execute();
}
$res1->closeCursor();
}
// as resources has changed we need to save it in the DB
if ($aclResourcesUpdated) {
$stmt = $pearDB->prepare(
"UPDATE acl_resources SET changed = '1' WHERE acl_res_id = :aclResId"
);
$stmt->bindValue(':aclResId', $row['acl_res_id'], PDO::PARAM_INT);
$stmt->execute();
}
$pearDB->commit();
} catch (PDOException $e) {
$pearDB->rollBack();
$centreonLog->insertLog(
2,
'CentACL CRON: failed to add new servicegroup'
);
}
}
/**
* Check that the ACL resources have changed
* if no : go away.
* if yes : let's go to build cache and update database
*/
$tabGroups = [];
$dbResult1 = $pearDB->query(
"SELECT DISTINCT acl_groups.acl_group_id
FROM acl_res_group_relations, `acl_groups`, `acl_resources`
WHERE acl_groups.acl_group_id = acl_res_group_relations.acl_group_id
AND acl_res_group_relations.acl_res_id = acl_resources.acl_res_id
AND acl_groups.acl_group_activate = '1'
AND (
acl_groups.acl_group_changed = '1' OR
(acl_resources.changed = '1' AND acl_resources.acl_res_activate IS NOT NULL)
)"
);
while ($result = $dbResult1->fetch()) {
$tabGroups[] = $result['acl_group_id'];
}
unset($result);
if ($tabGroups !== []) {
/**
* Cache for hosts and host Templates
*/
$hostTemplateCache = [];
$res = $pearDB->query(
'SELECT host_host_id, host_tpl_id FROM host_template_relation'
);
while ($row = $res->fetch()) {
if (! isset($hostTemplateCache[$row['host_tpl_id']])) {
$hostTemplateCache[$row['host_tpl_id']] = [];
}
$hostTemplateCache[$row['host_tpl_id']][$row['host_host_id']] = $row['host_host_id'];
}
$hostCache = [];
$dbResult = $pearDB->query(
"SELECT host_id, host_name FROM host WHERE host_register IN ('1', '2')"
);
while ($h = $dbResult->fetch()) {
$hostCache[$h['host_id']] = $h['host_name'];
}
unset($h);
/**
* Cache for host poller relation
*/
$hostPollerCache = [];
$res = $pearDB->query(
'SELECT nagios_server_id, host_host_id FROM ns_host_relation'
);
while ($row = $res->fetch()) {
if (! isset($hostPollerCache[$row['nagios_server_id']])) {
$hostPollerCache[$row['nagios_server_id']] = [];
}
$hostPollerCache[$row['nagios_server_id']][$row['host_host_id']] = $row['host_host_id'];
}
/**
* Get all included Hosts
*/
$hostIncCache = [];
$dbResult = $pearDB->query(
'SELECT host_host_id, acl_res_id
FROM acl_resources_host_relations'
);
while ($h = $dbResult->fetch()) {
if (! isset($hostIncCache[$h['acl_res_id']])) {
$hostIncCache[$h['acl_res_id']] = [];
}
$hostIncCache[$h['acl_res_id']][$h['host_host_id']] = 1;
}
/**
* Get all excluded Hosts
*/
$hostExclCache = [];
$dbResult = $pearDB->query(
'SELECT host_host_id, acl_res_id
FROM acl_resources_hostex_relations'
);
while ($h = $dbResult->fetch()) {
if (! isset($hostExclCache[$h['acl_res_id']])) {
$hostExclCache[$h['acl_res_id']] = [];
}
$hostExclCache[$h['acl_res_id']][$h['host_host_id']] = 1;
}
/**
* Service Cache
*/
$svcCache = [];
$dbResult = $pearDB->query(
"SELECT service_id FROM `service`
WHERE service_register = '1'"
);
while ($s = $dbResult->fetch()) {
$svcCache[$s['service_id']] = 1;
}
/**
* Host Host relation
*/
$hostHGRelation = [];
$dbResult = $pearDB->query('SELECT * FROM hostgroup_relation');
while ($hg = $dbResult->fetch()) {
if (! isset($hostHGRelation[$hg['hostgroup_hg_id']])) {
$hostHGRelation[$hg['hostgroup_hg_id']] = [];
}
$hostHGRelation[$hg['hostgroup_hg_id']][$hg['host_host_id']] = $hg['host_host_id'];
}
unset($hg);
/**
* Host Service relation
*/
$hsRelation = [];
$dbResult = $pearDB->query(
'SELECT hostgroup_hg_id, host_host_id, service_service_id
FROM host_service_relation'
);
while ($sr = $dbResult->fetch()) {
if (isset($sr['host_host_id']) && $sr['host_host_id']) {
if (! isset($hsRelation[$sr['host_host_id']])) {
$hsRelation[$sr['host_host_id']] = [];
}
$hsRelation[$sr['host_host_id']][$sr['service_service_id']] = 1;
} elseif (isset($hostHGRelation[$sr['hostgroup_hg_id']])) {
foreach ($hostHGRelation[$sr['hostgroup_hg_id']] as $hostId) {
if (! isset($hsRelation[$hostId])) {
$hsRelation[$hostId] = [];
}
$hsRelation[$hostId][$sr['service_service_id']] = 1;
}
}
}
$dbResult->closeCursor();
/**
* Create Service template model Cache
*/
$svcTplCache = [];
$dbResult = $pearDB->query('SELECT service_template_model_stm_id, service_id FROM service');
while ($tpl = $dbResult->fetch()) {
$svcTplCache[$tpl['service_id']] = $tpl['service_template_model_stm_id'];
}
$dbResult->closeCursor();
unset($tpl);
$svcCatCache = [];
$dbResult = $pearDB->query('SELECT sc_id, service_service_id FROM `service_categories_relation`');
while ($res = $dbResult->fetch()) {
if (! isset($svcCatCache[$res['service_service_id']])) {
$svcCatCache[$res['service_service_id']] = [];
}
$svcCatCache[$res['service_service_id']][$res['sc_id']] = 1;
}
$dbResult->closeCursor();
unset($res);
$sgCache = [];
$res = $pearDB->query(
"SELECT argr.`acl_res_id`, acl_group_id
FROM `acl_res_group_relations` argr, `acl_resources` ar
WHERE argr.acl_res_id = ar.acl_res_id
AND ar.acl_res_activate = '1'"
);
while ($row = $res->fetch()) {
$sgCache[$row['acl_res_id']] = [];
}
unset($row);
$res = $pearDB->query(
'SELECT service_service_id, sgr.host_host_id, acl_res_id
FROM servicegroup sg, acl_resources_sg_relations acl, servicegroup_relation sgr
WHERE acl.sg_id = sg.sg_id
AND sgr.servicegroup_sg_id = sg.sg_id '
);
while ($row = $res->fetch()) {
foreach (array_keys($sgCache) as $rId) {
if ($rId == $row['acl_res_id']) {
if (! isset($sgCache[$rId][$row['host_host_id']])) {
$sgCache[$rId][$row['host_host_id']] = [];
}
$sgCache[$rId][$row['host_host_id']][$row['service_service_id']] = 1;
}
}
}
unset($row);
$res = $pearDB->query(
'SELECT acl_res_id, hg_id
FROM hostgroup, acl_resources_hg_relations
WHERE acl_resources_hg_relations.hg_hg_id = hostgroup.hg_id'
);
$hgResCache = [];
while ($row = $res->fetch()) {
if (! isset($hgResCache[$row['acl_res_id']])) {
$hgResCache[$row['acl_res_id']] = [];
}
$hgResCache[$row['acl_res_id']][] = $row['hg_id'];
}
unset($row);
// Prepare statement
$deleteHandler = $pearDBO->prepare('DELETE FROM centreon_acl WHERE group_id = ?');
/**
* Begin to build ACL
*/
$cpt = 0;
$resourceCache = [];
foreach ($tabGroups as $aclGroupId) {
// Delete old data for this group
$deleteHandler->execute([$aclGroupId]);
/**
* Select
*/
$dbResult2 = $pearDB->prepare(
"SELECT DISTINCT(`acl_resources`.`acl_res_id`)
FROM `acl_res_group_relations`, `acl_resources`
WHERE `acl_res_group_relations`.`acl_group_id` = :aclGroupId
AND `acl_res_group_relations`.acl_res_id = `acl_resources`.acl_res_id
AND `acl_resources`.acl_res_activate = '1'"
);
$dbResult2->bindValue(':aclGroupId', $aclGroupId, PDO::PARAM_INT);
$dbResult2->execute();
if ($debug) {
$time_start = microtime_float2();
}
while ($res2 = $dbResult2->fetch()) {
if (! isset($resourceCache[$res2['acl_res_id']])) {
$resourceCache[$res2['acl_res_id']] = [];
$host = [];
// Get all Hosts
if (isset($hostIncCache[$res2['acl_res_id']])) {
foreach (array_keys($hostIncCache[$res2['acl_res_id']]) as $hostId) {
$host[$hostId] = 1;
}
}
if (isset($hgResCache[$res2['acl_res_id']])) {
foreach ($hgResCache[$res2['acl_res_id']] as $hgId) {
if (isset($hostHGRelation[$hgId])) {
foreach ($hostHGRelation[$hgId] as $hostId) {
if ($hostCache[$hostId]) {
$host[$hostId] = 1;
} else {
echo "Host {$hostId} unknown !\n";
}
}
}
}
}
if (isset($hostExclCache[$res2['acl_res_id']])) {
foreach (array_keys($hostExclCache[$res2['acl_res_id']]) as $hostId) {
unset($host[$hostId]);
}
}
// Give Authorized Categories
$authorizedCategories = getAuthorizedCategories($res2['acl_res_id']);
// get all Service groups
$dbResult3 = $pearDB->prepare(
'SELECT servicegroup_relation.host_host_id, servicegroup_relation.service_service_id
FROM `acl_resources_sg_relations`, `servicegroup_relation`
WHERE acl_res_id = :aclResId
AND servicegroup_relation.servicegroup_sg_id = acl_resources_sg_relations.sg_id
UNION
SELECT servicegroup_relation.host_host_id, servicegroup_relation.service_service_id
FROM `acl_resources_sg_relations`, `servicegroup_relation`, `hostgroup`, `hostgroup_relation`
WHERE acl_res_id = :aclResId
AND hostgroup.hg_id = servicegroup_relation.hostgroup_hg_id
AND servicegroup_relation.hostgroup_hg_id = hostgroup_relation.hostgroup_hg_id
AND servicegroup_relation.servicegroup_sg_id = acl_resources_sg_relations.sg_id'
);
$dbResult3->bindValue(':aclResId', $res2['acl_res_id'], PDO::PARAM_INT);
$dbResult3->execute();
$sgElem = [];
$tmpH = [];
while ($h = $dbResult3->fetch()) {
if (! isset($sgElem[$h['host_host_id']])) {
$sgElem[$h['host_host_id']] = [];
$tmpH[$h['host_host_id']] = 1;
}
$sgElem[$h['host_host_id']][$h['service_service_id']] = 1;
}
$tmpH = getFilteredHostCategories($tmpH, $res2['acl_res_id']);
$tmpH = getFilteredPollers($tmpH, $res2['acl_res_id']);
foreach ($sgElem as $hostId => $value) {
if (isset($tmpH[$hostId])) {
if (count($authorizedCategories) == 0) { // no category filter
$resourceCache[$res2['acl_res_id']][$hostId] = $value;
} else {
foreach (array_keys($value) as $serviceId) {
$linkedServiceCategories = getServiceTemplateCategoryList($serviceId);
foreach ($linkedServiceCategories as $linkedServiceCategory) {
// Check if category linked to service is allowed
if (in_array($linkedServiceCategory, $authorizedCategories)) {
$resourceCache[$res2['acl_res_id']][$hostId][$serviceId] = 1;
break;
}
}
}
}
}
}
unset($tmpH, $sgElem);
// Filter
$host = getFilteredHostCategories($host, $res2['acl_res_id']);
$host = getFilteredPollers($host, $res2['acl_res_id']);
// Initialize and first filter
foreach (array_keys($host) as $hostId) {
$tab = getAuthorizedServicesHost($hostId, $res2['acl_res_id'], $authorizedCategories);
if (! isset($resourceCache[$res2['acl_res_id']][$hostId])) {
$resourceCache[$res2['acl_res_id']][$hostId] = [];
}
foreach (array_keys($tab) as $serviceId) {
$resourceCache[$res2['acl_res_id']][$hostId][$serviceId] = 1;
}
unset($tab);
}
unset($host);
// Set meta services
$metaServices = getMetaServices($res2['acl_res_id'], $pearDB, $metaObj);
if (count($metaServices)) {
$resourceCache[$res2['acl_res_id']] += $metaServices;
}
}
$strBegin = 'INSERT INTO centreon_acl (host_id, service_id, group_id) VALUES ';
$strEnd = ' ON DUPLICATE KEY UPDATE `group_id` = ? ';
$str = '';
$params = [];
$i = 0;
foreach ($resourceCache[$res2['acl_res_id']] as $hostId => $svcList) {
if (isset($hostCache[$hostId])) {
if ($str != '') {
$str .= ', ';
}
$str .= ' (?, NULL, ?) ';
$params[] = $hostId;
$params[] = $aclGroupId;
foreach (array_keys($svcList) as $serviceId) {
if ($str != '') {
$str .= ', ';
}
$i++;
$str .= ' (?, ?, ?) ';
$params[] = $hostId;
$params[] = $serviceId;
$params[] = $aclGroupId;
if ($i >= 5000) {
$params[] = $aclGroupId; // argument for $strEnd
$stmt = $pearDBO->prepare($strBegin . $str . $strEnd);
$stmt->execute($params); // inject acl by bulk (1000 relations)
$str = '';
$params = [];
$i = 0;
}
}
}
}
// inject remaining acl (bulk of less than 1000 relations)
if ($str != '') {
$params[] = $aclGroupId; // argument for $strEnd
$stmt = $pearDBO->prepare($strBegin . $str . $strEnd);
$stmt->execute($params);
$str = '';
}
// reset flags of acl_resources
$stmt = $pearDB->prepare("UPDATE `acl_resources` SET `changed` = '0' WHERE acl_res_id = :aclResId");
$stmt->bindValue(':aclResId', $res2['acl_res_id'], PDO::PARAM_INT);
$stmt->execute();
}
if ($debug) {
$time_end = microtime_float2();
$now = $time_end - $time_start;
echo round($now, 3) . ' ' . _('seconds') . "\n";
}
$cpt++;
// reset flags of acl_groups
$stmt = $pearDB->prepare("UPDATE acl_groups SET acl_group_changed = '0' WHERE acl_group_id = :aclGroupId");
$stmt->bindValue(':aclGroupId', $aclGroupId, PDO::PARAM_INT);
$stmt->execute();
}
/**
* Include module specific ACL evaluation
*/
$extensionsPaths = getModulesExtensionsPaths($pearDB);
foreach ($extensionsPaths as $extensionPath) {
require_once $extensionPath . 'centAcl.php';
}
}
/**
* Remove lock
*/
$dbResult = $pearDB->prepare(
"UPDATE cron_operation
SET running = '0', last_execution_time = :time
WHERE id = :appId"
);
$dbResult->bindValue(':time', (time() - $beginTime), PDO::PARAM_INT);
$dbResult->bindValue(':appId', $appId, PDO::PARAM_INT);
$dbResult->execute();
// Close connection to databases
$pearDB = null;
$pearDBO = null;
} catch (Exception $e) {
programExit($e->getMessage());
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/cron/centreon-partitioning.php | centreon/cron/centreon-partitioning.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
*
*/
require_once realpath(__DIR__ . '/../config/centreon.config.php');
require_once _CENTREON_PATH_ . '/www/class/centreonPurgeEngine.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreon-partition/partEngine.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreon-partition/config.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreon-partition/mysqlTable.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreon-partition/options.class.php';
// Create partitioned tables
$centreonDb = new CentreonDB('centreon');
$centstorageDb = new CentreonDB('centstorage', 3);
$partEngine = new PartEngine();
if (! $partEngine->isCompatible($centstorageDb)) {
echo '[' . date(DATE_RFC822) . '] '
. "CRITICAL: MySQL server is not compatible with partitionning. MySQL version must be greater or equal to 5.1\n";
exit(1);
}
echo '[' . date(DATE_RFC822) . "] PARTITIONING STARTED\n";
$tables = [
'data_bin',
'logs',
'log_archive_host',
'log_archive_service',
];
try {
foreach ($tables as $table) {
$config = new Config(
$centstorageDb,
_CENTREON_PATH_ . '/config/partition.d/partitioning-' . $table . '.xml',
$centreonDb
);
$mysqlTable = $config->getTable($table);
$partEngine->updateParts($mysqlTable, $centstorageDb);
}
} catch (Exception $e) {
echo '[' . date(DATE_RFC822) . '] ' . $e->getMessage();
exit(1);
}
echo '[' . date(DATE_RFC822) . "] PARTITIONING COMPLETED\n";
exit(0);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/cron/centreon-send-stats.php | centreon/cron/centreon-send-stats.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
*
*/
require_once __DIR__ . '/../bootstrap.php';
require_once __DIR__ . '/../www/class/centreonRestHttp.class.php';
require_once __DIR__ . '/../config/centreon-statistics.config.php';
require_once __DIR__ . '/../www/class/centreonStatistics.class.php';
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\ConsoleOutput;
$shortopts = 'd';
$longopts = ['debug'];
$options = getopt($shortopts, $longopts);
$output = new ConsoleOutput();
$logger = new ConsoleLogger($output);
$shouldSendStatistics = false;
$isRemote = false;
$hasValidLicenses = false;
$isImpUser = false;
/**
* @var CentreonDB $db
*/
$db = $dependencyInjector['configuration_db'];
/**
* Log a message.
*
* If an exception is provided, the message will be stored in the PHP log.
*
* @param string $message Message to log
* @param Throwable $exception
*/
function logger(string $message, ?Throwable $exception = null)
{
try {
$datetime = new DateTime();
$datetime->setTimezone(new DateTimeZone('UTC'));
$logEntry = is_null($exception) ? $message : $message . ' - ' . $exception->getMessage();
printf("%s - %s\n", $datetime->format('Y/m/d H:i:s'), $logEntry);
} catch (Exception $ex) {
printf("Exception: %s\n", $ex->getMessage());
}
}
// Check if CEIP is enable
$result = $db->query("SELECT `value` FROM `options` WHERE `key` = 'send_statistics'");
if ($row = $result->fetch()) {
$shouldSendStatistics = (bool) $row['value'];
}
// Check if it's a Central server
$result = $db->query("SELECT `value` FROM `informations` WHERE `key` = 'isRemote'");
if ($row = $result->fetch()) {
$isRemote = $row['value'] === 'yes';
}
// Check if valid Centreon licences exist
$centreonLicensesDir = '/etc/centreon/license.d/';
if (is_dir($centreonLicensesDir) && ($dh = opendir($centreonLicensesDir)) !== false) {
$dateNow = new DateTime('NOW');
while (($file = readdir($dh)) !== false) {
try {
$statisticsFileName = $centreonLicensesDir . $file;
if (is_file($statisticsFileName)) {
$licenseContent = file_get_contents($statisticsFileName);
if (preg_match('/"end": "(\d{4}\-\d{2}\-\d{2})"/', $licenseContent, $matches)) {
$dateLicense = new DateTime((string) $matches[1]);
if ($dateLicense >= $dateNow) {
$hasValidLicenses = true;
break;
}
}
}
} catch (Exception $ex) {
logger('Error while reading statistics file ' . $statisticsFileName, $ex);
}
}
}
// Check if it's an IMP user
$result = $db->query("SELECT options.value FROM options WHERE options.key = 'impCompanyToken'");
if ($row = $result->fetch()) {
if (! empty($row['value'])) {
$isImpUser = true;
}
}
// Only send telemetry & statistics if it's a Centreon central server
if ($isRemote === false) {
try {
$http = new CentreonRestHttp();
$oStatistics = new CentreonStatistics($logger);
$timestamp = time();
$uuid = $oStatistics->getCentreonUUID();
if (empty($uuid)) {
throw new Exception('No UUID specified');
}
$versions = $oStatistics->getVersion();
$infos = $oStatistics->getPlatformInfo();
$timezone = $oStatistics->getPlatformTimezone();
$authentication = $oStatistics->getAuthenticationOptions();
$authentication['api_token'] = $oStatistics->getApiTokensInfo();
$additional = [];
$acc = $oStatistics->getAccData();
$pac = $oStatistics->getAgentConfigurationData();
/*
* Only send statistics if user using a free version has enabled this option
* or if at least a Centreon license is valid
*/
if ($shouldSendStatistics || $hasValidLicenses) {
try {
$additional = $oStatistics->getAdditionalData();
} catch (Throwable $e) {
$logger->error('Cannot get stats from modules');
}
}
// Construct the object gathering datas
$data = [
'timestamp' => "{$timestamp}",
'UUID' => $uuid,
'versions' => $versions,
'infos' => $infos,
'timezone' => $timezone,
'authentication' => $authentication,
'additional' => $additional,
'acc' => $acc,
'poller-agent-configuration' => $pac,
];
if (isset($options['d']) || isset($options['debug'])) {
echo json_encode($data, JSON_PRETTY_PRINT) . "\n";
} else {
$returnData = $http->call(CENTREON_STATS_URL, 'POST', $data, [], true);
logger(
sprintf(
'Response from [%s] : %s,body : %s',
CENTREON_STATS_URL,
$returnData['statusCode'],
$returnData['body']
)
);
}
} catch (Exception $ex) {
logger('Got error while sending data to [' . CENTREON_STATS_URL . ']', $ex);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/cron/centKnowledgeSynchronizer.php | centreon/cron/centKnowledgeSynchronizer.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
*
*/
require_once realpath(__DIR__ . '/../www/class/centreon-knowledge/wikiApi.class.php');
try {
$wikiApi = new WikiApi();
$wikiApi->synchronize();
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/cron/centAcl-Func.php | centreon/cron/centAcl-Func.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
*
*/
/**
* Init functions
*/
function microtime_float2()
{
[$usec, $sec] = explode(' ', microtime());
return (float) $usec + (float) $sec;
}
/**
* send a formatted message before exiting the script
* @param $msg
*/
function programExit($msg)
{
echo '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n";
exit;
}
/**
* set the `running` value to 0 to remove the DB's virtual lock
* @param int $appId , the process Id
*/
function removeLock(int $appId): void
{
global $pearDB;
if ($appId === 0) {
programExit("Error the process Id can't be null.");
}
try {
$stmt = $pearDB->prepare(
"UPDATE cron_operation SET running = '0'
WHERE id = :appId"
);
$stmt->bindValue(':appId', $appId, PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
programExit("Error can't unlock the process in the cron_operation table.");
}
}
/**
* set the `running` value to 1 to set a virtual lock on the DB
* @param int $appId , the process Id
*/
function putALock(int $appId): void
{
global $pearDB;
if ($appId === 0) {
programExit("Error the process Id can't be null.");
}
try {
$stmt = $pearDB->prepare(
"UPDATE cron_operation SET running = '1', time_launch = :currentTime
WHERE id = :appId"
);
$stmt->bindValue(':appId', $appId, PDO::PARAM_INT);
$stmt->bindValue(':currentTime', time(), PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
programExit("Error can't lock the process in the cron_operation table.");
}
}
/**
* get centAcl state in the DB
* @return array $data
*/
function getCentAclRunningState()
{
global $pearDB;
$data = [];
try {
$dbResult = $pearDB->query(
"SELECT id, running FROM cron_operation WHERE name LIKE 'centAcl.php'"
);
$data = $dbResult->fetch();
} catch (PDOException $e) {
programExit("Error can't check state while process is running.");
}
return $data;
}
/**
* Return host tab after poller filter
*
* @param array $host
* @param int $resId
* @return array $host
*/
function getFilteredPollers($host, $resId)
{
global $pearDB;
$dbResult = $pearDB->prepare(
'SELECT COUNT(*) AS count FROM acl_resources_poller_relations WHERE acl_res_id = :resId'
);
$dbResult->bindValue(':resId', $resId, PDO::PARAM_INT);
$dbResult->execute();
$row = $dbResult->fetch();
$isPollerFilter = $row['count'];
$hostTmp = $host;
$dbResult = $pearDB->prepare(
"SELECT host_host_id
FROM acl_resources_poller_relations, acl_resources, ns_host_relation
WHERE acl_resources_poller_relations.acl_res_id = acl_resources.acl_res_id
AND acl_resources.acl_res_id = :resId
AND ns_host_relation.nagios_server_id = acl_resources_poller_relations.poller_id
AND acl_res_activate = '1'"
);
$dbResult->bindValue(':resId', $resId, PDO::PARAM_INT);
$dbResult->execute();
if ($dbResult->rowCount()) {
$host = [];
while ($row = $dbResult->fetch()) {
if (isset($hostTmp[$row['host_host_id']])) {
$host[$row['host_host_id']] = 1;
}
}
} elseif ($isPollerFilter) {
// If result of query is empty and user have poller restrictions, clean host table.
$host = [];
}
return $host;
}
/**
* Return host tab after host categories filter.
* Add a cache for filtered ACL rights
* avoiding to recalculate it at each occurrence.
*
* @param array $host
* @param int $resId
* @return array $filteredHosts
*/
function getFilteredHostCategories($host, $resId)
{
global $pearDB, $hostTemplateCache;
$dbResult = $pearDB->prepare(
"SELECT DISTINCT host_host_id
FROM acl_resources_hc_relations, acl_res_group_relations, acl_resources, hostcategories_relation
WHERE acl_resources_hc_relations.acl_res_id = acl_resources.acl_res_id
AND acl_resources.acl_res_id = :resId
AND hostcategories_relation.hostcategories_hc_id = acl_resources_hc_relations.hc_id
AND acl_res_activate = '1'"
);
$dbResult->bindValue(':resId', $resId, PDO::PARAM_INT);
$dbResult->execute();
if (! $dbResult->rowCount()) {
return $host;
}
$treatedHosts = [];
$linkedHosts = [];
while ($row = $dbResult->fetch()) {
$linkedHosts[] = $row['host_host_id'];
}
$filteredHosts = [];
while ($linkedHostId = array_pop($linkedHosts)) {
$treatedHosts[] = $linkedHostId;
if (isset($host[$linkedHostId])) { // host
$filteredHosts[$linkedHostId] = 1;
} elseif (isset($hostTemplateCache[$linkedHostId])) { // host template
foreach ($hostTemplateCache[$linkedHostId] as $hostId) {
if (isset($host[$hostId])) {
$filteredHosts[$hostId] = 1;
}
if (isset($hostTemplateCache[$hostId])) {
foreach ($hostTemplateCache[$hostId] as $hostId2) {
if (! in_array($hostId2, $linkedHosts) && ! in_array($hostId2, $treatedHosts)) {
$linkedHosts[] = $hostId2;
}
}
}
}
}
}
return $filteredHosts;
}
/**
* Return enable categories for this resource access
*
* @param int $resId
* @return array $tabCategories
*/
function getAuthorizedCategories($resId)
{
global $pearDB;
$tabCategories = [];
$dbResult = $pearDB->prepare(
"SELECT sc_id FROM acl_resources_sc_relations, acl_resources
WHERE acl_resources_sc_relations.acl_res_id = acl_resources.acl_res_id
AND acl_resources.acl_res_id = :resId
AND acl_res_activate = '1'"
);
$dbResult->bindValue(':resId', $resId, PDO::PARAM_INT);
$dbResult->execute();
while ($res = $dbResult->fetch()) {
$tabCategories[$res['sc_id']] = $res['sc_id'];
}
$dbResult->closeCursor();
unset($res, $dbResult);
return $tabCategories;
}
/**
* Get a service template list for categories
*
* @param int $serviceId
* @return array|void $tabCategory
*/
function getServiceTemplateCategoryList($serviceId = null)
{
global $svcTplCache, $svcCatCache;
$tabCategory = [];
if (! $serviceId) {
return;
}
if (isset($svcCatCache[$serviceId])) {
foreach ($svcCatCache[$serviceId] as $ctId => $flag) {
$tabCategory[$ctId] = $ctId;
}
return $tabCategory;
}
// Init Table of template
$loopBreak = [];
while (1) {
if (isset($svcTplCache[$serviceId]) && ! isset($loopBreak[$serviceId])) {
$serviceId = $svcTplCache[$serviceId];
$tabCategory = getServiceTemplateCategoryList($serviceId);
$loopBreak[$serviceId] = true;
} else {
return $tabCategory;
}
}
}
/**
* Get ACLs for host from a servicegroup
*
* @param $pearDB
* @param int $hostId
* @param int $resId
* @return array|void $svc
*/
function getACLSGForHost($pearDB, $hostId, $resId)
{
global $sgCache;
if (! $pearDB || ! isset($hostId)) {
return;
}
$svc = [];
if (isset($sgCache[$resId])) {
foreach ($sgCache[$resId] as $sgHostId => $tab) {
if ($hostId == $sgHostId) {
foreach (array_keys($tab) as $serviceId) {
$svc[$serviceId] = 1;
}
}
}
}
return $svc;
}
/**
* If the resource ACL has poller filter
*
* @param int $resId The ACL resource id
* @return bool
*/
function hasPollerFilter($resId)
{
global $pearDB;
if (! is_numeric($resId)) {
return false;
}
try {
$res = $pearDB->prepare(
'SELECT COUNT(*) as c FROM acl_resources_poller_relations WHERE acl_res_id = :resId'
);
$res->bindValue(':resId', $resId, PDO::PARAM_INT);
$res->execute();
} catch (PDOException $e) {
return false;
}
$row = $res->fetch();
return (bool) ($row['c'] > 0);
}
/**
* If the resource ACL has host category filter
*
* @param int $resId The ACL resource id
* @return bool
*/
function hasHostCategoryFilter($resId)
{
global $pearDB;
if (! is_numeric($resId)) {
return false;
}
try {
$res = $pearDB->prepare(
'SELECT COUNT(*) as c FROM acl_resources_hc_relations WHERE acl_res_id = :resId'
);
$res->bindValue(':resId', $resId, PDO::PARAM_INT);
$res->execute();
} catch (PDOException $e) {
return false;
}
$row = $res->fetch();
return (bool) ($row['c'] > 0);
}
/**
* If the resource ACL has service category filter
*
* @param int $resId The ACL resource id
* @return bool
*/
function hasServiceCategoryFilter($resId)
{
global $pearDB;
if (! is_numeric($resId)) {
return false;
}
try {
$res = $pearDB->prepare(
'SELECT COUNT(*) as c FROM acl_resources_sc_relations WHERE acl_res_id = :resId'
);
$res->bindValue(':resId', $resId, PDO::PARAM_INT);
$res->execute();
} catch (PDOException $e) {
return false;
}
$row = $res->fetch();
return (bool) ($row['c'] > 0);
}
function getAuthorizedServicesHost($hostId, $resId, $authorizedCategories)
{
global $pearDB;
$tabSvc = getMyHostServicesByName($hostId);
// Get Service Groups
$svcSg = getACLSGForHost($pearDB, $hostId, $resId);
$tabServices = [];
if (count($authorizedCategories)) {
if ($tabSvc) {
foreach (array_keys($tabSvc) as $serviceId) {
$tab = getServiceTemplateCategoryList($serviceId);
foreach ($tab as $t) {
if (isset($authorizedCategories[$t])) {
$tabServices[$serviceId] = 1;
}
}
}
}
} else {
$tabServices = $tabSvc;
if ($svcSg) {
foreach (array_keys($svcSg) as $serviceId) {
$tabServices[$serviceId] = 1;
}
}
}
return $tabServices;
}
function hostIsAuthorized($hostId, $groupId)
{
global $pearDB;
$dbResult = $pearDB->prepare(
"SELECT rhr.host_host_id
FROM acl_resources_host_relations rhr, acl_resources res, acl_res_group_relations rgr
WHERE rhr.acl_res_id = res.acl_res_id
AND res.acl_res_id = rgr.acl_res_id
AND rgr.acl_group_id = :groupId
AND rhr.host_host_id = :hostId
AND res.acl_res_activate = '1'"
);
$dbResult->bindValue(':groupId', $groupId, PDO::PARAM_INT);
$dbResult->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$dbResult->execute();
if ($dbResult->rowCount()) {
return true;
}
try {
$dbRes2 = $pearDB->prepare(
"SELECT hgr.host_host_id
FROM hostgroup_relation hgr, acl_resources_hg_relations rhgr, acl_resources res, acl_res_group_relations rgr
WHERE rhgr.acl_res_id = res.acl_res_id
AND res.acl_res_id = rgr.acl_res_id
AND rgr.acl_group_id = :groupId
AND hgr.hostgroup_hg_id = rhgr.hg_hg_id
AND hgr.host_host_id = :hostId
AND res.acl_res_activate = '1'
AND hgr.host_host_id NOT IN (SELECT host_host_id FROM acl_resources_hostex_relations
WHERE acl_res_id = rhgr.acl_res_id)"
);
$dbRes2->bindValue(':groupId', $groupId, PDO::PARAM_INT);
$dbRes2->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$dbRes2->execute();
} catch (PDOException $e) {
echo 'DB Error : ' . $e->getMessage() . '<br />';
}
return (bool) ($dbRes2->rowCount());
}
// Retrieve service description
function getMyHostServicesByName($hostId = null)
{
global $hsRelation, $svcCache;
if (! $hostId) {
return;
}
$hSvs = [];
if (isset($hsRelation[$hostId])) {
foreach ($hsRelation[$hostId] as $serviceId => $flag) {
if (isset($svcCache[$serviceId])) {
$hSvs[$serviceId] = 1;
}
}
}
return $hSvs;
}
/**
* Get meta services
*
* @param int $resId
* @param CentreonDB $db
* @param CentreonMeta $metaObj
* @return array
*/
function getMetaServices($resId, $db, $metaObj)
{
$sql = 'SELECT meta_id FROM acl_resources_meta_relations WHERE acl_res_id = ' . (int) $resId;
$res = $db->query($sql);
$arr = [];
if ($res->rowCount()) {
$hostId = $metaObj->getRealHostId();
while ($row = $res->fetch()) {
$svcId = $metaObj->getRealServiceId($row['meta_id']);
$arr[$hostId][$svcId] = 1;
}
}
return $arr;
}
function getModulesExtensionsPaths($db)
{
$extensionsPaths = [];
$res = $db->query('SELECT name FROM modules_informations');
while ($row = $res->fetch()) {
$extensionsPaths = array_merge(
$extensionsPaths,
glob(_CENTREON_PATH_ . '/www/modules/' . $row['name'] . '/extensions/acl/')
);
}
return $extensionsPaths;
}
/**
* Get the list of contacts (ids) that are not linked to the acl group id provided.
* This method excludes 'service' contacts
*
* @param int $aclGroupId
* @return int[]
*/
function getContactsNotLinkedToAclGroup(int $aclGroupId): array
{
global $pearDB;
$request = <<<'SQL'
SELECT
contact_id
FROM contact
WHERE
is_service_account = '0'
AND contact_register = '1'
AND contact_activate = '1'
AND contact_admin = '0'
AND contact_id NOT IN (
SELECT DISTINCT contact_contact_id FROM acl_group_contacts_relations WHERE acl_group_id = :aclGroupId
)
SQL;
$statement = $pearDB->prepare($request);
$statement->bindValue(':aclGroupId', $aclGroupId, PDO::PARAM_INT);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_COLUMN, 0);
}
/**
* Get the list of contact groups (ids) that are not linked to the acl group id provided.
*
* @param int $aclGroupId
* @return int[]
*/
function getContactGroupsNotLinkedToAclGroup(int $aclGroupId): array
{
global $pearDB;
$request = <<<'SQL'
SELECT
cg_id
FROM contactgroup
WHERE cg_activate = '1'
AND cg_id NOT IN (
SELECT DISTINCT cg_cg_id FROM acl_group_contactgroups_relations WHERE acl_group_id = :aclGroupId
)
SQL;
$statement = $pearDB->prepare($request);
$statement->bindValue(':aclGroupId', $aclGroupId, PDO::PARAM_INT);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_COLUMN, 0);
}
/**
* @param int $accessGroupId
* @param int[] $contactIds
*/
function linkContactsToAccessGroup(int $accessGroupId, array $contactIds): void
{
global $pearDB;
if ($contactIds === []) {
return;
}
$bindValues = [];
$subValues = [];
foreach ($contactIds as $index => $contactId) {
$bindValues[":contact_id_{$index}"] = $contactId;
$subValues[] = "(:contact_id_{$index}, :accessGroupId)";
}
$subQueries = implode(', ', $subValues);
$request = <<<SQL
INSERT INTO acl_group_contacts_relations (contact_contact_id, acl_group_id) VALUES {$subQueries}
SQL;
$statement = $pearDB->prepare($request);
$statement->bindValue(':accessGroupId', $accessGroupId, PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, PDO::PARAM_INT);
}
$statement->execute();
}
/**
* @param int $accessGroupId
* @param int[] $contactGroupIds
*/
function linkContactGroupsToAccessGroup(int $accessGroupId, array $contactGroupIds): void
{
global $pearDB;
if ($contactGroupIds === []) {
return;
}
$bindValues = [];
$subValues = [];
foreach ($contactGroupIds as $index => $contactGroupId) {
$bindValues[":contact_group_id_{$index}"] = $contactGroupId;
$subValues[] = "(:contact_group_id_{$index}, :accessGroupId)";
}
$subQueries = implode(', ', $subValues);
$request = <<<SQL
INSERT INTO acl_group_contactgroups_relations (cg_cg_id, acl_group_id) VALUES {$subQueries}
SQL;
$statement = $pearDB->prepare($request);
$statement->bindValue(':accessGroupId', $accessGroupId, PDO::PARAM_INT);
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, PDO::PARAM_INT);
}
$statement->execute();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/cron/outdated-token-removal.php | centreon/cron/outdated-token-removal.php | #!@PHP_BIN@
<?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);
require_once realpath(__DIR__ . '/../config/centreon.config.php');
include_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
$centreonDbName = $conf_centreon['db'];
// Init DB connections
$pearDB = new CentreonDB();
$pearDB->beginTransaction();
try {
deleteExpiredProviderRefreshTokens($pearDB);
deleteExpiredProviderTokens($pearDB);
deleteExpiredSessions($pearDB);
$pearDB->commit();
} catch (Throwable) {
$pearDB->rollBack();
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'TokenRemoval CRON: failed to delete old tokens'
);
}
/**
* Delete expired provider refresh tokens.
*/
function deleteExpiredProviderRefreshTokens(CentreonDB $pearDB): void
{
try {
$pearDB->executeStatement(
<<<'SQL'
DELETE st FROM security_token st
WHERE st.expiration_date < UNIX_TIMESTAMP(NOW())
AND EXISTS (
SELECT 1
FROM security_authentication_tokens sat
WHERE sat.provider_token_refresh_id = st.id
AND sat.token_type = 'auto'
LIMIT 1
)
SQL
);
} catch (Throwable $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'TokenRemoval CRON: failed to delete expired refresh tokens'
);
throw $e;
}
}
/**
* Delete provider refresh tokens which are not linked to a refresh token.
*/
function deleteExpiredProviderTokens(CentreonDB $pearDB): void
{
try {
$pearDB->executeStatement(
<<<'SQL'
DELETE st FROM security_token st
WHERE st.expiration_date < UNIX_TIMESTAMP(NOW())
AND NOT EXISTS (
SELECT 1
FROM security_authentication_tokens sat
WHERE sat.provider_token_id = st.id
AND (sat.provider_token_refresh_id IS NOT NULL OR sat.token_type IN ('api', 'cma'))
LIMIT 1
)
SQL
);
} catch (Throwable $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'TokenRemoval CRON: failed to delete expired tokens which are not linked to a refresh toke'
);
throw $e;
}
}
/**
* Delete expired sessions.
*/
function deleteExpiredSessions(CentreonDB $pearDB): void
{
try {
$pearDB->executeStatement(
<<<'SQL'
DELETE s FROM session s
WHERE s.last_reload < (
SELECT UNIX_TIMESTAMP(NOW() - INTERVAL (`value` * 60) SECOND)
FROM options
WHERE `key` = 'session_expire'
)
OR s.last_reload IS NULL
OR s.session_id NOT IN (
SELECT token FROM security_authentication_tokens
)
SQL
);
} catch (Throwable $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_BUSINESS_LOG,
'TokenRemoval CRON: failed to delete expired sessions'
);
throw $e;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/cron/centstorage_purge.php | centreon/cron/centstorage_purge.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
*
*/
require_once realpath(__DIR__ . '/../www/class/centreonPurgeEngine.class.php');
echo '[' . date(DATE_RFC822) . "] PURGE STARTED\n";
try {
$engine = new CentreonPurgeEngine();
$engine->purge();
} catch (Exception $e) {
echo '[' . date(DATE_RFC822) . '] ' . $e->getMessage();
exit(1);
}
echo '[' . date(DATE_RFC822) . "] PURGE COMPLETED\n";
exit(0);
| 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.