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/Security/Token/Application/UseCase/AddToken/AddTokenTest.php
centreon/tests/php/Core/Security/Token/Application/UseCase/AddToken/AddTokenTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Token\Application\UseCase\AddToken; use Centreon\Domain\Common\Assertion\AssertionException; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ConflictResponse; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\InvalidArgumentResponse; use Core\Common\Domain\TrimmedString; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface; use Core\Security\ProviderConfiguration\Domain\Model\Configuration; use Core\Security\Token\Application\Exception\TokenException; use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface; use Core\Security\Token\Application\Repository\WriteTokenRepositoryInterface; use Core\Security\Token\Application\UseCase\AddToken\AddToken; use Core\Security\Token\Application\UseCase\AddToken\AddTokenRequest; use Core\Security\Token\Application\UseCase\AddToken\AddTokenResponse; use Core\Security\Token\Application\UseCase\AddToken\AddTokenValidation; use Core\Security\Token\Domain\Model\ApiToken; use Core\Security\Token\Domain\Model\JwtToken; use Core\Security\Token\Domain\Model\TokenTypeEnum; beforeEach(function (): void { $this->useCase = new AddToken( $this->writeTokenRepository = $this->createMock(WriteTokenRepositoryInterface::class), $this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class), $this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class), $this->validation = $this->createMock(AddTokenValidation::class), $this->user = $this->createMock(ContactInterface::class), ); $this->localProvider = $this->createMock(ProviderAuthenticationInterface::class); $this->configurationProvider = $this->createMock(Configuration::class); $this->creationDate = new \DateTimeImmutable(); $this->expirationDate = $this->creationDate->add(new \DateInterval('P1Y')); $this->linkedUser = ['id' => 23, 'name' => 'Jane Doe']; $this->creator = ['id' => 12, 'name' => 'John Doe']; $this->requestApi = new AddTokenRequest( name: ' token name API ', type: TokenTypeEnum::API, userId: $this->linkedUser['id'], expirationDate: $this->expirationDate ); $this->requestJwt = new AddTokenRequest( name: ' token name CMA ', type: TokenTypeEnum::CMA, userId: $this->linkedUser['id'], expirationDate: $this->expirationDate ); $this->tokenJwt = new JwtToken( name: new TrimmedString($this->requestJwt->name), creatorId: $this->creator['id'], creatorName: new TrimmedString($this->creator['name']), creationDate: $this->creationDate, expirationDate: $this->expirationDate, isRevoked: false ); $this->tokenApi = new ApiToken( name: new TrimmedString($this->requestApi->name), userId: $this->linkedUser['id'], userName: new TrimmedString($this->linkedUser['name']), creatorId: $this->creator['id'], creatorName: new TrimmedString($this->creator['name']), creationDate: $this->creationDate, expirationDate: $this->expirationDate, isRevoked: false ); }); it('should present an ErrorResponse when a generic exception is thrown', function (): void { $this->providerFactory ->expects($this->once()) ->method('create') ->willThrowException(new \Exception()); $response = ($this->useCase)($this->requestApi); expect($response) ->toBeInstanceOf(ErrorResponse::class) ->and($response->getMessage()) ->toBe(TokenException::addToken()->getMessage()); }); it('should present a ConflictResponse when name is already used', function (): void { $this->validation ->expects($this->once()) ->method('assertIsValidName') ->willThrowException( TokenException::nameAlreadyExists(trim($this->requestJwt->name)) ); $response = ($this->useCase)($this->requestJwt); expect($response) ->toBeInstanceOf(ConflictResponse::class) ->and($response->getMessage()) ->toBe( TokenException::nameAlreadyExists(trim($this->requestJwt->name))->getMessage() ); }); it('should present a ConflictResponse when user ID is not valid', function (): void { $this->validation ->expects($this->once()) ->method('assertIsValidUser') ->willThrowException( TokenException::invalidUserId($this->requestApi->userId) ); $response = ($this->useCase)($this->requestApi); expect($response) ->toBeInstanceOf(ConflictResponse::class) ->and($response->getMessage()) ->toBe(TokenException::invalidUserId($this->requestApi->userId)->getMessage()); }); it('should present a ConflictResponse when a creator cannot manage user\'s tokens', function (): void { $this->validation ->expects($this->once()) ->method('assertIsValidUser') ->willThrowException( TokenException::notAllowedToCreateTokenForUser($this->requestApi->userId) ); $response = ($this->useCase)($this->requestApi); expect($response) ->toBeInstanceOf(ConflictResponse::class) ->and($response->getMessage()) ->toBe(TokenException::notAllowedToCreateTokenForUser($this->requestApi->userId)->getMessage()); }); it('should present an InvalidArgumentResponse when a field assert failed', function (): void { $this->user ->expects($this->exactly(3)) ->method('getId') ->willReturn($this->creator['id']); $this->user ->expects($this->once()) ->method('getName') ->willReturn(''); $response = ($this->useCase)($this->requestJwt); expect($response) ->toBeInstanceOf(InvalidArgumentResponse::class) ->and($response->getMessage()) ->toBe(AssertionException::notEmptyString('NewJwtToken::creatorName')->getMessage()); }); it('should present an ErrorResponse if the newly created token cannot be retrieved', function (): void { // $this->providerFactory // ->expects($this->once()) // ->method('create') // ->willReturn($this->localProvider); // $this->localProvider // ->expects($this->once()) // ->method('getConfiguration') // ->willReturn($this->configurationProvider); // $this->configurationProvider // ->expects($this->once()) // ->method('getId') // ->willReturn(1); $this->user ->expects($this->exactly(4)) ->method('getId') ->willReturn($this->creator['id']); $this->user ->expects($this->once()) ->method('getName') ->willReturn($this->creator['name']); $this->writeTokenRepository ->expects($this->once()) ->method('add'); $this->readTokenRepository ->expects($this->once()) ->method('find') ->willReturn(null); $response = ($this->useCase)($this->requestJwt); expect($response) ->toBeInstanceOf(ErrorResponse::class) ->and($response->getMessage()) ->toBe(TokenException::errorWhileRetrievingObject()->getMessage()); }); it('should return created object on success (API)', function (): void { $this->validation->expects($this->once())->method('assertIsValidName'); $this->validation->expects($this->once())->method('assertIsValidUser'); $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->localProvider); $this->localProvider ->expects($this->once()) ->method('getConfiguration') ->willReturn($this->configurationProvider); $this->configurationProvider ->expects($this->once()) ->method('getId') ->willReturn(1); $this->user ->expects($this->exactly(2)) ->method('getId') ->willReturn($this->creator['id']); $this->user ->expects($this->once()) ->method('getName') ->willReturn($this->creator['name']); $this->writeTokenRepository ->expects($this->once()) ->method('add'); $this->readTokenRepository ->expects($this->once()) ->method('find') ->willReturn($this->tokenApi); $response = ($this->useCase)($this->requestApi); expect($response)->toBeInstanceOf(AddTokenResponse::class) ->and($response->token->getName()) ->toBe($this->tokenApi->getName()) ->and($response->token->getUserName()) ->toBe($this->linkedUser['name']) ->and($response->token->getUserId()) ->toBe($this->linkedUser['id']) ->and($response->token->getCreatorName()) ->toBe($this->creator['name']) ->and($response->token->getCreatorId()) ->toBe($this->creator['id']) ->and($response->token->getCreationDate()) ->toBe($this->creationDate) ->and($response->token->getExpirationDate()) ->toBe($this->expirationDate) ->and($response->token->isRevoked()) ->toBe($this->tokenApi->isRevoked()) ->and($response->token->getType()) ->toBe($this->tokenApi->getType()); }); it('should return created object on success (CMA)', function (): void { $this->validation->expects($this->once())->method('assertIsValidName'); $this->validation->expects($this->once())->method('assertIsValidUser'); $this->user ->expects($this->exactly(2)) ->method('getId') ->willReturn($this->creator['id']); $this->user ->expects($this->once()) ->method('getName') ->willReturn($this->creator['name']); $this->writeTokenRepository ->expects($this->once()) ->method('add'); $this->readTokenRepository ->expects($this->once()) ->method('find') ->willReturn($this->tokenJwt); $response = ($this->useCase)($this->requestJwt); expect($response)->toBeInstanceOf(AddTokenResponse::class) ->and($response->token->getName()) ->toBe($this->tokenJwt->getName()) ->and($response->token->getCreatorName()) ->toBe($this->creator['name']) ->and($response->token->getCreatorId()) ->toBe($this->creator['id']) ->and($response->token->getCreationDate()) ->toBe($this->creationDate) ->and($response->token->getExpirationDate()) ->toBe($this->expirationDate) ->and($response->token->isRevoked()) ->toBe($this->tokenJwt->isRevoked()) ->and($response->token->getType()) ->toBe($this->tokenJwt->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/Security/Token/Application/UseCase/GetToken/GetTokenTest.php
centreon/tests/php/Core/Security/Token/Application/UseCase/GetToken/GetTokenTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Token\Application\UseCase\GetToken; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Common\Domain\TrimmedString; use Core\Security\Token\Application\Exception\TokenException; use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface; use Core\Security\Token\Application\UseCase\GetToken\GetToken; use Core\Security\Token\Application\UseCase\GetToken\GetTokenResponse; use Core\Security\Token\Domain\Model\ApiToken; use Core\Security\Token\Domain\Model\JwtToken; beforeEach(function (): void { $this->useCase = new GetToken( $this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class), $this->user = $this->createMock(ContactInterface::class), ); $this->linkedUser = ['id' => 23, 'name' => 'Jane Doe']; $this->creator = ['id' => 12, 'name' => 'John Doe']; $this->tokenString = 'TokenString'; $this->token = new ApiToken( name: new TrimmedString($this->tokenName = 'TokenTestName'), userId: $this->linkedUser['id'], userName: new TrimmedString($this->linkedUser['name']), creatorId: $this->creator['id'], creatorName: new TrimmedString($this->creator['name']), creationDate: $this->creationDate = new \DateTimeImmutable(), expirationDate: $this->expirationDate = $this->creationDate->add(new \DateInterval('P1Y')), isRevoked: false ); $this->tokenCma = new JwtToken( name: new TrimmedString($this->tokenName = 'TokenTestName'), creatorId: $this->creator['id'], creatorName: new TrimmedString($this->creator['name']), creationDate: $this->creationDate = new \DateTimeImmutable(), expirationDate: $this->expirationDate = $this->creationDate->add(new \DateInterval('P1Y')), isRevoked: false, encodingKey: 'encodingKey', tokenString: $this->tokenString, ); }); it('should present an ErrorResponse when a generic exception is thrown', function (): void { $this->readTokenRepository ->expects($this->once()) ->method('findByNameAndUserId') ->willThrowException(new \Exception()); $response = ($this->useCase)($this->tokenName, $this->linkedUser['id']); expect($response) ->toBeInstanceOf(ErrorResponse::class) ->and($response->getMessage()) ->toBe(TokenException::errorWhileRetrievingObject()->getMessage()); }); it('should return a NotFoundResponse when token is not of type CMA', function (): void { $this->readTokenRepository ->expects($this->once()) ->method('findByNameAndUserId') ->willReturn($this->token); $response = ($this->useCase)($this->tokenName, $this->linkedUser['id']); expect($response)->toBeInstanceOf(NotFoundResponse::class) ->and($response->getMessage()) ->toBe((new NotFoundResponse('Token'))->getMessage()); }); it('should return created object on success', function (): void { $this->readTokenRepository ->expects($this->once()) ->method('findByNameAndUserId') ->willReturn($this->tokenCma); $response = ($this->useCase)($this->tokenName, $this->linkedUser['id']); expect($response)->toBeInstanceOf(GetTokenResponse::class) ->and($response->token) ->toBe($this->tokenCma) ->and($response->tokenString) ->toBe($this->tokenString); });
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/Security/Token/Application/UseCase/DeleteToken/DeleteTokenTest.php
centreon/tests/php/Core/Security/Token/Application/UseCase/DeleteToken/DeleteTokenTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Token\Application\UseCase\AddHostTemplate; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Common\Domain\TrimmedString; use Core\Infrastructure\Common\Api\DefaultPresenter; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\Token\Application\Exception\TokenException; use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface; use Core\Security\Token\Application\Repository\WriteTokenRepositoryInterface; use Core\Security\Token\Application\UseCase\DeleteToken\DeleteToken; use Core\Security\Token\Domain\Model\ApiToken; beforeEach(function (): void { $this->presenter = new DefaultPresenter( $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class) ); $this->useCase = new DeleteToken( $this->writeTokenRepository = $this->createMock(WriteTokenRepositoryInterface::class), $this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class), $this->user = $this->createMock(ContactInterface::class), ); $this->linkedUser = ['id' => 23, 'name' => 'Jane Doe']; $this->creator = ['id' => 12, 'name' => 'John Doe']; $this->creationDate = new \DateTimeImmutable(); $this->expirationDate = $this->creationDate->add(new \DateInterval('P1Y')); $this->token = new ApiToken( name: new TrimmedString('my-token-name'), userId: $this->linkedUser['id'], userName: new TrimmedString($this->linkedUser['name']), creatorId: $this->creator['id'], creatorName: new TrimmedString($this->creator['name']), creationDate: $this->creationDate, expirationDate: $this->expirationDate, isRevoked: false ); }); it('should present an ErrorResponse when a generic exception is thrown', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readTokenRepository ->expects($this->once()) ->method('findByNameAndUserId') ->willReturn($this->token); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->writeTokenRepository ->expects($this->once()) ->method('deleteByNameAndUserId') ->willThrowException(new \Exception()); ($this->useCase)($this->presenter, $this->token->getName(), $this->linkedUser['id']); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe(TokenException::deleteToken()->getMessage()); }); it('should present a ForbiddenResponse when a user has insufficient rights', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)($this->presenter, $this->token->getName()); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe(TokenException::deleteNotAllowed()->getMessage()); }); it('should present a NotFoundResponse when the token does not exist', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readTokenRepository ->expects($this->once()) ->method('findByNameAndUserId') ->willReturn(null); ($this->useCase)($this->presenter, $this->token->getName()); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(NotFoundResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe('Token not found'); }); it('should present a NoContentResponse on success', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readTokenRepository ->expects($this->once()) ->method('findByNameAndUserId') ->willReturn($this->token); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->writeTokenRepository ->expects($this->once()) ->method('deleteByNameAndUserId'); ($this->useCase)($this->presenter, $this->token->getName()); expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Token/Domain/Model/NewJwtTokenTest.php
centreon/tests/php/Core/Security/Token/Domain/Model/NewJwtTokenTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Token\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Common\Domain\TrimmedString; use Core\Security\Token\Domain\Model\NewApiToken; use Core\Security\Token\Domain\Model\NewToken; use Core\Security\Token\Domain\Model\Token; beforeEach(function (): void { $this->createToken = static fn (array $fields = []): NewToken => new NewApiToken( ...[ 'expirationDate' => (new \DateTimeImmutable())->add(new \DateInterval('P1Y')), 'userId' => 23, 'configurationProviderId' => 1, 'name' => new TrimmedString('token-name'), 'creatorId' => 12, 'creatorName' => new TrimmedString('John Doe'), ...$fields, ] ); }); it('should return properly set token instance', function (): void { $token = ($this->createToken)(); expect($token->getName())->toBe('token-name') ->and($token->getUserId())->toBe(23) ->and($token->getCreatorId())->toBe(12) ->and($token->getCreatorName())->toBe('John Doe'); }); foreach ( [ 'name', 'creatorName', ] as $field ) { it( "should throw an exception when token {$field} is an empty string", fn () => ($this->createToken)([$field => new TrimmedString(' ')]) )->throws( InvalidArgumentException::class, AssertionException::notEmptyString("NewApiToken::{$field}")->getMessage() ); } foreach ( [ 'name', 'creatorName', ] as $field ) { it( "should return a trimmed field {$field}", function () use ($field): void { $token = ($this->createToken)([$field => new TrimmedString(' some-text ')]); $valueFromGetter = $token->{'get' . $field}(); expect($valueFromGetter)->toBe('some-text'); } ); } // too long fields foreach ( [ 'name' => Token::MAX_TOKEN_NAME_LENGTH, 'creatorName' => Token::MAX_USER_NAME_LENGTH, ] as $field => $length ) { $tooLong = str_repeat('a', $length + 1); it( "should throw an exception when token {$field} is too long", fn () => ($this->createToken)([$field => new TrimmedString($tooLong)]) )->throws( InvalidArgumentException::class, AssertionException::maxLength($tooLong, $length + 1, $length, "NewApiToken::{$field}")->getMessage() ); } // foreign keys fields foreach ( [ 'creatorId', 'userId', 'configurationProviderId', ] as $field ) { it( "should throw an exception when token {$field} is not > 0", fn () => ($this->createToken)([$field => 0]) )->throws( InvalidArgumentException::class, AssertionException::positiveInt(0, "NewApiToken::{$field}")->getMessage() ); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Token/Domain/Model/NewApiTokenTest.php
centreon/tests/php/Core/Security/Token/Domain/Model/NewApiTokenTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Token\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Common\Domain\TrimmedString; use Core\Security\Token\Domain\Model\NewApiToken; use Core\Security\Token\Domain\Model\NewToken; use Core\Security\Token\Domain\Model\Token; beforeEach(function (): void { $this->createToken = static fn (array $fields = []): NewToken => new NewApiToken( ...[ 'expirationDate' => (new \DateTimeImmutable())->add(new \DateInterval('P1Y')), 'userId' => 23, 'configurationProviderId' => 1, 'name' => new TrimmedString('token-name'), 'creatorId' => 12, 'creatorName' => new TrimmedString('John Doe'), ...$fields, ] ); }); it('should return properly set token instance', function (): void { $token = ($this->createToken)(); expect($token->getName())->toBe('token-name') ->and($token->getUserId())->toBe(23) ->and($token->getCreatorId())->toBe(12) ->and($token->getCreatorName())->toBe('John Doe'); }); foreach ( [ 'name', 'creatorName', ] as $field ) { it( "should throw an exception when token {$field} is an empty string", fn () => ($this->createToken)([$field => new TrimmedString(' ')]) )->throws( InvalidArgumentException::class, AssertionException::notEmptyString("NewApiToken::{$field}")->getMessage() ); } foreach ( [ 'name', 'creatorName', ] as $field ) { it( "should return a trimmed field {$field}", function () use ($field): void { $token = ($this->createToken)([$field => new TrimmedString(' some-text ')]); $valueFromGetter = $token->{'get' . $field}(); expect($valueFromGetter)->toBe('some-text'); } ); } // too long fields foreach ( [ 'name' => Token::MAX_TOKEN_NAME_LENGTH, 'creatorName' => Token::MAX_USER_NAME_LENGTH, ] as $field => $length ) { $tooLong = str_repeat('a', $length + 1); it( "should throw an exception when token {$field} is too long", fn () => ($this->createToken)([$field => new TrimmedString($tooLong)]) )->throws( InvalidArgumentException::class, AssertionException::maxLength($tooLong, $length + 1, $length, "NewApiToken::{$field}")->getMessage() ); } // foreign keys fields foreach ( [ 'creatorId', 'userId', 'configurationProviderId', ] as $field ) { it( "should throw an exception when token {$field} is not > 0", fn () => ($this->createToken)([$field => 0]) )->throws( InvalidArgumentException::class, AssertionException::positiveInt(0, "NewApiToken::{$field}")->getMessage() ); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Token/Domain/Model/JwtTokenTest.php
centreon/tests/php/Core/Security/Token/Domain/Model/JwtTokenTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Token\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Common\Domain\TrimmedString; use Core\Security\Token\Domain\Model\ApiToken; use Core\Security\Token\Domain\Model\Token; beforeEach(function (): void { $this->createToken = static fn (array $fields = []): Token => new ApiToken( ...[ 'name' => new TrimmedString('token-name'), 'userId' => 23, 'userName' => new TrimmedString('John Doe'), 'creatorId' => 12, 'creatorName' => new TrimmedString('John Doe'), 'creationDate' => new \DateTimeImmutable(), 'expirationDate' => (new \DateTimeImmutable())->add(new \DateInterval('P1Y')), 'isRevoked' => false, ...$fields, ] ); }); it('should return properly set token instance', function (): void { $token = ($this->createToken)(); expect($token->getName())->toBe('token-name') ->and($token->getUserId())->toBe(23) ->and($token->getCreatorId())->toBe(12) ->and($token->getCreatorName())->toBe('John Doe') ->and($token->isRevoked())->toBe(false); }); foreach ( [ 'name', 'creatorName', ] as $field ) { it( "should throw an exception when token {$field} is an empty string", fn () => ($this->createToken)([$field => new TrimmedString(' ')]) )->throws( InvalidArgumentException::class, AssertionException::notEmptyString("ApiToken::{$field}")->getMessage() ); } foreach ( [ 'name', 'creatorName', ] as $field ) { it("should return a trimmed field {$field}", function () use ($field): void { $token = ($this->createToken)([$field => new TrimmedString(' some-text ')]); $valueFromGetter = $token->{'get' . $field}(); expect($valueFromGetter)->toBe('some-text'); }); } // too long fields foreach ( [ 'name' => Token::MAX_TOKEN_NAME_LENGTH, 'creatorName' => Token::MAX_USER_NAME_LENGTH, ] as $field => $length ) { $tooLong = str_repeat('a', $length + 1); it( "should throw an exception when token {$field} is too long", fn () => ($this->createToken)([$field => new TrimmedString($tooLong)]) )->throws( InvalidArgumentException::class, AssertionException::maxLength($tooLong, $length + 1, $length, "ApiToken::{$field}")->getMessage() ); } // foreign keys fields foreach ( [ // 'creatorId', 'userId', ] as $field ) { it( "should throw an exception when token {$field} is not > 0", fn () => ($this->createToken)([$field => 0]) )->throws( InvalidArgumentException::class, AssertionException::positiveInt(0, "ApiToken::{$field}")->getMessage() ); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Token/Domain/Model/ApiTokenTest.php
centreon/tests/php/Core/Security/Token/Domain/Model/ApiTokenTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Token\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Common\Domain\TrimmedString; use Core\Security\Token\Domain\Model\ApiToken; use Core\Security\Token\Domain\Model\Token; beforeEach(function (): void { $this->createToken = static fn (array $fields = []): Token => new ApiToken( ...[ 'name' => new TrimmedString('token-name'), 'userId' => 23, 'userName' => new TrimmedString('John Doe'), 'creatorId' => 12, 'creatorName' => new TrimmedString('John Doe'), 'creationDate' => new \DateTimeImmutable(), 'expirationDate' => (new \DateTimeImmutable())->add(new \DateInterval('P1Y')), 'isRevoked' => false, ...$fields, ] ); }); it('should return properly set token instance', function (): void { $token = ($this->createToken)(); expect($token->getName())->toBe('token-name') ->and($token->getUserId())->toBe(23) ->and($token->getCreatorId())->toBe(12) ->and($token->getCreatorName())->toBe('John Doe') ->and($token->isRevoked())->toBe(false); }); foreach ( [ 'name', 'creatorName', ] as $field ) { it( "should throw an exception when token {$field} is an empty string", fn () => ($this->createToken)([$field => new TrimmedString(' ')]) )->throws( InvalidArgumentException::class, AssertionException::notEmptyString("ApiToken::{$field}")->getMessage() ); } foreach ( [ 'name', 'creatorName', ] as $field ) { it("should return a trimmed field {$field}", function () use ($field): void { $token = ($this->createToken)([$field => new TrimmedString(' some-text ')]); $valueFromGetter = $token->{'get' . $field}(); expect($valueFromGetter)->toBe('some-text'); }); } // too long fields foreach ( [ 'name' => Token::MAX_TOKEN_NAME_LENGTH, 'creatorName' => Token::MAX_USER_NAME_LENGTH, ] as $field => $length ) { $tooLong = str_repeat('a', $length + 1); it( "should throw an exception when token {$field} is too long", fn () => ($this->createToken)([$field => new TrimmedString($tooLong)]) )->throws( InvalidArgumentException::class, AssertionException::maxLength($tooLong, $length + 1, $length, "ApiToken::{$field}")->getMessage() ); } // foreign keys fields foreach ( [ // 'creatorId', 'userId', ] as $field ) { it( "should throw an exception when token {$field} is not > 0", fn () => ($this->createToken)([$field => 0]) )->throws( InvalidArgumentException::class, AssertionException::positiveInt(0, "ApiToken::{$field}")->getMessage() ); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Token/Infrastructure/API/FindTokens/FindTokensPresenterStub.php
centreon/tests/php/Core/Security/Token/Infrastructure/API/FindTokens/FindTokensPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Token\Infrastructure\API\FindTokens; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Security\Token\Application\UseCase\FindTokens\FindTokensPresenterInterface; use Core\Security\Token\Application\UseCase\FindTokens\FindTokensResponse; class FindTokensPresenterStub extends AbstractPresenter implements FindTokensPresenterInterface { public ResponseStatusInterface|FindTokensResponse $response; public function presentResponse(ResponseStatusInterface|FindTokensResponse $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/Security/Token/Infrastructure/API/AddToken/AddTokenPresenterStub.php
centreon/tests/php/Core/Security/Token/Infrastructure/API/AddToken/AddTokenPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Token\Infrastructure\API\AddToken; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Security\Token\Application\UseCase\AddToken\AddTokenPresenterInterface; use Core\Security\Token\Application\UseCase\AddToken\AddTokenResponse; class AddTokenPresenterStub extends AbstractPresenter implements AddTokenPresenterInterface { public ResponseStatusInterface|AddTokenResponse $response; public function presentResponse(ResponseStatusInterface|AddTokenResponse $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/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfigurationPresenterStub.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfigurationPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\FindVaultConfiguration; use Core\Application\Common\UseCase\{AbstractPresenter, ResponseStatusInterface}; use Core\Security\Vault\Application\UseCase\FindVaultConfiguration\FindVaultConfigurationPresenterInterface; use Core\Security\Vault\Application\UseCase\FindVaultConfiguration\FindVaultConfigurationResponse; class FindVaultConfigurationPresenterStub extends AbstractPresenter implements FindVaultConfigurationPresenterInterface { /** * @var FindVaultConfigurationResponse|ResponseStatusInterface */ public FindVaultConfigurationResponse|ResponseStatusInterface $data; public function presentResponse(FindVaultConfigurationResponse|ResponseStatusInterface $data): void { $this->data = $data; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfigurationTest.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\FindVaultConfiguration; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\{ErrorResponse, ForbiddenResponse, NotFoundResponse}; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\Vault\Application\Exceptions\VaultConfigurationException; use Core\Security\Vault\Application\Repository\{ ReadVaultConfigurationRepositoryInterface }; use Core\Security\Vault\Application\UseCase\FindVaultConfiguration\{ FindVaultConfiguration, FindVaultConfigurationResponse }; use Core\Security\Vault\Domain\Model\{VaultConfiguration}; use Security\Encryption; beforeEach(function (): void { $this->readVaultConfigurationRepository = $this->createMock(ReadVaultConfigurationRepositoryInterface::class); $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class); $this->user = $this->createMock(ContactInterface::class); }); it('should present Forbidden Response when user is not admin', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $presenter = new FindVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new FindVaultConfiguration( $this->readVaultConfigurationRepository, $this->user ); $useCase($presenter); expect($presenter->data)->toBeInstanceOf(ForbiddenResponse::class); expect($presenter->data?->getMessage()) ->toBe(VaultConfigurationException::onlyForAdmin()->getMessage()); }); it('should present NotFound Response when vault configuration does not exist for a given id', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $presenter = new FindVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new FindVaultConfiguration( $this->readVaultConfigurationRepository, $this->user ); $useCase($presenter); expect($presenter->data)->toBeInstanceOf(NotFoundResponse::class); expect($presenter->data?->getMessage())->toBe( (new NotFoundResponse('Vault configuration'))->getMessage() ); }); it('should present ErrorResponse when an unhandled error occurs', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('exists') ->willThrowException(new \Exception()); $presenter = new FindVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new FindVaultConfiguration( $this->readVaultConfigurationRepository, $this->user ); $useCase($presenter); expect($presenter->data)->toBeInstanceOf(ErrorResponse::class); expect($presenter->data?->getMessage())->toBe( VaultConfigurationException::impossibleToFind()->getMessage() ); }); it('should present FindVaultConfigurationResponse', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $encryption = new Encryption(); $encryption->setFirstKey('myFirstKey'); $vaultConfiguration = new VaultConfiguration( $encryption, 'myVaultConfiguration', '127.0.0.1', 8200, 'myStorageFolder', 'mySalt', 'myEncryptedRoleId', 'myEncryptedSecretId' ); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('exists') ->willReturn(true); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('find') ->willReturn($vaultConfiguration); $presenter = new FindVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new FindVaultConfiguration( $this->readVaultConfigurationRepository, $this->user ); $findVaultConfigurationResponse = new FindVaultConfigurationResponse(); $findVaultConfigurationResponse->address = $vaultConfiguration->getAddress(); $findVaultConfigurationResponse->port = $vaultConfiguration->getPort(); $findVaultConfigurationResponse->rootPath = $vaultConfiguration->getRootPath(); $useCase($presenter); expect($presenter->data)->toBeInstanceOf(FindVaultConfigurationResponse::class); expect($presenter->data->address)->toBe($findVaultConfigurationResponse->address); expect($presenter->data->port)->toBe($findVaultConfigurationResponse->port); expect($presenter->data->rootPath)->toBe($findVaultConfigurationResponse->rootPath); });
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/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentialsTest.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentialsTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\MigrateAllCredentials; use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Broker\Application\Repository\ReadBrokerInputOutputRepositoryInterface; use Core\Broker\Application\Repository\WriteBrokerInputOutputRepositoryInterface; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Common\Infrastructure\FeatureFlags; use Core\Contact\Domain\Model\ContactTemplate; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\Host\Application\Repository\WriteHostRepositoryInterface; use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface; use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface; use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface; use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface; use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface; use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface; use Core\Option\Application\Repository\ReadOptionRepositoryInterface; use Core\Option\Application\Repository\WriteOptionRepositoryInterface; use Core\PollerMacro\Application\Repository\ReadPollerMacroRepositoryInterface; use Core\PollerMacro\Application\Repository\WritePollerMacroRepositoryInterface; use Core\Security\ProviderConfiguration\Application\OpenId\Repository\WriteOpenIdConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\Repository\ReadConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Domain\Model\ACLConditions; use Core\Security\ProviderConfiguration\Domain\Model\AuthenticationConditions; use Core\Security\ProviderConfiguration\Domain\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; use Core\Security\ProviderConfiguration\Domain\Model\GroupsMapping; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration; use Core\Security\Vault\Application\Exceptions\VaultException; use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialMigrator; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\MigrateAllCredentials; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\MigrateAllCredentialsResponse; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\Migrator\VmWareV6CredentialMigrator; use Core\Security\Vault\Domain\Model\VaultConfiguration; use Security\Interfaces\EncryptionInterface; beforeEach(function (): void { $this->encryption = $this->createMock(EncryptionInterface::class); $this->useCase = new MigrateAllCredentials( $this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class), $this->readVaultConfigurationRepository = $this->createMock(ReadVaultConfigurationRepositoryInterface::class), $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class), $this->readHostMacroRepository = $this->createMock(ReadHostMacroRepositoryInterface::class), $this->readHostTemplateRepository = $this->createMock(ReadHostTemplateRepositoryInterface::class), $this->readServiceMacroRepository = $this->createMock(ReadServiceMacroRepositoryInterface::class), $this->readOptionRepository = $this->createMock(ReadOptionRepositoryInterface::class), $this->readPollerMacroRepository = $this->createMock(ReadPollerMacroRepositoryInterface::class), $this->readProviderConfigurationRepository = $this->createMock(ReadConfigurationRepositoryInterface::class), $this->writeHostRepository = $this->createMock(WriteHostRepositoryInterface::class), $this->writeHostMacroRepository = $this->createMock(WriteHostMacroRepositoryInterface::class), $this->writeHostTemplateRepository = $this->createMock(WriteHostTemplateRepositoryInterface::class), $this->writeServiceMacroRepository = $this->createMock(WriteServiceMacroRepositoryInterface::class), $this->writeOptionRepository = $this->createMock(WriteOptionRepositoryInterface::class), $this->writePollerMacroRepository = $this->createMock(WritePollerMacroRepositoryInterface::class), $this->writeOpenIdConfigurationRepository = $this->createMock(WriteOpenIdConfigurationRepositoryInterface::class), $this->readBrokerInputOutputRepository = $this->createMock(ReadBrokerInputOutputRepositoryInterface::class), $this->writeBrokerInputOutputRepository = $this->createMock(WriteBrokerInputOutputRepositoryInterface::class), $this->readAccRepository = $this->createMock(ReadAccRepositoryInterface::class), $this->writeAccRepository = $this->createMock(WriteAccRepositoryInterface::class), $this->flags = new FeatureFlags(false, ''), $this->accCredentialMigrators = new \ArrayIterator([$this->createMock(VmWareV6CredentialMigrator::class)]), ); }); it('should present an Error Response when no vault are configured', function (): void { $this->readVaultConfigurationRepository ->expects($this->once()) ->method('find') ->willReturn(null); $presenter = new MigrateAllCredentialsPresenterStub(); ($this->useCase)($presenter); expect($presenter->response)->toBeInstanceOf(ErrorResponse::class) ->and($presenter->response->getMessage())->toBe(VaultException::noVaultConfigured()->getMessage()); }); it('should present a MigrateAllCredentialsResponse when no error occurs', function (): void { $vaultConfiguration = new VaultConfiguration( encryption: $this->encryption, name: 'vault', address: '127.0.0.1', port: 443, rootPath: 'mystorage', encryptedRoleId: 'role-id', encryptedSecretId: 'secret-id', salt: 'labaleine' ); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('find') ->willReturn($vaultConfiguration); $customConfiguration = new CustomConfiguration([ 'is_active' => true, 'client_id' => 'MyCl1ientId', 'client_secret' => 'MyCl1ientSuperSecr3tKey', 'base_url' => 'http://127.0.0.1/auth/openid-connect', 'auto_import' => false, 'authorization_endpoint' => '/authorization', 'token_endpoint' => '/token', 'introspection_token_endpoint' => '/introspect', 'userinfo_endpoint' => '/userinfo', 'contact_template' => new ContactTemplate(1, 'contact_template'), 'email_bind_attribute' => null, 'fullname_bind_attribute' => null, 'endsession_endpoint' => '/logout', 'connection_scopes' => [], 'login_claim' => 'preferred_username', 'authentication_type' => 'client_secret_post', 'verify_peer' => false, 'claim_name' => 'groups', 'roles_mapping' => new ACLConditions( false, false, '', new Endpoint(Endpoint::INTROSPECTION, ''), [] ), 'authentication_conditions' => new AuthenticationConditions(false, '', new Endpoint(), []), 'groups_mapping' => new GroupsMapping(false, '', new Endpoint(), []), 'redirect_url' => null, ]); $openIdProviderConfiguration = new Configuration( 1, type: Provider::OPENID, name: Provider::OPENID, jsonCustomConfiguration: '{}', isActive: true, isForced: false ); $openIdProviderConfiguration->setCustomConfiguration($customConfiguration); $this->readProviderConfigurationRepository ->expects($this->once()) ->method('getConfigurationByType') ->willReturn($openIdProviderConfiguration); $presenter = new MigrateAllCredentialsPresenterStub(); ($this->useCase)($presenter); expect($presenter->response)->toBeInstanceOf(MigrateAllCredentialsResponse::class) ->and($presenter->response->results)->toBeInstanceOf(CredentialMigrator::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentialsPresenterStub.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentialsPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\MigrateAllCredentials; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\MigrateAllCredentialsPresenterInterface; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\MigrateAllCredentialsResponse; class MigrateAllCredentialsPresenterStub implements MigrateAllCredentialsPresenterInterface { public ResponseStatusInterface|MigrateAllCredentialsResponse $response; public function presentResponse(ResponseStatusInterface|MigrateAllCredentialsResponse $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/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialMigratorTest.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialMigratorTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\MigrateAllCredentials; use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Acc; use Core\AdditionalConnectorConfiguration\Domain\Model\AccParametersInterface; use Core\AdditionalConnectorConfiguration\Domain\Model\Type as AccType; use Core\Broker\Application\Repository\ReadBrokerInputOutputRepositoryInterface; use Core\Broker\Application\Repository\WriteBrokerInputOutputRepositoryInterface; use Core\Broker\Domain\Model\BrokerInputOutput; use Core\Broker\Domain\Model\Type as BrokerIOType; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Contact\Domain\Model\ContactTemplate; use Core\Host\Application\Repository\WriteHostRepositoryInterface; use Core\Host\Domain\Model\Host; use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface; use Core\HostTemplate\Domain\Model\HostTemplate; use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface; use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface; use Core\Macro\Domain\Model\Macro; use Core\Option\Application\Repository\WriteOptionRepositoryInterface; use Core\PollerMacro\Application\Repository\WritePollerMacroRepositoryInterface; use Core\PollerMacro\Domain\Model\PollerMacro; use Core\Security\ProviderConfiguration\Application\OpenId\Repository\WriteOpenIdConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Domain\Model\ACLConditions; use Core\Security\ProviderConfiguration\Domain\Model\AuthenticationConditions; use Core\Security\ProviderConfiguration\Domain\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; use Core\Security\ProviderConfiguration\Domain\Model\GroupsMapping; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialDto; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialErrorDto; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialMigrator; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialRecordedDto; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialTypeEnum; use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\Migrator\VmWareV6CredentialMigrator; use Core\Security\Vault\Domain\Model\VaultConfiguration; use DateTimeImmutable; use Utility\UUIDGenerator; beforeEach(function (): void { $this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class); $this->writeHostRepository = $this->createMock(WriteHostRepositoryInterface::class); $this->writeHostTemplateRepository = $this->createMock(WriteHostTemplateRepositoryInterface::class); $this->writeHostMacroRepository = $this->createMock(WriteHostMacroRepositoryInterface::class); $this->writeServiceMacroRepository = $this->createMock(WriteServiceMacroRepositoryInterface::class); $this->writePollerMacroRepository = $this->createMock(WritePollerMacroRepositoryInterface::class); $this->writeOptionRepository = $this->createMock(WriteOptionRepositoryInterface::class); $this->writeOpenIdConfigurationRepository = $this->createMock(WriteOpenIdConfigurationRepositoryInterface::class); $this->readBrokerInputOutputRepository = $this->createMock(ReadBrokerInputOutputRepositoryInterface::class); $this->writeBrokerInputOutputRepository = $this->createMock(WriteBrokerInputOutputRepositoryInterface::class); $this->writeAccRepository = $this->createMock(WriteAccRepositoryInterface::class); $this->accCredentialMigrators = [$this->createMock(VmWareV6CredentialMigrator::class)]; $this->credential1 = new CredentialDto(); $this->credential1->resourceId = 1; $this->credential1->type = CredentialTypeEnum::TYPE_HOST; $this->credential1->name = VaultConfiguration::HOST_SNMP_COMMUNITY_KEY; $this->credential1->value = 'community'; $this->credential2 = new CredentialDto(); $this->credential2->resourceId = 2; $this->credential2->type = CredentialTypeEnum::TYPE_HOST_TEMPLATE; $this->credential2->name = VaultConfiguration::HOST_SNMP_COMMUNITY_KEY; $this->credential2->value = 'community'; $this->credential3 = new CredentialDto(); $this->credential3->resourceId = 3; $this->credential3->type = CredentialTypeEnum::TYPE_SERVICE; $this->credential3->name = 'MACRO'; $this->credential3->value = 'macro'; $this->credential4 = new CredentialDto(); $this->credential4->resourceId = 4; $this->credential4->type = CredentialTypeEnum::TYPE_POLLER_MACRO; $this->credential4->name = '$POLLERMACRO$'; $this->credential4->value = 'value'; $this->credential5 = new CredentialDto(); $this->credential5->resourceId = 5; $this->credential5->type = CredentialTypeEnum::TYPE_BROKER_INPUT_OUTPUT; $this->credential5->name = 'my-output_db_password'; $this->credential5->value = 'my-password'; $this->hosts = [ new Host(1, 1, 'Host1', '127.0.0.1'), ]; $this->hostTemplates = [ new HostTemplate(2, 'HostTemplate1', 'HostTemplate1'), ]; $this->hostMacro = new Macro(null, 1, '_MACRO_HOST1', 'value'); $this->hostMacro->setIsPassword(true); $this->hostMacros = [$this->hostMacro]; $this->serviceMacro = new Macro(null, 1, '_MACRO_SERVICE1', 'value'); $this->serviceMacro->setIsPassword(true); $this->serviceMacros = [$this->serviceMacro]; $this->pollerMacro = new PollerMacro(1, '$POLLERMACRO$', 'value', null, true, true); $this->pollerMacros = [$this->pollerMacro]; $customConfiguration = new CustomConfiguration([ 'is_active' => true, 'client_id' => 'MyCl1ientId', 'client_secret' => 'MyCl1ientSuperSecr3tKey', 'base_url' => 'http://127.0.0.1/auth/openid-connect', 'auto_import' => false, 'authorization_endpoint' => '/authorization', 'token_endpoint' => '/token', 'introspection_token_endpoint' => '/introspect', 'userinfo_endpoint' => '/userinfo', 'contact_template' => new ContactTemplate(1, 'contact_template'), 'email_bind_attribute' => null, 'fullname_bind_attribute' => null, 'endsession_endpoint' => '/logout', 'connection_scopes' => [], 'login_claim' => 'preferred_username', 'authentication_type' => 'client_secret_post', 'verify_peer' => false, 'claim_name' => 'groups', 'roles_mapping' => new ACLConditions( false, false, '', new Endpoint(Endpoint::INTROSPECTION, ''), [] ), 'authentication_conditions' => new AuthenticationConditions(false, '', new Endpoint(), []), 'groups_mapping' => new GroupsMapping(false, '', new Endpoint(), []), 'redirect_url' => null, ]); $this->openIdProviderConfiguration = new Configuration( 1, type: Provider::OPENID, name: Provider::OPENID, jsonCustomConfiguration: '{}', isActive: true, isForced: false ); $this->openIdProviderConfiguration->setCustomConfiguration($customConfiguration); $this->brokerInputOutputs = new BrokerInputOutput( id: 0, tag: 'output', type: new BrokerIOType(29, 'Database configuration writer'), name: 'my-output', parameters: [ 'db_type' => 'db2', 'db_host' => 'localhost', 'db_port' => 8080, 'db_user' => 'admin', 'db_password' => 'my-password', 'db_name' => 'centreon', ] ); $this->acc = new Acc( id: 1, name: 'my-ACC', type: AccType::VMWARE_V6, createdBy: 1, updatedBy: 1, createdAt: new DateTimeImmutable(), updatedAt: new DateTimeImmutable(), parameters: $this->createMock(AccParametersInterface::class) ); }); it('tests getIterator method with hosts, hostTemplates and service macros', function (): void { $credentials = new \ArrayIterator([$this->credential1, $this->credential2, $this->credential3]); $uuid = (new UUIDGenerator())->generateV4(); $this->writeVaultRepository->method('upsert')->willReturnOnConsecutiveCalls( [$this->credential1->name => 'secret::hashicorp_vault::vault/path/' . $uuid . '::' . $this->credential1->name], [$this->credential2->name => 'secret::hashicorp_vault::vault/path/' . $uuid . '::' . $this->credential2->name], ['_SERVICE' . $this->credential3->name => 'secret::hashicorp_vault::vault/path/' . $uuid . '::' . '_SERVICE' . $this->credential3->name], ); $credentialMigrator = new CredentialMigrator( credentials: $credentials, writeVaultRepository: $this->writeVaultRepository, writeHostRepository: $this->writeHostRepository, writeHostTemplateRepository: $this->writeHostTemplateRepository, writeHostMacroRepository: $this->writeHostMacroRepository, writeServiceMacroRepository: $this->writeServiceMacroRepository, writeOptionRepository: $this->writeOptionRepository, writePollerMacroRepository: $this->writePollerMacroRepository, writeOpenIdConfigurationRepository: $this->writeOpenIdConfigurationRepository, readBrokerInputOutputRepository: $this->readBrokerInputOutputRepository, writeBrokerInputOutputRepository: $this->writeBrokerInputOutputRepository, writeAccRepository: $this->writeAccRepository, accCredentialMigrators: $this->accCredentialMigrators, hosts: $this->hosts, hostTemplates: $this->hostTemplates, hostMacros: $this->hostMacros, serviceMacros: $this->serviceMacros, pollerMacros: $this->pollerMacros, openIdProviderConfiguration: $this->openIdProviderConfiguration, brokerInputOutputs: [5 => [$this->brokerInputOutputs]], accs: [$this->acc], ); foreach ($credentialMigrator as $status) { expect($status)->toBeInstanceOf(CredentialRecordedDto::class); expect($status->uuid)->toBe($uuid); expect($status->resourceId)->toBeIn([1, 2, 3]); expect($status->vaultPath)->toBe( 'secret::hashicorp_vault::vault/path/' . $uuid . '::' . ($status->type === CredentialTypeEnum::TYPE_SERVICE ? '_SERVICE' . $status->credentialName : $status->credentialName) ); expect($status->type)->toBeIn([CredentialTypeEnum::TYPE_HOST, CredentialTypeEnum::TYPE_HOST_TEMPLATE, CredentialTypeEnum::TYPE_SERVICE]); expect($status->credentialName)->toBeIn([VaultConfiguration::HOST_SNMP_COMMUNITY_KEY, 'MACRO']); } }); it('tests getIterator method with poller macros', function (): void { $credentials = new \ArrayIterator([$this->credential4]); $uuid = (new UUIDGenerator())->generateV4(); $this->writeVaultRepository->method('upsert')->willReturn( [$this->credential4->name => 'secret::hashicorp_vault::vault/path/' . $uuid . '::' . $this->credential4->name] ); $credentialMigrator = new CredentialMigrator( credentials: $credentials, writeVaultRepository: $this->writeVaultRepository, writeHostRepository: $this->writeHostRepository, writeHostTemplateRepository: $this->writeHostTemplateRepository, writeHostMacroRepository: $this->writeHostMacroRepository, writeServiceMacroRepository: $this->writeServiceMacroRepository, writeOptionRepository: $this->writeOptionRepository, writePollerMacroRepository: $this->writePollerMacroRepository, writeOpenIdConfigurationRepository: $this->writeOpenIdConfigurationRepository, readBrokerInputOutputRepository: $this->readBrokerInputOutputRepository, writeBrokerInputOutputRepository: $this->writeBrokerInputOutputRepository, writeAccRepository: $this->writeAccRepository, accCredentialMigrators: $this->accCredentialMigrators, hosts: $this->hosts, hostTemplates: $this->hostTemplates, hostMacros: $this->hostMacros, serviceMacros: $this->serviceMacros, pollerMacros: $this->pollerMacros, openIdProviderConfiguration: $this->openIdProviderConfiguration, brokerInputOutputs: [5 => [$this->brokerInputOutputs]], accs: [$this->acc], ); foreach ($credentialMigrator as $status) { expect($status)->toBeInstanceOf(CredentialRecordedDto::class); expect($status->uuid)->toBe($uuid); expect($status->resourceId)->toBeIn([4]); expect($status->vaultPath)->toBe( 'secret::hashicorp_vault::vault/path/' . $uuid . '::' . $this->credential4->name ); expect($status->type)->toBeIn([CredentialTypeEnum::TYPE_POLLER_MACRO]); expect($status->credentialName)->toBeIn(['$POLLERMACRO$']); } }); it('tests getIterator method with broker input/output configuration', function (): void { $credentials = new \ArrayIterator([$this->credential5]); $uuid = (new UUIDGenerator())->generateV4(); $this->writeVaultRepository->method('upsert')->willReturn( [$this->credential5->name => 'secret::hashicorp_vault::vault/path/' . $uuid . '::' . $this->credential5->name] ); $credentialMigrator = new CredentialMigrator( credentials: $credentials, writeVaultRepository: $this->writeVaultRepository, writeHostRepository: $this->writeHostRepository, writeHostTemplateRepository: $this->writeHostTemplateRepository, writeHostMacroRepository: $this->writeHostMacroRepository, writeServiceMacroRepository: $this->writeServiceMacroRepository, writeOptionRepository: $this->writeOptionRepository, writePollerMacroRepository: $this->writePollerMacroRepository, writeOpenIdConfigurationRepository: $this->writeOpenIdConfigurationRepository, readBrokerInputOutputRepository: $this->readBrokerInputOutputRepository, writeBrokerInputOutputRepository: $this->writeBrokerInputOutputRepository, writeAccRepository: $this->writeAccRepository, accCredentialMigrators: $this->accCredentialMigrators, hosts: $this->hosts, hostTemplates: $this->hostTemplates, hostMacros: $this->hostMacros, serviceMacros: $this->serviceMacros, pollerMacros: $this->pollerMacros, openIdProviderConfiguration: $this->openIdProviderConfiguration, brokerInputOutputs: [5 => [$this->brokerInputOutputs]], accs: [$this->acc], ); foreach ($credentialMigrator as $status) { expect($status)->toBeInstanceOf(CredentialRecordedDto::class); expect($status->uuid)->toBe($uuid); expect($status->resourceId)->toBeIn([5]); expect($status->vaultPath)->toBe( 'secret::hashicorp_vault::vault/path/' . $uuid . '::' . $this->credential5->name ); expect($status->type)->toBeIn([CredentialTypeEnum::TYPE_BROKER_INPUT_OUTPUT]); expect($status->credentialName)->toBeIn(['my-output_db_password']); } }); it('tests getIterator method with exception', function (): void { $credentials = new \ArrayIterator([$this->credential1]); $this->writeVaultRepository->method('upsert')->willThrowException(new \Exception('Test exception')); $credentialMigrator = new CredentialMigrator( credentials: $credentials, writeVaultRepository: $this->writeVaultRepository, writeHostRepository: $this->writeHostRepository, writeHostTemplateRepository: $this->writeHostTemplateRepository, writeHostMacroRepository: $this->writeHostMacroRepository, writeServiceMacroRepository: $this->writeServiceMacroRepository, writeOptionRepository: $this->writeOptionRepository, writePollerMacroRepository: $this->writePollerMacroRepository, writeOpenIdConfigurationRepository: $this->writeOpenIdConfigurationRepository, readBrokerInputOutputRepository: $this->readBrokerInputOutputRepository, writeBrokerInputOutputRepository: $this->writeBrokerInputOutputRepository, writeAccRepository: $this->writeAccRepository, accCredentialMigrators: $this->accCredentialMigrators, hosts: $this->hosts, hostTemplates: $this->hostTemplates, hostMacros: $this->hostMacros, serviceMacros: $this->serviceMacros, pollerMacros: $this->pollerMacros, openIdProviderConfiguration: $this->openIdProviderConfiguration, brokerInputOutputs: [5 => [$this->brokerInputOutputs]], accs: [$this->acc], ); foreach ($credentialMigrator as $status) { expect($status)->toBeInstanceOf(CredentialErrorDto::class); expect($status->resourceId)->toBe(1); expect($status->type)->toBe(CredentialTypeEnum::TYPE_HOST); expect($status->credentialName)->toBe(VaultConfiguration::HOST_SNMP_COMMUNITY_KEY); expect($status->message)->toBe('Test exception'); } });
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/Security/Vault/Application/UseCase/DeleteVaultConfiguration/DeleteVaultConfigurationTest.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/DeleteVaultConfiguration/DeleteVaultConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\DeleteVaultConfiguration; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\{ ErrorResponse, ForbiddenResponse, NoContentResponse, NotFoundResponse }; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\Vault\Application\Exceptions\VaultConfigurationException; use Core\Security\Vault\Application\Repository\{ ReadVaultConfigurationRepositoryInterface, WriteVaultConfigurationRepositoryInterface }; use Core\Security\Vault\Application\UseCase\DeleteVaultConfiguration\{ DeleteVaultConfiguration }; beforeEach(function (): void { $this->readVaultConfigurationRepository = $this->createMock(ReadVaultConfigurationRepositoryInterface::class); $this->writeVaultConfigurationRepository = $this->createMock(WriteVaultConfigurationRepositoryInterface::class); $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class); $this->user = $this->createMock(ContactInterface::class); }); it('should present ForbiddenResponse when user is not admin', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $presenter = new DeleteVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new DeleteVaultConfiguration( $this->readVaultConfigurationRepository, $this->writeVaultConfigurationRepository, $this->user ); $useCase($presenter); expect($presenter->getResponseStatus())->toBeInstanceOf(ForbiddenResponse::class); expect($presenter->getResponseStatus()?->getMessage()) ->toBe(VaultConfigurationException::onlyForAdmin()->getMessage()); }); it('should present NotFoundResponse when vault configuration does not exist for a given id', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $presenter = new DeleteVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new DeleteVaultConfiguration( $this->readVaultConfigurationRepository, $this->writeVaultConfigurationRepository, $this->user ); $useCase($presenter); expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class); expect($presenter->getResponseStatus()?->getMessage())->toBe( (new NotFoundResponse('Vault configuration'))->getMessage() ); }); it('should present ErrorResponse when an unhandled error occurs', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('exists') ->willThrowException(new \Exception()); $presenter = new DeleteVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new DeleteVaultConfiguration( $this->readVaultConfigurationRepository, $this->writeVaultConfigurationRepository, $this->user ); $useCase($presenter); expect($presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class); expect($presenter->getResponseStatus()?->getMessage())->toBe( VaultConfigurationException::impossibleToDelete()->getMessage() ); }); it('should present NoContentResponse when vault configuration is deleted with success', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('exists') ->willReturn(true); $presenter = new DeleteVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new DeleteVaultConfiguration( $this->readVaultConfigurationRepository, $this->writeVaultConfigurationRepository, $this->user ); $useCase($presenter); expect($presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Vault/Application/UseCase/DeleteVaultConfiguration/DeleteVaultConfigurationPresenterStub.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/DeleteVaultConfiguration/DeleteVaultConfigurationPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\DeleteVaultConfiguration; use Core\Application\Common\UseCase\{AbstractPresenter, PresenterInterface}; class DeleteVaultConfigurationPresenterStub extends AbstractPresenter implements PresenterInterface { }
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/Security/Vault/Application/UseCase/UpdateVaultConfiguration/UpdateVaultConfigurationTest.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/UpdateVaultConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\UpdateVaultConfiguration; use Centreon\Domain\Common\Assertion\AssertionException; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\{ ErrorResponse, ForbiddenResponse, InvalidArgumentResponse, NoContentResponse }; use Core\Common\Application\Repository\ReadVaultRepositoryInterface; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\Vault\Application\Exceptions\VaultConfigurationException; use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface; use Core\Security\Vault\Application\Repository\WriteVaultConfigurationRepositoryInterface; use Core\Security\Vault\Application\UseCase\UpdateVaultConfiguration\NewVaultConfigurationFactory; use Core\Security\Vault\Application\UseCase\UpdateVaultConfiguration\UpdateVaultConfiguration; use Core\Security\Vault\Application\UseCase\UpdateVaultConfiguration\UpdateVaultConfigurationRequest; use Core\Security\Vault\Domain\Model\{VaultConfiguration}; use Security\Encryption; beforeEach(function (): void { $this->readVaultConfigurationRepository = $this->createMock(ReadVaultConfigurationRepositoryInterface::class); $this->writeVaultConfigurationRepository = $this->createMock(WriteVaultConfigurationRepositoryInterface::class); $this->newVaultConfigurationFactory = $this->createMock(NewVaultConfigurationFactory::class); $this->readVaultRepository = $this->createMock(ReadVaultRepositoryInterface::class); $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class); $this->user = $this->createMock(ContactInterface::class); }); it('should present ForbiddenResponse when user is not admin', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $presenter = new UpdateVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new UpdateVaultConfiguration( $this->readVaultConfigurationRepository, $this->writeVaultConfigurationRepository, $this->newVaultConfigurationFactory, $this->readVaultRepository, $this->user ); $updateVaultConfigurationRequest = new UpdateVaultConfigurationRequest(); $useCase($presenter, $updateVaultConfigurationRequest); expect($presenter->getResponseStatus())->toBeInstanceOf(ForbiddenResponse::class); expect($presenter->getResponseStatus()?->getMessage()) ->toBe(VaultConfigurationException::onlyForAdmin()->getMessage()); }); it('should present InvalidArgumentResponse when one parameter is not valid', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readVaultConfigurationRepository ->expects($this->any()) ->method('exists') ->willReturn(true); $encryption = new Encryption(); $encryption->setFirstKey('myFirstKey'); $salt = $encryption->generateRandomString(VaultConfiguration::SALT_LENGTH); $vaultConfiguration = new VaultConfiguration( $encryption, 'myVaultConfiguration', '127.0.0.2', 8200, 'myStorageFolder', 'myEncryptedRoleId', 'myEncryptedSecretId', $salt ); $this->readVaultConfigurationRepository ->expects($this->any()) ->method('find') ->willReturn($vaultConfiguration); $presenter = new UpdateVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new UpdateVaultConfiguration( $this->readVaultConfigurationRepository, $this->writeVaultConfigurationRepository, $this->newVaultConfigurationFactory, $this->readVaultRepository, $this->user ); $invalidAddress = '._@'; $updateVaultConfigurationRequest = new UpdateVaultConfigurationRequest(); $updateVaultConfigurationRequest->address = $invalidAddress; $updateVaultConfigurationRequest->port = 8200; $updateVaultConfigurationRequest->rootPath = 'myStorageFolder'; $updateVaultConfigurationRequest->roleId = 'myRole'; $updateVaultConfigurationRequest->secretId = 'mySecretId'; $useCase($presenter, $updateVaultConfigurationRequest); expect($presenter->getResponseStatus())->toBeInstanceOf(InvalidArgumentResponse::class); expect($presenter->getResponseStatus()?->getMessage())->toBe( AssertionException::ipOrDomain( $invalidAddress, 'VaultConfiguration::address' )->getMessage() ); }); it('should present ErrorResponse when an unhandled error occurs', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('exists') ->willThrowException(new \Exception()); $presenter = new UpdateVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new UpdateVaultConfiguration( $this->readVaultConfigurationRepository, $this->writeVaultConfigurationRepository, $this->newVaultConfigurationFactory, $this->readVaultRepository, $this->user ); $updateVaultConfigurationRequest = new UpdateVaultConfigurationRequest(); $useCase($presenter, $updateVaultConfigurationRequest); expect($presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class); expect($presenter->getResponseStatus()?->getMessage())->toBe( VaultConfigurationException::impossibleToUpdate()->getMessage() ); }); it('should present NoContentResponse when vault configuration is created with success', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('exists') ->willReturn(true); $encryption = new Encryption(); $encryption->setFirstKey('myFirstKey'); $vaultConfiguration = new VaultConfiguration( $encryption, 'myVaultConfiguration', '127.0.0.2', 8201, 'myStorageFolder', 'myEncryptedRoleId', 'myEncryptedSecretId', 'mySalt' ); $this->readVaultConfigurationRepository ->expects($this->once()) ->method('find') ->willReturn($vaultConfiguration); $this->readVaultRepository ->expects($this->any()) ->method('testVaultConnection') ->willReturn(true); $presenter = new UpdateVaultConfigurationPresenterStub($this->presenterFormatter); $useCase = new UpdateVaultConfiguration( $this->readVaultConfigurationRepository, $this->writeVaultConfigurationRepository, $this->newVaultConfigurationFactory, $this->readVaultRepository, $this->user ); $updateVaultConfigurationRequest = new UpdateVaultConfigurationRequest(); $updateVaultConfigurationRequest->address = '127.0.0.1'; $updateVaultConfigurationRequest->port = 8200; $updateVaultConfigurationRequest->rootPath = 'myStorageFolder'; $updateVaultConfigurationRequest->roleId = 'myRole'; $updateVaultConfigurationRequest->secretId = 'mySecretId'; $useCase($presenter, $updateVaultConfigurationRequest); expect($presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/NewVaultConfigurationFactoryTest.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/NewVaultConfigurationFactoryTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\UpdateVaultConfiguration; use Core\Security\Vault\Application\UseCase\UpdateVaultConfiguration\NewVaultConfigurationFactory; use Core\Security\Vault\Application\UseCase\UpdateVaultConfiguration\UpdateVaultConfigurationRequest; use Core\Security\Vault\Domain\Model\{NewVaultConfiguration}; use Security\Encryption; it( 'should return an instance of NewVaultConfiguration when a valid request is passed to create method', function (): void { $encryption = new Encryption(); $factory = new NewVaultConfigurationFactory( $encryption->setFirstKey('myFirstKey') ); $updateVaultConfigurationRequest = new UpdateVaultConfigurationRequest(); $updateVaultConfigurationRequest->address = '127.0.0.1'; $updateVaultConfigurationRequest->port = 8200; $updateVaultConfigurationRequest->rootPath = 'myStorage'; $updateVaultConfigurationRequest->roleId = 'myRoleId'; $updateVaultConfigurationRequest->secretId = 'mySecretId'; $newVaultConfiguration = $factory->create($updateVaultConfigurationRequest); expect($newVaultConfiguration)->toBeInstanceOf(NewVaultConfiguration::class); } ); it('should encrypt roleId and secretId correctly', function (): void { $encryption = new Encryption(); $encryption = $encryption->setFirstKey('myFirstKey'); $factory = new NewVaultConfigurationFactory($encryption); $updateVaultConfigurationRequest = new UpdateVaultConfigurationRequest(); $updateVaultConfigurationRequest->address = '127.0.0.1'; $updateVaultConfigurationRequest->port = 8200; $updateVaultConfigurationRequest->rootPath = 'myStorage'; $updateVaultConfigurationRequest->roleId = 'myRoleId'; $updateVaultConfigurationRequest->secretId = 'mySecretId'; $newVaultConfiguration = $factory->create($updateVaultConfigurationRequest); $encryption = $encryption->setSecondKey($newVaultConfiguration->getSalt()); $roleId = $encryption->decrypt($newVaultConfiguration->getEncryptedRoleId()); $secretId = $encryption->decrypt($newVaultConfiguration->getEncryptedSecretId()); expect($roleId)->toBe($updateVaultConfigurationRequest->roleId); expect($secretId)->toBe($updateVaultConfigurationRequest->secretId); });
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/Security/Vault/Application/UseCase/UpdateVaultConfiguration/UpdateVaultConfigurationPresenterStub.php
centreon/tests/php/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/UpdateVaultConfigurationPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Application\UseCase\UpdateVaultConfiguration; use Core\Application\Common\UseCase\{AbstractPresenter, PresenterInterface}; class UpdateVaultConfigurationPresenterStub extends AbstractPresenter implements PresenterInterface { }
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/Security/Vault/Domain/Model/NewVaultConfigurationTest.php
centreon/tests/php/Core/Security/Vault/Domain/Model/NewVaultConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Vault\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Security\Vault\Domain\Model\NewVaultConfiguration; use Security\Encryption; $invalidMinLengthString = ''; $invalidMaxLengthString = ''; for ($index = 0; $index <= NewVaultConfiguration::MAX_LENGTH; $index++) { $invalidMaxLengthString .= 'a'; } $invalidNameMaxLengthString = str_repeat('a', NewVaultConfiguration::NAME_MAX_LENGTH + 1); beforeEach(function (): void { $this->encryption = new Encryption(); $this->encryption->setFirstKey('myFirstKey'); }); it( 'should throw InvalidArgumentException when vault configuration name is empty', function () use ($invalidMinLengthString): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', 8200, 'myStorage', 'myRoleId', 'mySecretId', $invalidMinLengthString, ); } )->throws( InvalidArgumentException::class, AssertionException::minLength( $invalidMinLengthString, mb_strlen($invalidMinLengthString), NewVaultConfiguration::MIN_LENGTH, 'NewVaultConfiguration::name' )->getMessage() ); it( 'should throw InvalidArgumentException when vault configuration name exceeds allowed max length', function () use ($invalidNameMaxLengthString): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', 8200, 'myStorage', 'myRoleId', 'mySecretId', $invalidNameMaxLengthString, ); } )->throws( InvalidArgumentException::class, AssertionException::maxLength( $invalidNameMaxLengthString, mb_strlen($invalidNameMaxLengthString), NewVaultConfiguration::NAME_MAX_LENGTH, 'NewVaultConfiguration::name' )->getMessage() ); it( 'should throw InvalidArgumentException when vault configuration address is empty', function () use ($invalidMinLengthString): void { new NewVaultConfiguration( $this->encryption, $invalidMinLengthString, 8200, 'myStorage', 'myRoleId', 'mySecretId', 'myVault', ); } )->throws( InvalidArgumentException::class, AssertionException::minLength( $invalidMinLengthString, mb_strlen($invalidMinLengthString), NewVaultConfiguration::MIN_LENGTH, 'NewVaultConfiguration::address' )->getMessage() ); it('should throw AssertionException when vault configuration address is \'._@\'', function (): void { new NewVaultConfiguration( $this->encryption, '._@', 8200, 'myStorage', 'myRoleId', 'mySecretId', 'myVault', ); })->throws( AssertionException::class, AssertionException::ipOrDomain('._@', 'NewVaultConfiguration::address')->getMessage() ); it( 'should throw InvalidArgumentException when vault configuration port value is lower than allowed range', function (): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', 0, 'myStorage', 'myRoleId', 'mySecretId', 'myVault', ); } )->throws( InvalidArgumentException::class, AssertionException::min( NewVaultConfiguration::MIN_PORT_VALUE - 1, NewVaultConfiguration::MIN_PORT_VALUE, 'NewVaultConfiguration::port' )->getMessage() ); it('should throw InvalidArgumentException when vault configuration port exceeds allowed range', function (): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', NewVaultConfiguration::MAX_PORT_VALUE + 1, 'myStorage', 'myRoleId', 'mySecretId', 'myVault', ); })->throws( InvalidArgumentException::class, AssertionException::max( NewVaultConfiguration::MAX_PORT_VALUE + 1, NewVaultConfiguration::MAX_PORT_VALUE, 'NewVaultConfiguration::port' )->getMessage() ); it( 'should throw InvalidArgumentException when vault configuration rootPath is empty', function () use ($invalidMinLengthString): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', 8200, $invalidMinLengthString, 'myRoleId', 'mySecretId', 'myVault', ); } )->throws( InvalidArgumentException::class, AssertionException::minLength( $invalidMinLengthString, mb_strlen($invalidMinLengthString), NewVaultConfiguration::MIN_LENGTH, 'NewVaultConfiguration::rootPath' )->getMessage() ); it( 'should throw InvalidArgumentException when vault configuration rootPath exceeds allowed max length', function () use ($invalidNameMaxLengthString): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', 8200, $invalidNameMaxLengthString, 'myRoleId', 'mySecretId', 'myVault', ); } )->throws( InvalidArgumentException::class, AssertionException::maxLength( $invalidNameMaxLengthString, mb_strlen($invalidNameMaxLengthString), NewVaultConfiguration::NAME_MAX_LENGTH, 'NewVaultConfiguration::rootPath' )->getMessage() ); it( 'should throw InvalidArgumentException when vault configuration role id is empty', function () use ($invalidMinLengthString): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', 8200, 'myStorage', $invalidMinLengthString, 'mySecretId', 'myVault', ); } )->throws( InvalidArgumentException::class, AssertionException::minLength( $invalidMinLengthString, mb_strlen($invalidMinLengthString), NewVaultConfiguration::MIN_LENGTH, 'NewVaultConfiguration::roleId' )->getMessage() ); it( 'should throw InvalidArgumentException when vault configuration role id exceeds allowed max length', function () use ($invalidMaxLengthString): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', 8200, 'myStorage', $invalidMaxLengthString, 'mySecretId', 'myVault', ); } )->throws( InvalidArgumentException::class, AssertionException::maxLength( $invalidMaxLengthString, mb_strlen($invalidMaxLengthString), NewVaultConfiguration::MAX_LENGTH, 'NewVaultConfiguration::roleId' )->getMessage() ); it( 'should throw InvalidArgumentException when vault configuration secret id is empty', function () use ($invalidMinLengthString): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', 8200, 'myStorage', 'myRoleId', $invalidMinLengthString, 'myVault', ); } )->throws( InvalidArgumentException::class, AssertionException::minLength( $invalidMinLengthString, mb_strlen($invalidMinLengthString), NewVaultConfiguration::MIN_LENGTH, 'NewVaultConfiguration::secretId' )->getMessage() ); it( 'should throw InvalidArgumentException when vault configuration secret id exceeds allowed max length', function () use ($invalidMaxLengthString): void { new NewVaultConfiguration( $this->encryption, '127.0.0.1', 8200, 'myStorage', 'myRoleId', $invalidMaxLengthString, 'myVault', ); } )->throws( InvalidArgumentException::class, AssertionException::maxLength( $invalidMaxLengthString, mb_strlen($invalidMaxLengthString), NewVaultConfiguration::MAX_LENGTH, 'NewVaultConfiguration::secretId' )->getMessage() ); it( 'should return an instance of NewVaultConfiguration when all vault configuration parametes are valid', function (): void { $newVaultConfiguration = new NewVaultConfiguration( $this->encryption, '127.0.0.1', 8200, 'myStorage', 'myRoleId', 'mySecretId', 'myVault', ); expect($newVaultConfiguration->getName())->toBe('myVault'); expect($newVaultConfiguration->getAddress())->toBe('127.0.0.1'); expect($newVaultConfiguration->getPort())->toBe(8200); expect($newVaultConfiguration->getRootPath())->toBe('myStorage'); } );
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/Security/Authentication/Application/UseCase/LoginOpenIdSession/LoginOpenIdSessionTest.php
centreon/tests/php/Core/Security/Authentication/Application/UseCase/LoginOpenIdSession/LoginOpenIdSessionTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Authentication\Application\UseCase\LoginOpenIdSession; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Menu\Interfaces\MenuServiceInterface; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Centreon\Infrastructure\Service\Exception\NotFoundException; use CentreonDB; use Core\Application\Common\UseCase\ErrorResponse; use Core\Contact\Application\Repository\WriteContactGroupRepositoryInterface; use Core\Contact\Domain\Model\ContactTemplate; use Core\Infrastructure\Common\Presenter\JsonFormatter; use Core\Security\AccessGroup\Application\Repository\WriteAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; 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\Application\Repository\WriteSessionTokenRepositoryInterface; use Core\Security\Authentication\Application\Repository\WriteTokenRepositoryInterface; use Core\Security\Authentication\Application\UseCase\Login\Login; use Core\Security\Authentication\Application\UseCase\Login\LoginRequest; use Core\Security\Authentication\Application\UseCase\Login\ThirdPartyLoginForm; use Core\Security\Authentication\Infrastructure\Api\Login\OpenId\LoginPresenter; use Core\Security\Authentication\Infrastructure\Provider\AclUpdaterInterface; use Core\Security\Authentication\Infrastructure\Repository\WriteSessionRepository; use Core\Security\ProviderConfiguration\Application\OpenId\Repository\ReadOpenIdConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Domain\Model\ACLConditions; use Core\Security\ProviderConfiguration\Domain\Model\AuthenticationConditions; use Core\Security\ProviderConfiguration\Domain\Model\AuthorizationRule; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; use Core\Security\ProviderConfiguration\Domain\Model\GroupsMapping; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration; use Pimple\Container; use Security\Domain\Authentication\Exceptions\ProviderException; use Security\Domain\Authentication\Interfaces\AuthenticationRepositoryInterface; use Security\Domain\Authentication\Interfaces\AuthenticationServiceInterface; use Security\Domain\Authentication\Interfaces\OpenIdProviderInterface; use Security\Domain\Authentication\Interfaces\ProviderServiceInterface; use Security\Domain\Authentication\Interfaces\SessionRepositoryInterface; use Security\Domain\Authentication\Model\AuthenticationTokens; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; beforeEach(function (): void { $this->repository = $this->createMock(ReadOpenIdConfigurationRepositoryInterface::class); $this->provider = $this->createMock(ProviderAuthenticationInterface::class); $this->legacyProvider = $this->createMock(OpenIdProviderInterface::class); $this->legacyProviderService = $this->createMock(ProviderServiceInterface::class); $this->requestStack = $this->createMock(RequestStack::class); $this->centreonDB = $this->createMock(CentreonDB::class); $this->dependencyInjector = new Container(['configuration_db' => $this->centreonDB]); $this->authenticationService = $this->createMock(AuthenticationServiceInterface::class); $this->authenticationRepository = $this->createMock(AuthenticationRepositoryInterface::class); $this->sessionRepository = $this->createMock(SessionRepositoryInterface::class); $this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class); $this->formatter = $this->createMock(JsonFormatter::class); $this->presenter = new LoginPresenter($this->formatter); $this->contact = $this->createMock(ContactInterface::class); $this->authenticationTokens = $this->createMock(AuthenticationTokens::class); $this->contactGroupRepository = $this->createMock(WriteContactGroupRepositoryInterface::class); $this->accessGroupRepository = $this->createMock(WriteAccessGroupRepositoryInterface::class); $this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class); $this->writeTokenRepository = $this->createMock(WriteTokenRepositoryInterface::class); $this->writeSessionRepository = $this->createMock(WriteSessionRepository::class); $this->writeSessionTokenRepository = $this->createMock(WriteSessionTokenRepositoryInterface::class); $this->aclUpdater = $this->createMock(AclUpdaterInterface::class); $this->menuService = $this->createMock(MenuServiceInterface::class); $this->defaultRedirectUri = '/monitoring/resources'; $this->thirdPartyLoginForm = new ThirdPartyLoginForm($this->createMock(UrlGeneratorInterface::class)); $configuration = new Configuration( 1, 'openid', 'openid', '{}', true, false ); $customConfiguration = new CustomConfiguration([ 'is_active' => true, 'client_id' => 'MyCl1ientId', 'client_secret' => 'MyCl1ientSuperSecr3tKey', 'base_url' => 'http://127.0.0.1/auth/openid-connect', 'auto_import' => false, 'authorization_endpoint' => '/authorization', 'token_endpoint' => '/token', 'introspection_token_endpoint' => '/introspect', 'userinfo_endpoint' => '/userinfo', 'contact_template' => new ContactTemplate(19, 'contact_template'), 'email_bind_attribute' => '', 'fullname_bind_attribute' => '', 'trusted_client_addresses' => [], 'blacklist_client_addresses' => [], 'endsession_endpoint' => '', 'connection_scopes' => [], 'login_claim' => 'preferred_username', 'authentication_type' => 'client_secret_post', 'verify_peer' => false, 'claim_name' => 'groups', 'roles_mapping' => new ACLConditions( false, false, '', new Endpoint(Endpoint::INTROSPECTION, ''), [] ), 'authentication_conditions' => new AuthenticationConditions(false, '', new Endpoint(), []), 'groups_mapping' => (new GroupsMapping(false, '', new Endpoint(), [])), 'redirect_url' => null, ]); $configuration->setCustomConfiguration($customConfiguration); $this->validOpenIdConfiguration = $configuration; }); it('expects to return an error message in presenter when no provider configuration is found', function (): void { $request = LoginRequest::createForOpenId('127.0.0.1', 'abcde-fghij-klmno'); $request->providerName = 'unknown provider'; $this->providerFactory ->expects($this->once()) ->method('create') ->with('unknown provider') ->will($this->throwException(ProviderException::providerConfigurationNotFound('unknown provider'))); $session = new Session(new MockArraySessionStorage()); $session->setId('session_abcd'); $this->requestStack ->expects($this->any()) ->method('getSession') ->willReturn($session); $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $useCase($request, $this->presenter); expect($this->presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class); }); it('expects to execute authenticateOrFail method from OpenIdProvider', function (): void { $request = LoginRequest::createForOpenId('127.0.0.1', 'abcde-fghij-klmno'); $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $this->provider ->expects($this->once()) ->method('authenticateOrFail'); $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $useCase($request, $this->presenter); }); it( 'expects to return an error message in presenter when the provider can\'t find the user and can\'t create it', function (): void { $request = LoginRequest::createForOpenId('127.0.0.1', 'abcde-fghij-klmno'); $this->provider ->expects($this->once()) ->method('authenticateOrFail'); $this->provider ->expects($this->once()) ->method('isAutoImportEnabled'); $this->provider ->expects($this->never()) ->method('importUser'); $this->provider ->expects($this->once()) ->method('findUserOrFail') ->will($this->throwException(new NotFoundException('User could not be created'))); $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $useCase($request, $this->presenter); expect($this->presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class); } ); it( 'expects to return an error message in presenter when the provider ' . 'wasn\'t be able to return a user after creating it', function (): void { $request = LoginRequest::createForOpenId('127.0.0.1', 'abcde-fghij-klmno'); $this->provider ->expects($this->once()) ->method('authenticateOrFail'); $this->provider ->expects($this->once()) ->method('isAutoImportEnabled') ->willReturn(true); $this->provider ->expects($this->never()) ->method('findUserOrFail'); $this->provider ->expects($this->once()) ->method('importUser') ->will($this->throwException(new NotFoundException('User not found'))); $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $useCase($request, $this->presenter); expect($this->presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class); } ); it('should update access groups for the authenticated user', function (): void { $request = LoginRequest::createForOpenId('127.0.0.1', 'abcde-fghij-klmno'); $accessGroup1 = new AccessGroup(1, 'access_group_1', 'access_group_1'); $accessGroup2 = new AccessGroup(2, 'access_group_2', 'access_group_2'); $authorizationRules = [ new AuthorizationRule('group1', $accessGroup1, 1), new AuthorizationRule('group2', $accessGroup2, 2), ]; $this->validOpenIdConfiguration->getCustomConfiguration()->setAuthorizationRules($authorizationRules); $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $this->provider ->expects($this->any()) ->method('getConfiguration') ->willReturn($this->validOpenIdConfiguration); $contact = (new Contact())->setId(1); $this->provider ->expects($this->once()) ->method('findUserOrFail') ->willReturn($contact); $this->aclUpdater ->expects($this->once()) ->method('updateForProviderAndUser') ->with($this->provider, $contact); $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $useCase($request, $this->presenter); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Authentication/Application/UseCase/LogoutSession/LogoutSessionTest.php
centreon/tests/php/Core/Security/Authentication/Application/UseCase/LogoutSession/LogoutSessionTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Authentication\Application\UseCase\LogoutSession; use Core\Application\Common\UseCase\ErrorResponse; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface; use Core\Security\Authentication\Application\Repository\ReadTokenRepositoryInterface; use Core\Security\Authentication\Application\Repository\WriteSessionRepositoryInterface; use Core\Security\Authentication\Application\Repository\WriteSessionTokenRepositoryInterface; use Core\Security\Authentication\Application\Repository\WriteTokenRepositoryInterface; use Core\Security\Authentication\Application\UseCase\LogoutSession\LogoutSession; use Core\Security\Authentication\Application\UseCase\LogoutSession\LogoutSessionPresenterInterface; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; class LogoutSessionTest extends TestCase { /** @var WriteSessionTokenRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private $writeSessionTokenRepository; /** @var WriteSessionRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private $writeSessionRepository; /** @var WriteTokenRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private $writeTokenRepository; /** @var LogoutSessionPresenterInterface&\PHPUnit\Framework\MockObject\MockObject */ private $logoutSessionPresenter; /** @var ReadTokenRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private ReadTokenRepositoryInterface $readTokenRepository; /** @var ProviderAuthenticationFactoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private ProviderAuthenticationFactoryInterface $providerFactory; /** @var RequestStack&\PHPUnit\Framework\MockObject\MockObject */ private RequestStack $requestStack; public function setUp(): void { $this->writeSessionTokenRepository = $this->createMock(WriteSessionTokenRepositoryInterface::class); $this->writeSessionRepository = $this->createMock(WriteSessionRepositoryInterface::class); $this->writeTokenRepository = $this->createMock(WriteTokenRepositoryInterface::class); $this->logoutSessionPresenter = $this->createMock(LogoutSessionPresenterInterface::class); $this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class); $this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->requestStack = $this->createMock(RequestStack::class); } /** * test Logout. */ public function testLogout(): void { $logoutSession = new LogoutSession( $this->writeSessionRepository, ); $session = new Session(new MockArraySessionStorage()); $session->setId('session_abcd'); $this->requestStack ->expects($this->any()) ->method('getSession') ->willReturn($session); $this->writeSessionRepository->expects($this->once()) ->method('invalidate'); $logoutSession('token', $this->logoutSessionPresenter); } /** * test Logout with bad token. */ public function testLogoutFailed(): void { $logoutSession = new LogoutSession( $this->writeSessionRepository, ); $this->logoutSessionPresenter->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse('No session token provided')); $logoutSession(null, $this->logoutSessionPresenter); } }
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/Security/Authentication/Application/UseCase/Login/LoginTest.php
centreon/tests/php/Core/Security/Authentication/Application/UseCase/Login/LoginTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Authentication\Application\UseCase\Login; use Centreon\Domain\Authentication\Exception\AuthenticationException as LegacyAuthenticationException; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Menu\Interfaces\MenuServiceInterface; use Centreon\Domain\Menu\Model\Page; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\UnauthorizedResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; 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\Application\Repository\WriteSessionRepositoryInterface; use Core\Security\Authentication\Application\Repository\WriteSessionTokenRepositoryInterface; use Core\Security\Authentication\Application\Repository\WriteTokenRepositoryInterface; use Core\Security\Authentication\Application\UseCase\Login\Login; use Core\Security\Authentication\Application\UseCase\Login\LoginRequest; use Core\Security\Authentication\Application\UseCase\Login\LoginResponse; use Core\Security\Authentication\Application\UseCase\Login\PasswordExpiredResponse; use Core\Security\Authentication\Application\UseCase\Login\ThirdPartyLoginForm; use Core\Security\Authentication\Domain\Exception\AuthenticationException; use Core\Security\Authentication\Domain\Exception\PasswordExpiredException; use Core\Security\Authentication\Domain\Model\NewProviderToken; use Core\Security\Authentication\Infrastructure\Provider\AclUpdaterInterface; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use Security\Domain\Authentication\Exceptions\ProviderException; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; beforeEach(function (): void { $this->provider = $this->createMock(ProviderAuthenticationInterface::class); $this->contact = $this->createMock(ContactInterface::class); $this->menuService = $this->createMock(MenuServiceInterface::class); $this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class); $this->requestStack = $this->createMock(RequestStack::class); $session = new Session(new MockArraySessionStorage()); $session->setId('session_abcd'); $this->requestStack ->expects($this->any()) ->method('getSession') ->willReturn($session); $this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class); $this->writeTokenRepository = $this->createMock(WriteTokenRepositoryInterface::class); $this->writeSessionTokenRepository = $this->createMock(WriteSessionTokenRepositoryInterface::class); $this->writeSessionRepository = $this->createMock(WriteSessionRepositoryInterface::class); $this->aclUpdater = $this->createMock(AclUpdaterInterface::class); $this->defaultRedirectUri = '/monitoring/resources'; $this->thirdPartyLoginForm = new ThirdPartyLoginForm($this->createMock(UrlGeneratorInterface::class)); $this->useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $this->authenticationRequest = LoginRequest::createForLocal('admin', 'password', '127.0.0.1'); $formater = $this->createMock(PresenterFormatterInterface::class); $this->presenter = new LoginPresenterStub($formater); }); it('should present an error response when the provider configuration is not found', function (): void { $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willThrowException(ProviderException::providerConfigurationNotFound(Provider::LOCAL)); $useCase($this->authenticationRequest, $this->presenter); expect($this->presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class); }); it('should present an UnauthorizedResponse when the authentication fails', function (): void { $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $this->provider ->expects($this->once()) ->method('authenticateOrFail') ->willThrowException(AuthenticationException::notAuthenticated()); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willReturn($this->provider); $useCase($this->authenticationRequest, $this->presenter); expect($this->presenter->getResponseStatus())->toBeInstanceOf(UnauthorizedResponse::class); }); it('should present a PasswordExpiredResponse when the user password is expired', function (): void { $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $this->provider ->expects($this->once()) ->method('authenticateOrFail') ->willThrowException(PasswordExpiredException::passwordIsExpired()); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willReturn($this->provider); $useCase($this->authenticationRequest, $this->presenter); expect($this->presenter->getResponseStatus())->toBeInstanceOf(PasswordExpiredResponse::class); }); it('should present an UnauthorizedResponse when user is not authorized to log in', function (): void { $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $useCase($this->authenticationRequest, $this->presenter); expect($this->presenter->getResponseStatus())->toBeInstanceOf(UnauthorizedResponse::class); }); it("should present an UnauthorizedResponse when user doesn't exist", function (): void { $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $this->provider ->expects($this->once()) ->method('authenticateOrFail'); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willReturn($this->provider); $this->provider ->expects($this->once()) ->method('findUserOrFail') ->willThrowException(LegacyAuthenticationException::userNotFound()); $useCase($this->authenticationRequest, $this->presenter); expect($this->presenter->getResponseStatus())->toBeInstanceOf(UnauthorizedResponse::class); }); it('should create a user when auto import is enabled', function (): void { $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $this->contact ->expects($this->once()) ->method('isAllowedToReachWeb') ->willReturn(true); $this->provider ->expects($this->once()) ->method('findUserOrFail') ->willReturn($this->contact); $this->provider ->expects($this->once()) ->method('isAutoImportEnabled') ->willReturn(true); $this->provider ->expects($this->once()) ->method('importUser'); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willReturn($this->provider); $useCase($this->authenticationRequest, $this->presenter); }); it('should create authentication tokens when user is correctly authenticated', function (): void { $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $this->contact ->method('isAllowedToReachWeb') ->willReturn(true); $this->provider ->expects($this->once()) ->method('findUserOrFail') ->willReturn($this->contact); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willReturn($this->provider); $this->writeSessionRepository ->expects($this->once()) ->method('start') ->willReturn(true); $this->readTokenRepository ->expects($this->once()) ->method('hasAuthenticationTokensByToken') ->willReturn(false); $providerToken = $this->createMock(NewProviderToken::class); $providerRefreshToken = $this->createMock(NewProviderToken::class); $this->provider ->expects($this->once()) ->method('getProviderToken') ->willReturn($providerToken); $this->provider ->expects($this->once()) ->method('getProviderRefreshToken') ->willReturn($providerRefreshToken); $this->writeTokenRepository ->expects($this->once()) ->method('createAuthenticationTokens'); $useCase($this->authenticationRequest, $this->presenter); }); it('should present the default page when user is correctly authenticated', function (): void { $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $this->contact ->method('isAllowedToReachWeb') ->willReturn(true); $this->provider ->expects($this->once()) ->method('findUserOrFail') ->willReturn($this->contact); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willReturn($this->provider); $this->writeSessionRepository ->expects($this->once()) ->method('start') ->willReturn(true); $this->readTokenRepository ->expects($this->once()) ->method('hasAuthenticationTokensByToken') ->willReturn(true); $useCase($this->authenticationRequest, $this->presenter); expect($this->presenter->getPresentedData())->toBeInstanceOf(LoginResponse::class); expect($this->presenter->getPresentedData()->getRedirectUri())->toBe('/monitoring/resources'); }); it('should present the custom redirection page when user is authenticated', function (): void { $useCase = new Login( $this->providerFactory, $this->requestStack, $this->dataStorageEngine, $this->writeSessionRepository, $this->readTokenRepository, $this->writeTokenRepository, $this->writeSessionTokenRepository, $this->aclUpdater, $this->menuService, $this->defaultRedirectUri, $this->thirdPartyLoginForm, ); $page = new Page(1, '/my_custom_page', 60101, true); $this->contact ->expects($this->any()) ->method('getDefaultPage') ->willReturn($page); $this->contact ->method('isAllowedToReachWeb') ->willReturn(true); $this->provider ->expects($this->once()) ->method('findUserOrFail') ->willReturn($this->contact); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willReturn($this->provider); $this->writeSessionRepository ->expects($this->once()) ->method('start') ->willReturn(true); $this->readTokenRepository ->expects($this->once()) ->method('hasAuthenticationTokensByToken') ->willReturn(true); $useCase($this->authenticationRequest, $this->presenter); expect($this->presenter->getPresentedData())->toBeInstanceOf(LoginResponse::class); expect($this->presenter->getPresentedData()->getRedirectUri())->toBe($page->getRedirectionUri()); });
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/Security/Authentication/Application/UseCase/Login/LoginPresenterStub.php
centreon/tests/php/Core/Security/Authentication/Application/UseCase/Login/LoginPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Authentication\Application\UseCase\Login; use Core\Application\Common\UseCase\AbstractPresenter; class LoginPresenterStub extends AbstractPresenter { }
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/Security/Authentication/Infrastructure/Api/LogoutSession/LogoutSessionControllerTest.php
centreon/tests/php/Core/Security/Authentication/Infrastructure/Api/LogoutSession/LogoutSessionControllerTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\Authentication\Infrastructure\Api\LogoutSession; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Infrastructure\Common\Presenter\JsonFormatter; use Core\Security\Authentication\Application\UseCase\LogoutSession\LogoutSession; use Core\Security\Authentication\Infrastructure\Api\LogoutSession\LogoutSessionController; use Core\Security\Authentication\Infrastructure\Api\LogoutSession\LogoutSessionPresenter; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\InputBag; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class LogoutSessionControllerTest extends TestCase { /** @var Request&\PHPUnit\Framework\MockObject\MockObject */ private $request; /** @var LogoutSession&\PHPUnit\Framework\MockObject\MockObject */ private $useCase; /** @var LogoutSessionPresenter */ private $logoutSessionPresenter; /** @var UrlGeneratorInterface&\PHPUnit\Framework\MockObject\MockObject */ private UrlGeneratorInterface $urlGenerator; public function setUp(): void { $this->request = $this->createMock(Request::class); $this->useCase = $this->createMock(LogoutSession::class); $this->logoutSessionPresenter = new LogoutSessionPresenter(new JsonFormatter()); $this->urlGenerator = $this->createMock(UrlGeneratorInterface::class); } /** * test Logout. */ public function testLogout(): void { $logoutSessionController = new LogoutSessionController(); $this->request->cookies = new InputBag(['PHPSESSID' => 'token']); $this->logoutSessionPresenter->setResponseStatus(new NoContentResponse()); $this->useCase->expects($this->once()) ->method('__invoke') ->with('token', $this->logoutSessionPresenter); $response = $logoutSessionController($this->useCase, $this->request, $this->logoutSessionPresenter); $this->assertEquals('/login', $response->headers->get('location')); } /** * test Logout with bad token. */ public function testLogoutFailed(): void { $logoutSessionController = new LogoutSessionController(); $this->request->cookies = new InputBag([]); $this->logoutSessionPresenter->setResponseStatus(new ErrorResponse('No session token provided')); $this->useCase->expects($this->once()) ->method('__invoke') ->with(null, $this->logoutSessionPresenter); $response = $logoutSessionController($this->useCase, $this->request, $this->logoutSessionPresenter); $this->assertEquals('/login', $response->headers->get('location')); } }
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/Security/User/Application/UseCase/RenewPassword/RenewPasswordTest.php
centreon/tests/php/Core/Security/User/Application/UseCase/RenewPassword/RenewPasswordTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\User\Application\UseCase\RenewPassword; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Application\Common\UseCase\UnauthorizedResponse; use Core\Security\ProviderConfiguration\Application\Repository\ReadConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Domain\Local\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\Local\Model\CustomConfiguration; use Core\Security\ProviderConfiguration\Domain\Local\Model\SecurityPolicy; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use Core\Security\User\Application\Repository\ReadUserRepositoryInterface; use Core\Security\User\Application\Repository\WriteUserRepositoryInterface; use Core\Security\User\Application\UseCase\RenewPassword\RenewPassword; use Core\Security\User\Application\UseCase\RenewPassword\RenewPasswordPresenterInterface; use Core\Security\User\Application\UseCase\RenewPassword\RenewPasswordRequest; use Core\Security\User\Domain\Model\User; use Core\Security\User\Domain\Model\UserPassword; use PHPUnit\Framework\TestCase; class RenewPasswordTest extends TestCase { /** @var ReadUserRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private $readRepository; /** @var WriteUserRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private $writeRepository; /** @var RenewPasswordPresenterInterface&\PHPUnit\Framework\MockObject\MockObject */ private $presenter; /** @var ReadConfigurationRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private $readConfigurationRepository; public function setUp(): void { $this->readRepository = $this->createMock(ReadUserRepositoryInterface::class); $this->writeRepository = $this->createMock(WriteUserRepositoryInterface::class); $this->presenter = $this->createMock(RenewPasswordPresenterInterface::class); $this->readConfigurationRepository = $this->createMock(ReadConfigurationRepositoryInterface::class); } /** * Test that a NotFoundResponse is set when the user is not found. */ public function testUseCaseWithNotFoundUser(): void { $request = new RenewPasswordRequest(); $request->userAlias = 'invalidUser'; $request->oldPassword = 'toto'; $request->newPassword = 'tata'; $this->readRepository ->expects($this->once()) ->method('findUserByAlias') ->willReturn(null); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new NotFoundResponse('User')); $useCase = new RenewPassword($this->readRepository, $this->writeRepository, $this->readConfigurationRepository); $useCase($this->presenter, $request); } /** * Test that an ErrorResponse is set when the password is invalid. */ public function testUseCaseWithInvalidPassword(): void { $request = new RenewPasswordRequest(); $request->userAlias = 'admin'; $request->oldPassword = 'toto'; $request->newPassword = 'tata'; $oldPasswords = []; $passwordValue = password_hash('titi', \CentreonAuth::PASSWORD_HASH_ALGORITHM); $password = new UserPassword(1, $passwordValue, new \DateTimeImmutable()); $user = new User(1, 'admin', $oldPasswords, $password, null, null); $this->readRepository ->expects($this->once()) ->method('findUserByAlias') ->willReturn($user); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new UnauthorizedResponse('Invalid credentials')); $useCase = new RenewPassword($this->readRepository, $this->writeRepository, $this->readConfigurationRepository); $useCase($this->presenter, $request); } /** * Test that a no content response is set if everything goes well. */ public function testUseCaseWithValidParameters(): void { $request = new RenewPasswordRequest(); $request->userAlias = 'admin'; $request->oldPassword = 'toto'; $request->newPassword = 'Centreon!2022'; $oldPasswords = []; $passwordValue = password_hash('toto', \CentreonAuth::PASSWORD_HASH_ALGORITHM); $password = new UserPassword(1, $passwordValue, new \DateTimeImmutable()); $user = new User(1, 'admin', $oldPasswords, $password, null, null); $securityPolicy = new SecurityPolicy( SecurityPolicy::MIN_PASSWORD_LENGTH, true, true, true, true, true, SecurityPolicy::MIN_ATTEMPTS, SecurityPolicy::MIN_BLOCKING_DURATION, SecurityPolicy::MIN_PASSWORD_EXPIRATION_DELAY, [], SecurityPolicy::MIN_NEW_PASSWORD_DELAY ); $configuration = new Configuration(1, mb_strtolower(Provider::LOCAL), Provider::LOCAL, '{}', true, true); $configuration->setCustomConfiguration(new CustomConfiguration($securityPolicy)); $this->readRepository ->expects($this->once()) ->method('findUserByAlias') ->willReturn($user); $this->writeRepository ->expects($this->once()) ->method('renewPassword'); $this->readConfigurationRepository ->expects($this->once()) ->method('getConfigurationByType') ->willReturn($configuration); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new NoContentResponse()); $useCase = new RenewPassword($this->readRepository, $this->writeRepository, $this->readConfigurationRepository); $useCase($this->presenter, $request); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/User/Infrastructure/Api/RenewPassword/RenewPasswordControllerTest.php
centreon/tests/php/Core/Security/User/Infrastructure/Api/RenewPassword/RenewPasswordControllerTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\User\Infrastructure\Api\RenewPassword; use Core\Security\User\Application\UseCase\RenewPassword\RenewPassword; use Core\Security\User\Application\UseCase\RenewPassword\RenewPasswordPresenterInterface; use Core\Security\User\Infrastructure\Api\RenewPassword\RenewPasswordController; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; class RenewPasswordControllerTest extends TestCase { /** @var RenewPassword&\PHPUnit\Framework\MockObject\MockObject */ private $useCase; /** @var Request&\PHPUnit\Framework\MockObject\MockObject */ private $request; /** @var RenewPasswordPresenterInterface&\PHPUnit\Framework\MockObject\MockObject */ private $presenter; public function setUp(): void { $this->useCase = $this->createMock(RenewPassword::class); $this->request = $this->createMock(Request::class); $this->presenter = $this->createMock(RenewPasswordPresenterInterface::class); } /** * Test that an exception is thrown is the received payload is invalid. */ public function testExceptionIsThrownWithInvalidPayload(): void { $controller = new RenewPasswordController(); $invalidPayload = json_encode([ 'old_password' => 'titi', ]); $this->request ->expects($this->once()) ->method('getContent') ->willReturn($invalidPayload); $this->expectException(\InvalidArgumentException::class); $controller($this->useCase, $this->request, $this->presenter, 'admin'); } }
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/Security/ProviderConfiguration/Application/UseCase/FindProviderConfigurations/FindProviderConfigurationsTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/UseCase/FindProviderConfigurations/FindProviderConfigurationsTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\UseCase\FindProviderConfigurations; use Core\Application\Common\UseCase\ErrorResponse; use Core\Common\Application\Repository\ReadVaultRepositoryInterface; use Core\Security\ProviderConfiguration\Application\Repository\ReadConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\Repository\ReadProviderConfigurationsRepositoryInterface; use Core\Security\ProviderConfiguration\Application\UseCase\FindProviderConfigurations\{FindProviderConfigurations, FindProviderConfigurationsPresenterInterface, FindProviderConfigurationsResponse, ProviderConfigurationDto, ProviderConfigurationDtoFactoryInterface }; use Core\Security\ProviderConfiguration\Domain\Model\Configuration; use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; beforeEach(function (): void { $this->readProviderConfigurationRepository = $this->createMock( ReadProviderConfigurationsRepositoryInterface::class ); $this->urlGenerator = $this->createMock(UrlGeneratorInterface::class); $this->readVaultConfigurationRepositoryInterface = $this->createMock( ReadVaultConfigurationRepositoryInterface::class ); $this->readVaultRepositoryInterface = $this->createMock(ReadVaultRepositoryInterface::class); $this->providerDtoFactory = $this->createMock(ProviderConfigurationDtoFactoryInterface::class); $this->presenter = $this->createMock(FindProviderConfigurationsPresenterInterface::class); $this->localConfiguration = $this->createMock(Configuration::class); $this->readConfigurationRepository = $this->createMock(ReadConfigurationRepositoryInterface::class); $this->useCase = new FindProviderConfigurations( new \ArrayObject([$this->providerDtoFactory]), $this->readConfigurationRepository ); }); it('returns error when there is an issue during configurations search', function (): void { $errorMessage = 'error during configurations search'; $this->readConfigurationRepository ->expects($this->once()) ->method('findConfigurations') ->willThrowException(new \Exception($errorMessage)); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse($errorMessage, [], new \Exception($errorMessage))); ($this->useCase)($this->presenter); }); it('presents an empty array when configurations are not found', function (): void { $this->readConfigurationRepository ->expects($this->once()) ->method('findConfigurations') ->willReturn([]); $response = new FindProviderConfigurationsResponse(); $response->providerConfigurations = []; $this->presenter ->expects($this->once()) ->method('presentResponse') ->with($response); ($this->useCase)($this->presenter); }); it('presents found configurations', function (): void { $this->readConfigurationRepository ->expects($this->once()) ->method('findConfigurations') ->willReturn([$this->localConfiguration]); $this->localConfiguration ->expects($this->once()) ->method('getType') ->willReturn('local'); $providerConfigurationDto = new ProviderConfigurationDto(); $providerConfigurationDto->id = 1; $providerConfigurationDto->type = 'local'; $providerConfigurationDto->name = 'local'; $providerConfigurationDto->isActive = true; $providerConfigurationDto->isForced = true; $this->providerDtoFactory ->expects($this->once()) ->method('supports') ->with('local') ->willReturn(true); $this->providerDtoFactory ->expects($this->once()) ->method('createResponse') ->with($this->localConfiguration) ->willReturn($providerConfigurationDto); $response = new FindProviderConfigurationsResponse(); $response->providerConfigurations = [$providerConfigurationDto]; $this->presenter ->expects($this->once()) ->method('presentResponse') ->with($response); ($this->useCase)($this->presenter); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Application/WebSSO/UseCase/FindWebSSOConfiguration/FindWebSSOConfigurationPresenterStub.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/WebSSO/UseCase/FindWebSSOConfiguration/FindWebSSOConfigurationPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\WebSSO\UseCase\FindWebSSOConfiguration; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Security\ProviderConfiguration\Application\WebSSO\UseCase\FindWebSSOConfiguration\{ FindWebSSOConfigurationPresenterInterface as PresenterInterface, FindWebSSOConfigurationResponse }; use Symfony\Component\HttpFoundation\Response; class FindWebSSOConfigurationPresenterStub extends AbstractPresenter implements PresenterInterface { /** @var FindWebSSOConfigurationResponse */ public $response; /** * @param FindWebSSOConfigurationResponse $response */ public function present(mixed $response): void { $this->response = $response; } /** * @return Response */ public function show(): Response { return new Response(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Application/WebSSO/UseCase/FindWebSSOConfiguration/FindWebSSOConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/WebSSO/UseCase/FindWebSSOConfiguration/FindWebSSOConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\WebSSO\UseCase\FindWebSSOConfiguration; use Centreon\Domain\Repository\RepositoryException; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\ProviderConfiguration\Application\WebSSO\Repository\ReadWebSSOConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\WebSSO\UseCase\FindWebSSOConfiguration\{ FindWebSSOConfiguration, FindWebSSOConfigurationResponse }; use Core\Security\ProviderConfiguration\Domain\WebSSO\Model\WebSSOConfiguration; beforeEach(function (): void { $this->repository = $this->createMock(ReadWebSSOConfigurationRepositoryInterface::class); $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class); }); it('should present a FindWebSSOConfigurationResponse when everything goes well', function (): void { $configuration = new WebSSOConfiguration( true, false, ['127.0.0.1'], [], 'HTTP_AUTH_USER', null, null, ); $useCase = new FindWebSSOConfiguration($this->repository); $presenter = new FindWebSSOConfigurationPresenterStub($this->presenterFormatter); $this->repository ->expects($this->once()) ->method('findConfiguration') ->willReturn($configuration); $useCase($presenter); expect($presenter->response)->toBeInstanceOf(FindWebSSOConfigurationResponse::class); expect($presenter->response->isActive)->toBeTrue(); expect($presenter->response->isForced)->toBeFalse(); expect($presenter->response->trustedClientAddresses)->toBe(['127.0.0.1']); expect($presenter->response->blacklistClientAddresses)->toBeEmpty(); expect($presenter->response->loginHeaderAttribute)->toBe('HTTP_AUTH_USER'); expect($presenter->response->patternMatchingLogin)->toBeNull(); expect($presenter->response->patternReplaceLogin)->toBeNull(); }); it('should present a NotFoundResponse when no configuration are found in Data storage', function (): void { $useCase = new FindWebSSOConfiguration($this->repository); $presenter = new FindWebSSOConfigurationPresenterStub($this->presenterFormatter); $this->repository ->expects($this->once()) ->method('findConfiguration') ->willReturn(null); $useCase($presenter); expect($presenter->getResponseStatus())->toBeInstanceOf(NotFoundResponse::class); expect($presenter->getResponseStatus()?->getMessage()) ->toBe((new NotFoundResponse('WebSSOConfiguration'))->getMessage()); }); it('should present an ErrorResponse when an error occured during the finding process', function (): void { $useCase = new FindWebSSOConfiguration($this->repository); $presenter = new FindWebSSOConfigurationPresenterStub($this->presenterFormatter); $exceptionMessage = 'An error occured'; $this->repository ->expects($this->once()) ->method('findConfiguration') ->willThrowException(new RepositoryException($exceptionMessage)); $useCase($presenter); expect($presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class); expect($presenter->getResponseStatus()?->getMessage())->toBe($exceptionMessage); });
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/Security/ProviderConfiguration/Application/WebSSO/UpdateWebSSOConfiguration/UseCase/UpdateWebSSOConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/WebSSO/UpdateWebSSOConfiguration/UseCase/UpdateWebSSOConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\WebSSO\UpdateWebSSOConfiguration\UseCase; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Security\ProviderConfiguration\Application\WebSSO\Repository\WriteWebSSOConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\WebSSO\UseCase\UpdateWebSSOConfiguration\{ UpdateWebSSOConfiguration, UpdateWebSSOConfigurationPresenterInterface, UpdateWebSSOConfigurationRequest }; use Core\Security\ProviderConfiguration\Domain\WebSSO\Model\WebSSOConfigurationFactory; beforeEach(function (): void { $this->repository = $this->createMock(WriteWebSSOConfigurationRepositoryInterface::class); $this->presenter = $this->createMock(UpdateWebSSOConfigurationPresenterInterface::class); }); it('execute the use case correctly when all parameters are valid', function (): void { $updateWebSSOConfigurationRequest = new UpdateWebSSOConfigurationRequest(); $updateWebSSOConfigurationRequest->isActive = true; $updateWebSSOConfigurationRequest->isForced = false; $updateWebSSOConfigurationRequest->trustedClientAddresses = []; $updateWebSSOConfigurationRequest->blacklistClientAddresses = []; $updateWebSSOConfigurationRequest->loginHeaderAttribute = 'HTTP_AUTH_USER'; $updateWebSSOConfigurationRequest->patternMatchingLogin = '/@.*/'; $updateWebSSOConfigurationRequest->patternReplaceLogin = 'sso_'; $configuration = WebSSOConfigurationFactory::createFromRequest($updateWebSSOConfigurationRequest); $this->repository ->expects($this->once()) ->method('updateConfiguration') ->with($configuration); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new NoContentResponse()); $useCase = new UpdateWebSSOConfiguration($this->repository); $useCase($this->presenter, $updateWebSSOConfigurationRequest); }); it('should have an Error Response when parameters are invalid', function (): void { $updateWebSSOConfigurationRequest = new UpdateWebSSOConfigurationRequest(); $updateWebSSOConfigurationRequest->isActive = true; $updateWebSSOConfigurationRequest->isForced = false; $badIpAddress = 'abcd_.@'; $updateWebSSOConfigurationRequest->trustedClientAddresses = [$badIpAddress]; $updateWebSSOConfigurationRequest->blacklistClientAddresses = []; $updateWebSSOConfigurationRequest->loginHeaderAttribute = 'HTTP_AUTH_USER'; $updateWebSSOConfigurationRequest->patternMatchingLogin = '/@.*/'; $updateWebSSOConfigurationRequest->patternReplaceLogin = 'sso_'; $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse( AssertionException::ipAddressNotValid( $badIpAddress, 'WebSSOConfiguration::trustedClientAddresses' )->getMessage() )); $useCase = new UpdateWebSSOConfiguration($this->repository); $useCase($this->presenter, $updateWebSSOConfigurationRequest); });
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/Security/ProviderConfiguration/Application/OpenId/UseCase/PartialUpdateOpenIdConfiguration/PartialUpdateOpenIdConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/OpenId/UseCase/PartialUpdateOpenIdConfiguration/PartialUpdateOpenIdConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\OpenId\UseCase\PartialUpdateOpenIdConfiguration; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface; use Core\Contact\Application\Repository\ReadContactTemplateRepositoryInterface; use Core\Contact\Domain\Model\ContactGroup; use Core\Contact\Domain\Model\ContactTemplate; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface; use Core\Security\ProviderConfiguration\Application\OpenId\Repository\ReadOpenIdConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\OpenId\Repository\WriteOpenIdConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\OpenId\UseCase\PartialUpdateOpenIdConfiguration\{ PartialUpdateOpenIdConfiguration, PartialUpdateOpenIdConfigurationPresenterInterface, PartialUpdateOpenIdConfigurationRequest }; use Core\Security\ProviderConfiguration\Domain\Exception\ConfigurationException; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration; use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface; beforeEach(function (): void { $this->repository = $this->createMock(WriteOpenIdConfigurationRepositoryInterface::class); $this->contactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class); $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class); $this->presenter = $this->createMock(PartialUpdateOpenIdConfigurationPresenterInterface::class); $this->readOpenIdRepository = $this->createMock(ReadOpenIdConfigurationRepositoryInterface::class); $this->contactTemplateRepository = $this->createMock(ReadContactTemplateRepositoryInterface::class); $this->readVaultConfigurationRepository = $this->createMock(ReadVaultConfigurationRepositoryInterface::class); $this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class); $this->contactGroup = new ContactGroup(1, 'contact_group', 'contact_group'); $this->contactTemplate = new ContactTemplate(1, 'contact_template'); $this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->provider = $this->createMock(ProviderAuthenticationInterface::class); $this->configuration = $this->createMock(Configuration::class); $this->customConfig = $this->createMock(CustomConfiguration::class); $this->customConfigArray = [ 'is_active' => false, 'is_forced' => false, 'base_url' => null, 'authorization_endpoint' => null, 'token_endpoint' => null, 'introspection_token_endpoint' => null, 'userinfo_endpoint' => null, 'endsession_endpoint' => null, 'connection_scopes' => [], 'login_claim' => null, 'client_id' => null, 'client_secret' => null, 'authentication_type' => 'client_secret_post', 'verify_peer' => true, 'auto_import' => false, 'contact_template' => null, 'email_bind_attribute' => null, 'fullname_bind_attribute' => null, 'roles_mapping' => [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => '', ], 'relations' => [], ], 'authentication_conditions' => [ 'is_enabled' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => null, ], 'authorized_values' => [], 'trusted_client_addresses' => [], 'blacklist_client_addresses' => [], ], 'groups_mapping' => [ 'is_enabled' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => null, ], 'relations' => [], ], 'redirect_url' => null, ]; }); it('should present a NoContentResponse when the use case is executed correctly', function (): void { $request = new PartialUpdateOpenIdConfigurationRequest(); $request->isActive = true; $request->isForced = true; $request->baseUrl = 'http://127.0.0.1/auth/openid-connect'; $request->authorizationEndpoint = '/authorization'; $request->tokenEndpoint = '/token'; $request->introspectionTokenEndpoint = '/introspect'; $request->userInformationEndpoint = '/userinfo'; $request->endSessionEndpoint = '/logout'; $request->connectionScopes = []; $request->loginClaim = 'preferred_username'; $request->clientId = 'MyCl1ientId'; $request->clientSecret = 'MyCl1ientSuperSecr3tKey'; $request->authenticationType = 'client_secret_post'; $request->verifyPeer = false; $request->isAutoImportEnabled = false; $request->contactTemplate = ['id' => 1]; $request->rolesMapping = [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => '', ], 'relations' => [], ]; $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $this->provider ->expects($this->once()) ->method('getConfiguration') ->willReturn($this->configuration); $this->configuration ->expects($this->once()) ->method('getCustomConfiguration') ->willReturn($this->customConfig); $this->customConfig ->expects($this->once()) ->method('toArray') ->willReturn($this->customConfigArray); $this->contactTemplateRepository ->expects($this->once()) ->method('find') ->with(1) ->willReturn($this->contactTemplate); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new NoContentResponse()); $useCase = new PartialUpdateOpenIdConfiguration( $this->repository, $this->contactTemplateRepository, $this->contactGroupRepository, $this->accessGroupRepository, $this->providerFactory, $this->readVaultConfigurationRepository, $this->writeVaultRepository ); $useCase($this->presenter, $request); }); it('should present an ErrorResponse when an error occured during the use case execution', function (): void { $request = new PartialUpdateOpenIdConfigurationRequest(); $request->isActive = true; $request->isForced = true; $request->baseUrl = 'http://127.0.0.1/auth/openid-connect'; $request->authorizationEndpoint = '/authorization'; $request->tokenEndpoint = '/token'; $request->introspectionTokenEndpoint = '/introspect'; $request->userInformationEndpoint = '/userinfo'; $request->endSessionEndpoint = '/logout'; $request->connectionScopes = []; $request->loginClaim = 'preferred_username'; $request->clientId = 'MyCl1ientId'; $request->clientSecret = 'MyCl1ientSuperSecr3tKey'; $request->authenticationType = 'client_secret_post'; $request->verifyPeer = false; $request->isAutoImportEnabled = false; $request->contactTemplate = ['id' => 1]; $request->rolesMapping = [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => '', ], 'relations' => [], ]; $request->authenticationConditions = [ 'is_enabled' => true, 'attribute_path' => 'info.groups', 'endpoint' => ['type' => 'introspection_endpoint', 'custom_endpoint' => null], 'authorized_values' => ['groupsA'], 'trusted_client_addresses' => ['abcd_.@'], 'blacklist_client_addresses' => [], ]; $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $this->provider ->expects($this->once()) ->method('getConfiguration') ->willReturn($this->configuration); $this->configuration ->expects($this->once()) ->method('getCustomConfiguration') ->willReturn($this->customConfig); $this->customConfig ->expects($this->once()) ->method('toArray') ->willReturn($this->customConfigArray); $this->contactTemplateRepository ->expects($this->once()) ->method('find') ->with(1) ->willReturn($this->contactTemplate); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse( AssertionException::ipOrDomain('abcd_.@', 'AuthenticationConditions::trustedClientAddresses')->getMessage() )); $useCase = new PartialUpdateOpenIdConfiguration( $this->repository, $this->contactTemplateRepository, $this->contactGroupRepository, $this->accessGroupRepository, $this->providerFactory, $this->readVaultConfigurationRepository, $this->writeVaultRepository ); $useCase($this->presenter, $request); }); it('should present an Error Response when auto import is enable and mandatory parameters are missing', function (): void { $request = new PartialUpdateOpenIdConfigurationRequest(); $request->isActive = true; $request->isForced = true; $request->baseUrl = 'http://127.0.0.1/auth/openid-connect2'; $request->authorizationEndpoint = '/authorization'; $request->tokenEndpoint = '/token'; $request->introspectionTokenEndpoint = '/introspect'; $request->userInformationEndpoint = '/userinfo'; $request->endSessionEndpoint = '/logout'; $request->connectionScopes = []; $request->loginClaim = 'preferred_username'; $request->clientId = 'MyCl1ientId'; $request->clientSecret = 'MyCl1ientSuperSecr3tKey'; $request->authenticationType = 'client_secret_post'; $request->verifyPeer = false; $request->isAutoImportEnabled = true; $request->rolesMapping = [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => '', ], 'relations' => [], ]; $missingParameters = [ 'contact_template', 'email_bind_attribute', 'fullname_bind_attribute', ]; $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $this->provider ->expects($this->once()) ->method('getConfiguration') ->willReturn($this->configuration); $this->configuration ->expects($this->once()) ->method('getCustomConfiguration') ->willReturn($this->customConfig); $this->customConfig ->expects($this->once()) ->method('toArray') ->willReturn($this->customConfigArray); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse( ConfigurationException::missingAutoImportMandatoryParameters($missingParameters)->getMessage() )); $useCase = new PartialUpdateOpenIdConfiguration( $this->repository, $this->contactTemplateRepository, $this->contactGroupRepository, $this->accessGroupRepository, $this->providerFactory, $this->readVaultConfigurationRepository, $this->writeVaultRepository ); $useCase($this->presenter, $request); }); it('should present an Error Response when auto import is enable and the contact template doesn\'t exist', function (): void { $request = new PartialUpdateOpenIdConfigurationRequest(); $request->isActive = true; $request->isForced = true; $request->baseUrl = 'http://127.0.0.1/auth/openid-connect'; $request->authorizationEndpoint = '/authorization'; $request->tokenEndpoint = '/token'; $request->introspectionTokenEndpoint = '/introspect'; $request->userInformationEndpoint = '/userinfo'; $request->endSessionEndpoint = '/logout'; $request->connectionScopes = []; $request->loginClaim = 'preferred_username'; $request->clientId = 'MyCl1ientId'; $request->clientSecret = 'MyCl1ientSuperSecr3tKey'; $request->authenticationType = 'client_secret_post'; $request->verifyPeer = false; $request->isAutoImportEnabled = true; $request->contactTemplate = ['id' => 1, 'name' => 'contact_template']; $request->emailBindAttribute = 'email'; $request->userNameBindAttribute = 'name'; $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $this->provider ->expects($this->once()) ->method('getConfiguration') ->willReturn($this->configuration); $this->configuration ->expects($this->once()) ->method('getCustomConfiguration') ->willReturn($this->customConfig); $this->customConfig ->expects($this->once()) ->method('toArray') ->willReturn($this->customConfigArray); $this->contactTemplateRepository ->expects($this->once()) ->method('find') ->with($request->contactTemplate['id']) ->willReturn(null); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse( ConfigurationException::contactTemplateNotFound($request->contactTemplate['name'])->getMessage() )); $useCase = new PartialUpdateOpenIdConfiguration( $this->repository, $this->contactTemplateRepository, $this->contactGroupRepository, $this->accessGroupRepository, $this->providerFactory, $this->readVaultConfigurationRepository, $this->writeVaultRepository ); $useCase($this->presenter, $request); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Application/OpenId/UseCase/FindOpenIdConfiguration/FindOpenIdConfigurationPresenterStub.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/OpenId/UseCase/FindOpenIdConfiguration/FindOpenIdConfigurationPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\OpenId\UseCase\FindOpenIdConfiguration; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Security\ProviderConfiguration\Application\OpenId\UseCase\FindOpenIdConfiguration\{ FindOpenIdConfigurationPresenterInterface as PresenterInterface, FindOpenIdConfigurationResponse }; use Symfony\Component\HttpFoundation\Response; class FindOpenIdConfigurationPresenterStub extends AbstractPresenter implements PresenterInterface { /** @var FindOpenIdConfigurationResponse */ public $response; /** * @param FindOpenIdConfigurationResponse $response */ public function present(mixed $response): void { $this->response = $response; } /** * @return Response */ public function show(): Response { return new Response(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Application/OpenId/UseCase/FindOpenIdConfiguration/FindOpenIdConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/OpenId/UseCase/FindOpenIdConfiguration/FindOpenIdConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\OpenId\UseCase\FindOpenIdConfiguration; use Core\Application\Common\UseCase\ErrorResponse; use Core\Contact\Domain\Model\ContactTemplate; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface; use Core\Security\ProviderConfiguration\Application\OpenId\Repository\ReadOpenIdConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\OpenId\UseCase\FindOpenIdConfiguration\{FindOpenIdConfiguration, FindOpenIdConfigurationResponse}; use Core\Security\ProviderConfiguration\Application\Repository\ReadConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Domain\Model\ACLConditions; use Core\Security\ProviderConfiguration\Domain\Model\AuthenticationConditions; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; use Core\Security\ProviderConfiguration\Domain\Model\GroupsMapping; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration; use Security\Domain\Authentication\Exceptions\ProviderException; beforeEach(function (): void { $this->repository = $this->createMock(ReadOpenIdConfigurationRepositoryInterface::class); $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class); $this->readConfiguration = $this->createMock(ReadConfigurationRepositoryInterface::class); $this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->provider = $this->createMock(ProviderAuthenticationInterface::class); }); it('should present a provider configuration', function (): void { $configuration = new Configuration(1, 'openid', 'openid', '{}', true, true); $customConfiguration = new CustomConfiguration([ 'is_active' => true, 'client_id' => 'MyCl1ientId', 'client_secret' => 'MyCl1ientSuperSecr3tKey', 'base_url' => 'http://127.0.0.1/auth/openid-connect', 'auto_import' => false, 'authorization_endpoint' => '/authorization', 'token_endpoint' => '/token', 'introspection_token_endpoint' => '/introspect', 'userinfo_endpoint' => '/userinfo', 'contact_template' => new ContactTemplate(1, 'contact_template'), 'email_bind_attribute' => null, 'fullname_bind_attribute' => null, 'endsession_endpoint' => '/logout', 'connection_scopes' => [], 'login_claim' => 'preferred_username', 'authentication_type' => 'client_secret_post', 'verify_peer' => false, 'claim_name' => 'groups', 'roles_mapping' => new ACLConditions( false, false, '', new Endpoint(Endpoint::INTROSPECTION, ''), [] ), 'authentication_conditions' => new AuthenticationConditions(false, '', new Endpoint(), []), 'groups_mapping' => new GroupsMapping(false, '', new Endpoint(), []), 'redirect_url' => null, ]); $configuration->setCustomConfiguration($customConfiguration); $this->provider ->method('getConfiguration') ->willReturn($configuration); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::OPENID) ->willReturn($this->provider); $useCase = new FindOpenIdConfiguration($this->providerFactory); $presenter = new FindOpenIdConfigurationPresenterStub($this->presenterFormatter); $useCase($presenter); expect($presenter->response)->toBeInstanceOf(FindOpenIdConfigurationResponse::class); expect($presenter->response->isActive)->toBeTrue(); expect($presenter->response->isForced)->toBeTrue(); expect($presenter->response->verifyPeer)->toBeFalse(); expect($presenter->response->baseUrl)->toBe('http://127.0.0.1/auth/openid-connect'); expect($presenter->response->authorizationEndpoint)->toBe('/authorization'); expect($presenter->response->tokenEndpoint)->toBe('/token'); expect($presenter->response->introspectionTokenEndpoint)->toBe('/introspect'); expect($presenter->response->userInformationEndpoint)->toBe('/userinfo'); expect($presenter->response->endSessionEndpoint)->toBe('/logout'); expect($presenter->response->connectionScopes)->toBeEmpty(); expect($presenter->response->connectionScopes)->toBeArray(); expect($presenter->response->loginClaim)->toBe('preferred_username'); expect($presenter->response->clientId)->toBe('MyCl1ientId'); expect($presenter->response->clientSecret)->toBe('MyCl1ientSuperSecr3tKey'); expect($presenter->response->authenticationType)->toBe('client_secret_post'); expect($presenter->response->contactTemplate)->toBe(['id' => 1, 'name' => 'contact_template']); expect($presenter->response->isAutoImportEnabled)->toBeFalse(); expect($presenter->response->emailBindAttribute)->toBeNull(); expect($presenter->response->userNameBindAttribute)->toBeNull(); expect($presenter->response->authenticationConditions)->toBeArray(); expect($presenter->response->groupsMapping)->toBeArray(); expect($presenter->response->redirectUrl)->toBeNull(); }); it('should present an ErrorResponse when an error occured during the process', function (): void { $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::OPENID) ->willThrowException(ProviderException::providerConfigurationNotFound(Provider::OPENID)); $useCase = new FindOpenIdConfiguration($this->providerFactory); $presenter = new FindOpenIdConfigurationPresenterStub($this->presenterFormatter); $useCase($presenter); expect($presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class); expect($presenter->getResponseStatus()?->getMessage())->toBe('Provider configuration (openid) not found'); });
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/Security/ProviderConfiguration/Application/OpenId/UseCase/UpdateOpenIdConfiguration/UpdateOpenIdConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/OpenId/UseCase/UpdateOpenIdConfiguration/UpdateOpenIdConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\OpenId\UseCase\UpdateOpenIdConfiguration; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface; use Core\Contact\Application\Repository\ReadContactTemplateRepositoryInterface; use Core\Contact\Domain\Model\ContactGroup; use Core\Contact\Domain\Model\ContactTemplate; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface; use Core\Security\ProviderConfiguration\Application\OpenId\Repository\ReadOpenIdConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\OpenId\Repository\WriteOpenIdConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\OpenId\UseCase\UpdateOpenIdConfiguration\{UpdateOpenIdConfiguration, UpdateOpenIdConfigurationPresenterInterface, UpdateOpenIdConfigurationRequest }; use Core\Security\ProviderConfiguration\Domain\Exception\ConfigurationException; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration; use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface; beforeEach(function (): void { $this->repository = $this->createMock(WriteOpenIdConfigurationRepositoryInterface::class); $this->contactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class); $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class); $this->presenter = $this->createMock(UpdateOpenIdConfigurationPresenterInterface::class); $this->readOpenIdRepository = $this->createMock(ReadOpenIdConfigurationRepositoryInterface::class); $this->contactTemplateRepository = $this->createMock(ReadContactTemplateRepositoryInterface::class); $this->contactTemplateRepository = $this->createMock(ReadContactTemplateRepositoryInterface::class); $this->readVaultConfigurationRepository = $this->createMock(ReadVaultConfigurationRepositoryInterface::class); $this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class); $this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->contactGroup = new ContactGroup(1, 'contact_group', 'contact_group'); $this->contactTemplate = new ContactTemplate(1, 'contact_template'); $this->provider = $this->createMock(ProviderAuthenticationInterface::class); $this->configuration = $this->createMock(Configuration::class); $this->customConfig = $this->createMock(CustomConfiguration::class); }); it('should present a NoContentResponse when the use case is executed correctly', function (): void { $request = new UpdateOpenIdConfigurationRequest(); $request->isActive = true; $request->isForced = true; $request->baseUrl = 'http://127.0.0.1/auth/openid-connect'; $request->authorizationEndpoint = '/authorization'; $request->tokenEndpoint = '/token'; $request->introspectionTokenEndpoint = '/introspect'; $request->userInformationEndpoint = '/userinfo'; $request->endSessionEndpoint = '/logout'; $request->connectionScopes = []; $request->loginClaim = 'preferred_username'; $request->clientId = 'MyCl1ientId'; $request->clientSecret = 'MyCl1ientSuperSecr3tKey'; $request->authenticationType = 'client_secret_post'; $request->verifyPeer = false; $request->isAutoImportEnabled = false; $request->contactTemplate = ['id' => 1]; $request->rolesMapping = [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => '', ], 'relations' => [], ]; $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $this->provider ->expects($this->once()) ->method('getConfiguration') ->willReturn($this->configuration); $this->configuration ->expects($this->once()) ->method('getCustomConfiguration') ->willReturn($this->customConfig); $this->contactTemplateRepository ->expects($this->once()) ->method('find') ->with(1) ->willReturn($this->contactTemplate); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new NoContentResponse()); $useCase = new UpdateOpenIdConfiguration( $this->repository, $this->contactTemplateRepository, $this->contactGroupRepository, $this->accessGroupRepository, $this->providerFactory, $this->readVaultConfigurationRepository, $this->writeVaultRepository ); $useCase($this->presenter, $request); }); it('should present an ErrorResponse when an error occured during the use case execution', function (): void { $request = new UpdateOpenIdConfigurationRequest(); $request->isActive = true; $request->isForced = true; $request->baseUrl = 'http://127.0.0.1/auth/openid-connect'; $request->authorizationEndpoint = '/authorization'; $request->tokenEndpoint = '/token'; $request->introspectionTokenEndpoint = '/introspect'; $request->userInformationEndpoint = '/userinfo'; $request->endSessionEndpoint = '/logout'; $request->connectionScopes = []; $request->loginClaim = 'preferred_username'; $request->clientId = 'MyCl1ientId'; $request->clientSecret = 'MyCl1ientSuperSecr3tKey'; $request->authenticationType = 'client_secret_post'; $request->verifyPeer = false; $request->isAutoImportEnabled = false; $request->contactTemplate = ['id' => 1]; $request->rolesMapping = [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => '', ], 'relations' => [], ]; $request->authenticationConditions = [ 'is_enabled' => true, 'attribute_path' => 'info.groups', 'endpoint' => ['type' => 'introspection_endpoint', 'custom_endpoint' => null], 'authorized_values' => ['groupsA'], 'trusted_client_addresses' => ['abcd_.@'], 'blacklist_client_addresses' => [], ]; $this->contactTemplateRepository ->expects($this->once()) ->method('find') ->with(1) ->willReturn($this->contactTemplate); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse( AssertionException::ipOrDomain('abcd_.@', 'AuthenticationConditions::trustedClientAddresses')->getMessage() )); $useCase = new UpdateOpenIdConfiguration( $this->repository, $this->contactTemplateRepository, $this->contactGroupRepository, $this->accessGroupRepository, $this->providerFactory, $this->readVaultConfigurationRepository, $this->writeVaultRepository ); $useCase($this->presenter, $request); }); it('should present an Error Response when auto import is enable and mandatory parameters are missing', function (): void { $request = new UpdateOpenIdConfigurationRequest(); $request->isActive = true; $request->isForced = true; $request->baseUrl = 'http://127.0.0.1/auth/openid-connect2'; $request->authorizationEndpoint = '/authorization'; $request->tokenEndpoint = '/token'; $request->introspectionTokenEndpoint = '/introspect'; $request->userInformationEndpoint = '/userinfo'; $request->endSessionEndpoint = '/logout'; $request->connectionScopes = []; $request->loginClaim = 'preferred_username'; $request->clientId = 'MyCl1ientId'; $request->clientSecret = 'MyCl1ientSuperSecr3tKey'; $request->authenticationType = 'client_secret_post'; $request->verifyPeer = false; $request->isAutoImportEnabled = true; $request->rolesMapping = [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => '', ], 'relations' => [], ]; $missingParameters = [ 'contact_template', 'email_bind_attribute', 'fullname_bind_attribute', ]; $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $this->provider ->expects($this->once()) ->method('getConfiguration') ->willReturn($this->configuration); $this->configuration ->expects($this->once()) ->method('getCustomConfiguration') ->willReturn($this->customConfig); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse( ConfigurationException::missingAutoImportMandatoryParameters($missingParameters)->getMessage() )); $useCase = new UpdateOpenIdConfiguration( $this->repository, $this->contactTemplateRepository, $this->contactGroupRepository, $this->accessGroupRepository, $this->providerFactory, $this->readVaultConfigurationRepository, $this->writeVaultRepository ); $useCase($this->presenter, $request); }); it('should present an Error Response when auto import is enable and the contact template doesn\'t exist', function (): void { $request = new UpdateOpenIdConfigurationRequest(); $request->isActive = true; $request->isForced = true; $request->baseUrl = 'http://127.0.0.1/auth/openid-connect'; $request->authorizationEndpoint = '/authorization'; $request->tokenEndpoint = '/token'; $request->introspectionTokenEndpoint = '/introspect'; $request->userInformationEndpoint = '/userinfo'; $request->endSessionEndpoint = '/logout'; $request->connectionScopes = []; $request->loginClaim = 'preferred_username'; $request->clientId = 'MyCl1ientId'; $request->clientSecret = 'MyCl1ientSuperSecr3tKey'; $request->authenticationType = 'client_secret_post'; $request->verifyPeer = false; $request->isAutoImportEnabled = true; $request->contactTemplate = ['id' => 1, 'name' => 'contact_template']; $request->emailBindAttribute = 'email'; $request->userNameBindAttribute = 'name'; $this->contactTemplateRepository ->expects($this->once()) ->method('find') ->with($request->contactTemplate['id']) ->willReturn(null); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse( ConfigurationException::contactTemplateNotFound($request->contactTemplate['name'])->getMessage() )); $useCase = new UpdateOpenIdConfiguration( $this->repository, $this->contactTemplateRepository, $this->contactGroupRepository, $this->accessGroupRepository, $this->providerFactory, $this->readVaultConfigurationRepository, $this->writeVaultRepository ); $useCase($this->presenter, $request); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Application/Local/UseCase/FindConfiguration/FindConfigurationPresenterFake.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/Local/UseCase/FindConfiguration/FindConfigurationPresenterFake.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\Local\UseCase\FindConfiguration; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Security\ProviderConfiguration\Application\Local\UseCase\FindConfiguration\FindConfigurationPresenterInterface; use Core\Security\ProviderConfiguration\Application\Local\UseCase\FindConfiguration\FindConfigurationResponse; use Symfony\Component\HttpFoundation\Response; class FindConfigurationPresenterFake implements FindConfigurationPresenterInterface { /** @var FindConfigurationResponse */ public $response; /** @var ResponseStatusInterface|null */ private $responseStatus; /** @var mixed[] */ private $responseHeaders; /** * @param FindConfigurationResponse $response */ public function present(mixed $response): void { $this->response = $response; } /** * @return Response */ public function show(): Response { return new Response(); } /** * @inheritDoc */ public function setResponseStatus(?ResponseStatusInterface $responseStatus): void { $this->responseStatus = $responseStatus; } /** * @inheritDoc */ public function getResponseStatus(): ?ResponseStatusInterface { return $this->responseStatus; } /** * @inheritDoc */ public function setResponseHeaders(array $responseHeaders): void { $this->responseHeaders = $responseHeaders; } /** * @inheritDoc */ public function getResponseHeaders(): array { return $this->responseHeaders; } /** * @inheritDoc */ public function getPresentedData(): mixed { return $this->response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Application/Local/UseCase/FindConfiguration/FindConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/Local/UseCase/FindConfiguration/FindConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\Local\UseCase\FindConfiguration; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface; use Core\Security\ProviderConfiguration\Application\Local\UseCase\FindConfiguration\FindConfiguration; use Core\Security\ProviderConfiguration\Domain\Local\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\Local\Model\CustomConfiguration; use Core\Security\ProviderConfiguration\Domain\Local\Model\SecurityPolicy; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class FindConfigurationTest extends TestCase { /** @var ProviderAuthenticationFactoryInterface&MockObject */ private ProviderAuthenticationFactoryInterface $providerAuthenticationFactory; /** @var ProviderAuthenticationInterface&MockObject */ private ProviderAuthenticationInterface $providerAuthentication; /** * @return void */ public function setUp(): void { $this->providerAuthenticationFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->providerAuthentication = $this->createMock(ProviderAuthenticationInterface::class); } /** * Test that the use case will correctly pass the configuration to the presenter. */ public function testFindConfiguration(): void { $securityPolicy = new SecurityPolicy( SecurityPolicy::MIN_PASSWORD_LENGTH, true, true, true, true, true, SecurityPolicy::MIN_ATTEMPTS, SecurityPolicy::MIN_BLOCKING_DURATION, SecurityPolicy::MIN_PASSWORD_EXPIRATION_DELAY, [], SecurityPolicy::MIN_NEW_PASSWORD_DELAY ); $customConfiguration = new CustomConfiguration($securityPolicy); $configuration = new Configuration(1, 'local', 'local', '{}', true, true); $configuration->setCustomConfiguration($customConfiguration); $this->providerAuthenticationFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willReturn($this->providerAuthentication); $this->providerAuthentication ->expects($this->once()) ->method('getConfiguration') ->willReturn($configuration); $useCase = new FindConfiguration($this->providerAuthenticationFactory); $presenter = new FindConfigurationPresenterFake(); $useCase($presenter); $this->assertEquals( $presenter->response->passwordMinimumLength, $configuration->getCustomConfiguration()->getSecurityPolicy()->getPasswordMinimumLength() ); $customConf = $configuration->getCustomConfiguration(); $this->assertEquals($presenter->response->hasUppercase, $customConf->getSecurityPolicy()->hasUppercase()); $this->assertEquals($presenter->response->hasLowercase, $customConf->getSecurityPolicy()->hasLowercase()); $this->assertEquals($presenter->response->hasNumber, $customConf->getSecurityPolicy()->hasNumber()); $this->assertEquals( $presenter->response->hasSpecialCharacter, $configuration->getCustomConfiguration()->getSecurityPolicy()->hasSpecialCharacter() ); $this->assertEquals( $presenter->response->canReusePasswords, $configuration->getCustomConfiguration()->getSecurityPolicy()->canReusePasswords() ); $this->assertEquals($presenter->response->attempts, $customConf->getSecurityPolicy()->getAttempts()); $this->assertEquals( $presenter->response->blockingDuration, $configuration->getCustomConfiguration()->getSecurityPolicy()->getBlockingDuration() ); $this->assertEquals( $presenter->response->passwordExpirationDelay, $configuration->getCustomConfiguration()->getSecurityPolicy()->getPasswordExpirationDelay() ); $this->assertEquals( $presenter->response->delayBeforeNewPassword, $configuration->getCustomConfiguration()->getSecurityPolicy()->getDelayBeforeNewPassword() ); } }
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/Security/ProviderConfiguration/Application/Local/UseCase/UpdateConfiguration/UpdateConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/Local/UseCase/UpdateConfiguration/UpdateConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\Local\UseCase\UpdateConfiguration; use Core\Application\Configuration\User\Repository\ReadUserRepositoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface; use Core\Security\ProviderConfiguration\Application\Local\Repository\WriteConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\Local\UseCase\UpdateConfiguration\{ UpdateConfigurationPresenterInterface}; use Core\Security\ProviderConfiguration\Application\Local\UseCase\UpdateConfiguration\UpdateConfiguration; use Core\Security\ProviderConfiguration\Application\Local\UseCase\UpdateConfiguration\UpdateConfigurationRequest; use Core\Security\ProviderConfiguration\Domain\Local\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\Local\Model\CustomConfiguration; use Core\Security\ProviderConfiguration\Domain\Local\Model\SecurityPolicy; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use PHPUnit\Framework\TestCase; class UpdateConfigurationTest extends TestCase { /** @var WriteConfigurationRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private $writeConfigurationRepository; /** @var ReadUserRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private $readUserRepository; /** @var UpdateConfigurationPresenterInterface&\PHPUnit\Framework\MockObject\MockObject */ private $presenter; /** @var ProviderAuthenticationFactoryInterface&\PHPUnit\Framework\MockObject\MockObject */ private ProviderAuthenticationFactoryInterface $providerAuthenticationFactory; /** @var ProviderAuthenticationInterface&\PHPUnit\Framework\MockObject\MockObject */ private $provider; public function setUp(): void { $this->writeConfigurationRepository = $this->createMock(WriteConfigurationRepositoryInterface::class); $this->readUserRepository = $this->createMock(ReadUserRepositoryInterface::class); $this->presenter = $this->createMock(UpdateConfigurationPresenterInterface::class); $this->providerAuthenticationFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->provider = $this->createMock(ProviderAuthenticationInterface::class); } /** * Test that the use case will correctly be executed. */ public function testUpdateConfiguration(): void { $excludedUserAliases = ['admin']; $securityPolicy = new SecurityPolicy( SecurityPolicy::MIN_PASSWORD_LENGTH, true, true, true, true, true, SecurityPolicy::MIN_ATTEMPTS, SecurityPolicy::MIN_BLOCKING_DURATION, SecurityPolicy::MIN_PASSWORD_EXPIRATION_DELAY, $excludedUserAliases, SecurityPolicy::MIN_NEW_PASSWORD_DELAY ); $customConfiguration = new CustomConfiguration($securityPolicy); $configuration = new Configuration(1, 'local', 'local', '{}', true, true); $configuration->setCustomConfiguration($customConfiguration); $this->provider ->expects($this->once()) ->method('getConfiguration') ->willReturn($configuration); $this->providerAuthenticationFactory ->expects($this->once()) ->method('create') ->with(Provider::LOCAL) ->willReturn($this->provider); $request = new UpdateConfigurationRequest(); $request->passwordMinimumLength = SecurityPolicy::MIN_PASSWORD_LENGTH; $request->hasUppercase = true; $request->hasLowercase = false; $request->hasNumber = true; $request->hasSpecialCharacter = true; $request->canReusePasswords = true; $request->attempts = SecurityPolicy::MIN_ATTEMPTS; $request->blockingDuration = SecurityPolicy::MIN_BLOCKING_DURATION; $request->passwordExpirationDelay = SecurityPolicy::MIN_PASSWORD_EXPIRATION_DELAY; $request->passwordExpirationExcludedUserAliases = $excludedUserAliases; $request->delayBeforeNewPassword = SecurityPolicy::MIN_NEW_PASSWORD_DELAY; $this->readUserRepository ->expects($this->once()) ->method('findUserIdsByAliases') ->with($excludedUserAliases) ->willReturn([1]); $this->writeConfigurationRepository ->expects($this->once()) ->method('updateConfiguration') ->with($configuration, [1]); $this->presenter ->expects($this->once()) ->method('setResponseStatus'); $useCase = new UpdateConfiguration( $this->writeConfigurationRepository, $this->readUserRepository, $this->providerAuthenticationFactory ); $useCase($this->presenter, $request); $this->assertNotEquals( $securityPolicy->hasLowercase(), $configuration->getCustomConfiguration()->getSecurityPolicy()->hasLowercase() ); } }
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/Security/ProviderConfiguration/Application/SAML/UseCase/FindSAMLConfiguration/FindSAMLConfigurationPresenterStub.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/SAML/UseCase/FindSAMLConfiguration/FindSAMLConfigurationPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\SAML\UseCase\FindSAMLConfiguration; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Security\ProviderConfiguration\Application\SAML\UseCase\FindSAMLConfiguration\FindSAMLConfigurationPresenterInterface; use Core\Security\ProviderConfiguration\Application\SAML\UseCase\FindSAMLConfiguration\FindSAMLConfigurationResponse; class FindSAMLConfigurationPresenterStub implements FindSAMLConfigurationPresenterInterface { public ResponseStatusInterface|FindSAMLConfigurationResponse $response; public function presentResponse(ResponseStatusInterface|FindSAMLConfigurationResponse $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/Security/ProviderConfiguration/Application/SAML/UseCase/FindSAMLConfiguration/FindSAMLConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/SAML/UseCase/FindSAMLConfiguration/FindSAMLConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\SAML\UseCase\FindSAMLConfiguration; use Core\Application\Common\UseCase\ErrorResponse; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface; use Core\Security\ProviderConfiguration\Application\SAML\UseCase\FindSAMLConfiguration\FindSAMLConfiguration; use Core\Security\ProviderConfiguration\Application\SAML\UseCase\FindSAMLConfiguration\FindSAMLConfigurationResponse; use Core\Security\ProviderConfiguration\Domain\Model\ACLConditions; use Core\Security\ProviderConfiguration\Domain\Model\AuthenticationConditions; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; use Core\Security\ProviderConfiguration\Domain\Model\GroupsMapping; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use Core\Security\ProviderConfiguration\Domain\SAML\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\SAML\Model\CustomConfiguration; use Security\Domain\Authentication\Exceptions\ProviderException; beforeEach(function (): void { $this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->provider = $this->createMock(ProviderAuthenticationInterface::class); $this->presenter = new FindSAMLConfigurationPresenterStub(); }); it('should present a SAML provider configuration', function (): void { $configuration = new Configuration(1, 'saml', 'saml', '{}', true, true); $customConfiguration = CustomConfiguration::createFromValues([ 'is_active' => true, 'is_forced' => false, 'entity_id_url' => 'http://127.0.0.1:4000/realms/my-realm', 'remote_login_url' => 'http://127.0.0.1:4000/realms/my-realm/protocol/saml/clients/my-client', 'certificate' => 'my-certificate', 'logout_from' => true, 'logout_from_url' => 'http://127.0.0.1:4000/realms/my-realm/protocol/saml', 'user_id_attribute' => 'email', 'requested_authn_context' => false, 'requested_authn_context_comparison' => 'exact', 'auto_import' => false, 'contact_template' => null, 'fullname_bind_attribute' => null, 'email_bind_attribute' => null, 'authentication_conditions' => new AuthenticationConditions(false, '', new Endpoint(), []), 'roles_mapping' => new ACLConditions(false, false, '', new Endpoint(Endpoint::INTROSPECTION, ''), []), 'groups_mapping' => new GroupsMapping(false, '', new Endpoint(), []), ]); $configuration->setCustomConfiguration($customConfiguration); $this->provider ->expects($this->any()) ->method('getConfiguration') ->willReturn($configuration); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::SAML) ->willReturn($this->provider); $useCase = new FindSAMLConfiguration($this->providerFactory); $useCase($this->presenter); expect($this->presenter->response)->toBeInstanceOf(FindSAMLConfigurationResponse::class) ->and($this->presenter->response->isActive)->toBeTrue() ->and($this->presenter->response->isForced)->toBeTrue() ->and($this->presenter->response->entityIdUrl)->toBe('http://127.0.0.1:4000/realms/my-realm') ->and($this->presenter->response->remoteLoginUrl)->toBe('http://127.0.0.1:4000/realms/my-realm/protocol/saml/clients/my-client') ->and($this->presenter->response->logoutFrom)->toBeTrue() ->and($this->presenter->response->logoutFromUrl)->toBe('http://127.0.0.1:4000/realms/my-realm/protocol/saml') ->and($this->presenter->response->userIdAttribute)->toBe('email') ->and($this->presenter->response->requestAuthnContext)->toBeFalse() ->and($this->presenter->response->requestedAuthnContextComparison->value)->toBe('exact'); }); it('should present an ErrorResponse when the provider has not found', function (): void { $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::SAML) ->willThrowException(ProviderException::providerConfigurationNotFound(Provider::SAML)); $useCase = new FindSAMLConfiguration($this->providerFactory); $useCase($this->presenter); expect($this->presenter->response)->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage())->toBe('Provider configuration (saml) not found'); });
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/Security/ProviderConfiguration/Application/SAML/UseCase/UpdateSAMLConfiguration/UpdateSAMLConfigurationPresenterStub.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/SAML/UseCase/UpdateSAMLConfiguration/UpdateSAMLConfigurationPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\SAML\UseCase\UpdateSAMLConfiguration; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Security\ProviderConfiguration\Application\SAML\UseCase\UpdateSAMLConfiguration\UpdateSAMLConfigurationPresenterInterface; class UpdateSAMLConfigurationPresenterStub implements UpdateSAMLConfigurationPresenterInterface { public ResponseStatusInterface $response; public function presentResponse(ResponseStatusInterface $response): void { $this->response = $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Application/SAML/UseCase/UpdateSAMLConfiguration/UpdateSAMLConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/SAML/UseCase/UpdateSAMLConfiguration/UpdateSAMLConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\SAML\UseCase\UpdateSAMLConfiguration; use Adaptation\Database\Connection\ConnectionInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Common\Infrastructure\Repository\DatabaseRepositoryManager; use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface; use Core\Contact\Application\Repository\ReadContactTemplateRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface; use Core\Security\Authentication\Application\Provider\ProviderAuthenticationInterface; use Core\Security\ProviderConfiguration\Application\SAML\Repository\WriteSAMLConfigurationRepositoryInterface; use Core\Security\ProviderConfiguration\Application\SAML\UseCase\UpdateSAMLConfiguration\UpdateSAMLConfiguration; use Core\Security\ProviderConfiguration\Application\SAML\UseCase\UpdateSAMLConfiguration\UpdateSAMLConfigurationRequest; use Core\Security\ProviderConfiguration\Domain\Model\ACLConditions; use Core\Security\ProviderConfiguration\Domain\Model\AuthenticationConditions; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; use Core\Security\ProviderConfiguration\Domain\Model\GroupsMapping; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use Core\Security\ProviderConfiguration\Domain\SAML\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\SAML\Model\CustomConfiguration; use Mockery; beforeEach(function (): void { $this->writeSAMLConfigurationRepository = $this->createMock(WriteSAMLConfigurationRepositoryInterface::class); $this->readContactTemplateRepository = $this->createMock(ReadContactTemplateRepositoryInterface::class); $this->readContactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class); $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class); $connection = Mockery::mock(ConnectionInterface::class); $connection ->shouldReceive('isTransactionActive') ->andReturn(false); $connection ->shouldReceive('startTransaction') ->andReturnNull(); $connection ->shouldReceive('commitTransaction') ->andReturnTrue(); $this->databaseRepositoryManager = new DatabaseRepositoryManager($connection); $this->providerFactory = $this->createMock(ProviderAuthenticationFactoryInterface::class); $this->provider = $this->createMock(ProviderAuthenticationInterface::class); $this->presenter = new UpdateSAMLConfigurationPresenterStub(); }); it('should present a No Content Response when the use case is executed correctly', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: true, isForced: true, remoteLoginUrl: 'http://127.0.0.1:4000/realms/my-realm/protocol/saml/clients/my-client', entityIdUrl: 'http://127.0.0.1:4000/realms/my-realm', publicCertificate: 'my-certificate', userIdAttribute: 'email', requestedAuthnContext: false, logoutFrom: true, logoutFromUrl: 'http://127.0.0.1:4000/realms/my-realm/protocol/saml', isAutoImportEnabled: false, rolesMapping: [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'relations' => [], ], authenticationConditions: [ 'is_enabled' => false, 'attribute_path' => '', 'authorized_values' => [], 'trusted_client_addresses' => [], 'blacklist_client_addresses' => [], ], groupsMapping: [ 'is_enabled' => false, 'attribute_path' => '', 'relations' => [], ], ); $this->providerFactory ->expects($this->once()) ->method('create') ->willReturn($this->provider); $configuration = new Configuration(1, 'saml', 'saml', '{}', true, false); $customConfiguration = CustomConfiguration::createFromValues([ 'is_active' => true, 'is_forced' => false, 'entity_id_url' => 'http://127.0.0.1:4000/realms/my-realm', 'remote_login_url' => 'http://127.0.0.1:4000/realms/my-realm/protocol/saml/clients/my-client', 'certificate' => 'my-old-certificate', 'logout_from' => true, 'logout_from_url' => 'http://127.0.0.1:4000/realms/my-realm/protocol/saml', 'user_id_attribute' => 'email', 'requested_authn_context' => false, 'requested_authn_context_comparison' => 'exact', 'auto_import' => false, 'contact_template' => null, 'fullname_bind_attribute' => null, 'email_bind_attribute' => null, 'authentication_conditions' => new AuthenticationConditions(false, '', new Endpoint(), []), 'roles_mapping' => new ACLConditions(false, false, '', new Endpoint(Endpoint::INTROSPECTION, ''), []), 'groups_mapping' => new GroupsMapping(false, '', new Endpoint(), []), ]); $configuration->setCustomConfiguration($customConfiguration); $this->provider ->expects($this->once()) ->method('getConfiguration') ->willReturn($configuration); $this->writeSAMLConfigurationRepository ->expects($this->once()) ->method('updateConfiguration'); $useCase = new UpdateSAMLConfiguration( $this->writeSAMLConfigurationRepository, $this->readContactTemplateRepository, $this->readContactGroupRepository, $this->readAccessGroupRepository, $this->databaseRepositoryManager, $this->providerFactory ); $useCase($this->presenter, $request); expect($this->presenter->response)->toBeInstanceOf(NoContentResponse::class) ->and($this->presenter->response->getMessage())->toBe('No content'); }); it('should present an Error Response when an error occurs during the process', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: true, isForced: true, remoteLoginUrl: 'http://127.0.0.1:4000/realms/my-realm/protocol/saml/clients/my-client', entityIdUrl: 'http://127.0.0.1:4000/realms/my-realm', publicCertificate: 'my-certificate', userIdAttribute: 'email', requestedAuthnContext: false, logoutFrom: true, logoutFromUrl: 'http://127.0.0.1:4000/realms/my-realm/protocol/saml', isAutoImportEnabled: false, rolesMapping: [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'relations' => [], ], authenticationConditions: [ 'is_enabled' => false, 'attribute_path' => '', 'authorized_values' => [], 'trusted_client_addresses' => [], 'blacklist_client_addresses' => [], ], groupsMapping: [ 'is_enabled' => false, 'attribute_path' => '', 'relations' => [], ], ); $this->providerFactory ->expects($this->once()) ->method('create') ->with(Provider::SAML) ->willThrowException(new \Exception('An error occured')); $useCase = new UpdateSAMLConfiguration( $this->writeSAMLConfigurationRepository, $this->readContactTemplateRepository, $this->readContactGroupRepository, $this->readAccessGroupRepository, $this->databaseRepositoryManager, $this->providerFactory ); $useCase($this->presenter, $request); expect($this->presenter->response)->toBeInstanceOf(ErrorResponse::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Application/SAML/UseCase/UpdateSAMLConfiguration/UpdateSAMLConfigurationRequestTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Application/SAML/UseCase/UpdateSAMLConfiguration/UpdateSAMLConfigurationRequestTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\SAML\UseCase\UpdateSAMLConfiguration; use Core\Security\ProviderConfiguration\Application\SAML\UseCase\UpdateSAMLConfiguration\UpdateSAMLConfigurationRequest; it('should throw an exception when a request property is invalid (active but no certificate)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, publicCertificate: null, ); })->throws(\InvalidArgumentException::class); it('should throw an exception when a request property is invalid (active but no entityIdUrl)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, entityIdUrl: '', ); })->throws(\InvalidArgumentException::class); it('should throw an exception when a request property is invalid (active but no remoteLoginUrl)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: '', publicCertificate: 'my-certificate', ); })->throws(\InvalidArgumentException::class); it('should throw an exception when a request property is invalid (active but no userIdAttribute)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: '', ); })->throws(\InvalidArgumentException::class); it( 'should throw an exception when a request property is invalid (active with requested_authn_context with invalid value for requested_authn_context_comparison)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', requestedAuthnContext: true, requestedAuthnContextComparison: 'invalid-value', ); } )->throws(\InvalidArgumentException::class); it('should throw an exception when a request property is invalid (logoutFrom but no logoutFromUrl)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', logoutFrom: true, logoutFromUrl: null, ); })->throws(\InvalidArgumentException::class); it( 'should throw an exception when a request property is invalid (logoutFrom but logoutFromUrl is empty)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', logoutFrom: true, logoutFromUrl: '', ); } )->throws(\InvalidArgumentException::class); it( 'should throw an exception when a request property is invalid (autoImport but no emailBindAttribute)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', logoutFrom: false, isAutoImportEnabled: true, emailBindAttribute: null, ); } )->throws(\InvalidArgumentException::class); it( 'should throw an exception when a request property is invalid (autoImport but emailBindAttribute is empty)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', logoutFrom: false, isAutoImportEnabled: true, emailBindAttribute: '', ); } )->throws(\InvalidArgumentException::class); it( 'should throw an exception when a request property is invalid (autoImport but no userNameBindAttribute)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', logoutFrom: false, isAutoImportEnabled: true, emailBindAttribute: 'email', userNameBindAttribute: null, ); } )->throws(\InvalidArgumentException::class); it( 'should throw an exception when a request property is invalid (autoImport but userNameBindAttribute is empty)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', logoutFrom: false, isAutoImportEnabled: true, emailBindAttribute: 'email', userNameBindAttribute: '', ); } )->throws(\InvalidArgumentException::class); it( 'should throw an exception when a request property is invalid (autoImport but no contactTemplate)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', logoutFrom: false, isAutoImportEnabled: true, contactTemplate: null, emailBindAttribute: 'email', userNameBindAttribute: 'fullname', ); } )->throws(\InvalidArgumentException::class); it( 'should throw an exception when a request property is invalid (autoImport but contactTemplate is empty)', function (): void { new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', logoutFrom: false, isAutoImportEnabled: true, contactTemplate: [], emailBindAttribute: 'email', userNameBindAttribute: 'fullname', ); } )->throws(\InvalidArgumentException::class); it( 'should instance request with success (not active, without forced, without requested_authn_context, without auto import)', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: false, ); expect($request)->toBeInstanceOf(UpdateSAMLConfigurationRequest::class) ->and($request->isActive)->toBeFalse() ->and($request->isForced)->toBeFalse() ->and($request->remoteLoginUrl)->toBe('') ->and($request->publicCertificate)->toBeNull() ->and($request->userIdAttribute)->toBe('') ->and($request->logoutFrom)->toBeTrue() ->and($request->isAutoImportEnabled)->toBeFalse() ->and($request->requestedAuthnContext)->toBeFalse() ->and($request->requestedAuthnContextComparison->value)->toBe('exact'); } ); it('should instance the request with success (not active but forced)', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: false, isForced: true, ); expect($request)->toBeInstanceOf(UpdateSAMLConfigurationRequest::class) ->and($request->isActive)->toBeFalse() ->and($request->isForced)->toBeTrue(); }); it('should instance the request with success (not active but has auto import)', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: false, isAutoImportEnabled: true, ); expect($request)->toBeInstanceOf(UpdateSAMLConfigurationRequest::class) ->and($request->isActive)->toBeFalse() ->and($request->isAutoImportEnabled)->toBeTrue(); }); it('should instance the request with success (not active but has requested_authn_context)', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: false, requestedAuthnContext: true, requestedAuthnContextComparison: 'minimum', ); expect($request)->toBeInstanceOf(UpdateSAMLConfigurationRequest::class) ->and($request->isActive)->toBeFalse() ->and($request->requestedAuthnContext)->toBeTrue() ->and($request->requestedAuthnContextComparison->value)->toBe('minimum'); }); it( 'should instance request with success (active without requested_authn_context, without auto import)', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', entityIdUrl: 'http://entity.id.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', requestedAuthnContext: false, logoutFrom: false, isAutoImportEnabled: false, ); expect($request)->toBeInstanceOf(UpdateSAMLConfigurationRequest::class) ->and($request->isActive)->toBeTrue() ->and($request->isForced)->toBeFalse() ->and($request->entityIdUrl)->toBe('http://entity.id.url') ->and($request->remoteLoginUrl)->toBe('http://remote.login.url') ->and($request->publicCertificate)->toBe('my-certificate') ->and($request->userIdAttribute)->toBe('email') ->and($request->logoutFrom)->toBeFalse() ->and($request->isAutoImportEnabled)->toBeFalse() ->and($request->requestedAuthnContext)->toBeFalse() ->and($request->requestedAuthnContextComparison->value)->toBe('exact'); } ); it( 'should instance request with success (active without requested_authn_context, with auto import)', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: true, remoteLoginUrl: 'http://remote.login.url', entityIdUrl: 'http://entity.id.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', requestedAuthnContext: false, logoutFrom: false, isAutoImportEnabled: true, contactTemplate: ['template' => 'value'], emailBindAttribute: 'email', userNameBindAttribute: 'fullname', ); expect($request)->toBeInstanceOf(UpdateSAMLConfigurationRequest::class) ->and($request->isActive)->toBeTrue() ->and($request->isForced)->toBeFalse() ->and($request->remoteLoginUrl)->toBe('http://remote.login.url') ->and($request->remoteLoginUrl)->toBe('http://remote.login.url') ->and($request->publicCertificate)->toBe('my-certificate') ->and($request->userIdAttribute)->toBe('email') ->and($request->logoutFrom)->toBeFalse() ->and($request->isAutoImportEnabled)->toBeTrue() ->and($request->emailBindAttribute)->toBe('email') ->and($request->userNameBindAttribute)->toBe('fullname') ->and($request->contactTemplate)->toBe(['template' => 'value']) ->and($request->requestedAuthnContext)->toBeFalse() ->and($request->requestedAuthnContextComparison->value)->toBe('exact'); } ); it( 'should instance request with success (active with forced, with requested_authn_context, with auto import)', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: true, isForced: true, remoteLoginUrl: 'http://remote.login.url', entityIdUrl: 'http://entity.id.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', requestedAuthnContext: true, requestedAuthnContextComparison: 'minimum', logoutFrom: false, isAutoImportEnabled: true, contactTemplate: ['template' => 'value'], emailBindAttribute: 'email', userNameBindAttribute: 'fullname', ); expect($request)->toBeInstanceOf(UpdateSAMLConfigurationRequest::class) ->and($request->isActive)->toBeTrue() ->and($request->isForced)->toBeTrue() ->and($request->entityIdUrl)->toBe('http://entity.id.url') ->and($request->remoteLoginUrl)->toBe('http://remote.login.url') ->and($request->publicCertificate)->toBe('my-certificate') ->and($request->userIdAttribute)->toBe('email') ->and($request->logoutFrom)->toBeFalse() ->and($request->isAutoImportEnabled)->toBeTrue() ->and($request->emailBindAttribute)->toBe('email') ->and($request->userNameBindAttribute)->toBe('fullname') ->and($request->contactTemplate)->toBe(['template' => 'value']) ->and($request->requestedAuthnContext)->toBeTrue() ->and($request->requestedAuthnContextComparison->value)->toBe('minimum'); } ); it('should have an array from request with success', function (): void { $request = new UpdateSAMLConfigurationRequest( isActive: true, isForced: true, remoteLoginUrl: 'http://remote.login.url', entityIdUrl: 'http://entity.id.url', publicCertificate: 'my-certificate', userIdAttribute: 'email', requestedAuthnContext: true, requestedAuthnContextComparison: 'minimum', logoutFrom: true, logoutFromUrl: 'http://logout.from.url', isAutoImportEnabled: true, contactTemplate: ['template' => 'value'], emailBindAttribute: 'email', userNameBindAttribute: 'fullname', ); expect($request)->toBeInstanceOf(UpdateSAMLConfigurationRequest::class) ->and($request->toArray())->toBe([ 'entity_id_url' => 'http://entity.id.url', 'remote_login_url' => 'http://remote.login.url', 'user_id_attribute' => 'email', 'requested_authn_context' => true, 'requested_authn_context_comparison' => 'minimum', 'certificate' => 'my-certificate', 'logout_from' => true, 'logout_from_url' => 'http://logout.from.url', 'contact_template' => ['template' => 'value'], 'auto_import' => true, 'email_bind_attribute' => 'email', 'fullname_bind_attribute' => 'fullname', 'authentication_conditions' => [ 'is_enabled' => false, 'attribute_path' => '', 'authorized_values' => [], 'trusted_client_addresses' => [], 'blacklist_client_addresses' => [], ], 'groups_mapping' => [ 'is_enabled' => false, 'attribute_path' => '', 'relations' => [], ], 'roles_mapping' => [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'relations' => [], ], ]); });
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/Security/ProviderConfiguration/Domain/Model/EndpointTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Domain/Model/EndpointTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Domain\Model; use Core\Security\ProviderConfiguration\Domain\Exception\InvalidEndpointException; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; beforeEach(function (): void { $this->custom_relative_url = '/info'; $this->custom_url = 'https://domain.com/info'; }); it('should throw an exception with a bad endpoint type', function (): void { (new Endpoint('bad_type', $this->custom_relative_url)); })->throws(InvalidEndpointException::class, InvalidEndpointException::invalidType()->getMessage()); it('should return an EndpointCondition instance with a correct relative URL', function (): void { $endpointCondition = new Endpoint(Endpoint::CUSTOM, $this->custom_relative_url); expect($endpointCondition->getUrl())->toBe($this->custom_relative_url); }); it('should return an EndpointCondition instance with a correct URL', function (): void { $endpointCondition = new Endpoint(Endpoint::CUSTOM, $this->custom_url); expect($endpointCondition->getUrl())->toBe($this->custom_url); }); it('should return an EndpointCondition instance with an empty URL if type is not custom', function (): void { $endpointCondition = new Endpoint(Endpoint::INTROSPECTION, $this->custom_url); expect($endpointCondition->getUrl())->toBeNull(); $endpointCondition = new Endpoint(Endpoint::USER_INFORMATION, $this->custom_url); expect($endpointCondition->getUrl())->toBeNull(); }); it('should throw an exception with a null URL and a custom type', function (): void { (new Endpoint(Endpoint::CUSTOM, null)); })->throws(InvalidEndpointException::class, InvalidEndpointException::invalidUrl()->getMessage()); it('should throw an exception with an empty URL and a custom type', function (): void { (new Endpoint(Endpoint::CUSTOM, '')); })->throws(InvalidEndpointException::class, InvalidEndpointException::invalidUrl()->getMessage()); it( 'should return an EndpointCondition instance when an URL type is Custom and it contains additional slashes', function (): void { $urlWithAdditionalShlashes = ' //info/ '; $sanitizedURL = '/info'; $endpointCondition = new Endpoint(Endpoint::CUSTOM, $urlWithAdditionalShlashes); expect($endpointCondition->getUrl())->toBe($sanitizedURL); } ); it('should throw an exception when a custom type URL contains only spaces and/or slashes', function (): void { (new Endpoint(Endpoint::CUSTOM, ' /// ')); })->throws(InvalidEndpointException::class, InvalidEndpointException::invalidUrl()->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/Security/ProviderConfiguration/Domain/Model/ACLConditionsTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Domain/Model/ACLConditionsTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Application\WebSSO\UseCase\FindWebSSOConfiguration; use Core\Security\ProviderConfiguration\Domain\Model\ACLConditions; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; use Core\Security\ProviderConfiguration\Domain\OpenId\Exceptions\ACLConditionsException; beforeEach(function (): void { $this->custom_relative_url = '/info'; $this->custom_url = 'https://domain.com/info'; }); it('should return a default ACLConditions instance', function (): void { $aclConditions = new ACLConditions( false, false, '', new Endpoint(), [] ); expect($aclConditions->isEnabled())->toBe(false) ->and($aclConditions->onlyFirstRoleIsApplied())->toBe(false) ->and($aclConditions->getAttributePath())->toHaveLength(0) ->and($aclConditions->getEndpoint())->toBeInstanceOf(Endpoint::class) ->and($aclConditions->getRelations())->toBeArray()->toHaveLength(0); }); it('should throw an exception for missing parameter attribute_path', function (): void { (new ACLConditions( true, false, '', new Endpoint(), [] )); })->throws( ACLConditionsException::class, ACLConditionsException::missingFields(['attribute_path'])->getMessage() ); it('it should throw an exception for missing parameter endpoint', function (): void { (new ACLConditions( true, false, '', new Endpoint(), [] )); })->throws( ACLConditionsException::class, ACLConditionsException::missingFields(['attribute_path'])->getMessage() ); it( 'it should throw an exception for missing parameter relations when applyOnlyFirstRole is enabled', function (): void { (new ACLConditions( true, true, 'info.path.role', new Endpoint(), [] )); } )->throws( ACLConditionsException::class, ACLConditionsException::missingFields(['relations'])->getMessage() ); it('it should throw an exception for all missing parameters', function (): void { (new ACLConditions( true, true, '', new Endpoint(), [] )); })->throws( ACLConditionsException::class, ACLConditionsException::missingFields(['attribute_path', 'relations'])->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/Security/ProviderConfiguration/Domain/OpenId/Model/CustomConfigurationTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Domain/OpenId/Model/CustomConfigurationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Domain\OpenId\Model; use Core\Contact\Domain\Model\ContactTemplate; use Core\Security\ProviderConfiguration\Domain\Model\{ ACLConditions, AuthenticationConditions, GroupsMapping }; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration; it( 'should sanitize URL/endpoint values when they contain additional slashes and/or spaces in the beginning and end', function (): void { $json = [ 'is_active' => true, 'is_forced' => false, 'base_url' => ' https://localhost:8080', 'authorization_endpoint' => '/authorize/ ', 'token_endpoint' => '/token ', 'introspection_token_endpoint' => '// introspection/', 'userinfo_endpoint' => '//userinfo', 'endsession_endpoint' => '/ logout', 'connection_scopes' => ['openid', 'offline_access'], 'login_claim' => 'given_name', 'client_id' => 'user2', 'client_secret' => 'Centreon!2021', 'authentication_type' => 'client_secret_post', 'verify_peer' => false, 'auto_import' => true, 'contact_template' => (new ContactTemplate(19, 'contact_template')), 'email_bind_attribute' => 'email', 'fullname_bind_attribute' => 'given_name', 'authentication_conditions' => ( new AuthenticationConditions( true, 'users.roles.info.status', (new Endpoint('custom_endpoint', ' /my/custom/endpoint')), ['status2'] ) ), 'roles_mapping' => ( new ACLConditions( false, false, 'users.roles.info.status', (new Endpoint('custom_endpoint', '///my/custom/endpoint')) ) ), 'groups_mapping' => ( new GroupsMapping( false, 'users.roles.info.status', (new Endpoint('custom_endpoint', '/my/custom/endpoint//')), [] ) ), 'redirect_url' => null, ]; $customConfiguration = new CustomConfiguration($json); expect($customConfiguration->getBaseUrl())->toBe('https://localhost:8080'); expect($customConfiguration->getAuthorizationEndpoint())->toBe('/authorize'); expect($customConfiguration->getTokenEndpoint())->toBe('/token'); expect($customConfiguration->getIntrospectionTokenEndpoint())->toBe('/introspection'); expect($customConfiguration->getUserInformationEndpoint())->toBe('/userinfo'); expect($customConfiguration->getEndSessionEndpoint())->toBe('/logout'); expect($customConfiguration->getAuthenticationConditions()->getEndpoint()->getUrl()) ->toBe('/my/custom/endpoint'); expect($customConfiguration->getACLConditions()->getEndpoint()->getUrl())->toBe('/my/custom/endpoint'); expect($customConfiguration->getGroupsMapping()->getEndpoint()->getUrl())->toBe('/my/custom/endpoint'); } );
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/Security/ProviderConfiguration/Infrastructure/WebSSO/Api/UpdateWebSSOConfiguration/UpdateWebSSOConfigurationControllerTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/WebSSO/Api/UpdateWebSSOConfiguration/UpdateWebSSOConfigurationControllerTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Infrastructure\WebSSO\Api\UpdateWebSSOConfiguration; use Centreon\Domain\Contact\Contact; use Core\Security\ProviderConfiguration\Application\WebSSO\UseCase\UpdateWebSSOConfiguration\{ UpdateWebSSOConfiguration, UpdateWebSSOConfigurationPresenterInterface }; use Core\Security\ProviderConfiguration\Infrastructure\WebSSO\Api\UpdateWebSSOConfiguration\{ UpdateWebSSOConfigurationController }; use Psr\Container\ContainerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; beforeEach(function (): void { $this->useCase = $this->createMock(UpdateWebSSOConfiguration::class); $this->presenter = $this->createMock(UpdateWebSSOConfigurationPresenterInterface::class); $timezone = new \DateTimeZone('Europe/Paris'); $adminContact = (new Contact()) ->setId(1) ->setName('admin') ->setAdmin(true) ->setTimezone($timezone); $adminContact->addTopologyRule(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_READ_WRITE); $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once()) ->method('isGranted') ->willReturn(true); $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($adminContact); $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->any()) ->method('getToken') ->willReturn($token); $this->container = $this->createMock(ContainerInterface::class); $this->container->expects($this->any()) ->method('has') ->willReturn(true); $this->container->expects($this->any()) ->method('get') ->willReturnOnConsecutiveCalls( $authorizationChecker, $tokenStorage, new class () { public function get(): string { return __DIR__ . '/../../../../../'; } } ); $this->request = $this->createMock(Request::class); }); it('throws an exception when the request body is invalid', function (): void { $controller = new UpdateWebSSOConfigurationController(); $controller->setContainer($this->container); $invalidPayload = json_encode([ 'is_active' => true, ]); $this->request ->expects($this->once()) ->method('getContent') ->willReturn($invalidPayload); $controller($this->useCase, $this->request, $this->presenter); })->throws(\InvalidArgumentException::class); it('show the response when everything is valid', function (): void { $controller = new UpdateWebSSOConfigurationController(); $controller->setContainer($this->container); $validPayload = json_encode([ 'is_active' => true, 'is_forced' => false, 'trusted_client_addresses' => [], 'blacklist_client_addresses' => [], 'login_header_attribute' => 'HTTP_AUTH_USER', 'pattern_matching_login' => '/@.*/', 'pattern_replace_login' => 'sso_', ]); $this->request ->expects($this->any()) ->method('getContent') ->willReturn($validPayload); $this->presenter ->expects($this->once()) ->method('show'); $controller($this->useCase, $this->request, $this->presenter); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/WebSSO/Api/FindWebSSOConfiguration/FindWebSSOConfigurationControllerTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/WebSSO/Api/FindWebSSOConfiguration/FindWebSSOConfigurationControllerTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Infrastructure\WebSSO\Api\FindWebSSOConfiguration; use Centreon\Domain\Contact\Contact; use Core\Security\ProviderConfiguration\Application\WebSSO\UseCase\FindWebSSOConfiguration\{ FindWebSSOConfiguration, FindWebSSOConfigurationPresenterInterface }; use Core\Security\ProviderConfiguration\Infrastructure\WebSSO\Api\FindWebSSOConfiguration\{ FindWebSSOConfigurationController }; use Psr\Container\ContainerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; beforeEach(function (): void { $this->useCase = $this->createMock(FindWebSSOConfiguration::class); $this->presenter = $this->createMock(FindWebSSOConfigurationPresenterInterface::class); $timezone = new \DateTimeZone('Europe/Paris'); $adminContact = (new Contact()) ->setId(1) ->setName('admin') ->setAdmin(true) ->setTimezone($timezone); $adminContact->addTopologyRule(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_READ_WRITE); $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once()) ->method('isGranted') ->willReturn(true); $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($adminContact); $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->any()) ->method('getToken') ->willReturn($token); $this->container = $this->createMock(ContainerInterface::class); $this->container->expects($this->any()) ->method('has') ->willReturn(true); $this->container->expects($this->any()) ->method('get') ->willReturnOnConsecutiveCalls( $authorizationChecker, $tokenStorage, new class () { public function get(): string { return __DIR__ . '/../../../../../'; } } ); $this->request = $this->createMock(Request::class); }); it('should call the use case', function (): void { $controller = new FindWebSSOConfigurationController(); $controller->setContainer($this->container); $this->useCase ->expects($this->once()) ->method('__invoke') ->with( $this->equalTo($this->presenter) ); $controller($this->useCase, $this->presenter); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/OpenId/Builder/DbConfigurationBuilderTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/OpenId/Builder/DbConfigurationBuilderTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Infrastructure\OpenId\Builder; use Core\Contact\Domain\Model\ContactGroup; use Core\Contact\Domain\Model\ContactTemplate; use Core\Security\ProviderConfiguration\Domain\Exception\ConfigurationException; use Core\Security\ProviderConfiguration\Domain\Model\ACLConditions; use Core\Security\ProviderConfiguration\Domain\Model\AuthenticationConditions; use Core\Security\ProviderConfiguration\Domain\Model\Endpoint; use Core\Security\ProviderConfiguration\Domain\Model\GroupsMapping; use Core\Security\ProviderConfiguration\Domain\Model\Provider; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\Configuration; use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration; beforeEach(function (): void { $this->customConfiguration = [ 'is_active' => true, 'client_id' => 'clientid', 'client_secret' => 'clientsecret', 'base_url' => 'http://127.0.0.1/openid', 'auto_import' => true, 'authorization_endpoint' => '/authorize', 'token_endpoint' => '/token', 'introspection_token_endpoint' => '/introspect', 'userinfo_endpoint' => '/userinfo', 'contact_template_id' => 1, 'email_bind_attribute' => 'email', 'fullname_bind_attribute' => 'name', 'trusted_client_addresses' => [], 'blacklist_client_addresses' => [], 'endsession_endpoint' => '/logout', 'connection_scopes' => [], 'login_claim' => 'preferred_username', 'authentication_type' => 'client_secret_post', 'verify_peer' => false, 'claim_name' => 'groups', 'roles_mapping' => new ACLConditions( false, false, '', new Endpoint(Endpoint::INTROSPECTION, ''), [] ), 'groups_mapping' => new GroupsMapping(false, '', new Endpoint(), []), 'redirect_url' => null, ]; }); it('should throw an exception when a mandatory parameter is empty and configuration is active', function (): void { $this->customConfiguration['base_url'] = null; $configuration = new Configuration( 2, mb_strtolower(Provider::OPENID), Provider::OPENID, json_encode($this->customConfiguration), true, false ); $configuration->setCustomConfiguration(new CustomConfiguration($this->customConfiguration)); })->throws(ConfigurationException::class, 'Missing mandatory parameters: base_url'); it( 'should throw an exception when both userinformation and introspection ' . 'endpoints are empty and a configuration is active', function (): void { $this->customConfiguration['userinfo_endpoint'] = null; $this->customConfiguration['introspection_token_endpoint'] = null; $configuration = new Configuration( 2, mb_strtolower(Provider::OPENID), Provider::OPENID, json_encode($this->customConfiguration), true, false ); $configuration->setCustomConfiguration(new CustomConfiguration($this->customConfiguration)); } )->throws( ConfigurationException::class, ConfigurationException::missingInformationEndpoint()->getMessage() ); it( 'should throw an exception when the configuration is active, autoimport enabled but with missing parameters', function (): void { $this->customConfiguration['contact_template'] = null; $this->customConfiguration['email_bind_attribute'] = null; $this->customConfiguration['fullname_bind_attribute'] = null; $configuration = new Configuration( 2, mb_strtolower(Provider::OPENID), Provider::OPENID, json_encode($this->customConfiguration), true, false ); $configuration->setCustomConfiguration(new CustomConfiguration($this->customConfiguration)); } )->throws( ConfigurationException::class, ConfigurationException::missingAutoImportMandatoryParameters( ['contact_template', 'email_bind_attribute', 'fullname_bind_attribute'] )->getMessage() ); it('should return a Provider when all mandatory parameters are present', function (): void { // Note: contact_template and contact_group are overridden $this->customConfiguration['contact_template'] = new ContactTemplate(1, 'contact_template'); $this->customConfiguration['contact_group'] = new ContactGroup(1, 'contact_group', 'contact_group'); $this->customConfiguration['authentication_conditions'] = new AuthenticationConditions( true, 'info.groups', new Endpoint(), ['groupA', 'groupB'] ); $configuration = new Configuration( 2, mb_strtolower(Provider::OPENID), Provider::OPENID, json_encode($this->customConfiguration), true, false ); $configuration->setCustomConfiguration(new CustomConfiguration($this->customConfiguration)); expect($configuration->getCustomConfiguration())->toBeInstanceOf(CustomConfiguration::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/OpenId/Api/FindOpenIdConfiguration/FindOpenIdConfigurationControllerTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/OpenId/Api/FindOpenIdConfiguration/FindOpenIdConfigurationControllerTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Infrastructure\OpenId\Api\FindOpenIdConfiguration; use Centreon\Domain\Contact\Contact; use Core\Security\ProviderConfiguration\Application\OpenId\UseCase\FindOpenIdConfiguration\{ FindOpenIdConfiguration, FindOpenIdConfigurationPresenterInterface }; use Core\Security\ProviderConfiguration\Infrastructure\OpenId\Api\FindOpenIdConfiguration\{ FindOpenIdConfigurationController }; use Psr\Container\ContainerInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; beforeEach(function (): void { $this->presenter = $this->createMock(FindOpenIdConfigurationPresenterInterface::class); $this->useCase = $this->createMock(FindOpenIdConfiguration::class); $timezone = new \DateTimeZone('Europe/Paris'); $adminContact = (new Contact()) ->setId(1) ->setName('admin') ->setAdmin(true) ->setTimezone($timezone); $adminContact->addTopologyRule(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_READ_WRITE); $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once()) ->method('isGranted') ->willReturn(true); $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($adminContact); $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->any()) ->method('getToken') ->willReturn($token); $this->container = $this->createMock(ContainerInterface::class); $this->container->expects($this->any()) ->method('has') ->willReturn(true); $this->container->expects($this->any()) ->method('get') ->willReturnOnConsecutiveCalls( $authorizationChecker, $tokenStorage, new class () { public function get(): string { return __DIR__ . '/../../../../../'; } } ); }); it('should execute the use case properly', function (): void { $controller = new FindOpenIdConfigurationController(); $controller->setContainer($this->container); $this->useCase ->expects($this->once()) ->method('__invoke') ->with( $this->equalTo($this->presenter) ); $controller($this->useCase, $this->presenter); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/OpenId/Api/UpdateOpenIdConfiguration/UpdateOpenIdConfigurationControllerTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/OpenId/Api/UpdateOpenIdConfiguration/UpdateOpenIdConfigurationControllerTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Infrastructure\OpenId\Api\UpdateOpenIdConfiguration; use Centreon\Domain\Contact\Contact; use Core\Security\ProviderConfiguration\Application\OpenId\UseCase\UpdateOpenIdConfiguration\{ UpdateOpenIdConfiguration, UpdateOpenIdConfigurationPresenterInterface }; use Core\Security\ProviderConfiguration\Infrastructure\OpenId\Api\UpdateOpenIdConfiguration\{ UpdateOpenIdConfigurationController }; use Psr\Container\ContainerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; beforeEach(function (): void { $this->presenter = $this->createMock(UpdateOpenIdConfigurationPresenterInterface::class); $this->useCase = $this->createMock(UpdateOpenIdConfiguration::class); $this->request = $this->createMock(Request::class); $timezone = new \DateTimeZone('Europe/Paris'); $adminContact = (new Contact()) ->setId(1) ->setName('admin') ->setAdmin(true) ->setTimezone($timezone); $adminContact->addTopologyRule(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_READ_WRITE); $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once()) ->method('isGranted') ->willReturn(true); $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($adminContact); $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->any()) ->method('getToken') ->willReturn($token); $this->container = $this->createMock(ContainerInterface::class); $this->container->expects($this->any()) ->method('has') ->willReturn(true); $this->container->expects($this->any()) ->method('get') ->willReturnOnConsecutiveCalls( $authorizationChecker, $tokenStorage, new class () { public function get(): string { return __DIR__ . '/../../../../../'; } } ); }); it('should thrown an exception when the request body is invalid', function (): void { $controller = new UpdateOpenIdConfigurationController(); $controller->setContainer($this->container); $invalidPayload = json_encode([]); $this->request ->expects($this->once()) ->method('getContent') ->willReturn($invalidPayload); $this->expectException(\InvalidArgumentException::class); $controller($this->useCase, $this->request, $this->presenter); }); it('should execute the usecase properly', function (): void { $controller = new UpdateOpenIdConfigurationController(); $controller->setContainer($this->container); $validPayload = json_encode([ 'is_active' => true, 'is_forced' => true, 'base_url' => 'http://127.0.0.1/auth/openid-connect', 'authorization_endpoint' => '/authorization', 'token_endpoint' => '/token', 'introspection_token_endpoint' => '/introspect', 'userinfo_endpoint' => '/userinfo', 'endsession_endpoint' => '/logout', 'connection_scopes' => [], 'login_claim' => 'preferred_username', 'client_id' => 'MyCl1ientId', 'client_secret' => 'MyCl1ientSuperSecr3tKey', 'authentication_type' => 'client_secret_post', 'verify_peer' => false, 'auto_import' => false, 'contact_template' => null, 'email_bind_attribute' => null, 'fullname_bind_attribute' => null, 'roles_mapping' => [ 'is_enabled' => false, 'apply_only_first_role' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => '', ], 'relations' => [], ], 'authentication_conditions' => [ 'is_enabled' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => null, ], 'authorized_values' => [], 'trusted_client_addresses' => [], 'blacklist_client_addresses' => [], ], 'groups_mapping' => [ 'is_enabled' => false, 'attribute_path' => '', 'endpoint' => [ 'type' => 'introspection_endpoint', 'custom_endpoint' => null, ], 'relations' => [], ], 'redirect_url' => null, ]); $this->request ->expects($this->exactly(2)) ->method('getContent') ->willReturn($validPayload); $this->useCase ->expects($this->once()) ->method('__invoke'); $controller($this->useCase, $this->request, $this->presenter); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/Local/Api/FindConfiguration/FindConfigurationControllerTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/Local/Api/FindConfiguration/FindConfigurationControllerTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Infrastructure\Local\Api\FindConfiguration; use Centreon\Domain\Contact\Contact; use Core\Security\ProviderConfiguration\Application\Local\UseCase\FindConfiguration\FindConfiguration; use Core\Security\ProviderConfiguration\Application\Local\UseCase\FindConfiguration\FindConfigurationPresenterInterface; use Core\Security\ProviderConfiguration\Infrastructure\Local\Api\FindConfiguration\FindConfigurationController; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; 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 FindConfigurationControllerTest extends TestCase { /** @var FindConfigurationPresenterInterface&\PHPUnit\Framework\MockObject\MockObject */ private $presenter; /** @var FindConfiguration&\PHPUnit\Framework\MockObject\MockObject */ private $useCase; /** @var ContainerInterface&\PHPUnit\Framework\MockObject\MockObject */ private $container; public function setUp(): void { $this->presenter = $this->createMock(FindConfigurationPresenterInterface::class); $this->useCase = $this->createMock(FindConfiguration::class); $timezone = new \DateTimeZone('Europe/Paris'); $adminContact = (new Contact()) ->setId(1) ->setName('admin') ->setAdmin(true) ->setTimezone($timezone); $adminContact->addTopologyRule(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_READ_WRITE); $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once()) ->method('isGranted') ->willReturn(true); $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($adminContact); $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->any()) ->method('getToken') ->willReturn($token); $this->container = $this->createMock(ContainerInterface::class); $this->container->expects($this->any()) ->method('has') ->willReturn(true); $this->container->expects($this->any()) ->method('get') ->willReturnOnConsecutiveCalls( $authorizationChecker, $tokenStorage, new class () { public function get(): string { return __DIR__ . '/../../../../../'; } } ); } /** * Test that the controller calls properly the usecase */ public function testFindControllerExecute(): void { $controller = new FindConfigurationController(); $controller->setContainer($this->container); $this->useCase ->expects($this->once()) ->method('__invoke') ->with( $this->equalTo($this->presenter) ); $controller($this->useCase, $this->presenter); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/Local/Api/UpdateConfiguration/UpdateConfigurationControllerTest.php
centreon/tests/php/Core/Security/ProviderConfiguration/Infrastructure/Local/Api/UpdateConfiguration/UpdateConfigurationControllerTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\ProviderConfiguration\Infrastructure\Local\Api\UpdateConfiguration; use Centreon\Domain\Contact\Contact; use Core\Security\ProviderConfiguration\Application\Local\UseCase\UpdateConfiguration\{ UpdateConfigurationPresenterInterface }; use Core\Security\ProviderConfiguration\Application\Local\UseCase\UpdateConfiguration\UpdateConfiguration; use Core\Security\ProviderConfiguration\Infrastructure\Local\Api\UpdateConfiguration\UpdateConfigurationController; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; class UpdateConfigurationControllerTest extends TestCase { /** @var Request&\PHPUnit\Framework\MockObject\MockObject */ private $request; /** @var UpdateConfigurationPresenterInterface&\PHPUnit\Framework\MockObject\MockObject */ private $presenter; /** @var UpdateConfiguration&\PHPUnit\Framework\MockObject\MockObject */ private $useCase; /** @var ContainerInterface&\PHPUnit\Framework\MockObject\MockObject */ private $container; public function setUp(): void { $this->presenter = $this->createMock(UpdateConfigurationPresenterInterface::class); $this->useCase = $this->createMock(UpdateConfiguration::class); $timezone = new \DateTimeZone('Europe/Paris'); $adminContact = (new Contact()) ->setId(1) ->setName('admin') ->setAdmin(true) ->setTimezone($timezone); $adminContact->addTopologyRule(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_READ_WRITE); $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once()) ->method('isGranted') ->willReturn(true); $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($adminContact); $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->any()) ->method('getToken') ->willReturn($token); $this->container = $this->createMock(ContainerInterface::class); $this->container->expects($this->any()) ->method('has') ->willReturn(true); $this->container->expects($this->any()) ->method('get') ->willReturnOnConsecutiveCalls( $authorizationChecker, $tokenStorage, new class () { public function get(): string { return __DIR__ . '/../../../../../'; } } ); $this->request = $this->createMock(Request::class); } /** * Test that a correct exception is thrown when body is invalid. */ public function testCreateUpdateConfigurationRequestWithInvalidBody(): void { $controller = new UpdateConfigurationController(); $controller->setContainer($this->container); $invalidPayload = json_encode([ 'password_security_policy' => [ 'has_uppercase' => true, ], ]); $this->expectException(\InvalidArgumentException::class); $controller($this->useCase, $this->request, $this->presenter); } /** * Test that use is called when body is valid. */ public function testCreateUpdateConfigurationRequestWithValidBody(): void { $controller = new UpdateConfigurationController(); $controller->setContainer($this->container); $validPayload = json_encode([ 'password_security_policy' => [ 'password_min_length' => 12, 'has_uppercase' => true, 'has_lowercase' => true, 'has_number' => true, 'has_special_character' => true, 'attempts' => 6, 'blocking_duration' => 900, 'password_expiration' => [ 'expiration_delay' => 15552000, 'excluded_users' => [ 'admin', ], ], 'can_reuse_passwords' => true, 'delay_before_new_password' => 3600, ], ]); $this->request ->expects($this->exactly(2)) ->method('getContent') ->willReturn($validPayload); $this->useCase ->expects($this->once()) ->method('__invoke'); $controller($this->useCase, $this->request, $this->presenter); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/AccessGroup/Application/UseCase/FindLocalUserAccessGroups/FindLocalUserAccessGroupsPresenterStub.php
centreon/tests/php/Core/Security/AccessGroup/Application/UseCase/FindLocalUserAccessGroups/FindLocalUserAccessGroupsPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups; use Core\Application\Common\UseCase\{ AbstractPresenter }; use Core\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups\FindLocalUserAccessGroupsPresenterInterface; use Core\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups\FindLocalUserAccessGroupsResponse; use Symfony\Component\HttpFoundation\Response; class FindLocalUserAccessGroupsPresenterStub extends AbstractPresenter implements FindLocalUserAccessGroupsPresenterInterface { /** @var FindLocalUserAccessGroupsResponse */ public $response; /** * @param FindLocalUserAccessGroupsResponse $response */ public function present(mixed $response): void { $this->response = $response; } /** * @return Response */ public function show(): Response { return new Response(); } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/AccessGroup/Application/UseCase/FindLocalUserAccessGroups/FindLocalUserAccessGroupsTest.php
centreon/tests/php/Core/Security/AccessGroup/Application/UseCase/FindLocalUserAccessGroups/FindLocalUserAccessGroupsTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups\FindLocalUserAccessGroups; use Core\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups\FindLocalUserAccessGroupsResponse; use Core\Security\AccessGroup\Domain\Model\AccessGroup; beforeEach(function (): void { $this->repository = $this->createMock(ReadAccessGroupRepositoryInterface::class); $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class); $this->user = $this->createMock(ContactInterface::class); }); it('should present an ErrorResponse while an exception occured', function (): void { $useCase = new FindLocalUserAccessGroups($this->repository, $this->user); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->repository ->expects($this->once()) ->method('findAllWithFilter') ->willThrowException(new \Exception()); $presenter = new FindLocalUserAccessGroupsPresenterStub($this->presenterFormatter); $useCase($presenter); expect($presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class); expect($presenter->getResponseStatus()?->getMessage())->toBe( 'Impossible to get contact groups from data storage' ); }); it('should call the method findAllWithFilter if the user is admin', function (): void { $useCase = new FindLocalUserAccessGroups($this->repository, $this->user); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->repository ->expects($this->once()) ->method('findAllWithFilter'); $presenter = new FindLocalUserAccessGroupsPresenterStub($this->presenterFormatter); $useCase($presenter); }); it('should call the method findByContact if the user is not admin', function (): void { $useCase = new FindLocalUserAccessGroups($this->repository, $this->user); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->repository ->expects($this->once()) ->method('findByContactWithFilter') ->with($this->user); $presenter = new FindLocalUserAccessGroupsPresenterStub($this->presenterFormatter); $useCase($presenter); }); it('should present a FindLocalUserAccessGroupsResponse when no error occured', function (): void { $useCase = new FindLocalUserAccessGroups($this->repository, $this->user); $accessGroup = (new AccessGroup(1, 'access_group', 'access_group_alias')) ->setActivate(true) ->setChanged(false); $this->repository ->expects($this->once()) ->method('findAllWithFilter') ->willReturn([$accessGroup]); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $presenter = new FindLocalUserAccessGroupsPresenterStub($this->presenterFormatter); $useCase($presenter); expect($presenter->response)->toBeInstanceOf(FindLocalUserAccessGroupsResponse::class); expect($presenter->response->accessGroups[0])->toBe( [ 'id' => 1, 'name' => 'access_group', 'alias' => 'access_group_alias', 'has_changed' => false, 'is_activated' => true, ] ); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/AccessGroup/Domain/Model/AccessGroupTest.php
centreon/tests/php/Core/Security/AccessGroup/Domain/Model/AccessGroupTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\AccessGroup\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Security\AccessGroup\Domain\Model\AccessGroup; it('should throw an Exception when an access group name is empty', function (): void { new AccessGroup(1, '', 'alias'); })->throws(InvalidArgumentException::class, AssertionException::notEmpty('AccessGroup::name')->getMessage()); it('should thrown an Exception when an access group alias is empty', function (): void { new AccessGroup(1, 'access_group', ''); })->throws(InvalidArgumentException::class, AssertionException::notEmpty('AccessGroup::alias')->getMessage());
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/AccessGroup/Infrastructure/Api/FindLocalUserAccessGroups/FindLocalUserAccessGroupsControllerTest.php
centreon/tests/php/Core/Security/AccessGroup/Infrastructure/Api/FindLocalUserAccessGroups/FindLocalUserAccessGroupsControllerTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Security\AccessGroup\Infrastructure\Api\FindLocalUserAccessGroups; use Centreon\Domain\Contact\Contact; use Core\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups\FindLocalUserAccessGroups; use Core\Security\AccessGroup\Application\UseCase\FindLocalUserAccessGroups\FindLocalUserAccessGroupsPresenterInterface; use Core\Security\AccessGroup\Infrastructure\Api\FindLocalUserAccessGroups\FindLocalUserAccessGroupsController; use Psr\Container\ContainerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; beforeEach(function (): void { $this->useCase = $this->createMock(FindLocalUserAccessGroups::class); $this->presenter = $this->createMock(FindLocalUserAccessGroupsPresenterInterface::class); $timezone = new \DateTimeZone('Europe/Paris'); $adminContact = (new Contact()) ->setId(1) ->setName('admin') ->setAdmin(true) ->setTimezone($timezone); $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class); $authorizationChecker->expects($this->once()) ->method('isGranted') ->willReturn(true); $token = $this->createMock(TokenInterface::class); $token->expects($this->any()) ->method('getUser') ->willReturn($adminContact); $tokenStorage = $this->createMock(TokenStorageInterface::class); $tokenStorage->expects($this->any()) ->method('getToken') ->willReturn($token); $this->container = $this->createMock(ContainerInterface::class); $this->container->expects($this->any()) ->method('has') ->willReturn(true); $this->container->expects($this->any()) ->method('get') ->willReturnOnConsecutiveCalls( $authorizationChecker, new class () { public function get(): string { return __DIR__ . '/../../../../../'; } } ); $this->request = $this->createMock(Request::class); }); it('should call the use case', function (): void { $controller = new FindLocalUserAccessGroupsController(); $controller->setContainer($this->container); $this->useCase ->expects($this->once()) ->method('__invoke') ->with( $this->equalTo($this->presenter) ); $controller($this->useCase, $this->presenter); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Platform/Application/UseCase/FindFeatures/FindFeaturesPresenterStub.php
centreon/tests/php/Core/Platform/Application/UseCase/FindFeatures/FindFeaturesPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Platform\Application\UseCase\FindFeatures; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Platform\Application\UseCase\FindFeatures\FindFeaturesPresenterInterface; use Core\Platform\Application\UseCase\FindFeatures\FindFeaturesResponse; class FindFeaturesPresenterStub implements FindFeaturesPresenterInterface { public FindFeaturesResponse|ResponseStatusInterface $data; public function presentResponse(FindFeaturesResponse|ResponseStatusInterface $data): void { $this->data = $data; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Platform/Application/UseCase/FindFeatures/FindFeaturesTest.php
centreon/tests/php/Core/Platform/Application/UseCase/FindFeatures/FindFeaturesTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Platform\Application\UseCase\FindFeatures; use Core\Application\Common\UseCase\ErrorResponse; use Core\Common\Application\FeatureFlagsInterface; use Core\Platform\Application\UseCase\FindFeatures\FindFeatures; use Core\Platform\Application\UseCase\FindFeatures\FindFeaturesResponse; use Exception; beforeEach(function (): void { $this->presenter = new FindFeaturesPresenterStub(); $this->useCase = new FindFeatures( $this->featureFlags = $this->createMock(FeatureFlagsInterface::class), ); }); it( 'should retrieve the "isCloudPlatform" correctly', function (bool $isCloudPlatform): void { $this->featureFlags->expects($this->once())->method('isCloudPlatform')->willReturn($isCloudPlatform); $this->featureFlags->expects($this->once())->method('getAll')->willReturn([]); ($this->useCase)($this->presenter); expect($this->presenter->data)->toBeInstanceOf(FindFeaturesResponse::class) ->and($this->presenter->data->isCloudPlatform)->toBe($isCloudPlatform); } )->with([ [true], [false], ]); it( 'should retrieve the "featureFlags" correctly', function (array $featureFlags): void { $this->featureFlags->expects($this->once())->method('isCloudPlatform')->willReturn(true); $this->featureFlags->expects($this->once())->method('getAll')->willReturn($featureFlags); ($this->useCase)($this->presenter); expect($this->presenter->data)->toBeInstanceOf(FindFeaturesResponse::class) ->and($this->presenter->data->featureFlags)->toBe($featureFlags); } )->with([ [['test_flag_1' => true]], [['test_flag_1' => true, 'test_flag_2' => false]], ]); it( 'should present an ErrorResponse is something fail', function (): void { $this->featureFlags->method('isCloudPlatform')->willThrowException(new Exception()); $this->featureFlags->method('getAll')->willThrowException(new Exception()); ($this->useCase)($this->presenter); expect($this->presenter->data)->toBeInstanceOf(ErrorResponse::class); } );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php
centreon/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Platform\Application\UseCase\UpdateVersions; use Centreon\Domain\Contact\Interfaces\ContactInterface; use CentreonModule\Infrastructure\Service\CentreonModuleService; use CentreonModule\ServiceProvider; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Engine\Application\Repository\EngineRepositoryInterface; use Core\Installation\Infrastructure\InstallationHelper; use Core\Platform\Application\Repository\ReadUpdateRepositoryInterface; use Core\Platform\Application\Repository\ReadVersionRepositoryInterface; use Core\Platform\Application\Repository\UpdateLockerRepositoryInterface; use Core\Platform\Application\Repository\WriteUpdateRepositoryInterface; use Core\Platform\Application\UseCase\UpdateVersions\UpdateVersions; use Core\Platform\Application\UseCase\UpdateVersions\UpdateVersionsPresenterInterface; use Core\Platform\Application\Validator\RequirementException; use Core\Platform\Application\Validator\RequirementValidatorsInterface; use Pimple\Container; use Security\Interfaces\EncryptionInterface; beforeEach(function (): void { $this->centreonModuleService = $this->createMock(CentreonModuleService::class); $this->engineRepository = $this->createMock(EngineRepositoryInterface::class); $this->useCase = new UpdateVersions( $this->requirementValidators = $this->createMock(RequirementValidatorsInterface::class), $this->updateLockerRepository = $this->createMock(UpdateLockerRepositoryInterface::class), $this->readVersionRepository = $this->createMock(ReadVersionRepositoryInterface::class), $this->readUpdateRepository = $this->createMock(ReadUpdateRepositoryInterface::class), $this->writeUpdateRepository = $this->createMock(WriteUpdateRepositoryInterface::class), $this->dependencyInjector = new Container([ServiceProvider::CENTREON_MODULE => $this->centreonModuleService]), $this->user = $this->createMock(ContactInterface::class), $this->installationHelper = new InstallationHelper( engineRepository: $this->engineRepository, encryption: $this->createMock(EncryptionInterface::class), appSecret:'app_secret' ), $this->engineRepository ); $this->presenter = $this->createMock(UpdateVersionsPresenterInterface::class); }); it('should present a Forbidden Response when user is not admin', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ForbiddenResponse('Only admin user can perform upgrades')); ($this->useCase)($this->presenter); }); it('should stop update process when an other update is already started', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->updateLockerRepository ->expects($this->once()) ->method('lock') ->willReturn(false); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse('Update already in progress')); ($this->useCase)($this->presenter); }); it('should present an error response if a requirement is not validated', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->requirementValidators ->expects($this->once()) ->method('validateRequirementsOrFail') ->willThrowException(new RequirementException('Requirement is not validated')); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse('Requirement is not validated')); ($this->useCase)($this->presenter); }); it('should present an error response if current centreon version is not found', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->updateLockerRepository ->expects($this->once()) ->method('lock') ->willReturn(true); $this->readVersionRepository ->expects($this->once()) ->method('findCurrentVersion') ->willReturn(null); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new ErrorResponse('Cannot retrieve the current version')); ($this->useCase)($this->presenter); }); it('should run found updates', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->updateLockerRepository ->expects($this->once()) ->method('lock') ->willReturn(true); $this->readVersionRepository ->expects($this->exactly(2)) ->method('findCurrentVersion') ->will($this->onConsecutiveCalls('22.04.0', '22.10.1')); $this->readUpdateRepository ->expects($this->once()) ->method('findOrderedAvailableUpdates') ->with('22.04.0') ->willReturn(['22.10.0-beta.1', '22.10.0', '22.10.1']); $this->centreonModuleService ->expects($this->exactly(2)) ->method('getList') ->will( $this->onConsecutiveCalls( ['module' => []], ['widget' => []], ) ); $this->writeUpdateRepository ->expects($this->exactly(3)) ->method('runUpdate'); $this->presenter ->expects($this->once()) ->method('setResponseStatus') ->with(new NoContentResponse()); $this->engineRepository ->expects($this->once()) ->method('engineSecretsHasContent') ->willReturn(true); ($this->useCase)($this->presenter); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Platform/Infrastructure/Repository/FsReadUpdateRepositoryTest.php
centreon/tests/php/Core/Platform/Infrastructure/Repository/FsReadUpdateRepositoryTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Platform\Infrastructure\Repository; use Core\Platform\Infrastructure\Repository\FsReadUpdateRepository; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; beforeEach(function (): void { $this->filesystem = $this->createMock(Filesystem::class); $this->finder = $this->createMock(Finder::class); }); it('should return an empty array when install directory does not exist', function (): void { $repository = new FsReadUpdateRepository(sys_get_temp_dir(), $this->filesystem, $this->finder); $this->filesystem ->expects($this->once()) ->method('exists') ->willReturn(false); $availableUpdates = $repository->findOrderedAvailableUpdates('22.04.0'); expect($availableUpdates)->toEqual([]); }); it('should order found updates', function (): void { $repository = new FsReadUpdateRepository(sys_get_temp_dir(), $this->filesystem, $this->finder); $this->filesystem ->expects($this->once()) ->method('exists') ->willReturn(true); $this->finder ->expects($this->once()) ->method('files') ->willReturn($this->finder); $this->finder ->expects($this->once()) ->method('in') ->willReturn($this->finder); $this->finder ->expects($this->once()) ->method('name') ->willReturn($this->finder); $this->finder ->expects($this->once()) ->method('getIterator') ->willReturn(new \ArrayIterator( [ new \SplFileInfo('Update-21.10.0.php'), new \SplFileInfo('Update-22.04.0.php'), new \SplFileInfo('Update-22.10.11.php'), new \SplFileInfo('Update-22.10.1.php'), new \SplFileInfo('Update-22.10.0-beta.3.php'), new \SplFileInfo('Update-22.10.0-alpha.1.php'), ] )); $availableUpdates = $repository->findOrderedAvailableUpdates('22.04.0'); expect($availableUpdates)->toEqual([ '22.10.0-alpha.1', '22.10.0-beta.3', '22.10.1', '22.10.11', ]); });
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/GraphTemplate/Application/UseCase/FindGraphTemplates/FindGraphTemplatesTest.php
centreon/tests/php/Core/GraphTemplate/Application/UseCase/FindGraphTemplates/FindGraphTemplatesTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\GraphTemplate\Application\UseCase\FindGraphTemplates; 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\GraphTemplate\Application\Exception\GraphTemplateException; use Core\GraphTemplate\Application\Repository\ReadGraphTemplateRepositoryInterface; use Core\GraphTemplate\Application\UseCase\FindGraphTemplates\FindGraphTemplates; use Core\GraphTemplate\Application\UseCase\FindGraphTemplates\FindGraphTemplatesResponse; use Core\GraphTemplate\Domain\Model\GraphTemplate; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Tests\Core\GraphTemplate\Infrastructure\API\FindGraphTemplates\FindGraphTemplatesPresenterStub; beforeEach(closure: function (): void { $this->readGraphTemplateRepository = $this->createMock(ReadGraphTemplateRepositoryInterface::class); $this->contact = $this->createMock(ContactInterface::class); $this->presenter = new FindGraphTemplatesPresenterStub($this->createMock(PresenterFormatterInterface::class)); $this->useCase = new FindGraphTemplates( $this->createMock(RequestParametersInterface::class), $this->readGraphTemplateRepository, $this->contact ); }); it('should present a ForbiddenResponse when the user has insufficient rights', function (): void { $this->contact ->expects($this->exactly(2)) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(GraphTemplateException::accessNotAllowed()->getMessage()); }); it( 'should present an ErrorResponse when an exception of type RequestParametersTranslatorException is thrown', function (): void { $this->contact ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $exception = new RequestParametersTranslatorException('Error'); $this->readGraphTemplateRepository ->expects($this->once()) ->method('findByRequestParameters') ->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('hasTopologyRole') ->willReturn(true); $exception = new \Exception('Error'); $this->readGraphTemplateRepository ->expects($this->once()) ->method('findByRequestParameters') ->willThrowException($exception); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(GraphTemplateException::errorWhileSearching($exception)->getMessage()); } ); it( 'should present a FindGraphTemplatesResponse when everything has gone well', function (): void { $graphTemplate = new GraphTemplate( id: 1, name: 'graph template name', verticalAxisLabel: 'vertical axis label', width: 150, height: 250, base: 1000, gridLowerLimit: 0, gridUpperLimit: 115, isUpperLimitSizedToMax: false, isGraphScaled: true, isDefaultCentreonTemplate: true, ); $this->contact ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readGraphTemplateRepository ->expects($this->once()) ->method('findByRequestParameters') ->willReturn([$graphTemplate]); ($this->useCase)($this->presenter); $graphTemplatesResponse = $this->presenter->response; expect($graphTemplatesResponse)->toBeInstanceOf(FindGraphTemplatesResponse::class); expect($graphTemplatesResponse->graphTemplates[0]->id)->toBe($graphTemplate->getId()); expect($graphTemplatesResponse->graphTemplates[0]->name)->toBe($graphTemplate->getName()); expect($graphTemplatesResponse->graphTemplates[0]->verticalAxisLabel)->toBe('vertical axis label'); expect($graphTemplatesResponse->graphTemplates[0]->width)->toBe(150); expect($graphTemplatesResponse->graphTemplates[0]->height)->toBe(250); expect($graphTemplatesResponse->graphTemplates[0]->base)->toBe(1000); expect($graphTemplatesResponse->graphTemplates[0]->gridLowerLimit)->toBe(0.0); expect($graphTemplatesResponse->graphTemplates[0]->gridUpperLimit)->toBe(115.0); expect($graphTemplatesResponse->graphTemplates[0]->isUpperLimitSizedToMax)->toBe(false); expect($graphTemplatesResponse->graphTemplates[0]->isGraphScaled)->toBe(true); expect($graphTemplatesResponse->graphTemplates[0]->isDefaultCentreonTemplate)->toBe(true); } );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/GraphTemplate/Domain/Model/GraphTemplateTest.php
centreon/tests/php/Core/GraphTemplate/Domain/Model/GraphTemplateTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\GraphTemplate\Domain\Model; use Centreon\Domain\Common\Assertion\AssertionException; use Core\GraphTemplate\Domain\Model\GraphTemplate; it('should return properly set instance', function (): void { $graphTemplate = new GraphTemplate( id: 1, name: 'graph template name', verticalAxisLabel: 'vertical axis label', width: 150, height: 250, base: 1000, gridLowerLimit: 0, gridUpperLimit: 115, isUpperLimitSizedToMax: false, isGraphScaled: true, isDefaultCentreonTemplate: true, ); expect($graphTemplate->getId())->toBe(1) ->and($graphTemplate->getName())->toBe('graph template name') ->and($graphTemplate->getVerticalAxisLabel())->toBe('vertical axis label') ->and($graphTemplate->getWidth())->toBe(150) ->and($graphTemplate->getHeight())->toBe(250) ->and($graphTemplate->getBase())->toBe(1000) ->and($graphTemplate->getGridLowerLimit())->toBe(0.0) ->and($graphTemplate->getGridUpperLimit())->toBe(115.0) ->and($graphTemplate->isUpperLimitSizedToMax())->toBe(false) ->and($graphTemplate->isGraphScaled())->toBe(true) ->and($graphTemplate->isDefaultCentreonTemplate())->toBe(true); }); it('should return set upperLimit to null when isUpperLimitSizedToMax is set to true', function (): void { $graphTemplate = new GraphTemplate( id: 1, name: 'graph template name', verticalAxisLabel: 'vertical axis label', width: 150, height: 250, gridUpperLimit: 115, isUpperLimitSizedToMax: true, ); expect($graphTemplate->getId())->toBe(1) ->and($graphTemplate->getGridUpperLimit())->toBe(null) ->and($graphTemplate->isUpperLimitSizedToMax())->toBe(true); }); it('should throw an exception when ID is < 0', function (): void { new GraphTemplate( id: 0, name: 'graph template name', verticalAxisLabel: 'vertical axis label', width: 150, height: 250, ); })->throws( \Assert\InvalidArgumentException::class, AssertionException::positiveInt(0, 'GraphTemplate::id')->getMessage() ); it('should throw an exception when name is empty', function (): void { new GraphTemplate( id: 1, name: '', verticalAxisLabel: 'vertical axis label', width: 150, height: 250, ); })->throws( \Assert\InvalidArgumentException::class, AssertionException::notEmptyString('GraphTemplate::name')->getMessage() ); it('should throw an exception when name is too long', function (): void { new GraphTemplate( id: 1, name: str_repeat('a', GraphTemplate::NAME_MAX_LENGTH + 1), verticalAxisLabel: 'vertical axis label', width: 150, height: 250, ); })->throws( \Assert\InvalidArgumentException::class, AssertionException::maxLength( str_repeat('a', GraphTemplate::NAME_MAX_LENGTH + 1), GraphTemplate::NAME_MAX_LENGTH + 1, GraphTemplate::NAME_MAX_LENGTH, 'GraphTemplate::name' )->getMessage() ); it('should throw an exception when vertical axis label is empty', function (): void { new GraphTemplate( id: 1, name: 'graph template name', verticalAxisLabel: '', width: 150, height: 250, ); })->throws( \Assert\InvalidArgumentException::class, AssertionException::notEmptyString('GraphTemplate::verticalAxisLabel')->getMessage() ); it('should throw an exception when vertical axis label is too long', function (): void { new GraphTemplate( id: 1, name: 'graph template name', verticalAxisLabel: str_repeat('a', GraphTemplate::LABEL_MAX_LENGTH + 1), width: 150, height: 250, ); })->throws( \Assert\InvalidArgumentException::class, AssertionException::maxLength( str_repeat('a', GraphTemplate::LABEL_MAX_LENGTH + 1), GraphTemplate::LABEL_MAX_LENGTH + 1, GraphTemplate::LABEL_MAX_LENGTH, 'GraphTemplate::verticalAxisLabel' )->getMessage() ); it('should throw an exception when base is different from 1000 or 1024', function (): void { new GraphTemplate( id: 1, name: 'graph template name', verticalAxisLabel: 'vertical axis label', width: 150, height: 250, base: 9999, ); })->throws( \Assert\InvalidArgumentException::class, AssertionException::inArray(9999, [1000, 1024], 'GraphTemplate::base')->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/GraphTemplate/Infrastructure/API/FindGraphTemplates/FindGraphTemplatesPresenterStub.php
centreon/tests/php/Core/GraphTemplate/Infrastructure/API/FindGraphTemplates/FindGraphTemplatesPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\GraphTemplate\Infrastructure\API\FindGraphTemplates; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\GraphTemplate\Application\UseCase\FindGraphTemplates\FindGraphTemplatesPresenterInterface; use Core\GraphTemplate\Application\UseCase\FindGraphTemplates\FindGraphTemplatesResponse; class FindGraphTemplatesPresenterStub extends AbstractPresenter implements FindGraphTemplatesPresenterInterface { public FindGraphTemplatesResponse|ResponseStatusInterface $response; public function presentResponse(ResponseStatusInterface|FindGraphTemplatesResponse $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/ResourceAccess/Application/UseCase/AddRule/AddRuleTest.php
centreon/tests/php/Core/ResourceAccess/Application/UseCase/AddRule/AddRuleTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Application\UseCase\AddRule; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\ConflictResponse; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\UseCase\AddRule\AddRule; use Core\ResourceAccess\Application\UseCase\AddRule\AddRuleRequest; use Core\ResourceAccess\Application\UseCase\AddRule\AddRuleResponse; use Core\ResourceAccess\Application\UseCase\AddRule\AddRuleValidation; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\MetaServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType; use Core\ResourceAccess\Domain\Model\Rule; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Tests\Core\ResourceAccess\Infrastructure\API\AddRule\AddRulePresenterStub; beforeEach(closure: function (): void { $this->presenter = new AddRulePresenterStub($this->createMock(PresenterFormatterInterface::class)); foreach ([ HostFilterType::class, HostGroupFilterType::class, HostCategoryFilterType::class, ServiceFilterType::class, ServiceGroupFilterType::class, ServiceCategoryFilterType::class, MetaServiceFilterType::class, ] as $className) { $this->filterTypes[] = new $className(); } $this->datasetValidator = new DatasetFilterValidator(new \ArrayObject($this->filterTypes)); $this->useCase = new AddRule( readRepository: $this->readRepository = $this->createMock(ReadResourceAccessRepositoryInterface::class), writeRepository: $this->writeRepository = $this->createMock(WriteResourceAccessRepositoryInterface::class), user: $this->user = $this->createMock(ContactInterface::class), dataStorageEngine: $this->createMock(DataStorageEngineInterface::class), validator: $this->validator = $this->createMock(AddRuleValidation::class), accessGroupRepository: $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), datasetValidator: $this->datasetValidator, isCloudPlatform: true ); $this->request = new AddRuleRequest(); $this->request->name = 'Rule 1'; $this->request->description = 'Description of Rule 1'; $this->request->isEnabled = true; $this->request->contactIds = [1, 2]; $this->request->contactGroupIds = [3, 4]; $datasetFilterData0 = [ 'type' => 'hostgroup', 'resources' => [11, 12], 'dataset_filter' => [ 'type' => 'host', 'resources' => [110, 120], 'dataset_filter' => null, ], ]; $datasetFilterData1 = [ 'type' => 'host', 'resources' => [111, 121], 'dataset_filter' => null, ]; $this->request->datasetFilters = [$datasetFilterData0, $datasetFilterData1]; $datasetFilter0 = new DatasetFilter( $datasetFilterData0['type'], $datasetFilterData0['resources'], $this->datasetValidator ); $datasetFilter0->setDatasetFilter( new DatasetFilter( $datasetFilterData0['dataset_filter']['type'], $datasetFilterData0['dataset_filter']['resources'], $this->datasetValidator ) ); $datasetFilter1 = new DatasetFilter( $datasetFilterData1['type'], $datasetFilterData1['resources'], $this->datasetValidator ); $this->datasetFilters = [$datasetFilter0, $datasetFilter1]; $this->rule = new Rule( id: 1, name: Rule::formatName($this->request->name), description: $this->request->name, linkedContacts: $this->request->contactIds, linkedContactGroups: $this->request->contactGroupIds, datasets: $this->datasetFilters, isEnabled: true ); }); it('should present a Forbidden response when user does not have sufficient rights (missing page access)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it('should present a Forbidden response when user does not have sufficient rights (not an admin)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'lame_acl', 'not an admin')] ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it( 'should present a ConflictResponse when name is already used', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->validator ->expects($this->once()) ->method('assertIsValidName') ->willThrowException( RuleException::nameAlreadyExists( Rule::formatName($this->request->name), $this->request->name ) ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->presenter->response->getMessage()) ->toBe( RuleException::nameAlreadyExists( Rule::formatName($this->request->name), $this->request->name )->getMessage() ); } ); it( 'should present an ErrorResponse when contact ids provided does not exist', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->validator ->expects($this->once()) ->method('assertContactIdsAreValid') ->willThrowException( RuleException::idsDoNotExist( 'contactIds', $this->request->contactIds ) ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe( RuleException::idsDoNotExist( 'contactIds', $this->request->contactIds )->getMessage() ); } ); it( 'should present an ErrorResponse when contact group ids provided does not exist', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->validator ->expects($this->once()) ->method('assertContactGroupIdsAreValid') ->willThrowException( RuleException::idsDoNotExist( 'contactGroupIds', $this->request->contactGroupIds ) ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe( RuleException::idsDoNotExist( 'contactGroupIds', $this->request->contactGroupIds )->getMessage() ); } ); it( 'should present an ErrorResponse when resources provided does not exist', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->validator ->expects($this->once()) ->method('assertIdsAreValid') ->with( $this->request->datasetFilters[0]['type'], $this->request->datasetFilters[0]['resources'] ) ->willThrowException( RuleException::idsDoNotExist( $this->request->datasetFilters[0]['type'], $this->request->datasetFilters[0]['resources'] ) ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe( RuleException::idsDoNotExist( $this->request->datasetFilters[0]['type'], $this->request->datasetFilters[0]['resources'] )->getMessage() ); } ); it('should present an ErrorResponse if the newly created rule cannot be retrieved', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->writeRepository ->expects($this->once()) ->method('add') ->willReturn(1); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn(null); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::errorWhileRetrievingARule()->getMessage()); }); it('should return created object on success', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->validator->expects($this->once())->method('assertIsValidName'); $this->validator->expects($this->once())->method('assertContactIdsAreValid'); $this->validator->expects($this->once())->method('assertContactGroupIdsAreValid'); $this->validator->expects($this->any())->method('assertIdsAreValid'); $this->writeRepository ->expects($this->once()) ->method('add') ->willReturn(1); $this->writeRepository ->expects($this->once()) ->method('linkContactsToRule'); $this->writeRepository ->expects($this->once()) ->method('linkContactGroupsToRule'); $this->writeRepository ->expects($this->any()) ->method('addDataset'); $this->writeRepository ->expects($this->any()) ->method('linkDatasetToRule'); $this->writeRepository ->expects($this->any()) ->method('linkResourcesToDataset'); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn($this->rule); ($this->useCase)($this->request, $this->presenter); $response = $this->presenter->response; expect($response)->toBeInstanceOf(AddRuleResponse::class) ->and($response->id)->toBe($this->rule->getId()) ->and($response->name)->toBe($this->rule->getName()) ->and($response->description)->toBe($this->rule->getDescription()) ->and($response->contactIds)->toBe($this->rule->getLinkedContactIds()) ->and($response->isEnabled)->toBeTrue() ->and($response->contactGroupIds)->toBe($this->rule->getLinkedContactGroupIds()) ->and($response->datasetFilters[0]['type'])->toBe($this->datasetFilters[0]->getType()) ->and($response->datasetFilters[0]['resources'])->toBe($this->datasetFilters[0]->getResourceIds()) ->and($response->datasetFilters[0]['dataset_filter']['type'])->toBe($this->datasetFilters[0]->getDatasetFilter()->getType()) ->and($response->datasetFilters[0]['dataset_filter']['resources'])->toBe($this->datasetFilters[0]->getDatasetFilter()->getResourceIds()) ->and($response->datasetFilters[0]['dataset_filter']['dataset_filter'])->toBeNull() ->and($response->datasetFilters[1]['type'])->toBe($this->datasetFilters[1]->getType()) ->and($response->datasetFilters[1]['resources'])->toBe($this->datasetFilters[1]->getResourceIds()) ->and($response->datasetFilters[1]['dataset_filter'])->toBeNull(); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Application/UseCase/PartialRuleUpdate/PartialRuleUpdateTest.php
centreon/tests/php/Core/ResourceAccess/Application/UseCase/PartialRuleUpdate/PartialRuleUpdateTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Application\UseCase\PartialRuleUpdate; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ConflictResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\UseCase\PartialRuleUpdate\PartialRuleUpdate; use Core\ResourceAccess\Application\UseCase\PartialRuleUpdate\PartialRuleUpdateRequest; use Core\ResourceAccess\Application\UseCase\UpdateRule\UpdateRuleValidation; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\MetaServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType; use Core\ResourceAccess\Domain\Model\NewRule; use Core\ResourceAccess\Domain\Model\Rule; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Tests\Core\ResourceAccess\Infrastructure\API\PartialRuleUpdate\PartialRuleUpdatePresenterStub; beforeEach(closure: function (): void { $this->presenter = new PartialRuleUpdatePresenterStub($this->createMock(PresenterFormatterInterface::class)); foreach ([ HostFilterType::class, HostGroupFilterType::class, HostCategoryFilterType::class, ServiceFilterType::class, ServiceGroupFilterType::class, ServiceCategoryFilterType::class, MetaServiceFilterType::class, ] as $className) { $this->filterTypes[] = new $className(); } $this->datasetValidator = new DatasetFilterValidator(new \ArrayObject($this->filterTypes)); $this->useCase = new PartialRuleUpdate( user: $this->user = $this->createMock(ContactInterface::class), accessGroupRepository: $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), readRepository: $this->readRepository = $this->createMock(ReadResourceAccessRepositoryInterface::class), writeRepository: $this->writeRepository = $this->createMock(WriteResourceAccessRepositoryInterface::class), validator: $this->validator = $this->createMock(UpdateRuleValidation::class), isCloudPlatform: true ); $this->request = new PartialRuleUpdateRequest(); $this->request->name = 'Rule 1'; $this->request->description = 'Description of Rule 1'; $this->request->isEnabled = true; $datasetFilterData0 = [ 'type' => 'hostgroup', 'resources' => [11, 12], 'dataset_filter' => [ 'type' => 'host', 'resources' => [110, 120], 'dataset_filter' => null, ], ]; $datasetFilterData1 = [ 'type' => 'host', 'resources' => [111, 121], 'dataset_filter' => null, ]; $datasetFilter0 = new DatasetFilter( $datasetFilterData0['type'], $datasetFilterData0['resources'], $this->datasetValidator ); $datasetFilter0->setDatasetFilter( new DatasetFilter( $datasetFilterData0['dataset_filter']['type'], $datasetFilterData0['dataset_filter']['resources'], $this->datasetValidator ) ); $datasetFilter1 = new DatasetFilter( $datasetFilterData1['type'], $datasetFilterData1['resources'], $this->datasetValidator ); $this->datasetFilters = [$datasetFilter0, $datasetFilter1]; $this->rule = new Rule( id: 1, name: Rule::formatName($this->request->name), description: $this->request->name, linkedContacts: [1], linkedContactGroups: [2], datasets: $this->datasetFilters, isEnabled: true ); }); it('should present a Forbidden response when user does not have sufficient rights (missing page access)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it('should present a Forbidden response when user does not have sufficient rights (not an admin)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'lame_acl', 'not an admin')] ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it( 'should present a NotFoundResponse when ruleId requested does not exist', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn(null); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus)->toBeInstanceOf(NotFoundResponse::class); } ); it( 'should present ConflictResponse when name provided is already used', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn($this->rule); $this->request->name = 'fake-existing-name'; $this->validator ->expects($this->once()) ->method('assertIsValidName') ->willThrowException( RuleException::nameAlreadyExists( NewRule::formatName($this->request->name), $this->request->name ) ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ConflictResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe( RuleException::nameAlreadyExists( NewRule::formatName($this->request->name), $this->request->name )->getMessage() ); } ); it( 'should present a NoContentResponse when everything goes well', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn($this->rule); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(NoContentResponse::class); } );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Application/UseCase/DeleteRule/DeleteRuleTest.php
centreon/tests/php/Core/ResourceAccess/Application/UseCase/DeleteRule/DeleteRuleTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Application\UseCase\DeleteRule; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\UseCase\DeleteRule\DeleteRule; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Tests\Core\ResourceAccess\Infrastructure\API\DeleteRule\DeleteRulePresenterStub; beforeEach(closure: function (): void { $this->useCase = new DeleteRule( readRepository: $this->readRepository = $this->createMock(ReadResourceAccessRepositoryInterface::class), writeRepository: $this->writeRepository = $this->createMock(WriteResourceAccessRepositoryInterface::class), user: $this->user = $this->createMock(ContactInterface::class), accessGroupRepository: $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), isCloudPlatform: true ); $this->presenter = new DeleteRulePresenterStub($this->createMock(PresenterFormatterInterface::class)); }); it('should present a Forbidden response when user does not have sufficient rights (missing page access)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)(1, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it('should present a Forbidden response when user does not have sufficient rights (not admin)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'centreon_not_admin', 'not an admin')] ); ($this->useCase)(1, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it('should present a NotFoundResponse when rule ID provided does not correspond to an existing rule', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('exists') ->willReturn(false); ($this->useCase)(1, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(NotFoundResponse::class) ->and($this->presenter->response->getMessage()) ->toBe((new NotFoundResponse('Resource access rule'))->getMessage()); }); it('should present a ErrorResponse when deletion goes wrong', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('exists') ->willReturn(true); $this->writeRepository ->expects($this->once()) ->method('deleteRuleAndDatasets') ->with(1) ->willThrowException(new \Exception()); ($this->useCase)(1, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::errorWhileDeleting(new \Exception())->getMessage()); }); it('should present a NoContentResponse when deletion goes well', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('exists') ->willReturn(true); $this->writeRepository ->expects($this->once()) ->method('deleteRuleAndDatasets') ->with(1); ($this->useCase)(1, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(NoContentResponse::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesTest.php
centreon/tests/php/Core/ResourceAccess/Application/UseCase/DeleteRules/DeleteRulesTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Application\UseCase\DeleteRules; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\MultiStatusResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRules; use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRulesRequest; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Tests\Core\ResourceAccess\Infrastructure\API\DeleteRules\DeleteRulesPresenterStub; beforeEach(closure: function (): void { $this->useCase = new DeleteRules( readRepository: $this->readRepository = $this->createMock(ReadResourceAccessRepositoryInterface::class), writeRepository: $this->writeRepository = $this->createMock(WriteResourceAccessRepositoryInterface::class), user: $this->user = $this->createMock(ContactInterface::class), accessGroupRepository: $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), dataStorageEngine: $this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class), isCloudPlatform: true ); $this->presenter = new DeleteRulesPresenterStub($this->createMock(PresenterFormatterInterface::class)); }); it('should present a Forbidden response when user does not have sufficient rights (missing page access)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); $request = new DeleteRulesRequest(); $request->ids = [1, 2]; ($this->useCase)($request, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it('should present a Forbidden response when user does not have sufficient rights (not admin)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'centreon_not_admin', 'not an admin')] ); $request = new DeleteRulesRequest(); $request->ids = [1, 2]; ($this->useCase)($request, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it('should present a Multi-Status Response when a bulk delete action is executed', function (): void { $request = new DeleteRulesRequest(); $request->ids = [1, 2]; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'customer_admin_acl')] ); $this->readRepository ->expects($this->exactly(2)) ->method('exists') ->willReturnOnConsecutiveCalls(true, false); ($this->useCase)($request, $this->presenter); $expectedResult = [ 'results' => [ [ 'self' => 'centreon/api/latest/administration/resource-access/rules/1', 'status' => 204, 'message' => null, ], [ 'self' => 'centreon/api/latest/administration/resource-access/rules/2', 'status' => 404, 'message' => 'Resource access rule not found', ], ], ]; expect($this->presenter->response) ->toBeInstanceOf(MultiStatusResponse::class) ->and($this->presenter->response->getPayload()) ->toBeArray() ->and($this->presenter->response->getPayload()) ->toBe($expectedResult); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRuleTest.php
centreon/tests/php/Core/ResourceAccess/Application/UseCase/UpdateRule/UpdateRuleTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Application\UseCase\UpdateRule; 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\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Common\Application\Repository\RepositoryManagerInterface; use Core\Contact\Application\Repository\ReadContactRepositoryInterface; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\UseCase\UpdateRule\UpdateRule; use Core\ResourceAccess\Application\UseCase\UpdateRule\UpdateRuleRequest; use Core\ResourceAccess\Application\UseCase\UpdateRule\UpdateRuleValidation; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ImageFolderFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\MetaServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType; use Core\ResourceAccess\Domain\Model\NewRule; use Core\ResourceAccess\Domain\Model\Rule; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Tests\Core\ResourceAccess\Infrastructure\API\UpdateRule\UpdateRulePresenterStub; beforeEach(closure: function (): void { $this->presenter = new UpdateRulePresenterStub($this->createMock(PresenterFormatterInterface::class)); foreach ([ HostFilterType::class, HostGroupFilterType::class, HostCategoryFilterType::class, ServiceFilterType::class, ServiceGroupFilterType::class, ServiceCategoryFilterType::class, MetaServiceFilterType::class, ImageFolderFilterType::class, ] as $className) { $this->filterTypes[] = new $className(); } $this->datasetValidator = new DatasetFilterValidator(new \ArrayObject($this->filterTypes)); $this->contactRepository = $this->createMock(ReadContactRepositoryInterface::class); $this->useCase = new UpdateRule( user: $this->user = $this->createMock(ContactInterface::class), accessGroupRepository: $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), readRepository: $this->readRepository = $this->createMock(ReadResourceAccessRepositoryInterface::class), writeRepository: $this->writeRepository = $this->createMock(WriteResourceAccessRepositoryInterface::class), validator: $this->validator = $this->createMock(UpdateRuleValidation::class), datasetValidator: $this->datasetValidator, repositoryManager: $this->createMock(RepositoryManagerInterface::class), isCloudPlatform: true ); $this->request = new UpdateRuleRequest(); $this->request->name = 'Rule 1'; $this->request->description = 'Description of Rule 1'; $this->request->isEnabled = true; $this->request->contactIds = [1, 2]; $this->request->contactGroupIds = [3, 4]; $datasetFilterData0 = [ 'type' => 'hostgroup', 'resources' => [11, 12], 'dataset_filter' => [ 'type' => 'host', 'resources' => [110, 120], 'dataset_filter' => null, ], ]; $datasetFilterData1 = [ 'type' => 'host', 'resources' => [111, 121], 'dataset_filter' => null, ]; $this->request->datasetFilters = [$datasetFilterData0, $datasetFilterData1]; $datasetFilter0 = new DatasetFilter( $datasetFilterData0['type'], $datasetFilterData0['resources'], $this->datasetValidator ); $datasetFilter0->setDatasetFilter( new DatasetFilter( $datasetFilterData0['dataset_filter']['type'], $datasetFilterData0['dataset_filter']['resources'], $this->datasetValidator ) ); $datasetFilter1 = new DatasetFilter( $datasetFilterData1['type'], $datasetFilterData1['resources'], $this->datasetValidator ); $this->datasetFilters = [$datasetFilter0, $datasetFilter1]; $this->rule = new Rule( id: 1, name: Rule::formatName($this->request->name), description: $this->request->name, linkedContacts: $this->request->contactIds, linkedContactGroups: $this->request->contactGroupIds, datasets: $this->datasetFilters, isEnabled: true ); }); it('should present a Forbidden response when user does not have sufficient rights (missing page access)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it('should present a Forbidden response when user does not have sufficient rights (not an admin)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'lame_acl', 'not an admin')] ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it( 'should present a NotFoundResponse when ruleId requested does not exist', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn(null); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus)->toBeInstanceOf(NotFoundResponse::class); } ); it( 'should present ConflictResponse when name provided is already used', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn($this->rule); $this->request->name = 'fake-existing-name'; $this->validator ->expects($this->once()) ->method('assertIsValidName') ->willThrowException( RuleException::nameAlreadyExists( NewRule::formatName($this->request->name), $this->request->name ) ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ConflictResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe( RuleException::nameAlreadyExists( NewRule::formatName($this->request->name), $this->request->name )->getMessage() ); } ); it( 'should present a RuleException when contacts and contactgroups are empty', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn($this->rule); $this->validator ->expects($this->once()) ->method('assertContactsAndContactGroupsAreNotEmpty') ->willThrowException( RuleException::noLinkToContactsOrContactGroups() ); $this->request->contactIds = []; $this->request->contactGroupIds = []; ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe( RuleException::noLinkToContactsOrContactGroups()->getMessage() ); } ); it( 'should present an ErrorResponse when contact ids provided does not exist', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn($this->rule); $this->validator ->expects($this->once()) ->method('assertContactIdsAreValid') ->willThrowException( RuleException::idsDoNotExist('contactIds', [10]) ); $this->request->contactIds = [10]; ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe( RuleException::idsDoNotExist( 'contactIds', $this->request->contactIds )->getMessage() ); } ); it( 'should present an ErrorResponse when contact group ids provided does not exist', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn($this->rule); $this->validator ->expects($this->once()) ->method('assertContactGroupIdsAreValid') ->willThrowException( RuleException::idsDoNotExist('contactGroupIds', [10]) ); $this->request->contactGroupIds = [10]; ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe( RuleException::idsDoNotExist( 'contactGroupIds', $this->request->contactGroupIds )->getMessage() ); } ); it( 'should present an ErrorResponse when resources provided does not exist', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn($this->rule); $this->validator ->expects($this->once()) ->method('assertIdsAreValid') ->with( $this->request->datasetFilters[0]['type'], $this->request->datasetFilters[0]['resources'] ) ->willThrowException( RuleException::idsDoNotExist( $this->request->datasetFilters[0]['type'], $this->request->datasetFilters[0]['resources'] ) ); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->responseStatus->getMessage()) ->toBe( RuleException::idsDoNotExist( $this->request->datasetFilters[0]['type'], $this->request->datasetFilters[0]['resources'] )->getMessage() ); } ); it( 'should present a NoContentResponse when everything goes well', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findById') ->willReturn($this->rule); ($this->useCase)($this->request, $this->presenter); expect($this->presenter->responseStatus) ->toBeInstanceOf(NoContentResponse::class); } );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Application/UseCase/FindRules/FindRulesTest.php
centreon/tests/php/Core/ResourceAccess/Application/UseCase/FindRules/FindRulesTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Application\UseCase\FindRules; 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\Contact\Domain\AdminResolver; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\UseCase\FindRules\FindRules; use Core\ResourceAccess\Application\UseCase\FindRules\FindRulesResponse; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\MetaServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType; use Core\ResourceAccess\Domain\Model\Rule; use Tests\Core\ResourceAccess\Infrastructure\API\FindRules\FindRulesPresenterStub; beforeEach(closure: function (): void { foreach ([ HostFilterType::class, HostGroupFilterType::class, HostCategoryFilterType::class, ServiceFilterType::class, ServiceGroupFilterType::class, ServiceCategoryFilterType::class, MetaServiceFilterType::class, ] as $className) { $this->filterTypes[] = new $className(); } $this->datasetValidator = new DatasetFilterValidator(new \ArrayObject($this->filterTypes)); $this->requestParameters = $this->createMock(RequestParametersInterface::class); $this->user = $this->createMock(ContactInterface::class); $this->repository = $this->createMock(ReadResourceAccessRepositoryInterface::class); $this->presenter = new FindRulesPresenterStub($this->createMock(PresenterFormatterInterface::class)); $this->adminResolver = $this->createMock(AdminResolver::class); $this->useCase = new FindRules($this->user, $this->repository, $this->requestParameters, $this->adminResolver); }); it('should present an ErrorResponse when an exception occurs', function (): void { $this->adminResolver ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $exception = new \Exception(); $this->repository ->expects($this->once()) ->method('findAllByRequestParameters') ->with($this->requestParameters) ->willThrowException($exception); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::errorWhileSearchingRules()->getMessage()); }); it('should present an ErrorResponse when an error occurs concerning the request parameters', function (): void { $this->adminResolver ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->repository ->expects($this->once()) ->method('findAllByRequestParameters') ->with($this->requestParameters) ->willThrowException(new RequestParametersTranslatorException()); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class); }); it('should present a FindRulesResponse when no error occurs (custom_admin)', function (): void { $this->adminResolver ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $rule = new Rule( id: 1, name: 'name', description: 'description', linkedContacts: [1], linkedContactGroups: [2], datasets: [new DatasetFilter('host', [3, 4], $this->datasetValidator)], isEnabled: true ); $rulesFound = [$rule]; $this->repository ->expects($this->once()) ->method('findAllByRequestParameters') ->with($this->requestParameters) ->willReturn($rulesFound); ($this->useCase)($this->presenter); $response = $this->presenter->response; expect($response)->toBeInstanceOf(FindRulesResponse::class) ->and($response->rulesDto[0]->id)->toBe($rule->getId()) ->and($response->rulesDto[0]->name)->toBe($rule->getName()) ->and($response->rulesDto[0]->description)->toBe($rule->getDescription()) ->and($response->rulesDto[0]->isEnabled)->toBe($rule->isEnabled()); }); it('should present a FindRulesResponse when no error occurs (custom_editor)', function (): void { $this->adminResolver ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $rule = new Rule( id: 1, name: 'name', description: 'description', linkedContacts: [1], linkedContactGroups: [2], datasets: [new DatasetFilter('host', [3, 4], $this->datasetValidator)], isEnabled: true ); $rulesFound = [$rule]; $this->repository ->expects($this->once()) ->method('findAllByRequestParametersAndUserId') ->with($this->requestParameters) ->willReturn($rulesFound); ($this->useCase)($this->presenter); $response = $this->presenter->response; expect($response)->toBeInstanceOf(FindRulesResponse::class) ->and($response->rulesDto[0]->id)->toBe($rule->getId()) ->and($response->rulesDto[0]->name)->toBe($rule->getName()) ->and($response->rulesDto[0]->description)->toBe($rule->getDescription()) ->and($response->rulesDto[0]->isEnabled)->toBe($rule->isEnabled()); });
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/ResourceAccess/Application/UseCase/FindRule/FindRuleTest.php
centreon/tests/php/Core/ResourceAccess/Application/UseCase/FindRule/FindRuleTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Application\UseCase\FindRule; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Configuration\MetaService\Repository\ReadMetaServiceRepositoryInterface; use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface; use Core\Contact\Application\Repository\ReadContactRepositoryInterface; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface; use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ResourceAccess\Application\Exception\RuleException; use Core\ResourceAccess\Application\Providers\HostCategoryProvider; use Core\ResourceAccess\Application\Providers\HostGroupProvider; use Core\ResourceAccess\Application\Providers\HostProvider; use Core\ResourceAccess\Application\Providers\MetaServiceProvider; use Core\ResourceAccess\Application\Providers\ServiceCategoryProvider; use Core\ResourceAccess\Application\Providers\ServiceGroupProvider; use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface; use Core\ResourceAccess\Application\UseCase\FindRule\FindRule; use Core\ResourceAccess\Application\UseCase\FindRule\FindRuleResponse; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\MetaServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType; use Core\ResourceAccess\Domain\Model\Rule; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface; use Tests\Core\ResourceAccess\Infrastructure\API\FindRule\FindRulePresenterStub; beforeEach(closure: function (): void { foreach ([ HostFilterType::class, HostGroupFilterType::class, HostCategoryFilterType::class, ServiceFilterType::class, ServiceGroupFilterType::class, ServiceCategoryFilterType::class, MetaServiceFilterType::class, ] as $className) { $filterTypes[] = new $className(); } $datasetValidator = new DatasetFilterValidator(new \ArrayObject($filterTypes)); $providers = new \ArrayObject([ new HostProvider($this->createMock(ReadHostRepositoryInterface::class)), new HostGroupProvider($this->createMock(ReadHostGroupRepositoryInterface::class)), new HostCategoryProvider($this->createMock(ReadHostCategoryRepositoryInterface::class)), new ServiceGroupProvider($this->createMock(ReadServiceGroupRepositoryInterface::class)), new ServiceCategoryProvider($this->createMock(ReadServiceCategoryRepositoryInterface::class)), new MetaServiceProvider($this->createMock(ReadMetaServiceRepositoryInterface::class)), ]); $hostDatasetFilter = new DatasetFilter('host', [1], $datasetValidator); $datasetFilter = new DatasetFilter('hostgroup', [1], $datasetValidator); $datasetFilter->setDatasetFilter($hostDatasetFilter); $this->rule = new Rule( id: 1, name: 'ResourceAccess', description: 'ResourceAccessDescription', linkedContacts: [1], linkedContactGroups: [2], datasets: [$datasetFilter] ); $this->user = $this->createMock(ContactInterface::class); $this->repository = $this->createMock(ReadResourceAccessRepositoryInterface::class); $this->presenter = new FindRulePresenterStub($this->createMock(PresenterFormatterInterface::class)); $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class); $this->contactRepository = $this->createMock(ReadContactRepositoryInterface::class); $this->contactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class); $this->useCase = new FindRule( user: $this->user, accessGroupRepository: $this->accessGroupRepository, repository: $this->repository, contactRepository: $this->contactRepository, contactGroupRepository: $this->contactGroupRepository, datasetFilterValidator: $datasetValidator, repositoryProviders: $providers, isCloudPlatform: true ); }); it('should present a Forbidden response when user does not have sufficient rights (missing page access)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)(1, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it('should present a Forbidden response when user does not have sufficient rights (not an admin)', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'lame_acl', 'not an admin')] ); ($this->useCase)(1, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::notAllowed()->getMessage()); }); it('should present an ErrorResponse when an exception occurs', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $exception = new \Exception(); $this->repository ->expects($this->once()) ->method('findById') ->with(1) ->willThrowException($exception); ($this->useCase)(1, $this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(RuleException::errorWhileSearchingRules()->getMessage()); }); it('should present a FindRuleResponse when no error occurs', function (): void { $this->accessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn( [new AccessGroup(1, 'customer_admin_acl', 'not an admin')] ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->repository ->expects($this->once()) ->method('findById') ->with(1) ->willReturn($this->rule); $this->contactRepository ->expects($this->any()) ->method('findAliasesByIds') ->with(...$this->rule->getLinkedContactIds()) ->willReturn(['1' => ['id' => 1, 'alias' => 'contact1']]); $this->contactGroupRepository ->expects($this->any()) ->method('findNamesByIds') ->with(...$this->rule->getLinkedContactGroupIds()) ->willReturn(['1' => ['id' => 1, 'name' => 'contactgroup1']]); ($this->useCase)(1, $this->presenter); $response = $this->presenter->response; expect($response)->toBeInstanceOf(FindRuleResponse::class) ->and($response->id)->toBe($this->rule->getId()) ->and($response->name)->toBe($this->rule->getName()) ->and($response->description)->toBe($this->rule->getDescription()) ->and($response->isEnabled)->toBe($this->rule->isEnabled()); });
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/ResourceAccess/Domain/Model/RuleTest.php
centreon/tests/php/Core/ResourceAccess/Domain/Model/RuleTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\MetaServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType; use Core\ResourceAccess\Domain\Model\Rule; beforeEach(function (): void { $this->contacts = [1, 2]; $this->contactGroups = [3, 4]; $this->resources = [10, 11]; foreach ([ HostFilterType::class, HostGroupFilterType::class, HostCategoryFilterType::class, ServiceFilterType::class, ServiceGroupFilterType::class, ServiceCategoryFilterType::class, MetaServiceFilterType::class, ] as $className) { $this->filterTypes[] = new $className(); } $this->validator = new DatasetFilterValidator(new \ArrayObject($this->filterTypes)); $this->datasets = [new DatasetFilter('host', $this->resources, $this->validator)]; }); it('should return properly set Rule instance (all properties)', function (): void { $rule = new Rule( id: 1, name: 'FULL', description: 'Full access', linkedContacts: $this->contacts, linkedContactGroups: $this->contactGroups, datasets: $this->datasets, isEnabled: true ); $dataset = ($rule->getDatasetFilters())[0]; expect($rule->getId())->toBe(1) ->and($rule->getName())->toBe('FULL') ->and($rule->getDescription())->toBe('Full access') ->and($rule->getLinkedContactIds())->toBe([1, 2]) ->and($rule->getLinkedContactGroupIds())->toBe([3, 4]) ->and($rule->isEnabled())->toBe(true); expect($dataset->getType())->toBe('host') ->and($dataset->getResourceIds())->toBe([10, 11]) ->and($dataset->getDatasetFilter())->toBeNull(); }); it('should return properly the name of the rule correctly formatted', function (): void { $rule = new Rule( id: 1, name: 'FULL access', description: 'Full access', linkedContacts: $this->contacts, linkedContactGroups: $this->contactGroups, datasets: $this->datasets, isEnabled: true ); $dataset = ($rule->getDatasetFilters())[0]; expect($rule->getId())->toBe(1) ->and($rule->getName())->toBe('FULL_access') ->and($rule->getDescription())->toBe('Full access') ->and($rule->getLinkedContactIds())->toBe([1, 2]) ->and($rule->getLinkedContactGroupIds())->toBe([3, 4]) ->and($rule->isEnabled())->toBe(true); expect($dataset->getType())->toBe('host') ->and($dataset->getResourceIds())->toBe([10, 11]) ->and($dataset->getDatasetFilter())->toBeNull(); }); it('should throw an exception when rules id is not a positive int', function (): void { new Rule( id: 0, name: 'FULL', description: 'Full access', linkedContacts: $this->contacts, linkedContactGroups: $this->contactGroups, datasets: $this->datasets, isEnabled: true ); })->throws( InvalidArgumentException::class, AssertionException::positiveInt(0, 'Rule::id')->getMessage() ); it('should throw an exception when rules name is an empty string', function (): void { new Rule( id: 1, name: '', description: 'Full access', linkedContacts: $this->contacts, linkedContactGroups: $this->contactGroups, datasets: $this->datasets, isEnabled: true ); })->throws( InvalidArgumentException::class, AssertionException::notEmptyString('Rule::name')->getMessage() ); it('should throw an exception when rules name is an string exceeding max size', function (): void { new Rule( id: 1, name: str_repeat('a', Rule::MAX_NAME_LENGTH + 1), description: 'Full access', linkedContacts: $this->contacts, linkedContactGroups: $this->contactGroups, datasets: $this->datasets, isEnabled: true ); })->throws( InvalidArgumentException::class, AssertionException::maxLength( str_repeat('a', Rule::MAX_NAME_LENGTH + 1), Rule::MAX_NAME_LENGTH + 1, Rule::MAX_NAME_LENGTH, 'Rule::name' )->getMessage(), ); it('should throw an exception when linked contacts is not an array of int', function (): void { new Rule( id: 1, name: 'FULL', description: 'Full access', linkedContacts: ['one', 'two'], linkedContactGroups: $this->contactGroups, datasets: $this->datasets, isEnabled: true ); })->throws( InvalidArgumentException::class, AssertionException::invalidTypeInArray('int', 'Rule::linkedContactIds')->getMessage() ); it('should throw an exception when linked contact groups is not an array of int', function (): void { new Rule( id: 1, name: 'FULL', description: 'Full access', linkedContacts: $this->contacts, linkedContactGroups: ['one', 'two'], datasets: $this->datasets, isEnabled: true ); })->throws( InvalidArgumentException::class, AssertionException::invalidTypeInArray('int', 'Rule::linkedContactGroupIds')->getMessage() ); it('should throw an exception when linked dataset filters is an empty array', function (): void { new Rule( id: 1, name: 'FULL', description: 'Full access', linkedContacts: $this->contacts, linkedContactGroups: $this->contactGroups, datasets: [], isEnabled: true ); })->throws( InvalidArgumentException::class, AssertionException::notEmpty('Rule::datasetFilters')->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/ResourceAccess/Domain/Model/DatasetFilterTest.php
centreon/tests/php/Core/ResourceAccess/Domain/Model/DatasetFilterTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\HostGroupFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\MetaServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceCategoryFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceFilterType; use Core\ResourceAccess\Domain\Model\DatasetFilter\Providers\ServiceGroupFilterType; beforeEach(function (): void { foreach ([ HostFilterType::class, HostGroupFilterType::class, HostCategoryFilterType::class, ServiceFilterType::class, ServiceGroupFilterType::class, ServiceCategoryFilterType::class, MetaServiceFilterType::class, ] as $className) { $this->filterTypes[] = new $className(); } $this->validator = new DatasetFilterValidator(new \ArrayObject($this->filterTypes)); $this->datasetFilter = new DatasetFilter(type: 'host', resourceIds: [1, 2], validator: $this->validator); }); it('should return properly set DatasetFilter instance (all properties)', function (): void { $datasetFilter = new DatasetFilter( type: 'hostgroup', resourceIds: [1], validator: $this->validator ); $datasetFilter->setDatasetFilter($this->datasetFilter); expect($datasetFilter->getType())->toBe('hostgroup') ->and($datasetFilter->getResourceIds())->toBe([1]) ->and($datasetFilter->getDatasetFilter()->getType())->toBe('host') ->and($datasetFilter->getDatasetFilter()->getResourceIds())->toBe([1, 2]) ->and($datasetFilter->getDatasetFilter()->getDatasetFilter())->toBeNull(); }); it('should throw an exception when dataset type is not an empty string', function (): void { new DatasetFilter( type: '', resourceIds: [1], validator: $this->validator ); })->throws( InvalidArgumentException::class, AssertionException::notEmptyString('DatasetFilter::type')->getMessage() ); it('should throw an exception when dataset type is not part of allowed types', function (): void { new DatasetFilter( type: 'typo', resourceIds: [1], validator: $this->validator ); })->throws( \InvalidArgumentException::class, 'Value provided is not supported for dataset filter type (was: typo)' ); it('should throw an exception when resources is an empty array with type not compatible with all_<type> feature', function (): void { new DatasetFilter( type: 'service_category', resourceIds: [], validator: $this->validator ); })->throws( InvalidArgumentException::class, AssertionException::notEmpty('DatasetFilter::resourceIds')->getMessage() ); it('should throw an exception when resources is an array of not integers', function (): void { new DatasetFilter( type: 'host', resourceIds: ['resource1', 'resource2'], validator: $this->validator ); })->throws( InvalidArgumentException::class, AssertionException::invalidTypeInArray('int', 'DatasetFilter::resourceIds')->getMessage() ); // Host hierarchy validation foreach ( [ HostCategoryFilterType::TYPE_NAME, HostGroupFilterType::TYPE_NAME, HostFilterType::TYPE_NAME, MetaServiceFilterType::TYPE_NAME, ] as $type ) { it( "should throw an exception for host parent filter with {$type} as child", function () use ($type): void { $datasetFilter = new DatasetFilter('host', [1, 2], $this->validator); $datasetFilter->setDatasetFilter( new DatasetFilter($type, [3, 4], $this->validator) ); } )->throws( \InvalidArgumentException::class, "Dataset filter hierarchy assertion failed ({$type} not a sub-filter of host)" ); } // Hostgroups hierarchy validation foreach ( [ HostGroupFilterType::TYPE_NAME, MetaServiceFilterType::TYPE_NAME, ] as $type ) { it( "should throw an exception for hostgroup parent filter with {$type} as child", function () use ($type): void { $datasetFilter = new DatasetFilter('hostgroup', [1, 2], $this->validator); $datasetFilter->setDatasetFilter( new DatasetFilter($type, [3, 4], $this->validator) ); } )->throws( \InvalidArgumentException::class, "Dataset filter hierarchy assertion failed ({$type} not a sub-filter of hostgroup)" ); } // HostCategory hierarchy validation foreach ( [ HostCategoryFilterType::TYPE_NAME, MetaServiceFilterType::TYPE_NAME, ] as $type ) { it( "should throw an exception for host_category parent filter with {$type} as child", function () use ($type): void { $datasetFilter = new DatasetFilter('host_category', [1, 2], $this->validator); $datasetFilter->setDatasetFilter( new DatasetFilter($type, [3, 4], $this->validator) ); } )->throws( \InvalidArgumentException::class, "Dataset filter hierarchy assertion failed ({$type} not a sub-filter of host_category)" ); } // Service hierarchy validation foreach ( [ HostGroupFilterType::TYPE_NAME, HostFilterType::TYPE_NAME, HostCategoryFilterType::TYPE_NAME, ServiceGroupFilterType::TYPE_NAME, ServiceCategoryFilterType::TYPE_NAME, ServiceFilterType::TYPE_NAME, MetaServiceFilterType::TYPE_NAME, ] as $type ) { it( "should throw an exception for service parent filter with {$type} as child (no sub-filter possible)", function () use ($type): void { $datasetFilter = new DatasetFilter('service', [1, 2], $this->validator); $datasetFilter->setDatasetFilter( new DatasetFilter($type, [3, 4], $this->validator) ); } )->throws( \InvalidArgumentException::class, "Dataset filter hierarchy assertion failed ({$type} not a sub-filter of service)" ); } // MetaService hierarchy validation foreach ( [ HostGroupFilterType::TYPE_NAME, HostFilterType::TYPE_NAME, HostCategoryFilterType::TYPE_NAME, ServiceGroupFilterType::TYPE_NAME, ServiceCategoryFilterType::TYPE_NAME, ServiceFilterType::TYPE_NAME, MetaServiceFilterType::TYPE_NAME, ] as $type ) { it( "should throw an exception for meta_service parent filter with {$type} as child (no sub-filter possible)", function () use ($type): void { $datasetFilter = new DatasetFilter('meta_service', [1, 2], $this->validator); $datasetFilter->setDatasetFilter( new DatasetFilter($type, [3, 4], $this->validator) ); } )->throws( \InvalidArgumentException::class, "Dataset filter hierarchy assertion failed ({$type} not a sub-filter of meta_service)" ); } // Servicegroup hierarchy validation foreach ( [ HostGroupFilterType::TYPE_NAME, HostFilterType::TYPE_NAME, HostCategoryFilterType::TYPE_NAME, ServiceGroupFilterType::TYPE_NAME, MetaServiceFilterType::TYPE_NAME, ] as $type ) { it( "should throw an exception for servicegroup parent filter with {$type} as child", function () use ($type): void { $datasetFilter = new DatasetFilter('servicegroup', [1, 2], $this->validator); $datasetFilter->setDatasetFilter( new DatasetFilter($type, [3, 4], $this->validator) ); } )->throws( \InvalidArgumentException::class, "Dataset filter hierarchy assertion failed ({$type} not a sub-filter of servicegroup)" ); } // ServiceCategory hierarchy validation foreach ( [ HostGroupFilterType::TYPE_NAME, HostFilterType::TYPE_NAME, HostCategoryFilterType::TYPE_NAME, ServiceCategoryFilterType::TYPE_NAME, MetaServiceFilterType::TYPE_NAME, ] as $type ) { it( "should throw an exception for service_category parent filter with {$type} as child", function () use ($type): void { $datasetFilter = new DatasetFilter('service_category', [1, 2], $this->validator); $datasetFilter->setDatasetFilter( new DatasetFilter($type, [3, 4], $this->validator) ); } )->throws( \InvalidArgumentException::class, "Dataset filter hierarchy assertion failed ({$type} not a sub-filter of service_category)" ); }
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/ResourceAccess/Domain/Model/Dataset/DatasetFilterValidatorTest.php
centreon/tests/php/Core/ResourceAccess/Domain/Model/Dataset/DatasetFilterValidatorTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Domain\Model\Dataset; use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterValidator; beforeEach(function (): void { $this->validator = $this->createMock(DatasetFilterValidator::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Infrastructure/API/AddRule/AddRulePresenterStub.php
centreon/tests/php/Core/ResourceAccess/Infrastructure/API/AddRule/AddRulePresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Infrastructure\API\AddRule; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\ResourceAccess\Application\UseCase\AddRule\AddRulePresenterInterface; use Core\ResourceAccess\Application\UseCase\AddRule\AddRuleResponse; class AddRulePresenterStub extends AbstractPresenter implements AddRulePresenterInterface { public AddRuleResponse|ResponseStatusInterface $response; public function presentResponse(AddRuleResponse|ResponseStatusInterface $response): void { $this->response = $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Infrastructure/API/PartialRuleUpdate/PartialRuleUpdatePresenterStub.php
centreon/tests/php/Core/ResourceAccess/Infrastructure/API/PartialRuleUpdate/PartialRuleUpdatePresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Infrastructure\API\PartialRuleUpdate; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; class PartialRuleUpdatePresenterStub extends AbstractPresenter { public ?ResponseStatusInterface $responseStatus = null; public function setResponseStatus(?ResponseStatusInterface $responseStatus): void { $this->responseStatus = $responseStatus; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Infrastructure/API/DeleteRule/DeleteRulePresenterStub.php
centreon/tests/php/Core/ResourceAccess/Infrastructure/API/DeleteRule/DeleteRulePresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Infrastructure\API\DeleteRule; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; class DeleteRulePresenterStub extends AbstractPresenter { public ?ResponseStatusInterface $response = null; public function setResponseStatus(?ResponseStatusInterface $responseStatus): void { $this->response = $responseStatus; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Infrastructure/API/DeleteRules/DeleteRulesPresenterStub.php
centreon/tests/php/Core/ResourceAccess/Infrastructure/API/DeleteRules/DeleteRulesPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Infrastructure\API\DeleteRules; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\MultiStatusResponse; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRulesPresenterInterface; use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRulesResponse; use Core\ResourceAccess\Application\UseCase\DeleteRules\DeleteRulesStatusResponse; use Core\ResourceAccess\Domain\Model\ResponseCode; use Symfony\Component\HttpFoundation\Response; class DeleteRulesPresenterStub extends AbstractPresenter implements DeleteRulesPresenterInterface { private const HREF = 'centreon/api/latest/administration/resource-access/rules/'; /** @var ResponseStatusInterface */ public ResponseStatusInterface $response; public function presentResponse(DeleteRulesResponse|ResponseStatusInterface $response): void { if ($response instanceof DeleteRulesResponse) { $multiStatusResponse = [ 'results' => array_map(fn (DeleteRulesStatusResponse $dto) => [ 'self' => self::HREF . $dto->id, 'status' => $this->enumToIntConverter($dto->status), 'message' => $dto->message, ], $response->responseStatuses), ]; $this->response = new MultiStatusResponse($multiStatusResponse); } else { $this->response = $response; } } /** * @param ResponseCode $code * * @return int */ private function enumToIntConverter(ResponseCode $code): int { return match ($code) { ResponseCode::OK => Response::HTTP_NO_CONTENT, ResponseCode::NotFound => Response::HTTP_NOT_FOUND, ResponseCode::Error => Response::HTTP_INTERNAL_SERVER_ERROR, }; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Infrastructure/API/UpdateRule/UpdateRulePresenterStub.php
centreon/tests/php/Core/ResourceAccess/Infrastructure/API/UpdateRule/UpdateRulePresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Infrastructure\API\UpdateRule; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\ResourceAccess\Application\UseCase\UpdateRule\UpdateRulePresenterInterface; class UpdateRulePresenterStub extends AbstractPresenter implements UpdateRulePresenterInterface { public ?ResponseStatusInterface $responseStatus = null; public function __construct(protected PresenterFormatterInterface $presenterFormatter) { parent::__construct($presenterFormatter); } /** * @param NoContentResponse|ResponseStatusInterface $response */ public function presentResponse(NoContentResponse|ResponseStatusInterface $response): void { $this->responseStatus = $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Infrastructure/API/FindRules/FindRulesPresenterStub.php
centreon/tests/php/Core/ResourceAccess/Infrastructure/API/FindRules/FindRulesPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Infrastructure\API\FindRules; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\ResourceAccess\Application\UseCase\FindRules\FindRulesPresenterInterface; use Core\ResourceAccess\Application\UseCase\FindRules\FindRulesResponse; class FindRulesPresenterStub extends AbstractPresenter implements FindRulesPresenterInterface { public FindRulesResponse|ResponseStatusInterface $response; public function presentResponse(FindRulesResponse|ResponseStatusInterface $response): void { $this->response = $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ResourceAccess/Infrastructure/API/FindRule/FindRulePresenterStub.php
centreon/tests/php/Core/ResourceAccess/Infrastructure/API/FindRule/FindRulePresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\ResourceAccess\Infrastructure\API\FindRule; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\ResourceAccess\Application\UseCase\FindRule\FindRulePresenterInterface; use Core\ResourceAccess\Application\UseCase\FindRule\FindRuleResponse; class FindRulePresenterStub extends AbstractPresenter implements FindRulePresenterInterface { public FindRuleResponse|ResponseStatusInterface $response; public function presentResponse(FindRuleResponse|ResponseStatusInterface $response): void { $this->response = $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Application/UseCase/DeploySevices/DeployServicesTest.php
centreon/tests/php/Core/Service/Application/UseCase/DeploySevices/DeployServicesTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Application\UseCase\DeployServices; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Security\AccessGroup\Domain\Model\AccessGroup; use Core\Service\Application\Repository\ReadServiceRepositoryInterface; use Core\Service\Application\Repository\WriteRealTimeServiceRepositoryInterface; use Core\Service\Application\Repository\WriteServiceRepositoryInterface; use Core\Service\Application\UseCase\DeployServices\DeployServices; use Core\Service\Application\UseCase\DeployServices\DeployServicesResponse; use Core\Service\Domain\Model\Service; use Core\Service\Domain\Model\ServiceNamesByHost; use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface; use Core\ServiceTemplate\Domain\Model\ServiceTemplate; use Tests\Core\Service\Infrastructure\API\DeployServices\DeployServicesPresenterStub; beforeEach(function (): void { $this->useCasePresenter = new DeployServicesPresenterStub( $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class) ); $this->deployServicesUseCase = new DeployServices( $this->contact = $this->createMock(ContactInterface::class), $this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class), $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class), $this->readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class), $this->readServiceTemplateRepository = $this->createMock(ReadServiceTemplateRepositoryInterface::class), $this->writeServiceRepository = $this->createMock(WriteServiceRepositoryInterface::class), $this->writeRealTimeServiceRepository = $this->createMock(WriteRealTimeServiceRepositoryInterface::class) ); }); it('should present a Forbidden Response when the user has insufficient rights', function (): void { $this->contact ->expects($this->any()) ->method('hasTopologyRole') ->willReturn(false); $hostId = 15; ($this->deployServicesUseCase)($this->useCasePresenter, $hostId); expect($this->useCasePresenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe('User does not have sufficient rights'); }); it('should present a Not Found Response when provided host ID does not exist for a non-admin user', function (): void { $this->contact ->expects($this->any()) ->method('hasTopologyRole') ->willReturn(true); $this->contact ->expects($this->any()) ->method('isAdmin') ->willReturn(false); $this->readHostRepository ->expects($this->any()) ->method('findParents') ->willReturn([['parent_id' => 3, 'child_id' => 15, 'order' => 2]]); $accessGroups = [(new AccessGroup(1, 'nonAdmin', 'nonAdmin')), (new AccessGroup(3, 'SimpleUser', 'SimpleUser'))]; $this->readAccessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn($accessGroups); $this->readHostRepository ->expects($this->once()) ->method('existsByAccessGroups') ->willReturn(false); $hostId = 15; ($this->deployServicesUseCase)($this->useCasePresenter, $hostId); expect($this->useCasePresenter->response) ->toBeInstanceOf(NotFoundResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe('Host not found'); }); it('should present a Not Found Response when provided host ID does not exist for a admin user', function (): void { $this->contact ->expects($this->any()) ->method('hasTopologyRole') ->willReturn(true); $this->contact ->expects($this->any()) ->method('isAdmin') ->willReturn(true); $this->readHostRepository ->expects($this->any()) ->method('findParents') ->willReturn([['parent_id' => 3, 'child_id' => 15, 'order' => 2]]); $this->readHostRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $hostId = 15; ($this->deployServicesUseCase)($this->useCasePresenter, $hostId); expect($this->useCasePresenter->response) ->toBeInstanceOf(NotFoundResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe('Host not found'); }); it( 'should present a No Content Response when provided host ID does not have associated host templates', function (): void { $this->contact ->expects($this->any()) ->method('hasTopologyRole') ->willReturn(true); $this->contact ->expects($this->any()) ->method('isAdmin') ->willReturn(false); $this->readHostRepository ->expects($this->any()) ->method('findParents') ->willReturn([['parent_id' => 3, 'child_id' => 15, 'order' => 2]]); $accessGroups = [(new AccessGroup(1, 'nonAdmin', 'nonAdmin')), (new AccessGroup(3, 'SimpleUser', 'SimpleUser'))]; $this->readAccessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn($accessGroups); $this->readHostRepository ->expects($this->once()) ->method('existsByAccessGroups') ->willReturn(true); $this->readHostRepository ->expects($this->once()) ->method('findParents') ->willReturn([]); $hostId = 15; ($this->deployServicesUseCase)($this->useCasePresenter, $hostId); expect($this->useCasePresenter->response) ->toBeInstanceOf(NoContentResponse::class); } ); it('should present a No Content Response when threre are no services to deploy', function (): void { $this->contact ->expects($this->any()) ->method('hasTopologyRole') ->willReturn(true); $this->contact ->expects($this->any()) ->method('isAdmin') ->willReturn(false); $accessGroups = [(new AccessGroup(1, 'nonAdmin', 'nonAdmin')), (new AccessGroup(3, 'SimpleUser', 'SimpleUser'))]; $this->readAccessGroupRepository ->expects($this->once()) ->method('findByContact') ->willReturn($accessGroups); $this->readHostRepository ->expects($this->once()) ->method('existsByAccessGroups') ->willReturn(true); $hostParents = [ ['parent_id' => 3, 'child_id' => 5, 'order' => 0], ]; $this->readHostRepository ->expects($this->once()) ->method('findParents') ->willReturn($hostParents); $serviceTemplates = [ (new ServiceTemplate(2, 'generic-ping', 'generic-ping')), (new ServiceTemplate(3, 'generic-disk', 'generic-disk')), ]; $this->readServiceTemplateRepository ->expects($this->any()) ->method('findByHostId') ->willReturn($serviceTemplates); $serviceNames = new ServiceNamesByHost(12, ['generic-ping', 'generic-disk']); $this->readServiceRepository ->expects($this->any()) ->method('findServiceNamesByHost') ->willReturn($serviceNames); $hostId = 15; ($this->deployServicesUseCase)($this->useCasePresenter, $hostId); expect($this->useCasePresenter->response) ->toBeInstanceOf(NoContentResponse::class); }); it('should present an Error Response when an unhandled error occurs', function (): void { $this->contact ->expects($this->any()) ->method('hasTopologyRole') ->willReturn(true); $this->contact ->expects($this->any()) ->method('isAdmin') ->willReturn(false); $this->readHostRepository ->expects($this->any()) ->method('findParents') ->willReturn([['parent_id' => 3, 'child_id' => 15, 'order' => 2]]); $this->readAccessGroupRepository ->expects($this->once()) ->method('findByContact') ->willThrowException(new \Exception()); $hostId = 15; ($this->deployServicesUseCase)($this->useCasePresenter, $hostId); expect($this->useCasePresenter->response) ->toBeInstanceOf(ErrorResponse::class); }); it('should present a Created Response when services were successfully deployed', function (): void { $this->contact ->expects($this->any()) ->method('hasTopologyRole') ->willReturn(true); $this->contact ->expects($this->any()) ->method('isAdmin') ->willReturn(true); $this->readHostRepository ->expects($this->once()) ->method('exists') ->willReturn(true); $hostParents = [ ['parent_id' => 3, 'child_id' => 5, 'order' => 0], ]; $this->readHostRepository ->expects($this->once()) ->method('findParents') ->willReturn($hostParents); $serviceTemplates = [ (new ServiceTemplate(2, 'generic-ping', 'generic-ping')), (new ServiceTemplate(3, 'generic-disk', 'generic-disk')), ]; $this->readServiceTemplateRepository ->expects($this->any()) ->method('findByHostId') ->willReturn($serviceTemplates); $serviceNames = new ServiceNamesByHost(15, []); $this->readServiceRepository ->expects($this->any()) ->method('findServiceNamesByHost') ->willReturn($serviceNames); $hostId = 15; $createdPing = new Service(16, 'generic-ping', $hostId); $createdDisk = new Service(17, 'generic-disk', $hostId); $this->readServiceRepository ->expects($this->any()) ->method('findById') ->willReturn($createdPing); $this->readServiceRepository ->expects($this->any()) ->method('findById') ->willReturn($createdDisk); $this->dataStorageEngine ->expects($this->once()) ->method('commitTransaction') ->willReturn(true); ($this->deployServicesUseCase)($this->useCasePresenter, $hostId); expect($this->useCasePresenter->response) ->toBeInstanceOf(DeployServicesResponse::class) ->and($this->useCasePresenter->response->services) ->toBeArray(); });
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/Service/Application/UseCase/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesTest.php
centreon/tests/php/Core/Service/Application/UseCase/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Application\UseCase\FindRealTimeUniqueServiceNames; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Service\Application\Exception\ServiceException; use Core\Service\Application\Repository\ReadRealTimeServiceRepositoryInterface; use Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames\FindRealTimeUniqueServiceNames; use Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames\FindRealTimeUniqueServiceNamesResponse; use Tests\Core\Service\Infrastructure\API\FindRealTimeUniqueServiceNames\FindRealTimeUniqueServiceNamesPresenterStub; beforeEach(function (): void { $this->useCase = new FindRealTimeUniqueServiceNames( $this->user = $this->createMock(ContactInterface::class), $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), $this->requestParameters = $this->createMock(RequestParametersInterface::class), $this->repository = $this->createMock(ReadRealTimeServiceRepositoryInterface::class) ); $this->presenter = new FindRealTimeUniqueServiceNamesPresenterStub( $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class) ); }); it('should present an ErrorResponse when an exception is thrown', function (): void { $this->user ->expects($this->exactly(2)) ->method('isAdmin') ->willReturn(true); $this->repository ->expects($this->once()) ->method('findUniqueServiceNamesByRequestParameters') ->willThrowException(new \Exception()); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(ServiceException::errorWhileSearching(new \Exception())->getMessage()); }); it('should present a ForbiddenResponse when user has insufficient rights', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(ServiceException::accessNotAllowed()->getMessage()); }); it('should present a FindRealTimeUniqueServiceNamesResponse when everything goes well - ADMIN', function (): void { $this->user ->expects($this->exactly(2)) ->method('isAdmin') ->willReturn(true); $this->repository ->expects($this->once()) ->method('findUniqueServiceNamesByRequestParameters') ->willReturn(['uniqueServiceName1']); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(FindRealTimeUniqueServiceNamesResponse::class) ->and($this->presenter->response->names[0]) ->toBe('uniqueServiceName1'); });
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/Service/Application/UseCase/FindServices/FindServicesTest.php
centreon/tests/php/Core/Service/Application/UseCase/FindServices/FindServicesTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Application\UseCase\FindServices; use Centreon\Domain\Contact\Contact; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Common\Domain\TrimmedString; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\Host\Domain\Model\HostNamesById; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Service\Application\Exception\ServiceException; use Core\Service\Application\Repository\ReadServiceRepositoryInterface; use Core\Service\Application\UseCase\FindServices\FindServices; use Core\Service\Application\UseCase\FindServices\FindServicesResponse; use Core\Service\Application\UseCase\FindServices\ServiceDto; use Core\Service\Domain\Model\ServiceLight; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceCategory\Domain\Model\ServiceCategoryNamesById; use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface; use Core\ServiceGroup\Domain\Model\ServiceGroupNamesById; use Core\ServiceGroup\Domain\Model\ServiceGroupRelation; use Tests\Core\Service\Infrastructure\API\FindServices\FindServicesPresenterStub; beforeEach(function (): void { $this->usecase = new FindServices( $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), $this->readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class), $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class), $this->readServiceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class), $this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class), $this->requestParameters = $this->createMock(RequestParametersInterface::class), $this->user = $this->createMock(ContactInterface::class), ); $this->presenter = new FindServicesPresenterStub( $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class) ); $this->service = new ServiceLight( id: 1, name: new TrimmedString('my-service-name'), hostIds: [1], categoryIds: [2], groups: [new ServiceGroupRelation(3, 1, 1)], serviceTemplate: null, notificationTimePeriod: null, checkTimePeriod: null, severity: null, normalCheckInterval: null, retryCheckInterval: null, isActivated: true, ); $this->hostNames = new HostNamesById(); $this->hostNames->addName(1, new TrimmedString('host-name')); $this->categoryNames = new ServiceCategoryNamesById(); $this->categoryNames->addName(2, new TrimmedString('category-name')); $this->groupNames = new ServiceGroupNamesById(); $this->groupNames->addName(3, new TrimmedString('group-name')); $this->responseDto = new ServiceDto(); $this->responseDto->id = 1; $this->responseDto->name = 'my-service-name'; $this->responseDto->isActivated = true; $this->responseDto->normalCheckInterval = null; $this->responseDto->retryCheckInterval = null; $this->responseDto->serviceTemplate = null; $this->responseDto->checkTimePeriod = null; $this->responseDto->notificationTimePeriod = null; $this->responseDto->severity = null; $this->responseDto->hosts = [ ['id' => 1, 'name' => 'host-name'], ]; $this->responseDto->categories = [ ['id' => 2, 'name' => 'category-name'], ]; $this->responseDto->groups = [ ['id' => 3, 'name' => 'group-name', 'hostId' => 1, 'hostName' => 'host-name'], ]; }); it('should present an ErrorResponse when an exception is thrown', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readServiceRepository ->expects($this->once()) ->method('findByRequestParameter') ->willThrowException(new \Exception()); ($this->usecase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(ServiceException::errorWhileSearching(new \Exception())->getMessage()); }); it('should present a ForbiddenResponse when user has insufficient rights', function (): void { $this->user ->expects($this->exactly(2)) ->method('hasTopologyRole') ->willReturn(false); ($this->usecase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(ServiceException::accessNotAllowed()->getMessage()); }); it('should present a FindServicesResponse with non-admin user', function (): void { $this->user ->expects($this->exactly(2)) ->method('hasTopologyRole') ->willReturnMap( [ [Contact::ROLE_CONFIGURATION_SERVICES_READ, false], [Contact::ROLE_CONFIGURATION_SERVICES_WRITE, true], ] ); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->readAccessGroupRepository ->expects($this->once()) ->method('findByContact'); $this->readServiceRepository ->expects($this->once()) ->method('findByRequestParameterAndAccessGroup') ->willReturn([$this->service]); $this->readServiceCategoryRepository ->expects($this->once()) ->method('findNames') ->willReturn($this->categoryNames); $this->readServiceGroupRepository ->expects($this->once()) ->method('findNames') ->willReturn($this->groupNames); $this->readHostRepository ->expects($this->once()) ->method('findNames') ->willReturn($this->hostNames); ($this->usecase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(FindServicesResponse::class) ->and($this->presenter->response->services[0]->id) ->toBe($this->responseDto->id) ->and($this->presenter->response->services[0]->name) ->toBe($this->responseDto->name) ->and($this->presenter->response->services[0]->isActivated) ->toBe($this->responseDto->isActivated) ->and($this->presenter->response->services[0]->normalCheckInterval) ->toBe($this->responseDto->normalCheckInterval) ->and($this->presenter->response->services[0]->retryCheckInterval) ->toBe($this->responseDto->retryCheckInterval) ->and($this->presenter->response->services[0]->serviceTemplate) ->toBe($this->responseDto->serviceTemplate) ->and($this->presenter->response->services[0]->checkTimePeriod) ->toBe($this->responseDto->checkTimePeriod) ->and($this->presenter->response->services[0]->notificationTimePeriod) ->toBe($this->responseDto->notificationTimePeriod) ->and($this->presenter->response->services[0]->severity) ->toBe($this->responseDto->severity) ->and($this->presenter->response->services[0]->hosts) ->toBe($this->responseDto->hosts) ->and($this->presenter->response->services[0]->categories) ->toBe($this->responseDto->categories) ->and($this->presenter->response->services[0]->groups) ->toBe($this->responseDto->groups); }); it('should present a FindServicesResponse with admin user', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readServiceRepository ->expects($this->once()) ->method('findByRequestParameter') ->willReturn([$this->service]); $this->readServiceCategoryRepository ->expects($this->once()) ->method('findNames') ->willReturn($this->categoryNames); $this->readServiceGroupRepository ->expects($this->once()) ->method('findNames') ->willReturn($this->groupNames); $this->readHostRepository ->expects($this->once()) ->method('findNames') ->willReturn($this->hostNames); ($this->usecase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(FindServicesResponse::class) ->and($this->presenter->response->services[0]->id) ->toBe($this->responseDto->id) ->and($this->presenter->response->services[0]->name) ->toBe($this->responseDto->name) ->and($this->presenter->response->services[0]->isActivated) ->toBe($this->responseDto->isActivated) ->and($this->presenter->response->services[0]->normalCheckInterval) ->toBe($this->responseDto->normalCheckInterval) ->and($this->presenter->response->services[0]->retryCheckInterval) ->toBe($this->responseDto->retryCheckInterval) ->and($this->presenter->response->services[0]->serviceTemplate) ->toBe($this->responseDto->serviceTemplate) ->and($this->presenter->response->services[0]->checkTimePeriod) ->toBe($this->responseDto->checkTimePeriod) ->and($this->presenter->response->services[0]->notificationTimePeriod) ->toBe($this->responseDto->notificationTimePeriod) ->and($this->presenter->response->services[0]->severity) ->toBe($this->responseDto->severity) ->and($this->presenter->response->services[0]->hosts) ->toBe($this->responseDto->hosts) ->and($this->presenter->response->services[0]->categories) ->toBe($this->responseDto->categories) ->and($this->presenter->response->services[0]->groups) ->toBe($this->responseDto->groups); });
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/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountTest.php
centreon/tests/php/Core/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Application\UseCase\FindRealTimeServiceStatusesCount; 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\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Service\Application\Exception\ServiceException; use Core\Service\Application\Repository\ReadRealTimeServiceRepositoryInterface; use Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount\FindRealTimeServiceStatusesCount; use Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount\FindRealTimeServiceStatusesCountResponse; use Core\Service\Domain\Model\ServiceStatusesCount; beforeEach(closure: function (): void { $this->useCase = new FindRealTimeServiceStatusesCount( $this->user = $this->createMock(ContactInterface::class), $this->repository = $this->createMock(ReadRealTimeServiceRepositoryInterface::class), $this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), $this->requestParameters = $this->createMock(RequestParametersInterface::class), ); $this->presenter = new FindRealTimeServiceStatusesCountPresenterStub($this->createMock(PresenterFormatterInterface::class)); }); it('should present an Error response when something goes wrong in repository', function (): void { $this->user ->expects($this->any()) ->method('isAdmin') ->willReturn(true); $exception = new \Exception(); $this->repository ->expects($this->once()) ->method('findStatusesByRequestParameters') ->willThrowException($exception); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(ServiceException::errorWhileRetrievingServiceStatusesCount()->getMessage()); }); it('should present an Error response when something goes wrong with RequestParameters', function (): void { $this->user ->expects($this->any()) ->method('isAdmin') ->willReturn(true); $this->repository ->expects($this->once()) ->method('findStatusesByRequestParameters') ->willThrowException(new RequestParametersTranslatorException()); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ErrorResponse::class); }); it('should present a Forbidden response when user does not have sufficient rights', function (): void { $this->user ->expects($this->any()) ->method('isAdmin') ->willReturn(false); $this->user ->expects($this->exactly(2)) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->response->getMessage()) ->toBe(ServiceException::accessNotAllowedForRealTime()->getMessage()); }); it('should present a FindRealTimeServiceStatusesCountResponse when ok - ADMIN', function (): void { $this->user ->expects($this->any()) ->method('isAdmin') ->willReturn(true); $statuses = new ServiceStatusesCount( totalOk: 1, totalWarning: 1, totalUnknown: 1, totalCritical: 1, totalPending: 1, ); $this->repository ->expects($this->once()) ->method('findStatusesByRequestParameters') ->willReturn($statuses); ($this->useCase)($this->presenter); expect($this->presenter->response) ->toBeInstanceOf(FindRealTimeServiceStatusesCountResponse::class) ->and($this->presenter->response->okStatuses) ->toBe($statuses->getTotalOk()) ->and($this->presenter->response->warningStatuses) ->toBe($statuses->getTotalWarning()) ->and($this->presenter->response->unknownStatuses) ->toBe($statuses->getTotalUnknown()) ->and($this->presenter->response->criticalStatuses) ->toBe($statuses->getTotalCritical()) ->and($this->presenter->response->pendingStatuses) ->toBe($statuses->getTotalPending()) ->and($this->presenter->response->total) ->toBe($statuses->getTotal()); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountPresenterStub.php
centreon/tests/php/Core/Service/Application/UseCase/FindRealTimeServiceStatusesCount/FindRealTimeServiceStatusesCountPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Application\UseCase\FindRealTimeServiceStatusesCount; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount\FindRealTimeServiceStatusesCountPresenterInterface; use Core\Service\Application\UseCase\FindRealTimeServiceStatusesCount\FindRealTimeServiceStatusesCountResponse; class FindRealTimeServiceStatusesCountPresenterStub extends AbstractPresenter implements FindRealTimeServiceStatusesCountPresenterInterface { public FindRealTimeServiceStatusesCountResponse|ResponseStatusInterface $response; public function presentResponse(FindRealTimeServiceStatusesCountResponse|ResponseStatusInterface $response): void { $this->response = $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateServiceTest.php
centreon/tests/php/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateServiceTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Tests\Core\ServiceTemplate\Application\UseCase\PartialUpdateService; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Option\OptionService; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\ConflictResponse; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface; use Core\CommandMacro\Domain\Model\CommandMacro; use Core\CommandMacro\Domain\Model\CommandMacroType; use Core\Common\Application\Repository\ReadVaultRepositoryInterface; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Infrastructure\Common\Api\DefaultPresenter; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface; use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface; use Core\Macro\Domain\Model\Macro; use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface; use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Service\Application\Exception\ServiceException; use Core\Service\Application\Repository\ReadServiceRepositoryInterface; use Core\Service\Application\Repository\WriteServiceRepositoryInterface; use Core\Service\Application\UseCase\PartialUpdateService\MacroDto; use Core\Service\Application\UseCase\PartialUpdateService\PartialUpdateService; use Core\Service\Application\UseCase\PartialUpdateService\PartialUpdateServiceRequest; use Core\Service\Application\UseCase\PartialUpdateService\PartialUpdateServiceValidation; use Core\Service\Domain\Model\Service; use Core\Service\Domain\Model\ServiceInheritance; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface; use Core\ServiceCategory\Domain\Model\ServiceCategory; use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface; use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface; use Core\ServiceGroup\Domain\Model\ServiceGroup; use Exception; beforeEach(closure: function (): void { $this->presenter = new DefaultPresenter( $this->createMock(PresenterFormatterInterface::class) ); $this->useCase = new PartialUpdateService( $this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class), $this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class), $this->readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class), $this->writeServiceRepository = $this->createMock(WriteServiceRepositoryInterface::class), $this->readServiceMacroRepository = $this->createMock(ReadServiceMacroRepositoryInterface::class), $this->readCommandMacroRepository = $this->createMock(ReadCommandMacroRepositoryInterface::class), $this->writeServiceMacroRepository = $this->createMock(WriteServiceMacroRepositoryInterface::class), $this->readServiceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class), $this->writeServiceCategoryRepository = $this->createMock(WriteServiceCategoryRepositoryInterface::class), $this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class), $this->writeServiceGroupRepository = $this->createMock(WriteServiceGroupRepositoryInterface::class), $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), $this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class), $this->validation = $this->createMock(PartialUpdateServiceValidation::class), $this->optionService = $this->createMock(OptionService::class), $this->user = $this->createMock(ContactInterface::class), $this->isCloudPlatform = false, $this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class), $this->readVaultRepository = $this->createMock(ReadVaultRepositoryInterface::class), ); $this->service = new Service(id: 1, name: 'service-name', hostId: 2); // Settup request $this->request = new PartialUpdateServiceRequest(); $this->request->hostId = 3; $this->request->name = 'service-name-edited'; $this->request->commandId = 8; $this->request->graphTemplateId = 9; $this->request->eventHandlerId = 10; $this->request->checkTimePeriodId = 11; $this->request->notificationTimePeriodId = 12; $this->request->iconId = 13; $this->request->severityId = 14; // Settup categories $this->categoryA = new ServiceCategory(4, 'cat-name-A', 'cat-alias-A'); $this->categoryB = new ServiceCategory(5, 'cat-name-B', 'cat-alias-B'); $this->request->categories = [$this->categoryB->getId()]; // Settup groups $this->groupA = new ServiceGroup(6, 'grp-name-A', 'grp-alias-A', null, 'comment A', true); $this->groupB = new ServiceGroup(7, 'grp-name-B', 'grp-alias-B', null, 'comment B', true); $this->request->groups = [$this->groupB->getId()]; // Settup macros $this->macroA = new Macro(null, $this->service->getId(), 'macroNameA', 'macroValueA'); $this->macroA->setOrder(0); $this->macroB = new Macro(null, $this->service->getId(), 'macroNameB', 'macroValueB'); $this->macroB->setOrder(1); $this->commandMacro = new CommandMacro(1, CommandMacroType::Service, 'commandMacroName'); $this->commandMacros = [ $this->commandMacro->getName() => $this->commandMacro, ]; $this->macros = [ $this->macroA->getName() => $this->macroA, $this->macroB->getName() => $this->macroB, ]; $this->parentTemplates = [15, 16]; $this->inheritance = [ new ServiceInheritance($this->parentTemplates[0], $this->service->getId()), new ServiceInheritance($this->parentTemplates[1], $this->parentTemplates[0]), ]; $this->request->template = $this->parentTemplates[0]; $this->request->macros = [ new MacroDto( name: $this->macroA->getName(), value: $this->macroA->getValue() . '_edit', isPassword: $this->macroA->isPassword(), description: $this->macroA->getDescription() ), new MacroDto( name: 'macroNameC', value: 'macroValueC', isPassword: false, description: null ), ]; }); it('should present a ForbiddenResponse when the user has insufficient rights', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)(new PartialUpdateServiceRequest(), $this->presenter, $this->service->getId()); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe(ServiceException::editNotAllowed()->getMessage()); }); it('should present an ErrorResponse when an exception is thrown', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->readAccessGroupRepository ->expects($this->once()) ->method('findByContact') ->willThrowException(new Exception()); ($this->useCase)(new PartialUpdateServiceRequest(), $this->presenter, $this->service->getId()); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe(ServiceException::errorWhileEditing()->getMessage()); }); it('should present a NotFoundResponse when the service does not exist', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->exactly(2)) ->method('isAdmin') ->willReturn(true); $this->readServiceRepository ->expects($this->once()) ->method('findById') ->willReturn(null); ($this->useCase)(new PartialUpdateServiceRequest(), $this->presenter, $this->service->getId()); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(NotFoundResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe((new NotFoundResponse('Service'))->getMessage()); }); it('should present a ConflictResponse when the host ID does not exist', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->exactly(2)) ->method('isAdmin') ->willReturn(true); $this->readServiceRepository ->expects($this->once()) ->method('findById') ->willReturn($this->service); $this->validation ->expects($this->once()) ->method('assertIsValidHost') ->willThrowException( ServiceException::idDoesNotExist('host_id', $this->request->hostId) ); ($this->useCase)($this->request, $this->presenter, $this->service->getId()); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(ConflictResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe(ServiceException::idDoesNotExist('host_id', $this->request->hostId)->getMessage()); }); it('should present a ConflictResponse when a category does not exist', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->exactly(2)) ->method('isAdmin') ->willReturn(true); $this->readServiceRepository ->expects($this->once()) ->method('findById') ->willReturn($this->service); // Service $this->optionService ->expects($this->once()) ->method('findSelectedOptions'); $this->writeServiceRepository ->expects($this->once()) ->method('update'); // Categories $this->validation ->expects($this->once()) ->method('assertAreValidCategories') ->willThrowException(ServiceException::idsDoNotExist('categories', $this->request->categories)); ($this->useCase)($this->request, $this->presenter, $this->service->getId()); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(ConflictResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe(ServiceException::idsDoNotExist('categories', $this->request->categories)->getMessage()); }); it('should present a ConflictResponse when a group does not exist', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->exactly(3)) ->method('isAdmin') ->willReturn(true); $this->readServiceRepository ->expects($this->once()) ->method('findById') ->willReturn($this->service); // Service $this->optionService ->expects($this->once()) ->method('findSelectedOptions'); $this->writeServiceRepository ->expects($this->once()) ->method('update'); // Categories $this->readServiceCategoryRepository ->expects($this->once()) ->method('findByService') ->willReturn([$this->categoryA]); $this->writeServiceCategoryRepository ->expects($this->once()) ->method('linkToService'); $this->writeServiceCategoryRepository ->expects($this->once()) ->method('unlinkFromService'); // Groups $this->validation ->expects($this->once()) ->method('assertAreValidGroups') ->willThrowException(ServiceException::idsDoNotExist('groups', $this->request->groups)); ($this->useCase)($this->request, $this->presenter, $this->service->getId()); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(ConflictResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe(ServiceException::idsDoNotExist('groups', $this->request->groups)->getMessage()); }); it('should present a NoContentResponse on success', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->exactly(4)) ->method('isAdmin') ->willReturn(true); $this->readServiceRepository ->expects($this->once()) ->method('findById') ->willReturn($this->service); // Service $this->optionService ->expects($this->once()) ->method('findSelectedOptions'); $this->validation->expects($this->once())->method('assertIsValidHost'); $this->validation->expects($this->once())->method('assertIsValidName'); $this->validation->expects($this->once())->method('assertIsValidCommand'); $this->validation->expects($this->once())->method('assertIsValidGraphTemplate'); $this->validation->expects($this->once())->method('assertIsValidEventHandler'); $this->validation->expects($this->exactly(2))->method('assertIsValidTimePeriod'); $this->validation->expects($this->once())->method('assertIsValidIcon'); $this->validation->expects($this->once())->method('assertIsValidSeverity'); $this->writeServiceRepository ->expects($this->once()) ->method('update'); // Categories $this->validation->expects($this->once())->method('assertAreValidCategories'); $this->readServiceCategoryRepository ->expects($this->once()) ->method('findByService') ->willReturn([$this->categoryA]); $this->writeServiceCategoryRepository ->expects($this->once()) ->method('linkToService'); $this->writeServiceCategoryRepository ->expects($this->once()) ->method('unlinkFromService'); // Groups $this->validation->expects($this->once())->method('assertAreValidGroups'); $this->readServiceGroupRepository ->expects($this->once()) ->method('findByService') ->willReturn([$this->groupA]); $this->writeServiceGroupRepository ->expects($this->once()) ->method('unlink'); $this->writeServiceGroupRepository ->expects($this->once()) ->method('link'); // Macros $this->readServiceRepository ->expects($this->once()) ->method('findParents') ->willReturn($this->inheritance); $this->readServiceMacroRepository ->expects($this->once()) ->method('findByServiceIds') ->willReturn($this->macros); $this->readCommandMacroRepository ->expects($this->once()) ->method('findByCommandIdAndType') ->willReturn($this->commandMacros); $this->writeServiceMacroRepository ->expects($this->once()) ->method('delete'); $this->writeServiceMacroRepository ->expects($this->once()) ->method('add'); $this->writeServiceMacroRepository ->expects($this->once()) ->method('update'); ($this->useCase)($this->request, $this->presenter, $this->service->getId()); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(NoContentResponse::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateServiceValidationTest.php
centreon/tests/php/Core/Service/Application/UseCase/PartialUpdateService/PartialUpdateServiceValidationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Application\UseCase\PartialUpdateService; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Command\Application\Repository\ReadCommandRepositoryInterface; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\PerformanceGraph\Application\Repository\ReadPerformanceGraphRepositoryInterface; use Core\Service\Application\Exception\ServiceException; use Core\Service\Application\Repository\ReadServiceRepositoryInterface; use Core\Service\Application\UseCase\PartialUpdateService\PartialUpdateServiceRequest; use Core\Service\Application\UseCase\PartialUpdateService\PartialUpdateServiceValidation; use Core\Service\Domain\Model\Service; use Core\Service\Domain\Model\ServiceNamesByHost; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface; use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface; use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface; use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface; use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface; beforeEach(closure: function (): void { $this->validation = new PartialUpdateServiceValidation( $this->readServiceTemplateRepository = $this->createMock(ReadServiceTemplateRepositoryInterface::class), $this->readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class), $this->serviceSeverityRepository = $this->createMock(ReadServiceSeverityRepositoryInterface::class), $this->performanceGraphRepository = $this->createMock(ReadPerformanceGraphRepositoryInterface::class), $this->readCommandRepository = $this->createMock(ReadCommandRepositoryInterface::class), $this->timePeriodRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class), $this->imageRepository = $this->createMock(ReadViewImgRepositoryInterface::class), $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class), $this->readServiceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class), $this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class), $this->contact = $this->createMock(ContactInterface::class), ); }); it('should raise an exception when the new name already exists', function (): void { $serviceNamesByHost = new ServiceNamesByHost(hostId: 1, servicesName: ['new_name']); $request = new PartialUpdateServiceRequest(); $request->hostId = 1; $request->name = 'new_name'; $service = new Service(id: 2, name: 'old_name', hostId: 1); $this->readServiceRepository ->expects($this->once()) ->method('findServiceNamesByHost') ->willReturn($serviceNamesByHost); $this->validation->assertIsValidName($request->name, $service); })->throws( ServiceException::class, ServiceException::nameAlreadyExists('new_name', 1)->getMessage() ); it('should raise an exception when the service template ID does not exist', function (): void { $this->readServiceTemplateRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $this->validation->assertIsValidTemplate(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('service_template_id', 1)->getMessage() ); it('should raise an exception when the command ID does not exist', function (): void { $this->readCommandRepository ->expects($this->once()) ->method('existsByIdAndCommandType') ->willReturn(false); $this->validation->assertIsValidCommand(1, 2); })->throws( ServiceException::class, ServiceException::idDoesNotExist('check_command_id', 1)->getMessage() ); it('should raise an exception when the event handler ID does not exist', function (): void { $this->readCommandRepository ->expects($this->once()) ->method('exists') ->with(1) ->willReturn(false); $this->validation->assertIsValidEventHandler(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('event_handler_command_id', 1)->getMessage() ); it('should raise an exception when the time period ID does not exist', function (): void { $this->timePeriodRepository ->expects($this->once()) ->method('exists') ->with(1) ->willReturn(false); $this->validation->assertIsValidTimePeriod(1, 'check_timeperiod_id'); })->throws( ServiceException::class, ServiceException::idDoesNotExist('check_timeperiod_id', 1)->getMessage() ); it('should raise an exception when the severity ID does not exist', function (): void { $this->serviceSeverityRepository ->expects($this->once()) ->method('exists') ->with(1) ->willReturn(false); $this->validation->assertIsValidSeverity(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('severity_id', 1)->getMessage() ); it('should raise an exception when the notification time period ID does not exist', function (): void { $this->timePeriodRepository ->expects($this->once()) ->method('exists') ->with(1) ->willReturn(false); $this->validation->assertIsValidTimePeriod(1, 'notification_timeperiod_id'); })->throws( ServiceException::class, ServiceException::idDoesNotExist('notification_timeperiod_id', 1)->getMessage() ); it('should raise an exception when the icon ID does not exist', function (): void { $this->imageRepository ->expects($this->once()) ->method('existsOne') ->with(1) ->willReturn(false); $this->validation->assertIsValidIcon(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('icon_id', 1)->getMessage() ); it('should raise an exception when the host ID does not exist, as an administrator', function (): void { $this->contact ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readHostRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $this->validation->assertIsValidHost(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('host_id', 1)->getMessage() ); it('should raise an exception when the host ID does not exist, as a non-administrator', function (): void { $this->contact ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->readHostRepository ->expects($this->once()) ->method('existsByAccessGroups') ->willReturn(false); $this->validation->assertIsValidHost(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('host_id', 1)->getMessage() ); it('should raise an exception when the service category IDs do not exist, as an administrator', function (): void { $this->contact ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readServiceCategoryRepository ->expects($this->once()) ->method('findAllExistingIds') ->willReturn([2]); $this->validation->assertAreValidCategories([1, 2]); })->throws( ServiceException::class, ServiceException::idsDoNotExist('service_categories', [1])->getMessage() ); it('should raise an exception when the service category IDs do not exist, as a non-administrator', function (): void { $this->contact ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->readServiceCategoryRepository ->expects($this->once()) ->method('findAllExistingIdsByAccessGroups') ->willReturn([2]); $this->validation->assertAreValidCategories([1, 2]); })->throws( ServiceException::class, ServiceException::idsDoNotExist('service_categories', [1])->getMessage() ); it('should raise an exception when the service group IDs do not exist, as an administrator', function (): void { $serviceGroupIds = [1, 2, 3]; $this->contact ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readServiceGroupRepository ->expects($this->once()) ->method('exist') ->willReturn([2]); $this->validation->assertAreValidGroups($serviceGroupIds); })->throws( ServiceException::class, ServiceException::idsDoNotExist('service_groups', [1, 3])->getMessage() ); it('should raise an exception when the service group IDs do not exist, as a non-administrator', function (): void { $serviceGroupIds = [1, 2, 3]; $this->contact ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->readServiceGroupRepository ->expects($this->once()) ->method('existByAccessGroups') ->willReturn([2]); $this->validation->assertAreValidGroups($serviceGroupIds); })->throws( ServiceException::class, ServiceException::idsDoNotExist('service_groups', [1, 3])->getMessage() );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Application/UseCase/DeleteService/DeleteServiceTest.php
centreon/tests/php/Core/Service/Application/UseCase/DeleteService/DeleteServiceTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Application\UseCase\DeleteService; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\Application\Common\UseCase\NoContentResponse; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Infrastructure\Common\Api\DefaultPresenter; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface; use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Service\Application\Exception\ServiceException; use Core\Service\Application\Repository\ReadServiceRepositoryInterface; use Core\Service\Application\Repository\WriteServiceRepositoryInterface; use Core\Service\Application\UseCase\DeleteService\DeleteService; beforeEach(closure: function (): void { $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class); $this->presenter = new DefaultPresenter($this->presenterFormatter); $this->useCase = new DeleteService( $this->readRepository = $this->createMock(ReadServiceRepositoryInterface::class), $this->writeRepository = $this->createMock(WriteServiceRepositoryInterface::class), $this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class), $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), $this->storageEngine = $this->createMock(DataStorageEngineInterface::class), $this->user = $this->createMock(ContactInterface::class), $this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class), $this->readServiceMacroRepository = $this->createMock(ReadServiceMacroRepositoryInterface::class), ); }); it('should present a ForbiddenResponse when the user has insufficient rights', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->useCase)(1, $this->presenter); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe(ServiceException::deleteNotAllowed()->getMessage()); }); it('should present a NotFoundResponse when the service is not found', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('exists') ->willReturn(false); ($this->useCase)(1, $this->presenter); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(NotFoundResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe((new NotFoundResponse('Service'))->getMessage()); }); it('should present an ErrorResponse when an exception is thrown', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('exists') ->willThrowException(new \Exception()); ($this->useCase)(1, $this->presenter); expect($this->presenter->getResponseStatus()) ->toBeInstanceOf(ErrorResponse::class) ->and($this->presenter->getResponseStatus()->getMessage()) ->toBe(ServiceException::errorWhileDeleting(new \Exception())->getMessage()); }); it('should present a NoContentResponse when the service has been deleted', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('exists') ->willReturn(true); $this->readRepository ->expects($this->once()) ->method('findMonitoringServerId') ->willReturn(1); $this->writeRepository ->expects($this->once()) ->method('delete') ->with(1); $this->writeMonitoringServerRepository ->expects($this->once()) ->method('notifyConfigurationChange'); ($this->useCase)(1, $this->presenter); expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Application/UseCase/DeleteServices/DeleteServicesTest.php
centreon/tests/php/Core/Service/Application/UseCase/DeleteServices/DeleteServicesTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\NotFoundResponse; use Core\Common\Domain\ResponseCodeEnum; use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Service\Application\Exception\ServiceException; use Core\Service\Application\Repository\ReadServiceRepositoryInterface; use Core\Service\Application\Repository\WriteServiceRepositoryInterface; use Core\Service\Application\UseCase\DeleteServices\DeleteServices; use Core\Service\Application\UseCase\DeleteServices\DeleteServicesRequest; use Core\Service\Application\UseCase\DeleteServices\DeleteServicesResponse; beforeEach(function (): void { $this->useCase = new DeleteServices( $this->contact = $this->createMock(ContactInterface::class), $this->writeRepository = $this->createMock(WriteServiceRepositoryInterface::class), $this->readRepository = $this->createMock(ReadServiceRepositoryInterface::class), $this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class), $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), $this->storageEngine = $this->createMock(DataStorageEngineInterface::class) ); $this->request = new DeleteServicesRequest([1, 2, 3]); }); it('should check that services exists as admin', function (): void { $this->contact ->expects($this->any()) ->method('isAdmin') ->willReturn(true); $this->readRepository ->expects($this->exactly(3)) ->method('exists'); ($this->useCase)($this->request); }); it('should check that services exists as user', function (): void { $this->contact ->expects($this->any()) ->method('isAdmin') ->willReturn(false); $this->readRepository ->expects($this->exactly(3)) ->method('existsByAccessGroups'); ($this->useCase)($this->request); }); it('should return a DeleteServicesResponse', function (): void { $this->contact ->expects($this->any()) ->method('isAdmin') ->willReturn(true); $this->readRepository ->expects($this->exactly(3)) ->method('exists') ->willReturnOnConsecutiveCalls(true, false, true); $ex = new Exception('Error while deleting a service configuration'); $this->writeRepository ->expects($this->exactly(2)) ->method('delete') ->will($this->onConsecutiveCalls(null, $this->throwException($ex))); $response = ($this->useCase)($this->request); expect($response)->toBeInstanceOf(DeleteServicesResponse::class) ->and($response->getData())->toBeArray() ->and($response->getData())->toHaveCount(3) ->and($response->getData()[0]->id)->toBe(1) ->and($response->getData()[0]->status)->toBe(ResponseCodeEnum::OK) ->and($response->getData()[0]->message)->toBeNull() ->and($response->getData()[1]->id)->toBe(2) ->and($response->getData()[1]->status)->toBe(ResponseCodeEnum::NotFound) ->and($response->getData()[1]->message)->toBe((new NotFoundResponse('Service'))->getMessage()) ->and($response->getData()[2]->id)->toBe(3) ->and($response->getData()[2]->status)->toBe(ResponseCodeEnum::Error) ->and($response->getData()[2]->message)->toBe(ServiceException::errorWhileDeleting($ex)->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/Service/Application/UseCase/AddService/AddServiceTest.php
centreon/tests/php/Core/Service/Application/UseCase/AddService/AddServiceTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Application\UseCase\AddService; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Centreon\Domain\Option\Option; use Centreon\Domain\Option\OptionService; use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface; use Core\Application\Common\UseCase\ConflictResponse; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\ForbiddenResponse; use Core\CommandMacro\Application\Repository\ReadCommandMacroRepositoryInterface; use Core\Common\Application\Repository\ReadVaultRepositoryInterface; use Core\Common\Application\Repository\WriteVaultRepositoryInterface; use Core\Common\Domain\YesNoDefault; use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface; use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface; use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface; use Core\Macro\Domain\Model\Macro; use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface; use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface; use Core\MonitoringServer\Model\MonitoringServer; use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface; use Core\Service\Application\Exception\ServiceException; use Core\Service\Application\Repository\ReadServiceRepositoryInterface; use Core\Service\Application\Repository\WriteRealTimeServiceRepositoryInterface; use Core\Service\Application\Repository\WriteServiceRepositoryInterface; use Core\Service\Application\UseCase\AddService\AddService; use Core\Service\Application\UseCase\AddService\AddServiceRequest; use Core\Service\Application\UseCase\AddService\AddServiceResponse; use Core\Service\Application\UseCase\AddService\AddServiceValidation; use Core\Service\Application\UseCase\AddService\MacroDto; use Core\Service\Domain\Model\NotificationType; use Core\Service\Domain\Model\Service; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceCategory\Application\Repository\WriteServiceCategoryRepositoryInterface; use Core\ServiceCategory\Domain\Model\ServiceCategory; use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface; use Core\ServiceGroup\Application\Repository\WriteServiceGroupRepositoryInterface; use Core\ServiceGroup\Domain\Model\ServiceGroup; use Core\ServiceGroup\Domain\Model\ServiceGroupRelation; use Core\ServiceTemplate\Domain\Model\ServiceTemplateInheritance; use Tests\Core\Service\Infrastructure\API\AddService\AddServicePresenterStub; beforeEach(function (): void { $this->useCasePresenter = new AddServicePresenterStub( $this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class) ); $this->addUseCase = new AddService( $this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class), $this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class), $this->readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class), $this->writeServiceRepository = $this->createMock(WriteServiceRepositoryInterface::class), $this->readServiceMacroRepository = $this->createMock(ReadServiceMacroRepositoryInterface::class), $this->readCommandMacroRepository = $this->createMock(ReadCommandMacroRepositoryInterface::class), $this->writeServiceMacroRepository = $this->createMock(WriteServiceMacroRepositoryInterface::class), $this->storageEngine = $this->createMock(DataStorageEngineInterface::class), $this->readServiceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class), $this->writeServiceCategoryRepository = $this->createMock(WriteServiceCategoryRepositoryInterface::class), $this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class), $this->writeServiceGroupRepository = $this->createMock(WriteServiceGroupRepositoryInterface::class), $this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class), $this->validation = $this->createMock(AddServiceValidation::class), $this->optionService = $this->createMock(OptionService::class), $this->user = $this->createMock(ContactInterface::class), $this->isCloudPlatform = false, $this->writeVaultRepository = $this->createMock(WriteVaultRepositoryInterface::class), $this->readVaultRepository = $this->createMock(ReadVaultRepositoryInterface::class), $this->writeRealTimeServiceRepository = $this->createMock(WriteRealTimeServiceRepositoryInterface::class), ); $this->request = new AddServiceRequest(); $this->inheritanceModeOption = new Option(); $this->inheritanceModeOption->setName('inheritanceMode')->setValue('1'); }); it('should present a ForbiddenResponse when the user has insufficient rights', function (): void { $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(false); ($this->addUseCase)(new AddServiceRequest(), $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ForbiddenResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe(ServiceException::addNotAllowed()->getMessage()); }); it('should present an ErrorResponse when the service name already exists', function (): void { $fakeName = 'fake_name'; $hostId = 1; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertServiceName') ->willThrowException( ServiceException::nameAlreadyExists( Service::formatName($fakeName), $hostId ) ); $this->request->name = $fakeName; $this->request->hostId = $hostId; ($this->addUseCase)($this->request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe(ServiceException::nameAlreadyExists($fakeName, $hostId)->getMessage()); }); it('should present a ConflictResponse when the severity ID is not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidSeverity') ->willThrowException(ServiceException::idDoesNotExist('severity_id', $request->severityId)); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe(ServiceException::idDoesNotExist('severity_id', $request->severityId)->getMessage()); }); it('should present a ConflictResponse when the performance graph ID is not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidPerformanceGraph') ->willThrowException(ServiceException::idDoesNotExist('graph_template_id', $request->severityId)); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe(ServiceException::idDoesNotExist('graph_template_id', $request->severityId)->getMessage()); }); it('should present a ConflictResponse when the service template ID is not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 1; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidServiceTemplate') ->willThrowException(ServiceException::idDoesNotExist('service_template_id', $request->severityId)); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe(ServiceException::idDoesNotExist('service_template_id', $request->severityId)->getMessage()); }); it('should present a ConflictResponse when the command ID is not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 1; $request->commandId = 1; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidCommandForOnPremPlatform') ->willThrowException(ServiceException::idDoesNotExist('check_command_id', $request->severityId)); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe(ServiceException::idDoesNotExist('check_command_id', $request->severityId)->getMessage()); }); it('should present a ConflictResponse when the event handler ID is not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 1; $request->commandId = 1; $request->eventHandlerId = 12; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidEventHandler') ->willThrowException( ServiceException::idDoesNotExist( 'event_handler_command_id', $request->eventHandlerId ) ); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe( ServiceException::idDoesNotExist( 'event_handler_command_id', $request->eventHandlerId )->getMessage() ); }); it('should present a ConflictResponse when the time period ID is not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 1; $request->commandId = 1; $request->eventHandlerId = 12; $request->checkTimePeriodId = 13; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidTimePeriod') ->willThrowException( ServiceException::idDoesNotExist( 'check_timeperiod_id', $request->checkTimePeriodId ) ); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe( ServiceException::idDoesNotExist( 'check_timeperiod_id', $request->checkTimePeriodId )->getMessage() ); }); it('should present a ConflictResponse when the icon ID is not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 1; $request->commandId = 1; $request->eventHandlerId = 12; $request->checkTimePeriodId = 13; $request->notificationTimePeriodId = 14; $request->iconId = 15; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidIcon') ->willThrowException( ServiceException::idDoesNotExist( 'icon_id', $request->iconId ) ); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe( ServiceException::idDoesNotExist( 'icon_id', $request->iconId )->getMessage() ); }); it('should present a ConflictResponse when the host ID is not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 1; $request->commandId = 1; $request->eventHandlerId = 12; $request->checkTimePeriodId = 13; $request->notificationTimePeriodId = 14; $request->iconId = 15; $request->hostId = 2; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidHost') ->willThrowException( ServiceException::idDoesNotExist( 'host_id', $request->hostId ) ); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe( ServiceException::idDoesNotExist( 'host_id', $request->hostId )->getMessage() ); }); it('should present a ConflictResponse when the service category IDs are not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 1; $request->commandId = 1; $request->eventHandlerId = 12; $request->checkTimePeriodId = 13; $request->notificationTimePeriodId = 14; $request->iconId = 15; $request->serviceCategories = [2, 3]; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidServiceCategories') ->willThrowException( ServiceException::idsDoNotExist( 'service_categories', [$request->serviceCategories[1]] ) ); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe( ServiceException::idsDoNotExist( 'service_categories', [$request->serviceCategories[1]] )->getMessage() ); }); it('should present a ConflictResponse when the service group IDs are not valid', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 1; $request->commandId = 1; $request->eventHandlerId = 12; $request->checkTimePeriodId = 13; $request->notificationTimePeriodId = 14; $request->iconId = 15; $request->hostId = 4; $request->serviceGroups = [2, 3]; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->validation ->expects($this->once()) ->method('assertIsValidServiceGroups') ->willThrowException( ServiceException::idsDoNotExist( 'service_groups', [$request->serviceGroups[1]] ) ); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ConflictResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe( ServiceException::idsDoNotExist( 'service_groups', [$request->serviceGroups[1]] )->getMessage() ); }); it('should present an ErrorResponse when an exception is thrown', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 1; $request->commandId = 1; $request->eventHandlerId = 12; $request->checkTimePeriodId = 13; $request->notificationTimePeriodId = 14; $request->iconId = 15; $request->hostId = 4; $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->optionService ->expects($this->once()) ->method('findSelectedOptions') ->willThrowException(new \Exception()); ($this->addUseCase)($request, $this->useCasePresenter); expect($this->useCasePresenter->response) ->toBeInstanceOf(ErrorResponse::class) ->and($this->useCasePresenter->response->getMessage()) ->toBe(ServiceException::errorWhileAdding(new \Exception())->getMessage()); }); it('should present an AddServiceResponse when everything has gone well', function (): void { $request = new AddServiceRequest(); $request->name = 'fake_name'; $request->hostId = 1; $request->severityId = 1; $request->graphTemplateId = 1; $request->serviceTemplateParentId = 10; $request->commandId = 1; $request->eventHandlerId = 12; $request->checkTimePeriodId = 13; $request->notificationTimePeriodId = 14; $request->iconId = 15; $request->macros = [ new MacroDto('MACROA', 'A', false, null), new MacroDto('MACROB', 'B', false, null), ]; $request->serviceCategories = [12, 13]; $request->serviceGroups = [15]; $newServiceId = 99; $serviceTemplateInheritances = [ new ServiceTemplateInheritance(9, 99), new ServiceTemplateInheritance(8, 9), new ServiceTemplateInheritance(1, 8), ]; $categories = [ $categoryA = new ServiceCategory(12, 'cat-name-A', 'cat-alias-A'), $categoryB = new ServiceCategory(13, 'cat-name-B', 'cat-alias-B'), ]; $macroA = new Macro(null, $newServiceId, 'MACROA', 'A'); $macroB = new Macro(null, $newServiceId, 'MACROB', 'B'); $serviceGroup = new ServiceGroup(15, 'SG-name', 'SG-alias', null, '', true); $serviceGroupRelation = new ServiceGroupRelation( serviceGroupId: $serviceGroup->getId(), serviceId: $newServiceId, hostId: $request->hostId ); $serviceFound = new Service( id: $newServiceId, name: $request->name, commandArguments: ['a', 'b'], eventHandlerArguments: ['c', 'd'], notificationTypes: [NotificationType::Unknown], hostId: 1, contactAdditiveInheritance: true, contactGroupAdditiveInheritance: true, isActivated: true, activeChecks: YesNoDefault::Yes, passiveCheck: YesNoDefault::No, volatility: YesNoDefault::Default, checkFreshness: YesNoDefault::Yes, eventHandlerEnabled: YesNoDefault::No, flapDetectionEnabled: YesNoDefault::Default, notificationsEnabled: YesNoDefault::Yes, comment: 'comment', note: 'note', noteUrl: 'note_url', actionUrl: 'action_url', iconAlternativeText: 'icon_aternative_text', graphTemplateId: $request->graphTemplateId, serviceTemplateParentId: $request->serviceTemplateParentId, commandId: $request->commandId, eventHandlerId: $request->eventHandlerId, notificationTimePeriodId: 6, checkTimePeriodId: $request->checkTimePeriodId, iconId: $request->iconId, severityId: $request->severityId, maxCheckAttempts: 5, normalCheckInterval: 1, retryCheckInterval: 3, freshnessThreshold: 1, lowFlapThreshold: 10, highFlapThreshold: 99, notificationInterval: $request->notificationTimePeriodId, recoveryNotificationDelay: 0, firstNotificationDelay: 0, acknowledgementTimeout: 0, ); $this->user ->expects($this->once()) ->method('hasTopologyRole') ->willReturn(true); $this->user ->expects($this->exactly(2)) ->method('isAdmin') ->willReturn(true); $this->validation->expects($this->once())->method('assertIsValidSeverity'); $this->validation->expects($this->once())->method('assertIsValidPerformanceGraph'); $this->validation->expects($this->once())->method('assertIsValidServiceTemplate'); $this->validation->expects($this->once())->method('assertIsValidEventHandler'); $this->validation->expects($this->once())->method('assertIsValidTimePeriod'); $this->validation->expects($this->once())->method('assertIsValidNotificationTimePeriod'); $this->validation->expects($this->once())->method('assertIsValidIcon'); $this->validation->expects($this->once())->method('assertIsValidHost'); $this->validation->expects($this->once())->method('assertIsValidCommandForOnPremPlatform'); $this->validation->expects($this->once())->method('assertServiceName'); $this->validation->expects($this->once())->method('assertIsValidServiceCategories'); $this->validation->expects($this->once())->method('assertIsValidServiceGroups'); $this->optionService ->expects($this->once()) ->method('findSelectedOptions') ->willReturn(['inheritance_mode' => $this->inheritanceModeOption]); $this->writeServiceRepository ->expects($this->once()) ->method('add') ->willReturn($newServiceId); $this->readServiceRepository ->expects($this->once()) ->method('findParents') ->willReturn($serviceTemplateInheritances); $this->readServiceMacroRepository ->expects($this->exactly(2)) ->method('findByServiceIds') ->willReturnMap( [ [9, 8, 1, []], [$newServiceId, [$macroA, $macroB]], ], ); $this->readCommandMacroRepository ->expects($this->once()) ->method('findByCommandIdAndType') ->willReturn([]); $this->writeServiceMacroRepository ->expects($this->exactly(2)) ->method('add'); $this->writeServiceCategoryRepository ->expects($this->once()) ->method('linkToService'); $this->writeServiceGroupRepository ->expects($this->once()) ->method('link'); $this->readMonitoringServerRepository ->expects($this->once()) ->method('findByHost') ->willReturn(new MonitoringServer(1, 'ms-name')); $this->writeMonitoringServerRepository ->expects($this->once()) ->method('notifyConfigurationChange'); $this->readServiceRepository ->expects($this->once()) ->method('findById') ->willReturn($serviceFound); $this->readServiceCategoryRepository ->expects($this->once()) ->method('findByService') ->willReturn($categories); $this->readServiceGroupRepository ->expects($this->once()) ->method('findByService') ->willReturn([ ['relation' => $serviceGroupRelation, 'serviceGroup' => $serviceGroup], ]); ($this->addUseCase)($request, $this->useCasePresenter); $dto = $this->useCasePresenter->response; expect($dto)->toBeInstanceOf(AddServiceResponse::class); expect($dto->id)->toBe($serviceFound->getId()); expect($dto->name)->toBe($serviceFound->getName()); expect($dto->comment)->toBe($serviceFound->getComment()); expect($dto->hostId)->toBe($serviceFound->getHostId()); expect($dto->serviceTemplateId)->toBe($serviceFound->getServiceTemplateParentId()); expect($dto->commandId)->toBe($serviceFound->getCommandId()); expect($dto->commandArguments)->toBe($serviceFound->getCommandArguments()); expect($dto->checkTimePeriodId)->toBe($serviceFound->getCheckTimePeriodId()); expect($dto->maxCheckAttempts)->toBe($serviceFound->getMaxCheckAttempts()); expect($dto->normalCheckInterval)->toBe($serviceFound->getNormalCheckInterval()); expect($dto->retryCheckInterval)->toBe($serviceFound->getRetryCheckInterval()); expect($dto->activeChecks)->toBe($serviceFound->getActiveChecks()); expect($dto->passiveCheck)->toBe($serviceFound->getPassiveCheck()); expect($dto->volatility)->toBe($serviceFound->getVolatility()); expect($dto->notificationsEnabled)->toBe($serviceFound->getNotificationsEnabled()); expect($dto->isContactAdditiveInheritance)->toBe($serviceFound->isContactAdditiveInheritance()); expect($dto->isContactGroupAdditiveInheritance) ->toBe($serviceFound->isContactGroupAdditiveInheritance()); expect($dto->notificationInterval)->toBe($serviceFound->getNotificationInterval()); expect($dto->notificationTimePeriodId)->toBe($serviceFound->getNotificationTimePeriodId()); expect($dto->notificationTypes)->toBe($serviceFound->getNotificationTypes()); expect($dto->firstNotificationDelay)->toBe($serviceFound->getFirstNotificationDelay()); expect($dto->recoveryNotificationDelay)->toBe($serviceFound->getRecoveryNotificationDelay()); expect($dto->acknowledgementTimeout)->toBe($serviceFound->getAcknowledgementTimeout()); expect($dto->checkFreshness)->toBe($serviceFound->getCheckFreshness()); expect($dto->freshnessThreshold)->toBe($serviceFound->getFreshnessThreshold()); expect($dto->flapDetectionEnabled)->toBe($serviceFound->getFlapDetectionEnabled()); expect($dto->lowFlapThreshold)->toBe($serviceFound->getLowFlapThreshold()); expect($dto->highFlapThreshold)->toBe($serviceFound->getHighFlapThreshold()); expect($dto->eventHandlerEnabled)->toBe($serviceFound->getEventHandlerEnabled()); expect($dto->eventHandlerId)->toBe($serviceFound->getEventHandlerId()); expect($dto->eventHandlerArguments)->toBe($serviceFound->getEventHandlerArguments()); expect($dto->graphTemplateId)->toBe($serviceFound->getGraphTemplateId()); expect($dto->note)->toBe($serviceFound->getNote()); expect($dto->noteUrl)->toBe($serviceFound->getNoteUrl()); expect($dto->actionUrl)->toBe($serviceFound->getActionUrl()); expect($dto->iconId)->toBe($serviceFound->getIconId()); expect($dto->iconAlternativeText)->toBe($serviceFound->getIconAlternativeText()); expect($dto->severityId)->toBe($serviceFound->getSeverityId()); expect($dto->isActivated)->toBe($serviceFound->isActivated()); foreach ($dto->macros as $index => $expectedMacro) { expect($expectedMacro->name)->toBe($request->macros[$index]->name) ->and($expectedMacro->value)->toBe($request->macros[$index]->value) ->and($expectedMacro->isPassword)->toBe($request->macros[$index]->isPassword) ->and($expectedMacro->description)->toBe(''); } expect($dto->groups)->toBe( [['id' => $serviceGroup->getId(), 'name' => $serviceGroup->getName()]] ); expect($dto->categories)->toBe( [ ['id' => $categoryA->getId(), 'name' => $categoryA->getName()], ['id' => $categoryB->getId(), 'name' => $categoryB->getName()], ] ); });
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Application/UseCase/AddService/AddServiceValidationTest.php
centreon/tests/php/Core/Service/Application/UseCase/AddService/AddServiceValidationTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Application\UseCase\AddService; use Centreon\Domain\Contact\Interfaces\ContactInterface; use Core\Command\Application\Repository\ReadCommandRepositoryInterface; use Core\Host\Application\Repository\ReadHostRepositoryInterface; use Core\PerformanceGraph\Application\Repository\ReadPerformanceGraphRepositoryInterface; use Core\Service\Application\Exception\ServiceException; use Core\Service\Application\Repository\ReadServiceRepositoryInterface; use Core\Service\Application\UseCase\AddService\AddServiceRequest; use Core\Service\Application\UseCase\AddService\AddServiceValidation; use Core\Service\Domain\Model\ServiceNamesByHost; use Core\ServiceCategory\Application\Repository\ReadServiceCategoryRepositoryInterface; use Core\ServiceGroup\Application\Repository\ReadServiceGroupRepositoryInterface; use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface; use Core\ServiceTemplate\Application\Repository\ReadServiceTemplateRepositoryInterface; use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface; use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface; beforeEach(function (): void { $this->validation = new AddServiceValidation( $this->readServiceTemplateRepository = $this->createMock(ReadServiceTemplateRepositoryInterface::class), $this->readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class), $this->serviceSeverityRepository = $this->createMock(ReadServiceSeverityRepositoryInterface::class), $this->performanceGraphRepository = $this->createMock(ReadPerformanceGraphRepositoryInterface::class), $this->commandRepository = $this->createMock(ReadCommandRepositoryInterface::class), $this->timePeriodRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class), $this->imageRepository = $this->createMock(ReadViewImgRepositoryInterface::class), $this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class), $this->readServiceCategoryRepository = $this->createMock(ReadServiceCategoryRepositoryInterface::class), $this->readServiceGroupRepository = $this->createMock(ReadServiceGroupRepositoryInterface::class), $this->user = $this->createMock(ContactInterface::class), ); }); it('throws an exception when service name already exists for associated host', function (): void { $this->readServiceRepository ->expects($this->once()) ->method('findServiceNamesByHost') ->willReturn(new ServiceNamesByHost(1, ['toto'])); $request = new AddServiceRequest(); $request->name = ' toto '; $request->hostId = 1; $this->validation->assertServiceName($request); })->throws( ServiceException::class, ServiceException::nameAlreadyExists('toto', 1)->getMessage() ); it('throws an exception when parent template ID does not exist', function (): void { $this->readServiceTemplateRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $this->validation->assertIsValidServiceTemplate(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('service_template_id', 1)->getMessage() ); it('throws an exception when command ID does not exist', function (): void { $this->commandRepository ->expects($this->once()) ->method('existsByIdAndCommandType') ->willReturn(false); $this->validation->assertIsValidCommandForOnPremPlatform(1, null); })->throws( ServiceException::class, ServiceException::idDoesNotExist('check_command_id', 1)->getMessage() ); it('throws an exception when command ID and service template are not defined', function (): void { $this->validation->assertIsValidCommandForOnPremPlatform(null, null); })->throws( ServiceException::class, ServiceException::checkCommandCannotBeNull()->getMessage() ); it('throws an exception when event handler ID does not exist', function (): void { $this->commandRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $this->validation->assertIsValidEventHandler(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('event_handler_command_id', 1)->getMessage() ); it('throws an exception when check time period ID does not exist', function (): void { $this->timePeriodRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $this->validation->assertIsValidTimePeriod(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('check_timeperiod_id', 1)->getMessage() ); it('throws an exception when icon ID does not exist', function (): void { $this->imageRepository ->expects($this->once()) ->method('existsOne') ->willReturn(false); $this->validation->assertIsValidIcon(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('icon_id', 1)->getMessage() ); it('throws an exception when notification time period ID does not exist', function (): void { $this->timePeriodRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $this->validation->assertIsValidNotificationTimePeriod(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('notification_timeperiod_id', 1)->getMessage() ); it('throws an exception when severity ID does not exist', function (): void { $this->serviceSeverityRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $this->validation->assertIsValidSeverity(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('severity_id', 1)->getMessage() ); it('throws an exception when performance graph ID does not exist', function (): void { $this->performanceGraphRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $this->validation->assertIsValidPerformanceGraph(1); })->throws( ServiceException::class, ServiceException::idDoesNotExist('graph_template_id', 1)->getMessage() ); it('throws an exception when host ID does not exist', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readHostRepository ->expects($this->once()) ->method('exists') ->willReturn(false); $this->validation->assertIsValidHost(4); })->throws( ServiceException::class, ServiceException::idDoesNotExist('host_id', 4)->getMessage() ); it('throws an exception when category ID does not exist with admin user', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readServiceCategoryRepository ->expects($this->once()) ->method('findAllExistingIds') ->willReturn([]); $this->validation->assertIsValidServiceCategories([1, 3]); })->throws( ServiceException::class, ServiceException::idsDoNotExist('service_categories', [1, 3])->getMessage() ); it('throws an exception when category ID does not exist with non-admin user', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->readServiceCategoryRepository ->expects($this->once()) ->method('findAllExistingIdsByAccessGroups') ->willReturn([]); $this->validation->assertIsValidServiceCategories([1, 3]); })->throws( ServiceException::class, ServiceException::idsDoNotExist('service_categories', [1, 3])->getMessage() ); it('throws an exception when group ID does not exist with admin user', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(true); $this->readServiceGroupRepository ->expects($this->once()) ->method('exist') ->willReturn([]); $this->validation->assertIsValidServiceGroups([1, 2], 3); })->throws( ServiceException::class, ServiceException::idsDoNotExist('service_groups', [1, 2])->getMessage() ); it('throws an exception when group ID does not exist with non-admin user', function (): void { $this->user ->expects($this->once()) ->method('isAdmin') ->willReturn(false); $this->readServiceGroupRepository ->expects($this->once()) ->method('existByAccessGroups') ->willReturn([]); $this->validation->assertIsValidServiceGroups([1, 2], 3); })->throws( ServiceException::class, ServiceException::idsDoNotExist('service_groups', [1, 2])->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/Service/Domain/Model/ServiceLightTest.php
centreon/tests/php/Core/Service/Domain/Model/ServiceLightTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Common\Domain\SimpleEntity; use Core\Common\Domain\TrimmedString; use Core\Service\Domain\Model\NewService; use Core\Service\Domain\Model\ServiceLight; use Core\ServiceGroup\Domain\Model\ServiceGroupRelation; beforeEach(function (): void { $this->createService = static fn (array $fields = []): ServiceLight => new ServiceLight( ...[ 'id' => 1, 'name' => new TrimmedString('service-name'), 'hostIds' => [3], 'categoryIds' => [], 'groups' => [new ServiceGroupRelation(2, 1, 3)], 'serviceTemplate' => new SimpleEntity(1, new TrimmedString('serviceTemplate-name'), 'ServiceLigth::serviceTemplate'), 'notificationTimePeriod' => new SimpleEntity(1, new TrimmedString('notificationTimePeriod-name'), 'ServiceLigth::notificationTimePeriod'), 'checkTimePeriod' => new SimpleEntity(1, new TrimmedString('checkTimePeriod-name'), 'ServiceLigth::checkTimePeriod'), 'severity' => new SimpleEntity(1, new TrimmedString('severity-name'), 'ServiceLigth::severity'), 'normalCheckInterval' => 5, 'retryCheckInterval' => 1, 'isActivated' => true, ...$fields, ] ); }); it('should return properly set service instance (all properties)', function (): void { $service = ($this->createService)(); expect($service->getId())->toBe(1) ->and($service->getName())->toBe('service-name') ->and($service->getHostIds())->toBe([3]) ->and($service->getCategoryIds())->toBe([]) ->and($service->getGroups()[0]->getServiceGroupId())->toBe(2) ->and($service->getServiceTemplate()->getName())->toBe('serviceTemplate-name') ->and($service->getNotificationTimePeriod()->getName())->toBe('notificationTimePeriod-name') ->and($service->getCheckTimePeriod()->getName())->toBe('checkTimePeriod-name') ->and($service->getSeverity()->getName())->toBe('severity-name') ->and($service->getNormalCheckInterval())->toBe(5) ->and($service->getRetryCheckInterval())->toBe(1) ->and($service->isActivated())->toBe(true); }); it('should return properly set host instance (mandatory properties only)', function (): void { $service = new ServiceLight(id: 1, name: new TrimmedString('service-name'), hostIds: [1]); expect($service->getId())->toBe(1) ->and($service->getName())->toBe('service-name') ->and($service->getHostIds())->toBe([1]) ->and($service->getCategoryIds())->toBe([]) ->and($service->getGroups())->toBe([]) ->and($service->getServiceTemplate())->toBe(null) ->and($service->getNotificationTimePeriod())->toBe(null) ->and($service->getCheckTimePeriod())->toBe(null) ->and($service->getSeverity())->toBe(null) ->and($service->getNormalCheckInterval())->toBe(null) ->and($service->getRetryCheckInterval())->toBe(null) ->and($service->isActivated())->toBe(true); }); // mandatory fields it( 'should throw an exception when service name is an empty string', fn () => ($this->createService)(['name' => new TrimmedString(' ')]) )->throws( InvalidArgumentException::class, AssertionException::notEmptyString('ServiceLight::name')->getMessage() ); // too long field $tooLong = str_repeat('a', NewService::MAX_NAME_LENGTH + 1); it( 'should throw an exception when service name is too long', fn () => ($this->createService)(['name' => new TrimmedString($tooLong)]) )->throws( InvalidArgumentException::class, AssertionException::maxLength( $tooLong, NewService::MAX_NAME_LENGTH + 1, NewService::MAX_NAME_LENGTH, 'ServiceLight::name' )->getMessage() );
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Domain/Model/NewServiceTest.php
centreon/tests/php/Core/Service/Domain/Model/NewServiceTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Common\Domain\YesNoDefault; use Core\Domain\Common\GeoCoords; use Core\Service\Domain\Model\NewService; use Core\Service\Domain\Model\NotificationType; beforeEach(function (): void { $this->createService = static function (array $fields = []): NewService { $service = new NewService( name: 'service-name', hostId: 1, commandId: 1, ); $additionalProperties = [ 'commandArguments' => ['args1', 'args2'], 'eventHandlerArguments' => ['args3', 'args4'], 'notificationTypes' => [NotificationType::Warning, NotificationType::Critical], 'isContactAdditiveInheritance' => false, 'isContactGroupAdditiveInheritance' => false, 'isActivated' => true, 'activeChecks' => YesNoDefault::Yes, 'passiveCheck' => YesNoDefault::No, 'volatility' => YesNoDefault::Yes, 'checkFreshness' => YesNoDefault::No, 'eventHandlerEnabled' => YesNoDefault::Yes, 'flapDetectionEnabled' => YesNoDefault::No, 'notificationsEnabled' => YesNoDefault::Yes, 'comment' => 'some-comment', 'note' => 'some-note', 'noteUrl' => 'some-url', 'actionUrl' => 'some-action-url', 'iconAlternativeText' => 'icon-alt', 'graphTemplateId' => 12, 'serviceTemplateParentId' => 52, 'eventHandlerId' => 14, 'notificationTimePeriodId' => 65, 'checkTimePeriodId' => 82, 'iconId' => 27, 'severityId' => 16, 'maxCheckAttempts' => 3, 'normalCheckInterval' => 5, 'retryCheckInterval' => 1, 'freshnessThreshold' => 12, 'lowFlapThreshold' => 6, 'highFlapThreshold' => 8, 'notificationInterval' => 15, 'recoveryNotificationDelay' => 10, 'firstNotificationDelay' => 5, 'acknowledgementTimeout' => 20, 'geoCoords' => new GeoCoords('12.25', '46.8'), ]; $fields = array_merge($additionalProperties, $fields); foreach ($fields as $fieldName => $fieldValue) { if (in_array($fieldName, ['commandArguments', 'eventHandlerArguments', 'notificationTypes'], true)) { $setterMethod = 'add' . ucfirst(mb_substr($fieldName, 0, mb_strlen($fieldName) - 1)); foreach ($fieldValue as $value) { $service->{$setterMethod}($value); } } else { $setterMethod = 'set' . ucfirst( str_starts_with($fieldName, 'is') ? mb_substr($fieldName, 2) : $fieldName ); if (method_exists(NewService::class, $setterMethod)) { $service->{$setterMethod}($fieldValue); } } } return $service; }; }); it('should return properly set service instance (all properties)', function (): void { $service = ($this->createService)(); expect($service->getName())->toBe('service-name') ->and($service->getHostId())->toBe(1) ->and($service->getCommandId())->toBe(1) ->and($service->getCommandArguments())->toBe(['args1', 'args2']) ->and($service->getEventHandlerArguments())->toBe(['args3', 'args4']) ->and($service->getNotificationTypes())->toBe([NotificationType::Warning, NotificationType::Critical]) ->and($service->isContactAdditiveInheritance())->toBe(false) ->and($service->isContactGroupAdditiveInheritance())->toBe(false) ->and($service->isActivated())->toBe(true) ->and($service->getActiveChecks())->toBe(YesNoDefault::Yes) ->and($service->getPassiveCheck())->toBe(YesNoDefault::No) ->and($service->getVolatility())->toBe(YesNoDefault::Yes) ->and($service->getCheckFreshness())->toBe(YesNoDefault::No) ->and($service->getEventHandlerEnabled())->toBe(YesNoDefault::Yes) ->and($service->getFlapDetectionEnabled())->toBe(YesNoDefault::No) ->and($service->getNotificationsEnabled())->toBe(YesNoDefault::Yes) ->and($service->getComment())->toBe('some-comment') ->and($service->getNote())->toBe('some-note') ->and($service->getNoteUrl())->toBe('some-url') ->and($service->getActionUrl())->toBe('some-action-url') ->and($service->getIconAlternativeText())->toBe('icon-alt') ->and($service->getGraphTemplateId())->toBe(12) ->and($service->getServiceTemplateParentId())->toBe(52) ->and($service->getEventHandlerId())->toBe(14) ->and($service->getNotificationTimePeriodId())->toBe(65) ->and($service->getCheckTimePeriodId())->toBe(82) ->and($service->getIconId())->toBe(27) ->and($service->getSeverityId())->toBe(16) ->and($service->getMaxCheckAttempts())->toBe(3) ->and($service->getNormalCheckInterval())->toBe(5) ->and($service->getRetryCheckInterval())->toBe(1) ->and($service->getFreshnessThreshold())->toBe(12) ->and($service->getLowFlapThreshold())->toBe(6) ->and($service->getHighFlapThreshold())->toBe(8) ->and($service->getNotificationInterval())->toBe(15) ->and($service->getRecoveryNotificationDelay())->toBe(10) ->and($service->getFirstNotificationDelay())->toBe(5) ->and($service->getAcknowledgementTimeout())->toBe(20) ->and($service->getGeoCoords()->__toString())->toBe((new GeoCoords('12.25', '46.8'))->__toString()); }); it('should return properly set host instance (mandatory properties only)', function (): void { $service = new NewService(name: 'service-name', hostId: 1, commandId: 1); expect($service->getName())->toBe('service-name') ->and($service->getHostId())->toBe(1) ->and($service->getCommandId())->toBe(1) ->and($service->getCommandArguments())->toBe([]) ->and($service->getEventHandlerArguments())->toBe([]) ->and($service->getNotificationTypes())->toBe([]) ->and($service->isContactAdditiveInheritance())->toBe(false) ->and($service->isContactGroupAdditiveInheritance())->toBe(false) ->and($service->isActivated())->toBe(true) ->and($service->getActiveChecks())->toBe(YesNoDefault::Default) ->and($service->getPassiveCheck())->toBe(YesNoDefault::Default) ->and($service->getVolatility())->toBe(YesNoDefault::Default) ->and($service->getCheckFreshness())->toBe(YesNoDefault::Default) ->and($service->getEventHandlerEnabled())->toBe(YesNoDefault::Default) ->and($service->getFlapDetectionEnabled())->toBe(YesNoDefault::Default) ->and($service->getNotificationsEnabled())->toBe(YesNoDefault::Default) ->and($service->getComment())->toBe(null) ->and($service->getNote())->toBe(null) ->and($service->getNoteUrl())->toBe(null) ->and($service->getActionUrl())->toBe(null) ->and($service->getIconAlternativeText())->toBe(null) ->and($service->getGraphTemplateId())->toBe(null) ->and($service->getServiceTemplateParentId())->toBe(null) ->and($service->getEventHandlerId())->toBe(null) ->and($service->getNotificationTimePeriodId())->toBe(null) ->and($service->getCheckTimePeriodId())->toBe(null) ->and($service->getIconId())->toBe(null) ->and($service->getSeverityId())->toBe(null) ->and($service->getMaxCheckAttempts())->toBe(null) ->and($service->getNormalCheckInterval())->toBe(null) ->and($service->getRetryCheckInterval())->toBe(null) ->and($service->getFreshnessThreshold())->toBe(null) ->and($service->getLowFlapThreshold())->toBe(null) ->and($service->getHighFlapThreshold())->toBe(null) ->and($service->getNotificationInterval())->toBe(null) ->and($service->getRecoveryNotificationDelay())->toBe(null) ->and($service->getFirstNotificationDelay())->toBe(null) ->and($service->getAcknowledgementTimeout())->toBe(null) ->and($service->getGeoCoords())->toBe(null); }); // mandatory fields it( 'should throw an exception when service name is an empty string', fn () => ($this->createService)(['name' => ' ']) )->throws( InvalidArgumentException::class, AssertionException::notEmptyString('NewService::name')->getMessage() ); // foreign keys fields foreach ( [ 'hostId', 'graphTemplateId', 'serviceTemplateParentId', 'commandId', 'eventHandlerId', 'notificationTimePeriodId', 'checkTimePeriodId', 'iconId', 'severityId', ] as $field ) { it( "should throw an exception when service {$field} is not > 0", fn () => ($this->createService)([$field => 0]) )->throws( InvalidArgumentException::class, AssertionException::positiveInt(0, "NewService::{$field}")->getMessage() ); } // name and commands args should be formated it('should return trimmed and formatted name field after construct', function (): void { $service = ($this->createService)(['name' => ' service name ']); expect($service->getName())->toBe('service name'); }); foreach ( [ 'name', 'comment', 'note', 'noteUrl', 'actionUrl', 'iconAlternativeText', ] as $field ) { it( "should return trimmed field {$field} after construct", function () use ($field): void { $service = ($this->createService)([$field => ' abc ']); $valueFromGetter = $service->{'get' . $field}(); expect($valueFromGetter)->toBe('abc'); } ); } // too long fields foreach ( [ 'name' => NewService::MAX_NAME_LENGTH, 'comment' => NewService::MAX_COMMENT_LENGTH, 'note' => NewService::MAX_NOTES_LENGTH, 'noteUrl' => NewService::MAX_NOTES_URL_LENGTH, 'actionUrl' => NewService::MAX_ACTION_URL_LENGTH, 'iconAlternativeText' => NewService::MAX_ICON_ALT_LENGTH, ] as $field => $length ) { $tooLong = str_repeat('a', $length + 1); it( "should throw an exception when service {$field} is too long", fn () => ($this->createService)([$field => $tooLong]) )->throws( InvalidArgumentException::class, AssertionException::maxLength($tooLong, $length + 1, $length, "NewService::{$field}")->getMessage() ); } // integer >= 0 field foreach ( [ 'maxCheckAttempts', 'normalCheckInterval', 'retryCheckInterval', 'freshnessThreshold', 'lowFlapThreshold', 'highFlapThreshold', 'notificationInterval', 'recoveryNotificationDelay', 'firstNotificationDelay', 'acknowledgementTimeout', ] as $field ) { it( "should throw an exception when service {$field} is not >= 0", fn () => ($this->createService)([$field => -1]) )->throws( InvalidArgumentException::class, AssertionException::min(-1, 0, "NewService::{$field}")->getMessage() ); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Domain/Model/ServiceTest.php
centreon/tests/php/Core/Service/Domain/Model/ServiceTest.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ declare(strict_types=1); namespace Tests\Core\Service\Domain\Model; use Assert\InvalidArgumentException; use Centreon\Domain\Common\Assertion\AssertionException; use Core\Common\Domain\YesNoDefault; use Core\Domain\Common\GeoCoords; use Core\Service\Domain\Model\NotificationType; use Core\Service\Domain\Model\Service; beforeEach(function (): void { $this->createService = static fn (array $fields = []): Service => new Service( ...[ 'id' => 1, 'name' => 'service-name', 'hostId' => 1, 'commandId' => 1, 'commandArguments' => ['args1', 'args2'], 'eventHandlerArguments' => ['args3', 'args4'], 'notificationTypes' => [NotificationType::Warning, NotificationType::Critical], 'contactAdditiveInheritance' => false, 'contactGroupAdditiveInheritance' => false, 'isActivated' => true, 'activeChecks' => YesNoDefault::Yes, 'passiveCheck' => YesNoDefault::No, 'volatility' => YesNoDefault::Yes, 'checkFreshness' => YesNoDefault::No, 'eventHandlerEnabled' => YesNoDefault::Yes, 'flapDetectionEnabled' => YesNoDefault::No, 'notificationsEnabled' => YesNoDefault::Yes, 'comment' => 'some-comment', 'note' => 'some-note', 'noteUrl' => 'some-url', 'actionUrl' => 'some-action-url', 'iconAlternativeText' => 'icon-alt', 'graphTemplateId' => 12, 'serviceTemplateParentId' => 52, 'eventHandlerId' => 14, 'notificationTimePeriodId' => 65, 'checkTimePeriodId' => 82, 'iconId' => 27, 'severityId' => 16, 'maxCheckAttempts' => 3, 'normalCheckInterval' => 5, 'retryCheckInterval' => 1, 'freshnessThreshold' => 12, 'lowFlapThreshold' => 6, 'highFlapThreshold' => 8, 'notificationInterval' => 15, 'recoveryNotificationDelay' => 10, 'firstNotificationDelay' => 5, 'acknowledgementTimeout' => 20, 'geoCoords' => new GeoCoords('12.25', '46.8'), ...$fields, ] ); }); it('should return properly set service instance (all properties)', function (): void { $service = ($this->createService)(); expect($service->getName())->toBe('service-name') ->and($service->getHostId())->toBe(1) ->and($service->getCommandId())->toBe(1) ->and($service->getCommandArguments())->toBe(['args1', 'args2']) ->and($service->getEventHandlerArguments())->toBe(['args3', 'args4']) ->and($service->getNotificationTypes())->toBe([NotificationType::Warning, NotificationType::Critical]) ->and($service->isContactAdditiveInheritance())->toBe(false) ->and($service->isContactGroupAdditiveInheritance())->toBe(false) ->and($service->isActivated())->toBe(true) ->and($service->getActiveChecks())->toBe(YesNoDefault::Yes) ->and($service->getPassiveCheck())->toBe(YesNoDefault::No) ->and($service->getVolatility())->toBe(YesNoDefault::Yes) ->and($service->getCheckFreshness())->toBe(YesNoDefault::No) ->and($service->getEventHandlerEnabled())->toBe(YesNoDefault::Yes) ->and($service->getFlapDetectionEnabled())->toBe(YesNoDefault::No) ->and($service->getNotificationsEnabled())->toBe(YesNoDefault::Yes) ->and($service->getComment())->toBe('some-comment') ->and($service->getNote())->toBe('some-note') ->and($service->getNoteUrl())->toBe('some-url') ->and($service->getActionUrl())->toBe('some-action-url') ->and($service->getIconAlternativeText())->toBe('icon-alt') ->and($service->getGraphTemplateId())->toBe(12) ->and($service->getServiceTemplateParentId())->toBe(52) ->and($service->getEventHandlerId())->toBe(14) ->and($service->getNotificationTimePeriodId())->toBe(65) ->and($service->getCheckTimePeriodId())->toBe(82) ->and($service->getIconId())->toBe(27) ->and($service->getSeverityId())->toBe(16) ->and($service->getMaxCheckAttempts())->toBe(3) ->and($service->getNormalCheckInterval())->toBe(5) ->and($service->getRetryCheckInterval())->toBe(1) ->and($service->getFreshnessThreshold())->toBe(12) ->and($service->getLowFlapThreshold())->toBe(6) ->and($service->getHighFlapThreshold())->toBe(8) ->and($service->getNotificationInterval())->toBe(15) ->and($service->getRecoveryNotificationDelay())->toBe(10) ->and($service->getFirstNotificationDelay())->toBe(5) ->and($service->getAcknowledgementTimeout())->toBe(20) ->and($service->getGeoCoords()->__toString())->toBe((new GeoCoords('12.25', '46.8'))->__toString()); }); it('should return properly set host instance (mandatory properties only)', function (): void { $service = new Service(id: 1, name: 'service-name', hostId: 1); expect($service->getName())->toBe('service-name') ->and($service->getHostId())->toBe(1) ->and($service->getCommandId())->toBe(null) ->and($service->getCommandArguments())->toBe([]) ->and($service->getEventHandlerArguments())->toBe([]) ->and($service->getNotificationTypes())->toBe([]) ->and($service->isContactAdditiveInheritance())->toBe(false) ->and($service->isContactGroupAdditiveInheritance())->toBe(false) ->and($service->isActivated())->toBe(true) ->and($service->getActiveChecks())->toBe(YesNoDefault::Default) ->and($service->getPassiveCheck())->toBe(YesNoDefault::Default) ->and($service->getVolatility())->toBe(YesNoDefault::Default) ->and($service->getCheckFreshness())->toBe(YesNoDefault::Default) ->and($service->getEventHandlerEnabled())->toBe(YesNoDefault::Default) ->and($service->getFlapDetectionEnabled())->toBe(YesNoDefault::Default) ->and($service->getNotificationsEnabled())->toBe(YesNoDefault::Default) ->and($service->getComment())->toBe(null) ->and($service->getNote())->toBe(null) ->and($service->getNoteUrl())->toBe(null) ->and($service->getActionUrl())->toBe(null) ->and($service->getIconAlternativeText())->toBe(null) ->and($service->getGraphTemplateId())->toBe(null) ->and($service->getServiceTemplateParentId())->toBe(null) ->and($service->getEventHandlerId())->toBe(null) ->and($service->getNotificationTimePeriodId())->toBe(null) ->and($service->getCheckTimePeriodId())->toBe(null) ->and($service->getIconId())->toBe(null) ->and($service->getSeverityId())->toBe(null) ->and($service->getMaxCheckAttempts())->toBe(null) ->and($service->getNormalCheckInterval())->toBe(null) ->and($service->getRetryCheckInterval())->toBe(null) ->and($service->getFreshnessThreshold())->toBe(null) ->and($service->getLowFlapThreshold())->toBe(null) ->and($service->getHighFlapThreshold())->toBe(null) ->and($service->getNotificationInterval())->toBe(null) ->and($service->getRecoveryNotificationDelay())->toBe(null) ->and($service->getFirstNotificationDelay())->toBe(null) ->and($service->getAcknowledgementTimeout())->toBe(null) ->and($service->getGeoCoords())->toBe(null); }); // mandatory fields it( 'should throw an exception when service name is an empty string', fn () => ($this->createService)(['name' => ' ']) )->throws( InvalidArgumentException::class, AssertionException::notEmptyString('Service::name')->getMessage() ); // foreign keys fields foreach ( [ 'hostId', 'graphTemplateId', 'serviceTemplateParentId', 'commandId', 'eventHandlerId', 'notificationTimePeriodId', 'checkTimePeriodId', 'iconId', 'severityId', ] as $field ) { it( "should throw an exception when service {$field} is not > 0", fn () => ($this->createService)([$field => 0]) )->throws( InvalidArgumentException::class, AssertionException::positiveInt(0, "Service::{$field}")->getMessage() ); } // name and commands args should be formated it('should return trimmed and formatted name field after construct', function (): void { $service = ($this->createService)(['name' => ' service name ']); expect($service->getName())->toBe('service name'); }); foreach ( [ 'name', 'comment', 'note', 'noteUrl', 'actionUrl', 'iconAlternativeText', ] as $field ) { it( "should return trimmed field {$field} after construct", function () use ($field): void { $service = ($this->createService)([$field => ' abc ']); $valueFromGetter = $service->{'get' . $field}(); expect($valueFromGetter)->toBe('abc'); } ); } // too long fields foreach ( [ 'name' => Service::MAX_NAME_LENGTH, 'comment' => Service::MAX_COMMENT_LENGTH, 'note' => Service::MAX_NOTES_LENGTH, 'noteUrl' => Service::MAX_NOTES_URL_LENGTH, 'actionUrl' => Service::MAX_ACTION_URL_LENGTH, 'iconAlternativeText' => Service::MAX_ICON_ALT_LENGTH, ] as $field => $length ) { $tooLong = str_repeat('a', $length + 1); it( "should throw an exception when service {$field} is too long", fn () => ($this->createService)([$field => $tooLong]) )->throws( InvalidArgumentException::class, AssertionException::maxLength($tooLong, $length + 1, $length, "Service::{$field}")->getMessage() ); } // integer >= 0 field foreach ( [ 'maxCheckAttempts', 'normalCheckInterval', 'retryCheckInterval', 'freshnessThreshold', 'lowFlapThreshold', 'highFlapThreshold', 'notificationInterval', 'recoveryNotificationDelay', 'firstNotificationDelay', 'acknowledgementTimeout', ] as $field ) { it( "should throw an exception when service {$field} is not >= 0", fn () => ($this->createService)([$field => -1]) )->throws( InvalidArgumentException::class, AssertionException::min(-1, 0, "Service::{$field}")->getMessage() ); }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Infrastructure/API/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesPresenterStub.php
centreon/tests/php/Core/Service/Infrastructure/API/FindRealTimeUniqueServiceNames/FindRealTimeUniqueServiceNamesPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Infrastructure\API\FindRealTimeUniqueServiceNames; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames\FindRealTimeUniqueServiceNamesPresenterInterface; use Core\Service\Application\UseCase\FindRealTimeUniqueServiceNames\FindRealTimeUniqueServiceNamesResponse; class FindRealTimeUniqueServiceNamesPresenterStub extends AbstractPresenter implements FindRealTimeUniqueServiceNamesPresenterInterface { public ResponseStatusInterface|FindRealTimeUniqueServiceNamesResponse $response; public function presentResponse(ResponseStatusInterface|FindRealTimeUniqueServiceNamesResponse $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/Service/Infrastructure/API/FindServices/FindServicesPresenterStub.php
centreon/tests/php/Core/Service/Infrastructure/API/FindServices/FindServicesPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Infrastructure\API\FindServices; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Service\Application\UseCase\FindServices\FindServicesPresenterInterface; use Core\Service\Application\UseCase\FindServices\FindServicesResponse; class FindServicesPresenterStub extends AbstractPresenter implements FindServicesPresenterInterface { public ResponseStatusInterface|FindServicesResponse $response; public function presentResponse(ResponseStatusInterface|FindServicesResponse $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/Service/Infrastructure/API/DeleteService/DeleteServicePresenterStub.php
centreon/tests/php/Core/Service/Infrastructure/API/DeleteService/DeleteServicePresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Infrastructure\API\DeleteService; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; class DeleteServicePresenterStub extends AbstractPresenter { public ?ResponseStatusInterface $response = null; public function setResponseStatus(?ResponseStatusInterface $responseStatus): void { $this->response = $responseStatus; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false
centreon/centreon
https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Service/Infrastructure/API/DeployServices/DeployServicesPresenterStub.php
centreon/tests/php/Core/Service/Infrastructure/API/DeployServices/DeployServicesPresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Infrastructure\API\DeployServices; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Service\Application\UseCase\DeployServices\DeployServicesPresenterInterface; use Core\Service\Application\UseCase\DeployServices\DeployServicesResponse; class DeployServicesPresenterStub extends AbstractPresenter implements DeployServicesPresenterInterface { public ResponseStatusInterface|DeployServicesResponse $response; public function presentResponse(ResponseStatusInterface|DeployServicesResponse $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/Service/Infrastructure/API/AddService/AddServicePresenterStub.php
centreon/tests/php/Core/Service/Infrastructure/API/AddService/AddServicePresenterStub.php
<?php /* * Copyright 2005 - 2025 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the 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\Service\Infrastructure\API\AddService; use Core\Application\Common\UseCase\AbstractPresenter; use Core\Application\Common\UseCase\ResponseStatusInterface; use Core\Service\Application\UseCase\AddService\AddServicePresenterInterface; use Core\Service\Application\UseCase\AddService\AddServiceResponse; class AddServicePresenterStub extends AbstractPresenter implements AddServicePresenterInterface { public ResponseStatusInterface|AddServiceResponse $response; public function presentResponse(ResponseStatusInterface|AddServiceResponse $response): void { $this->response = $response; } }
php
Apache-2.0
6ae83001e94de0a4cec11e084780fcfa63f1c985
2026-01-05T04:45:18.914281Z
false