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/Common/Domain/ValueObject/LiteralStringTest.php | centreon/tests/php/Core/Common/Domain/ValueObject/LiteralStringTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain\ValueObject;
use Core\Common\Domain\ValueObject\LiteralString;
it('correct instanciation', function (): void {
$string = 'foo';
$literalString = new LiteralString($string);
expect($literalString->getValue())->toBe($string);
});
it('get value', function (): void {
$string = 'foo';
$literalString = new LiteralString($string);
expect($literalString->getValue())->toBe($string);
});
it('is empty', function (): void {
$string = '';
$literalString = new LiteralString($string);
expect($literalString->isEmpty())->toBeTrue();
});
it('length', function (): void {
$literalString = new LiteralString('foo');
expect($literalString->length())->toBe(3);
});
it('to uppercase', function (): void {
$literalString = new LiteralString('foo');
$newLiteralString = $literalString->toUpperCase();
expect($literalString)
->toBeInstanceOf(LiteralString::class)
->and($literalString->getValue())
->toBe('foo')
->and($newLiteralString)
->toBeInstanceOf(LiteralString::class)
->and($newLiteralString->getValue())
->toBe('FOO');
});
it('to lowercase', function (): void {
$literalString = new LiteralString('FOO');
$newLiteralString = $literalString->toLowerCase();
expect($literalString)
->toBeInstanceOf(LiteralString::class)
->and($literalString->getValue())
->toBe('FOO')
->and($newLiteralString)
->toBeInstanceOf(LiteralString::class)
->and($newLiteralString->getValue())
->toBe('foo');
});
it('trim', function (): void {
$literalString = new LiteralString(' foo ');
$newLiteralString = $literalString->trim();
expect($literalString)
->toBeInstanceOf(LiteralString::class)
->and($literalString->getValue())
->toBe(' foo ')
->and($newLiteralString)
->toBeInstanceOf(LiteralString::class)
->and($newLiteralString->getValue())
->toBe('foo');
});
it('starts with', function (): void {
$literalString = new LiteralString('foo');
expect($literalString->startsWith('f'))->toBeTrue();
});
it('not starts with', function (): void {
$literalString = new LiteralString('foo');
expect($literalString->startsWith('bar'))->toBeFalse();
});
it('ends with', function (): void {
$literalString = new LiteralString('foo');
expect($literalString->endsWith('o'))->toBeTrue();
});
it('not ends with', function (): void {
$literalString = new LiteralString('foo');
expect($literalString->endsWith('bar'))->toBeFalse();
});
it('replace', function (): void {
$literalString = new LiteralString('foo');
$newLiteralString = $literalString->replace('foo', 'bar');
expect($literalString)
->toBeInstanceOf(LiteralString::class)
->and($literalString->getValue())
->toBe('foo')
->and($newLiteralString)
->toBeInstanceOf(LiteralString::class)
->and($newLiteralString->getValue())
->toBe('bar');
});
it('contains', function (): void {
$literalString = new LiteralString('foo');
expect($literalString->contains('o'))->toBeTrue();
});
it('not contains', function (): void {
$literalString = new LiteralString('foo');
expect($literalString->contains('bar'))->toBeFalse();
});
it('append', function (): void {
$literalString = new LiteralString('foo');
$newLiteralString = $literalString->append('bar');
expect($literalString)
->toBeInstanceOf(LiteralString::class)
->and($literalString->getValue())
->toBe('foo')
->and($newLiteralString)
->toBeInstanceOf(LiteralString::class)
->and($newLiteralString->getValue())
->toBe('foobar');
});
it('equal', function (): void {
$literalString1 = new LiteralString('foo');
$literalString2 = new LiteralString('foo');
expect($literalString1->equals($literalString2))->toBeTrue();
});
it('not equal', function (): void {
$literalString1 = new LiteralString('foo');
$literalString2 = new LiteralString('bar');
expect($literalString1->equals($literalString2))->toBeFalse();
});
it('equal with incorrect type', function (): void {
$literalString1 = new LiteralString('foo');
$dateTime = new \DateTime();
$literalString1->equals($dateTime);
})->throws(\TypeError::class);
it('magic method toString', function (): void {
$literalString = new LiteralString('foo');
expect("{$literalString}")->toBe('foo');
});
it('json serialize', function (): void {
$literalString = new LiteralString('foo');
expect($literalString->jsonSerialize())->toBe('foo');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Domain/ValueObject/Web/IpAddressTest.php | centreon/tests/php/Core/Common/Domain/ValueObject/Web/IpAddressTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain\ValueObject\Web;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Domain\ValueObject\Identity\Email;
use Core\Common\Domain\ValueObject\Web\IpAddress;
it('with valid IPv4', function (): void {
$string = '170.0.0.1';
$ipAddress = new IpAddress($string);
expect($ipAddress->getValue())->toBe($string);
});
it('with valid IPv6', function (): void {
$string = '2001:0db8:85a3:0000:0000:8a2e:0370:7334';
$ipAddress = new IpAddress($string);
expect($ipAddress->getValue())->toBe($string);
});
it('with invalid IPv6', function (): void {
$string = '2001:0db8:85a3:0000:0000:8a2e:0370';
$ipAddress = new IpAddress($string);
})->throws(ValueObjectException::class);
it('with an incorrect ip address', function (): void {
$string = 'yoyo';
$ipAddress = new IpAddress($string);
})->throws(ValueObjectException::class);
it('is not empty', function (): void {
$string = '170.0.0.1';
$ipAddress = new IpAddress($string);
expect($ipAddress->isEmpty())->toBeFalse();
});
it('is empty', function (): void {
$string = '';
$ipAddress = new IpAddress($string);
})->throws(ValueObjectException::class);
it('starts with', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
expect($ipAddress->startsWith('170'))->toBeTrue();
});
it('not starts with', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
expect($ipAddress->startsWith('200'))->toBeFalse();
});
it('ends with', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
expect($ipAddress->endsWith('.1'))->toBeTrue();
});
it('not ends with', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
expect($ipAddress->endsWith('.180'))->toBeFalse();
});
it('replace', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
$newIpAddress = $ipAddress->replace('170', '200');
expect($ipAddress)
->toBeInstanceOf(IpAddress::class)
->and($ipAddress->getValue())
->toBe('170.0.0.1')
->and($newIpAddress)
->toBeInstanceOf(IpAddress::class)
->and($newIpAddress->getValue())
->toBe('200.0.0.1');
});
it('contains', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
expect($ipAddress->contains('0.1'))->toBeTrue();
});
it('not contains', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
expect($ipAddress->contains('0.3'))->toBeFalse();
});
it('append', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
$newIpAddress = $ipAddress->append('82');
expect($ipAddress)
->toBeInstanceOf(IpAddress::class)
->and($ipAddress->getValue())
->toBe('170.0.0.1')
->and($newIpAddress)
->toBeInstanceOf(IpAddress::class)
->and($newIpAddress->getValue())
->toBe('170.0.0.182');
});
it('length', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
expect($ipAddress->length())->toBe(9);
});
it('equal', function (): void {
$IpAddress1 = new IpAddress('170.0.0.1');
$IpAddress2 = new IpAddress('170.0.0.1');
expect($IpAddress1->equals($IpAddress2))->toBeTrue();
});
it('not equal', function (): void {
$IpAddress1 = new IpAddress('170.0.0.1');
$IpAddress2 = new IpAddress('170.0.0.2');
expect($IpAddress1->equals($IpAddress2))->toBeFalse();
});
it('equal with incorrect type', function (): void {
$IpAddress1 = new IpAddress('170.0.0.1');
$IpAddress2 = new \DateTime();
$IpAddress1->equals($IpAddress2);
})->throws(\TypeError::class);
it('equal with incorrect value object type', function (): void {
$IpAddress1 = new IpAddress('170.0.0.1');
$IpAddress2 = new Email('yoyo@toto.fr');
$IpAddress1->equals($IpAddress2);
})->throws(ValueObjectException::class);
it('magic method toString', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
expect("{$ipAddress}")->toBe('170.0.0.1');
});
it('json serialize', function (): void {
$ipAddress = new IpAddress('170.0.0.1');
expect($ipAddress->jsonSerialize())->toBe('170.0.0.1');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Domain/ValueObject/Identity/EmailTest.php | centreon/tests/php/Core/Common/Domain/ValueObject/Identity/EmailTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain\ValueObject\Identity;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Domain\ValueObject\Identity\Email;
use Core\Common\Domain\ValueObject\Web\IpAddress;
it('is correct', function (): void {
$string = 'yoyo@toto.fr';
$email = new Email($string);
expect($email->getValue())->toBe($string);
});
it('with special characters', function (): void {
$email = new Email('user+tag@example.com');
expect($email->getValue())->toBe('user+tag@example.com');
});
it('with quoted local part', function (): void {
$email = new Email('"test.email"@example.com');
expect($email->getValue())->toBe('"test.email"@example.com');
});
it('with an incorrect email', function (): void {
$string = 'yoyo';
$email = new Email($string);
})->throws(ValueObjectException::class);
it('get value', function (): void {
$string = 'yoyo@toto.fr';
$email = new Email($string);
expect($email->getValue())->toBe($string);
});
it('is not empty', function (): void {
$string = 'yoyo@toto.fr';
$email = new Email($string);
expect($email->isEmpty())->toBeFalse();
});
it('is empty', function (): void {
$string = '';
$email = new Email($string);
})->throws(ValueObjectException::class);
it('length', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->length())->toBe(12);
});
it('to uppercase', function (): void {
$email = new Email('yoyo@toto.fr');
$newEmail = $email->toUpperCase();
expect($email)
->toBeInstanceOf(Email::class)
->and($email->getValue())
->toBe('yoyo@toto.fr')
->and($newEmail)
->toBeInstanceOf(Email::class)
->and($newEmail->getValue())
->toBe('YOYO@TOTO.FR');
});
it('to lowercase', function (): void {
$email = new Email('YOYO@TOTO.FR');
$newEmail = $email->toLowerCase();
expect($email)
->toBeInstanceOf(Email::class)
->and($email->getValue())
->toBe('YOYO@TOTO.FR')
->and($newEmail)
->toBeInstanceOf(Email::class)
->and($newEmail->getValue())
->toBe('yoyo@toto.fr');
});
it('starts with', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->startsWith('yoyo'))->toBeTrue();
});
it('not starts with', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->startsWith('bar'))->toBeFalse();
});
it('ends with', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->endsWith('fr'))->toBeTrue();
});
it('not ends with', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->endsWith('bar'))->toBeFalse();
});
it('replace', function (): void {
$email = new Email('yoyo@toto.fr');
$newEmail = $email->replace('yoyo', 'yaya');
expect($email)
->toBeInstanceOf(Email::class)
->and($email->getValue())
->toBe('yoyo@toto.fr')
->and($newEmail)
->toBeInstanceOf(Email::class)
->and($newEmail->getValue())
->toBe('yaya@toto.fr');
});
it('contains', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->contains('yoyo'))->toBeTrue();
});
it('not contains', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->contains('bar'))->toBeFalse();
});
it('append', function (): void {
$email = new Email('yoyo@toto.fr');
$newEmail = $email->append('ance');
expect($email)
->toBeInstanceOf(Email::class)
->and($email->getValue())
->toBe('yoyo@toto.fr')
->and($newEmail)
->toBeInstanceOf(Email::class)
->and($newEmail->getValue())
->toBe('yoyo@toto.france');
});
it('equal', function (): void {
$email1 = new Email('yoyo@toto.fr');
$email2 = new Email('yoyo@toto.fr');
expect($email1->equals($email2))->toBeTrue();
});
it('not equal', function (): void {
$email1 = new Email('yoyo@toto.fr');
$email2 = new Email('yoyo@toto.com');
expect($email1->equals($email2))->toBeFalse();
});
it('equal with incorrect type', function (): void {
$email = new Email('yoyo@toto.fr');
$dateTime = new \DateTime();
$email->equals($dateTime);
})->throws(\TypeError::class);
it('equal with incorrect value object type', function (): void {
$email = new Email('yoyo@toto.fr');
$ipAddress = new IpAddress('170.0.0.1');
$email->equals($ipAddress);
})->throws(ValueObjectException::class);
it('magic method toString', function (): void {
$email = new Email('yoyo@toto.fr');
expect("{$email}")->toBe('yoyo@toto.fr');
});
it('get local part', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->getLocalPart()->getValue())->toBe('yoyo');
});
it('get domain part', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->getDomainPart()->getValue())->toBe('toto.fr');
});
it('json serialize', function (): void {
$email = new Email('yoyo@toto.fr');
expect($email->jsonSerialize())->toBe('yoyo@toto.fr');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Domain/Exception/ExceptionFormatterTest.php | centreon/tests/php/Core/Common/Domain/Exception/ExceptionFormatterTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain\Exception;
use Core\Common\Domain\Exception\ExceptionFormatter;
use Core\Common\Domain\Exception\RepositoryException;
it('test format native exception without previous', function (): void {
$exception = new \LogicException('logic_exception_message', 99);
$format = ExceptionFormatter::format($exception);
expect($format)->toBeArray()
->and($format)->toHaveKey('type')
->and($format['type'])->toBe('LogicException')
->and($format)->toHaveKey('message')
->and($format['message'])->toBe('logic_exception_message')
->and($format)->toHaveKey('file')
->and($format['file'])->toBe(__FILE__)
->and($format)->toHaveKey('line')
->and($format['line'])->toBe(__LINE__ - 10)
->and($format)->toHaveKey('code')
->and($format['code'])->toBe(99)
->and($format)->toHaveKey('class')
->and($format['class'])->toBe('P\\Tests\\php\\Core\\Common\\Domain\\Exception\\ExceptionFormatterTest')
->and($format)->toHaveKey('method')
->and($format['method'])->toBe('Tests\\Core\\Common\\Domain\\Exception\\{closure}')
->and($format)->toHaveKey('previous')
->and($format['previous'])->toBeNull();
});
it('test format business logic exception without previous', function (): void {
$exception = new RepositoryException('repository_exception_message');
$format = ExceptionFormatter::format($exception);
expect($format)->toBeArray()
->and($format)->toHaveKey('type')
->and($format['type'])->toBe(RepositoryException::class)
->and($format)->toHaveKey('message')
->and($format['message'])->toBe('repository_exception_message')
->and($format)->toHaveKey('file')
->and($format['file'])->toBe(__FILE__)
->and($format)->toHaveKey('line')
->and($format['line'])->toBe(__LINE__ - 10)
->and($format)->toHaveKey('code')
->and($format['code'])->toBe(1)
->and($format)->toHaveKey('class')
->and($format['class'])->toBe('P\\Tests\\php\\Core\\Common\\Domain\\Exception\\ExceptionFormatterTest')
->and($format)->toHaveKey('method')
->and($format['method'])->toBe('Tests\\Core\\Common\\Domain\\Exception\\{closure}')
->and($format)->toHaveKey('previous')
->and($format['previous'])->toBeNull();
});
it('test format business logic exception without previous with context', function (): void {
$exception = new RepositoryException('repository_exception_message', ['contact' => 1, 'name' => 'John']);
$format = ExceptionFormatter::format($exception);
expect($format)->toBeArray()
->and($format)->toHaveKey('type')
->and($format['type'])->toBe(RepositoryException::class)
->and($format)->toHaveKey('message')
->and($format['message'])->toBe('repository_exception_message')
->and($format)->toHaveKey('file')
->and($format['file'])->toBe(__FILE__)
->and($format)->toHaveKey('line')
->and($format['line'])->toBe(__LINE__ - 10)
->and($format)->toHaveKey('code')
->and($format['code'])->toBe(1)
->and($format)->toHaveKey('class')
->and($format['class'])->toBe('P\\Tests\\php\\Core\\Common\\Domain\\Exception\\ExceptionFormatterTest')
->and($format)->toHaveKey('method')
->and($format['method'])->toBe('Tests\\Core\\Common\\Domain\\Exception\\{closure}')
->and($format)->toHaveKey('previous')
->and($format['previous'])->toBeNull();
});
it('test format business logic exception with previous', function (): void {
$exception = new RepositoryException(
'repository_exception_message',
previous: new \LogicException(
'logic_exception_message',
99
)
);
$format = ExceptionFormatter::format($exception);
expect($format)->toBeArray()
->and($format)->toHaveKey('type')
->and($format['type'])->toBe(RepositoryException::class)
->and($format)->toHaveKey('message')
->and($format['message'])->toBe('repository_exception_message')
->and($format)->toHaveKey('file')
->and($format['file'])->toBe(__FILE__)
->and($format)->toHaveKey('line')
->and($format['line'])->toBe(__LINE__ - 16)
->and($format)->toHaveKey('code')
->and($format['code'])->toBe(1)
->and($format)->toHaveKey('class')
->and($format['class'])->toBe('P\\Tests\\php\\Core\\Common\\Domain\\Exception\\ExceptionFormatterTest')
->and($format)->toHaveKey('method')
->and($format['method'])->toBe('Tests\\Core\\Common\\Domain\\Exception\\{closure}')
->and($format)->toHaveKey('previous')
->and($format['previous'])->toBeArray()
->and($format['previous'])->toHaveKey('type')
->and($format['previous']['type'])->toBe('LogicException')
->and($format['previous'])->toHaveKey('message')
->and($format['previous']['message'])->toBe('logic_exception_message')
->and($format['previous'])->toHaveKey('file')
->and($format['previous']['file'])->toBe(__FILE__)
->and($format['previous'])->toHaveKey('line')
->and($format['previous']['line'])->toBe(__LINE__ - 30)
->and($format['previous'])->toHaveKey('code')
->and($format['previous']['code'])->toBe(99)
->and($format['previous'])->toHaveKey('class')
->and($format['previous']['class'])->toBe(
'P\\Tests\\php\\Core\\Common\\Domain\\Exception\\ExceptionFormatterTest'
)
->and($format['previous'])->toHaveKey('method')
->and($format['previous']['method'])->toBe('Tests\\Core\\Common\\Domain\\Exception\\{closure}')
->and($format['previous'])->toHaveKey('previous')
->and($format['previous']['previous'])->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/Common/Domain/Exception/BusinessLogicExceptionTest.php | centreon/tests/php/Core/Common/Domain/Exception/BusinessLogicExceptionTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Domain\Exception;
use Core\Common\Domain\Exception\BusinessLogicException;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use LogicException;
it('test with a basic context from a repository exception', function (): void {
try {
throw new LogicException('logic_message', 100);
} catch (LogicException $logicException) {
try {
throw new RepositoryException(
message: 'repository_message',
context: ['name' => 'John', 'age' => 42],
previous: $logicException
);
} catch (BusinessLogicException $exception) {
expect($exception->getMessage())->toBe('repository_message')
->and($exception->getCode())->toBe(1)
->and($exception->getPrevious())->toBeInstanceOf(LogicException::class)
->and($exception->getContext())->toBeArray()
->and($exception->getContext())->toBe(
[
'type' => RepositoryException::class,
'message' => 'repository_message',
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'code' => 1,
'class' => 'P\Tests\php\Core\Common\Domain\Exception\BusinessLogicExceptionTest',
'method' => 'Tests\Core\Common\Domain\Exception\{closure}',
'previous' => [
'type' => LogicException::class,
'message' => 'logic_message',
'file' => $exception->getPrevious()->getFile(),
'line' => $exception->getPrevious()->getLine(),
'code' => 100,
'class' => 'P\Tests\php\Core\Common\Domain\Exception\BusinessLogicExceptionTest',
'method' => 'Tests\Core\Common\Domain\Exception\{closure}',
'previous' => null,
],
'context' => [
'name' => 'John',
'age' => 42,
'previous' => null,
],
]
);
}
}
});
it('test with a business context from a repository exception', function (): void {
try {
throw new CollectionException('collection_message', ['name' => 'Anna', 'age' => 25]);
} catch (CollectionException $collectionException) {
try {
throw new RepositoryException(
message: 'repository_message',
context: ['name' => 'John', 'age' => 42],
previous: $collectionException
);
} catch (BusinessLogicException $exception) {
expect($exception->getMessage())->toBe('repository_message')
->and($exception->getCode())->toBe(1)
->and($exception->getPrevious())->toBeInstanceOf(CollectionException::class)
->and($exception->getContext())->toBeArray()
->and($exception->getContext())->toBe(
[
'type' => RepositoryException::class,
'message' => 'repository_message',
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'code' => 1,
'class' => 'P\Tests\php\Core\Common\Domain\Exception\BusinessLogicExceptionTest',
'method' => 'Tests\Core\Common\Domain\Exception\{closure}',
'previous' => [
'type' => CollectionException::class,
'message' => 'collection_message',
'file' => $exception->getPrevious()->getFile(),
'line' => $exception->getPrevious()->getLine(),
'code' => 0,
'class' => 'P\Tests\php\Core\Common\Domain\Exception\BusinessLogicExceptionTest',
'method' => 'Tests\Core\Common\Domain\Exception\{closure}',
'previous' => null,
],
'context' => [
'name' => 'John',
'age' => 42,
'previous' => [
'name' => 'Anna',
'age' => 25,
'previous' => null,
],
],
]
);
}
}
});
it('test with a business context with previous from a repository exception', function (): void {
try {
try {
throw new LogicException('logic_message', 100);
} catch (LogicException $logicException) {
throw new CollectionException(
message: 'collection_message',
context: ['name' => 'Anna', 'age' => 25],
previous: $logicException
);
}
} catch (CollectionException $collectionException) {
try {
throw new RepositoryException(
message: 'repository_message',
context: ['name' => 'John', 'age' => 42],
previous: $collectionException
);
} catch (BusinessLogicException $exception) {
expect($exception->getMessage())->toBe('repository_message')
->and($exception->getCode())->toBe(1)
->and($exception->getPrevious())->toBeInstanceOf(CollectionException::class)
->and($exception->getContext())->toBeArray()
->and($exception->getContext())->toBe(
[
'type' => RepositoryException::class,
'message' => 'repository_message',
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'code' => 1,
'class' => 'P\Tests\php\Core\Common\Domain\Exception\BusinessLogicExceptionTest',
'method' => 'Tests\Core\Common\Domain\Exception\{closure}',
'previous' => [
'type' => CollectionException::class,
'message' => 'collection_message',
'file' => $exception->getPrevious()->getFile(),
'line' => $exception->getPrevious()->getLine(),
'code' => 0,
'class' => 'P\Tests\php\Core\Common\Domain\Exception\BusinessLogicExceptionTest',
'method' => 'Tests\Core\Common\Domain\Exception\{closure}',
'previous' => [
'type' => LogicException::class,
'message' => 'logic_message',
'file' => $exception->getPrevious()->getPrevious()->getFile(),
'line' => $exception->getPrevious()->getPrevious()->getLine(),
'code' => 100,
'class' => 'P\Tests\php\Core\Common\Domain\Exception\BusinessLogicExceptionTest',
'method' => 'Tests\Core\Common\Domain\Exception\{closure}',
'previous' => null,
],
],
'context' => [
'name' => 'John',
'age' => 42,
'previous' => [
'name' => 'Anna',
'age' => 25,
'previous' => null,
],
],
]
);
}
}
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/FeatureFlagsTest.php | centreon/tests/php/Core/Common/Infrastructure/FeatureFlagsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Infrastructure;
use Core\Common\Infrastructure\FeatureFlags;
it(
'should be ok for On-Prem',
fn (string $json, array $expected) => expect((new FeatureFlags(false, $json))->getAll())
->toBe($expected)
)->with([
['not-a-valid-json', []],
['{"foo": 0}', ['foo' => false]],
['{"foo": 1}', ['foo' => true]],
['{"foo": 2}', ['foo' => false]],
['{"foo": 3}', ['foo' => true]],
]);
it(
'should be ok for Cloud',
fn (string $json, array $expected) => expect((new FeatureFlags(true, $json))->getAll())
->toBe($expected)
)->with([
['not-a-valid-json', []],
['{"foo": 0}', ['foo' => false]],
['{"foo": 1}', ['foo' => false]],
['{"foo": 2}', ['foo' => true]],
['{"foo": 3}', ['foo' => true]],
]);
it(
'should be false by default for not existing features',
fn () => expect((new FeatureFlags(false, '{}'))->isEnabled('not-existing'))
->toBe(false)
);
it(
'should ignore wrong feature bitmask value',
fn (string $json) => expect((new FeatureFlags(false, $json))->getAll())->toBe([])
)->with([
['{"foo": null}'],
['{"foo": true}'],
['{"foo": 3.14}'],
['{"foo": "abc"}'],
['{"foo": [1, 2, 3]}'],
['{"foo": {"bar": 123}}'],
]);
it(
'should ignore wrong feature name considered as integer',
fn (int $int) => expect((new FeatureFlags(false, '{"' . $int . '": 1, "i' . $int . '": 1}'))->getAll())
->toBe(['i' . $int => true])
)->with([
[0],
[42],
[-66],
]);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/ExceptionLogger/ExceptionLoggerTest.php | centreon/tests/php/Core/Common/Infrastructure/ExceptionLogger/ExceptionLoggerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Infrastructure\ExceptionLogger;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Psr\Log\LogLevel;
beforeEach(function (): void {
$this->logFilePath = __DIR__ . '/log';
$this->logFileName = 'test.log';
$this->logPathFileName = $this->logFilePath . '/test.log';
if (! file_exists($this->logFilePath)) {
mkdir($this->logFilePath);
}
$this->logger = new LoggerStub($this->logPathFileName);
$this->exceptionLogger = new ExceptionLogger($this->logger);
});
afterEach(function (): void {
if (file_exists($this->logPathFileName)) {
expect(unlink($this->logPathFileName))->toBeTrue();
$successDeleteFile = rmdir($this->logFilePath);
expect($successDeleteFile)->toBeTrue();
}
});
it('test log a native exception', function (): void {
$this->exceptionLogger->log(new \LogicException('logic_exception_message'));
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'{"custom":null,"exception":{"exceptions":[{"type":"LogicException","message":"logic_exception_message","file":"' . __FILE__ . '","line":' . (__LINE__ - 4) . ',"code":0,"class":"P\\\\Tests\\\\php\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\ExceptionLoggerTest","method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\{closure}"}],"traces":[{"'
);
});
it('test log an exception that extends BusinessLogicException without context and previous', function (): void {
$this->exceptionLogger->log(new RepositoryException('repository_exception_message'));
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'{"custom":{"from_exception":[]},"exception":{"exceptions":[{"type":"Core\\\\Common\\\\Domain\\\\Exception\\\\RepositoryException","message":"repository_exception_message","file":"' . __FILE__ . '","line":' . (__LINE__ - 4) . ',"code":1,"class":"P\\\\Tests\\\\php\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\ExceptionLoggerTest","method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\{closure}"}],"traces":[{"'
);
});
it('test log an exception that extends BusinessLogicException with context without previous', function (): void {
$this->exceptionLogger->log(new RepositoryException('repository_exception_message', ['contact' => 1]));
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'{"custom":{"from_exception":[{"contact":1}]},"exception":{"exceptions":[{"type":"Core\\\\Common\\\\Domain\\\\Exception\\\\RepositoryException","message":"repository_exception_message","file":"' . __FILE__ . '","line":' . (__LINE__ - 4) . ',"code":1,"class":"P\\\\Tests\\\\php\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\ExceptionLoggerTest","method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\{closure}"}],"traces":[{"'
);
});
it(
'test log an exception that extends BusinessLogicException with context with a previous (native exception)',
function (): void {
$this->exceptionLogger->log(
new RepositoryException(
'repository_exception_message',
['contact' => 1],
new \LogicException('logic_exception_message')
)
);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'{"custom":{"from_exception":[{"contact":1}]},"exception":{"exceptions":[{"type":"Core\\\\Common\\\\Domain\\\\Exception\\\\RepositoryException","message":"repository_exception_message","file":"' . __FILE__ . '","line":' . (__LINE__ - 9) . ',"code":1,"class":"P\\\\Tests\\\\php\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\ExceptionLoggerTest","method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\{closure}"},{"type":"LogicException","message":"logic_exception_message","file":"' . __FILE__ . '","line":' . (__LINE__ - 6) . ',"code":0,"class":"P\\\\Tests\\\\php\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\ExceptionLoggerTest","method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\{closure}"}],"traces":[{"'
);
}
);
it(
'test log an exception that extends BusinessLogicException with context and a previous that extends a BusinessLogicException',
function (): void {
$this->exceptionLogger->log(
new RepositoryException(
'repository_exception_message',
['contact' => 1],
new RepositoryException('repository_exception_message_2')
)
);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'{"custom":{"from_exception":[{"contact":1}]},"exception":{"exceptions":[{"type":"Core\\\\Common\\\\Domain\\\\Exception\\\\RepositoryException","message":"repository_exception_message","file":"' . __FILE__ . '","line":' . (__LINE__ - 9) . ',"code":1,"class":"P\\\\Tests\\\\php\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\ExceptionLoggerTest","method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\{closure}"},{"type":"Core\\\\Common\\\\Domain\\\\Exception\\\\RepositoryException","message":"repository_exception_message_2","file":"' . __FILE__ . '","line":' . (__LINE__ - 6) . ',"code":1,"class":"P\\\\Tests\\\\php\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\ExceptionLoggerTest","method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\{closure}"}],"traces":[{"'
);
}
);
it(
'test log an exception that extends BusinessLogicException with context and a previous that extends a BusinessLogicException which has context',
function (): void {
$this->exceptionLogger->log(
new RepositoryException(
'repository_exception_message',
['contact' => 1],
new RepositoryException('repository_exception_message_2', ['contact' => 2])
)
);
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain(
'{"custom":{"from_exception":[{"contact":1},{"contact":2}]},"exception":{"exceptions":[{"type":"Core\\\\Common\\\\Domain\\\\Exception\\\\RepositoryException","message":"repository_exception_message","file":"' . __FILE__ . '","line":' . (__LINE__ - 9) . ',"code":1,"class":"P\\\\Tests\\\\php\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\ExceptionLoggerTest","method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\{closure}"},{"type":"Core\\\\Common\\\\Domain\\\\Exception\\\\RepositoryException","message":"repository_exception_message_2","file":"' . __FILE__ . '","line":' . (__LINE__ - 6) . ',"code":1,"class":"P\\\\Tests\\\\php\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\ExceptionLoggerTest","method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\{closure}"}],"traces":[{"'
);
}
);
it(
'test log an exception that extends BusinessLogicException with context and a previous that extends a BusinessLogicException which has context and a previous exception',
function (): void {
function testExceptionLogger(int $int, string $string): void
{
throw new RepositoryException(
'repository_exception_message',
['contact' => 1],
new RepositoryException(
'repository_exception_message_2',
['contact' => 2],
new \LogicException('logic_exception_message')
)
);
}
try {
testExceptionLogger(1, 'string');
} catch (RepositoryException $e) {
$this->exceptionLogger->log($e, ['name' => 'John Doe', 'age' => 42], LogLevel::CRITICAL);
}
expect(file_exists($this->logPathFileName))->toBeTrue();
$contentLog = file_get_contents($this->logPathFileName);
expect($contentLog)->toContain('test_exception_logger.CRITICAL: repository_exception_message')
->and($contentLog)->toContain('{"custom":{"name":"John Doe","age":42,"from_exception":[{"contact":1},{"contact":2}]},"exception":{"exceptions":[{"type":"Core\\\\Common\\\\Domain\\\\Exception\\\\RepositoryException","message":"repository_exception_message","file":"' . __FILE__ . '","line":' . (__LINE__ - 19) . ',"code":1,"class":null,"method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\testExceptionLogger"},{"type":"Core\\\\Common\\\\Domain\\\\Exception\\\\RepositoryException","message":"repository_exception_message_2","file":"' . __FILE__ . '","line":' . (__LINE__ - 16) . ',"code":1,"class":null,"method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\testExceptionLogger"},{"type":"LogicException","message":"logic_exception_message","file":"' . __FILE__ . '","line":' . (__LINE__ - 13) . ',"code":0,"class":null,"method":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\testExceptionLogger"}],"traces":[{"file":"' . __FILE__ . '","line":' . (__LINE__ - 8) . ',"function":"Tests\\\\Core\\\\Common\\\\Infrastructure\\\\ExceptionLogger\\\\testExceptionLogger"}');
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/ExceptionLogger/LoggerStub.php | centreon/tests/php/Core/Common/Infrastructure/ExceptionLogger/LoggerStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Infrastructure\ExceptionLogger;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\ContactForDebug;
use Centreon\Domain\Log\LoggerTrait;
use Mockery;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
/**
* Class
*
* @class LoggerStub
* @package Tests\Centreon\Domain\Log
*/
class LoggerStub implements LoggerInterface
{
use LoggerTrait {
emergency as traitEmergency;
alert as traitAlert;
critical as traitCritical;
error as traitError;
warning as traitWarning;
notice as traitNotice;
info as traitInfo;
debug as traitDebug;
log as traitLog;
}
/** @var Logger */
private Logger $monolog;
/** @var string */
private string $logPathFileName;
/**
* LoggerStub constructor
*
* @param string $logPathFileName
*/
public function __construct(string $logPathFileName)
{
$this->monolog = new Logger('test_exception_logger');
$this->monolog->pushHandler(new StreamHandler($logPathFileName));
$this->setLogger($this->monolog);
$this->loggerContact = Mockery::mock(ContactInterface::class);
$this->loggerContactForDebug = Mockery::mock(ContactForDebug::class);
$this->loggerContactForDebug->shouldReceive('isValidForContact')->andReturnTrue();
}
/**
* Factory
*
* @param string $logPathFileName
*
* @return LoggerInterface
*/
public static function create(string $logPathFileName): LoggerInterface
{
return new self($logPathFileName);
}
/**
* @inheritDoc
*/
public function emergency(string|\Stringable $message, array $context = []): void
{
$this->traitEmergency($message, $context);
}
/**
* @inheritDoc
*/
public function alert(string|\Stringable $message, array $context = []): void
{
$this->traitAlert($message, $context);
}
/**
* @inheritDoc
*/
public function critical(string|\Stringable $message, array $context = []): void
{
$this->traitCritical($message, $context);
}
/**
* @inheritDoc
*/
public function error(string|\Stringable $message, array $context = []): void
{
$this->traitError($message, $context);
}
/**
* @inheritDoc
*/
public function warning(string|\Stringable $message, array $context = []): void
{
$this->traitWarning($message, $context);
}
/**
* @inheritDoc
*/
public function notice(string|\Stringable $message, array $context = []): void
{
$this->traitNotice($message, $context);
}
/**
* @inheritDoc
*/
public function info(string|\Stringable $message, array $context = []): void
{
$this->traitInfo($message, $context);
}
/**
* @inheritDoc
*/
public function debug(string|\Stringable $message, array $context = []): void
{
$this->traitDebug($message, $context);
}
/**
* @inheritDoc
*/
public function log($level, string|\Stringable $message, array $context = []): void
{
$this->traitLog($level, $message, $context);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/Upload/ZipFileIteratorTest.php | centreon/tests/php/Core/Common/Infrastructure/Upload/ZipFileIteratorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Infrastructure\Upload;
use Core\Common\Infrastructure\Upload\ZipFileIterator;
use Symfony\Component\HttpFoundation\File\File;
it('should iterate on each files of ZIP archive', function (): void {
$fileIterator = new ZipFileIterator(new File(__DIR__ . DIRECTORY_SEPARATOR . 'archive.zip'));
foreach ($fileIterator as $filename => $contentFile) {
echo null; // To ensure that we can iterate several times
}
$files = [];
foreach ($fileIterator as $filename => $contentFile) {
/** @var list<array{filename: string, md5: string}> $files */
$files[] = [
'filename' => $filename,
'md5' => md5($contentFile),
];
}
expect($fileIterator)->toHaveCount(2)
->and($files)->toHaveCount(2)
->and($files[0]['filename'])->toEqual('logo_in_archive.jpg')
->and($files[0]['md5'])->toEqual('f7d5fc06a33946703054046c7174bbf4')
->and($files[1]['filename'])->toEqual('logo_in_archive.svg')
->and($files[1]['md5'])->toEqual('50dfb12940f9b30ad4d961ad92b3569b');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/Upload/CommonFileIteratorTest.php | centreon/tests/php/Core/Common/Infrastructure/Upload/CommonFileIteratorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Infrastructure\Upload;
use Core\Common\Infrastructure\Upload\CommonFileIterator;
use Symfony\Component\HttpFoundation\File\UploadedFile;
it('should iterate on each files', function (): void {
$fileIterator = new CommonFileIterator();
$fileIterator->addFile(new UploadedFile(__DIR__ . DIRECTORY_SEPARATOR . 'logo.jpg', 'logo.jpg'));
$fileIterator->addFile(new UploadedFile(__DIR__ . DIRECTORY_SEPARATOR . 'logo.svg', 'logo.svg'));
$files = [];
foreach ($fileIterator as $filename => $contentFile) {
echo null; // To ensure that we can iterate several times
}
foreach ($fileIterator as $filename => $contentFile) {
/** @var list<array{filename: string, md5: string}> $files */
$files[] = [
'filename' => $filename,
'md5' => md5($contentFile),
];
}
expect($fileIterator)->toHaveCount(2)
->and($files)->toHaveCount(2)
->and($files[0]['filename'])->toEqual('logo.jpg')
->and($files[0]['md5'])->toEqual('f7d5fc06a33946703054046c7174bbf4')
->and($files[1]['filename'])->toEqual('logo.svg')
->and($files[1]['md5'])->toEqual('50dfb12940f9b30ad4d961ad92b3569b');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/Upload/FileIteratorTest.php | centreon/tests/php/Core/Common/Infrastructure/Upload/FileIteratorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Infrastructure\Upload;
use Core\Common\Infrastructure\Upload\FileCollection;
use Symfony\Component\HttpFoundation\File\UploadedFile;
it('should iterate on each files of ZIP archive and others', function (): void {
$fileManager = new FileCollection();
$fileManager->addFile(new UploadedFile(__DIR__ . DIRECTORY_SEPARATOR . 'archive.zip', 'archive.zip'));
$fileManager->addFile(new UploadedFile(__DIR__ . DIRECTORY_SEPARATOR . 'logo.jpg', 'logo.jpg'));
$fileManager->addFile(new UploadedFile(__DIR__ . DIRECTORY_SEPARATOR . 'logo.svg', 'logo.svg'));
foreach ($fileManager->getFiles() as $filename => $contentFile) {
echo null; // To ensure that we can iterate several times
}
$files = [];
foreach ($fileManager->getFiles() as $filename => $contentFile) {
/** @var list<array{filename: string, md5: string}> $files */
$files[] = [
'filename' => $filename,
'md5' => md5($contentFile),
];
}
expect($files)->toHaveCount(4)
->and($files[0]['filename'])->toEqual('logo.jpg')
->and($files[0]['md5'])->toEqual('f7d5fc06a33946703054046c7174bbf4')
->and($files[1]['filename'])->toEqual('logo.svg')
->and($files[1]['md5'])->toEqual('50dfb12940f9b30ad4d961ad92b3569b')
->and($files[2]['filename'])->toEqual('logo_in_archive.jpg')
->and($files[2]['md5'])->toEqual('f7d5fc06a33946703054046c7174bbf4')
->and($files[3]['filename'])->toEqual('logo_in_archive.svg')
->and($files[3]['md5'])->toEqual('50dfb12940f9b30ad4d961ad92b3569b');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/RequestParameters/Transformer/SearchRequestParametersTransformerTest.php | centreon/tests/php/Core/Common/Infrastructure/RequestParameters/Transformer/SearchRequestParametersTransformerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\TransformerException;
use Core\Common\Infrastructure\RequestParameters\Transformer\SearchRequestParametersTransformer;
it('transform from query parameters', function (): void {
$queryParameters = QueryParameters::create(
[
QueryParameter::int('contact_id', 110),
QueryParameter::string('contact_name', 'foo_name'),
QueryParameter::string('contact_alias', 'foo_alias'),
QueryParameter::bool('contact_active', true),
QueryParameter::bool('contact_is_admin', false),
QueryParameter::null('contact_email'),
QueryParameter::largeObject('contact_token', 'fghfhffhhj545d4f4sfdsfsdfdsfs4fsdf'),
]
);
$requestParameters = SearchRequestParametersTransformer::transformFromQueryParameters($queryParameters);
expect($requestParameters)->toBeArray()->toHaveCount(7)
->and($requestParameters)->toBe([
'contact_id' => [PDO::PARAM_INT => 110],
'contact_name' => [PDO::PARAM_STR => 'foo_name'],
'contact_alias' => [PDO::PARAM_STR => 'foo_alias'],
'contact_active' => [PDO::PARAM_BOOL => true],
'contact_is_admin' => [PDO::PARAM_BOOL => false],
'contact_email' => [PDO::PARAM_NULL => null],
'contact_token' => [PDO::PARAM_LOB => 'fghfhffhhj545d4f4sfdsfsdfdsfs4fsdf'],
]);
});
it('reverse to query parameters', function (): void {
$requestParameters = [
'contact_id' => [PDO::PARAM_INT => 110],
'contact_name' => [PDO::PARAM_STR => 'foo_name'],
'contact_alias' => [PDO::PARAM_STR => 'foo_alias'],
'contact_active' => [PDO::PARAM_BOOL => true],
'contact_is_admin' => [PDO::PARAM_BOOL => false],
'contact_email' => [PDO::PARAM_NULL => null],
'contact_token' => [PDO::PARAM_LOB => 'fghfhffhhj545d4f4sfdsfsdfdsfs4fsdf'],
];
$queryParameters = SearchRequestParametersTransformer::reverseToQueryParameters($requestParameters);
expect($queryParameters)->toBeInstanceOf(QueryParameters::class)
->and($queryParameters->length())->toBe(7)
->and($queryParameters->get('contact_id'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('contact_id')->getType())->toBe(QueryParameterTypeEnum::INTEGER)
->and($queryParameters->get('contact_id')->getValue())->toBe(110)
->and($queryParameters->get('contact_name'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('contact_name')->getType())->toBe(QueryParameterTypeEnum::STRING)
->and($queryParameters->get('contact_name')->getValue())->toBe('foo_name')
->and($queryParameters->get('contact_alias'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('contact_alias')->getType())->toBe(QueryParameterTypeEnum::STRING)
->and($queryParameters->get('contact_alias')->getValue())->toBe('foo_alias')
->and($queryParameters->get('contact_active'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('contact_active')->getType())->toBe(QueryParameterTypeEnum::BOOLEAN)
->and($queryParameters->get('contact_active')->getValue())->toBeTrue()
->and($queryParameters->get('contact_is_admin'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('contact_is_admin')->getType())->toBe(QueryParameterTypeEnum::BOOLEAN)
->and($queryParameters->get('contact_is_admin')->getValue())->toBeFalse()
->and($queryParameters->get('contact_email'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('contact_email')->getType())->toBe(QueryParameterTypeEnum::NULL)
->and($queryParameters->get('contact_email')->getValue())->toBeNull()
->and($queryParameters->get('contact_token'))->toBeInstanceOf(QueryParameter::class)
->and($queryParameters->get('contact_token')->getType())->toBe(QueryParameterTypeEnum::LARGE_OBJECT)
->and($queryParameters->get('contact_token')->getValue())->toBe('fghfhffhhj545d4f4sfdsfsdfdsfs4fsdf');
});
it('reverse to query parameters with unknown PDO type', function (): void {
$requestParameters = [
'contact_id' => [PDO::PARAM_INT => 110],
'contact_name' => [PDO::PARAM_STR => 'foo_name'],
'contact_alias' => [PDO::PARAM_STR_CHAR => 'foo_alias'],
'contact_active' => [PDO::PARAM_BOOL => true],
'contact_is_admin' => [PDO::PARAM_BOOL => false],
'contact_email' => [PDO::PARAM_NULL => null],
'contact_token' => [PDO::PARAM_LOB => 'fghfhffhhj545d4f4sfdsfsdfdsfs4fsdf'],
];
SearchRequestParametersTransformer::reverseToQueryParameters($requestParameters);
})->throws(TransformerException::class);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/RequestParameters/Normalizer/BoolToIntegerNormalizerTest.php | centreon/tests/php/Core/Common/Infrastructure/RequestParameters/Normalizer/BoolToIntegerNormalizerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Infrastructure\RequestParameters\Normalizer;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToIntegerNormalizer;
// Testing nullability
it(
'should success with NULL when allowed',
fn () => expect(
(new BoolToIntegerNormalizer(nullable: true))
->normalize(null)
)->toBe(null)
);
// Expected success values
it(
'should success',
fn ($tested, $expected) => expect(
(new BoolToIntegerNormalizer(4321, 1234))
->normalize($tested)
)->toBe($expected)
)
->with(
[
// truthy
[true, 1234],
[1, 1234],
['true', 1234],
['TRUE', 1234],
[1234, 1234],
// falsy
[false, 4321],
[0, 4321],
['false', 4321],
['FALSE', 4321],
[4321, 4321],
]
);
// Expected failure values
it(
'should fail',
fn ($tested) => (new BoolToIntegerNormalizer())->normalize($tested)
)
->with(
[
null,
-1,
2,
'FooBar',
'TrUe',
'fAlSe',
]
)
->throws(\TypeError::class);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/RequestParameters/Normalizer/BoolToEnumNormalizerTest.php | centreon/tests/php/Core/Common/Infrastructure/RequestParameters/Normalizer/BoolToEnumNormalizerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Infrastructure\RequestParameters\Normalizer;
use Core\Common\Infrastructure\RequestParameters\Normalizer\BoolToEnumNormalizer;
// Testing nullability
it(
'should success with NULL when allowed',
fn () => expect(
(new BoolToEnumNormalizer(nullable: true))
->normalize(null)
)->toBe(null)
);
// Expected success values
it(
'should success',
fn ($tested, $expected) => expect(
(new BoolToEnumNormalizer('customFALSE', 'customTRUE'))
->normalize($tested)
)->toBe($expected)
)
->with(
[
// truthy
[true, 'customTRUE'],
[1, 'customTRUE'],
['true', 'customTRUE'],
['TRUE', 'customTRUE'],
['customTRUE', 'customTRUE'],
// falsy
[false, 'customFALSE'],
[0, 'customFALSE'],
['false', 'customFALSE'],
['FALSE', 'customFALSE'],
['customFALSE', 'customFALSE'],
]
);
// Expected failure values
it(
'should fail',
fn ($tested) => (new BoolToEnumNormalizer())->normalize($tested)
)
->with(
[
null,
-1,
2,
'FooBar',
'TrUe',
'fAlSe',
]
)
->throws(\TypeError::class);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/Repository/DatabaseRepositoryManagerTest.php | centreon/tests/php/Core/Common/Infrastructure/Repository/DatabaseRepositoryManagerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Centreon\Infrastructure\Repository;
use Adaptation\Database\Connection\Adapter\Dbal\DbalConnectionAdapter;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Model\ConnectionConfig;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Centreon\Infrastructure\DatabaseConnection;
use CentreonDB;
use Core\Common\Infrastructure\Repository\DatabaseRepositoryManager;
/**
* @param string $nameEnvVar
*
* @return string|null
*/
function getEnvironmentVariable(string $nameEnvVar): ?string
{
$envVarValue = getenv($nameEnvVar, true) ?: getenv($nameEnvVar);
return (is_string($envVarValue) && ! empty($envVarValue)) ? $envVarValue : null;
}
$dbHost = getEnvironmentVariable('MYSQL_HOST');
$dbUser = getEnvironmentVariable('MYSQL_USER');
$dbPassword = getEnvironmentVariable('MYSQL_PASSWORD');
$dbConfigCentreon = null;
if (! is_null($dbHost) && ! is_null($dbUser) && ! is_null($dbPassword)) {
$dbConfigCentreon = new ConnectionConfig(
host: $dbHost,
user: $dbUser,
password: $dbPassword,
databaseNameConfiguration: 'centreon',
databaseNameRealTime: 'centreon_storage',
port: 3306
);
}
/**
* @param ConnectionConfig $connectionConfig
*
* @return bool
*/
function hasConnectionDb(ConnectionConfig $connectionConfig): bool
{
try {
new \PDO(
$connectionConfig->getMysqlDsn(),
$connectionConfig->getUser(),
$connectionConfig->getPassword(),
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
);
return true;
} catch (\PDOException $exception) {
return false;
}
}
if (! is_null($dbConfigCentreon) && hasConnectionDb($dbConfigCentreon)) {
it('test commit a transaction using DbalConnectionAdapter with success', function () use ($dbConfigCentreon): void {
$connection = DbalConnectionAdapter::createFromConfig($dbConfigCentreon);
$databaseRepositoryManager = new DatabaseRepositoryManager($connection);
// Check starting transaction
$databaseRepositoryManager->startTransaction();
expect($databaseRepositoryManager->isTransactionActive())->toBeTrue()
->and($connection->isTransactionActive())->toBeTrue();
// Check transaction
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $connection->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// Check commit transaction
$successCommit = $databaseRepositoryManager->commitTransaction();
expect($successCommit)->toBeTrue()
->and($connection->isTransactionActive())->toBeFalse();
// clean up the database
$deleted = $connection->delete(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 110)])
);
expect($deleted)->toBeInt()->toBe(1);
});
it('test rollback a transaction using DbalConnectionAdapter with success', function () use ($dbConfigCentreon): void {
$connection = DbalConnectionAdapter::createFromConfig($dbConfigCentreon);
$databaseRepositoryManager = new DatabaseRepositoryManager($connection);
// Check starting transaction
$databaseRepositoryManager->startTransaction();
expect($databaseRepositoryManager->isTransactionActive())->toBeTrue()
->and($connection->isTransactionActive())->toBeTrue();
// Check transaction
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $connection->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// Check rollback transaction
$successRollback = $databaseRepositoryManager->rollbackTransaction();
expect($successRollback)->toBeTrue()
->and($connection->isTransactionActive())->toBeFalse();
// Check that the data was not inserted
$contact = $connection->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 110)])
);
expect($contact)->toBeFalse();
});
it('test commit a transaction using DatabaseConnection with success', function () use ($dbConfigCentreon): void {
$connection = DatabaseConnection::createFromConfig($dbConfigCentreon);
$databaseRepositoryManager = new DatabaseRepositoryManager($connection);
// Check starting transaction
$databaseRepositoryManager->startTransaction();
expect($databaseRepositoryManager->isTransactionActive())->toBeTrue()
->and($connection->isTransactionActive())->toBeTrue();
// Check transaction
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $connection->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// Check commit transaction
$successCommit = $databaseRepositoryManager->commitTransaction();
expect($successCommit)->toBeTrue()
->and($connection->isTransactionActive())->toBeFalse();
// clean up the database
$deleted = $connection->delete(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 110)])
);
expect($deleted)->toBeInt()->toBe(1);
});
it('test rollback a transaction using DatabaseConnection with success', function () use ($dbConfigCentreon): void {
$connection = DatabaseConnection::createFromConfig($dbConfigCentreon);
$databaseRepositoryManager = new DatabaseRepositoryManager($connection);
// Check starting transaction
$databaseRepositoryManager->startTransaction();
expect($databaseRepositoryManager->isTransactionActive())->toBeTrue()
->and($connection->isTransactionActive())->toBeTrue();
// Check transaction
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $connection->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// Check rollback transaction
$successRollback = $databaseRepositoryManager->rollbackTransaction();
expect($successRollback)->toBeTrue()
->and($connection->isTransactionActive())->toBeFalse();
// Check that the data was not inserted
$contact = $connection->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 110)])
);
expect($contact)->toBeFalse();
});
it('test commit a transaction using CentreonDB with success', function () use ($dbConfigCentreon): void {
$connection = CentreonDB::createFromConfig($dbConfigCentreon);
$databaseRepositoryManager = new DatabaseRepositoryManager($connection);
// Check starting transaction
$databaseRepositoryManager->startTransaction();
expect($databaseRepositoryManager->isTransactionActive())->toBeTrue()
->and($connection->isTransactionActive())->toBeTrue();
// Check transaction
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $connection->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// Check commit transaction
$successCommit = $databaseRepositoryManager->commitTransaction();
expect($successCommit)->toBeTrue()
->and($connection->isTransactionActive())->toBeFalse();
// clean up the database
$deleted = $connection->delete(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 110)])
);
expect($deleted)->toBeInt()->toBe(1);
});
it('test rollback a transaction using CentreonDB with success', function () use ($dbConfigCentreon): void {
$connection = CentreonDB::createFromConfig($dbConfigCentreon);
$databaseRepositoryManager = new DatabaseRepositoryManager($connection);
// Check starting transaction
$databaseRepositoryManager->startTransaction();
expect($databaseRepositoryManager->isTransactionActive())->toBeTrue()
->and($connection->isTransactionActive())->toBeTrue();
// Check transaction
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $connection->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// Check rollback transaction
$successRollback = $databaseRepositoryManager->rollbackTransaction();
expect($successRollback)->toBeTrue()
->and($connection->isTransactionActive())->toBeFalse();
// Check that the data was not inserted
$contact = $connection->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 110)])
);
expect($contact)->toBeFalse();
});
it(
'test commit a transaction using two different connectors is not correct',
function () use ($dbConfigCentreon): void {
$connection = DbalConnectionAdapter::createFromConfig($dbConfigCentreon);
$databaseRepositoryManager = new DatabaseRepositoryManager(
DatabaseConnection::createFromConfig($dbConfigCentreon)
);
// Check starting transaction
$databaseRepositoryManager->startTransaction();
expect($databaseRepositoryManager->isTransactionActive())->toBeTrue()
->and($connection->isTransactionActive())->toBeFalse();
}
);
it(
'test rollback a transaction using two different connectors is not correct',
function () use ($dbConfigCentreon): void {
$connection = DbalConnectionAdapter::createFromConfig($dbConfigCentreon);
$databaseRepositoryManager = new DatabaseRepositoryManager(
DatabaseConnection::createFromConfig($dbConfigCentreon)
);
// Check starting transaction
$databaseRepositoryManager->startTransaction();
// Check transaction
$queryParameters = QueryParameters::create(
[
QueryParameter::int('id', 110),
QueryParameter::string('name', 'foo_name'),
QueryParameter::string('alias', 'foo_alias'),
]
);
$inserted = $connection->insert(
'INSERT INTO contact(contact_id, contact_name, contact_alias) VALUES(:id, :name, :alias)',
$queryParameters
);
expect($inserted)->toBeInt()->toBe(1);
// Check rollback transaction
$successRollback = $databaseRepositoryManager->rollbackTransaction();
expect($successRollback)->toBeTrue()
->and($connection->isTransactionActive())->toBeFalse();
// Check that the data was not inserted
$contact = $connection->fetchAssociative(
'SELECT * FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 110)])
);
expect($contact)->toBeArray()
->and($contact)->toHaveKey('contact_id')
->and($contact['contact_id'])->toBe(110);
// clean up the database
$deleted = $connection->delete(
'DELETE FROM contact WHERE contact_id = :id',
QueryParameters::create([QueryParameter::int('id', 110)])
);
expect($deleted)->toBeInt()->toBe(1);
}
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Common/Infrastructure/Repository/ValuesByPacketsTest.php | centreon/tests/php/Core/Common/Infrastructure/Repository/ValuesByPacketsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Common\Infrastructure;
use Core\Common\Infrastructure\Repository\ValuesByPackets;
const NO_LIMIT = 1000000;
it('should divide the values according to the maxItemsByPackets limitation only', function (): void {
$maxItemsByPackets = 5;
$maxQueryStringLength = NO_LIMIT;
$values = range(1, 1000);
$valuesByPackets = new ValuesByPackets($values, $maxItemsByPackets, $maxQueryStringLength);
foreach ($valuesByPackets as $iterationNumber => $valuesToCheck) {
expect(count($valuesToCheck))->toBeLessThanOrEqual($maxItemsByPackets);
for ($index = 0; $index < $maxItemsByPackets && array_key_exists($index, $valuesToCheck); $index++) {
expect($values[$index + ($iterationNumber * $maxItemsByPackets)])->toEqual($valuesToCheck[$index]);
}
}
});
it('should divide the values according to the maxQueryStringLength limitation only', function (): void {
$maxItemsByPackets = NO_LIMIT;
$maxQueryStringLength = 50;
$values = range(1, 1000);
$valueSeparator = ',';
$valuesByPackets = new ValuesByPackets($values, $maxItemsByPackets, $maxQueryStringLength, mb_strlen($valueSeparator));
foreach ($valuesByPackets as $valuesToCheck) {
expect(mb_strlen(implode($valueSeparator, $valuesToCheck)) <= $maxQueryStringLength)->toBeTrue();
}
});
it('should divide the values according to all the limitations', function (): void {
$maxItemsByPackets = 10;
$maxQueryStringLength = 50;
$values = range(1, 1000);
$valueSeparator = ',';
$valuesByPackets = new ValuesByPackets($values, $maxItemsByPackets, $maxQueryStringLength, mb_strlen($valueSeparator));
foreach ($valuesByPackets as $iterationNumber => $valuesToCheck) {
expect(count($valuesToCheck))->toBeLessThanOrEqual($maxItemsByPackets);
expect(mb_strlen(implode($valueSeparator, $valuesToCheck)) <= $maxQueryStringLength)->toBeTrue();
for ($index = 0; $index < $maxItemsByPackets && array_key_exists($index, $valuesToCheck); $index++) {
expect($values[$index + ($iterationNumber * $maxItemsByPackets)])->toEqual($valuesToCheck[$index]);
}
}
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceSeverity/Application/UseCase/UpdateServiceSeverity/UpdateServiceSeverityTest.php | centreon/tests/php/Core/ServiceSeverity/Application/UseCase/UpdateServiceSeverity/UpdateServiceSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceSeverity\Application\UseCase\UpdateServiceSeverity;
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\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Exception\ServiceSeverityException;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\WriteServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\UseCase\UpdateServiceSeverity\UpdateServiceSeverity;
use Core\ServiceSeverity\Application\UseCase\UpdateServiceSeverity\UpdateServiceSeverityRequest;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(function (): void {
$this->presenter = new DefaultPresenter(
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class)
);
$this->useCase = new UpdateServiceSeverity(
$this->writeServiceSeverityRepository = $this->createMock(WriteServiceSeverityRepositoryInterface::class),
$this->readServiceSeverityRepository = $this->createMock(ReadServiceSeverityRepositoryInterface::class),
$this->readViewImgRepository = $this->createMock(ReadViewImgRepositoryInterface::class),
$this->readAccessGroupRepositoryInterface = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class)
);
$this->severity = new ServiceSeverity(
1,
'sev-name',
'sev-alias',
2,
1,
);
$this->request = new UpdateServiceSeverityRequest();
$this->request->name = $this->severity->getName() . '-edited';
$this->request->alias = $this->severity->getAlias() . '-edited';
$this->request->level = $this->severity->getLevel();
$this->request->iconId = $this->severity->getIconId();
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('findById')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter, $this->severity->getId());
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceSeverityException::editServiceSeverity(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter, $this->severity->getId());
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceSeverityException::editNotAllowed()->getMessage());
});
it('should present a ConflictResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->severity);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
($this->useCase)($this->request, $this->presenter, $this->severity->getId());
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceSeverityException::serviceNameAlreadyExists()->getMessage());
});
it('should throw a ConflictResponse if the service severity icon does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->severity);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
($this->useCase)($this->request, $this->presenter, $this->severity->getId());
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceSeverityException::iconDoesNotExist($this->request->iconId)->getMessage());
});
it('should present an InvalidArgumentResponse when a field assert failed', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->severity);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->request->level = ServiceSeverity::MIN_LEVEL_VALUE - 1;
$expectedException = AssertionException::min(
$this->request->level,
ServiceSeverity::MIN_LEVEL_VALUE,
'ServiceSeverity::level'
);
($this->useCase)($this->request, $this->presenter, $this->severity->getId());
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe($expectedException->getMessage());
});
it('should return created object on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->severity);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->writeServiceSeverityRepository
->expects($this->once())
->method('update');
($this->useCase)($this->request, $this->presenter, $this->severity->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/ServiceSeverity/Application/UseCase/AddServiceSeverity/AddServiceSeverityTest.php | centreon/tests/php/Core/ServiceSeverity/Application/UseCase/AddServiceSeverity/AddServiceSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceSeverity\Application\UseCase\AddServiceSeverity;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\ServiceSeverity\Application\Exception\ServiceSeverityException;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\WriteServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\UseCase\AddServiceSeverity\AddServiceSeverity;
use Core\ServiceSeverity\Application\UseCase\AddServiceSeverity\AddServiceSeverityRequest;
use Core\ServiceSeverity\Domain\Model\NewServiceSeverity;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(function (): void {
$this->writeServiceSeverityRepository = $this->createMock(WriteServiceSeverityRepositoryInterface::class);
$this->readServiceSeverityRepository = $this->createMock(ReadServiceSeverityRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->request = new AddServiceSeverityRequest();
$this->request->name = 'sc-name';
$this->request->alias = 'sc-alias';
$this->request->level = 2;
$this->request->iconId = 1;
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->useCase = new AddServiceSeverity(
$this->writeServiceSeverityRepository,
$this->readServiceSeverityRepository,
$this->readViewImgRepository = $this->createMock(ReadViewImgRepositoryInterface::class),
$this->user
);
$this->serviceSeverity = new ServiceSeverity(
1,
$this->request->name,
$this->request->alias,
$this->request->level,
$this->request->iconId,
);
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceSeverityException::addServiceSeverity(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceSeverityException::addNotAllowed()->getMessage());
});
it('should present a ConflictResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceSeverityException::serviceNameAlreadyExists()->getMessage());
});
it('should present an InvalidArgumentResponse when a field assert failed', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->request->level = NewServiceSeverity::MIN_LEVEL_VALUE - 1;
$expectedException = AssertionException::min(
$this->request->level,
NewServiceSeverity::MIN_LEVEL_VALUE,
'NewServiceSeverity::level'
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe($expectedException->getMessage());
});
it('should throw a ConflictResponse if the service severity icon does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceSeverityException::iconDoesNotExist($this->request->iconId)->getMessage());
});
it('should present an ErrorResponse if the newly created service severity cannot be retrieved', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->writeServiceSeverityRepository
->expects($this->once())
->method('add')
->willReturn(1);
$this->readServiceSeverityRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceSeverityException::errorWhileRetrievingJustCreated()->getMessage());
});
it('should return created object on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->writeServiceSeverityRepository
->expects($this->once())
->method('add')
->willReturn(1);
$this->readServiceSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->serviceSeverity);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getPresentedData())->toBeInstanceOf(CreatedResponse::class);
expect($this->presenter->getPresentedData()->getResourceId())->toBe($this->serviceSeverity->getId());
$payload = $this->presenter->getPresentedData()->getPayload();
expect($payload->name)
->toBe($this->serviceSeverity->getName())
->and($payload->alias)
->toBe($this->serviceSeverity->getAlias())
->and($payload->isActivated)
->toBe($this->serviceSeverity->isActivated());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceSeverity/Application/UseCase/DeleteServiceSeverity/DeleteServiceSeverityTest.php | centreon/tests/php/Core/ServiceSeverity/Application/UseCase/DeleteServiceSeverity/DeleteServiceSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceSeverity\Application\UseCase\DeleteServiceSeverity;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Exception\ServiceSeverityException;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\Repository\WriteServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\UseCase\DeleteServiceSeverity\DeleteServiceSeverity;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
beforeEach(function (): void {
$this->writeServiceSeverityRepository = $this->createMock(WriteServiceSeverityRepositoryInterface::class);
$this->readServiceSeverityRepository = $this->createMock(ReadServiceSeverityRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->user = $this->createMock(ContactInterface::class);
$this->serviceSeverity = $this->createMock(ServiceSeverity::class);
$this->serviceSeverityId = 1;
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$useCase = new DeleteServiceSeverity(
$this->writeServiceSeverityRepository,
$this->readServiceSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->writeServiceSeverityRepository
->expects($this->once())
->method('deleteById')
->willThrowException(new \Exception());
$useCase($this->serviceSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceSeverityException::deleteServiceSeverity(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has insufficient rights', function (): void {
$useCase = new DeleteServiceSeverity(
$this->writeServiceSeverityRepository,
$this->readServiceSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
$useCase($this->serviceSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceSeverityException::deleteNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the service severity does not exist (with admin user)', function (): void {
$useCase = new DeleteServiceSeverity(
$this->writeServiceSeverityRepository,
$this->readServiceSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$useCase($this->serviceSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Service severity not found');
});
it('should present a NotFoundResponse when the service severity does not exist (with non-admin user)', function (): void {
$useCase = new DeleteServiceSeverity(
$this->writeServiceSeverityRepository,
$this->readServiceSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(false);
$useCase($this->serviceSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Service severity not found');
});
it('should present a NoContentResponse on success (with admin user)', function (): void {
$useCase = new DeleteServiceSeverity(
$this->writeServiceSeverityRepository,
$this->readServiceSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$serviceSeverityId = 1;
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->writeServiceSeverityRepository
->expects($this->once())
->method('deleteById');
$useCase($serviceSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
it('should present a NoContentResponse on success (with non-admin user)', function (): void {
$useCase = new DeleteServiceSeverity(
$this->writeServiceSeverityRepository,
$this->readServiceSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readServiceSeverityRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(true);
$this->writeServiceSeverityRepository
->expects($this->once())
->method('deleteById');
$useCase($this->serviceSeverityId, $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/ServiceSeverity/Application/UseCase/FindServiceSeverities/FindServiceSeveritiesTest.php | centreon/tests/php/Core/ServiceSeverity/Application/UseCase/FindServiceSeverities/FindServiceSeveritiesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceSeverity\Application\UseCase\FindServiceSeverities;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ServiceSeverity\Application\Exception\ServiceSeverityException;
use Core\ServiceSeverity\Application\Repository\ReadServiceSeverityRepositoryInterface;
use Core\ServiceSeverity\Application\UseCase\FindServiceSeverities\FindServiceSeverities;
use Core\ServiceSeverity\Application\UseCase\FindServiceSeverities\FindServiceSeveritiesResponse;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
use Exception;
beforeEach(function (): void {
$this->serviceSeverityRepository = $this->createMock(ReadServiceSeverityRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->usecase = new FindServiceSeverities(
$this->serviceSeverityRepository,
$this->accessGroupRepository,
$this->requestParameters,
$this->user
);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->serviceSeverity = new ServiceSeverity(
1,
$this->serviceSeverityName = 'sc-name',
$this->serviceSeverityAlias = 'sc-alias',
$this->serviceSeverityLevel = 2,
$this->serviceSeverityIconId = 1
);
$this->responseArray = [
'id' => 1,
'name' => $this->serviceSeverityName,
'alias' => $this->serviceSeverityAlias,
'level' => $this->serviceSeverityLevel,
'iconId' => $this->serviceSeverityIconId,
'isActivated' => true,
];
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->serviceSeverityRepository
->expects($this->once())
->method('findByRequestParameter')
->willThrowException(new Exception());
($this->usecase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(ServiceSeverityException::findServiceSeverities(new Exception())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE, false],
]
);
($this->usecase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(ServiceSeverityException::accessNotAllowed()->getMessage());
});
it('should present a FindServiceGroupsResponse when a non-admin user has read only rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ, true],
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE, false],
]
);
$this->serviceSeverityRepository
->expects($this->once())
->method('findByRequestParameterAndAccessGroups')
->willReturn([$this->serviceSeverity]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindServiceSeveritiesResponse::class)
->and($this->presenter->getPresentedData()->serviceSeverities[0])
->toBe($this->responseArray);
});
it('should present a FindServiceGroupsResponse when a non-admin user has read/write rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_SERVICES_CATEGORIES_READ_WRITE, true],
]
);
$this->serviceSeverityRepository
->expects($this->once())
->method('findByRequestParameterAndAccessGroups')
->willReturn([$this->serviceSeverity]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindServiceSeveritiesResponse::class)
->and($this->presenter->getPresentedData()->serviceSeverities[0])
->toBe($this->responseArray);
});
it('should present a FindServiceSeveritiesResponse with admin user', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->serviceSeverityRepository
->expects($this->once())
->method('findByRequestParameter')
->willReturn([$this->serviceSeverity]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindServiceSeveritiesResponse::class)
->and($this->presenter->getPresentedData()->serviceSeverities[0])
->toBe($this->responseArray);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/ServiceSeverity/Domain/Model/NewServiceSeverityTest.php | centreon/tests/php/Core/ServiceSeverity/Domain/Model/NewServiceSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceSeverity\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\ServiceSeverity\Domain\Model\NewServiceSeverity;
beforeEach(function (): void {
$this->severityName = 'service-name';
$this->severityAlias = 'service-alias';
$this->level = 1;
$this->iconId = 2;
});
it('should return properly set service severity instance', function (): void {
$serviceSeverity = new NewServiceSeverity($this->severityName, $this->severityAlias, $this->level, $this->iconId);
expect($serviceSeverity->getName())->toBe($this->severityName)
->and($serviceSeverity->getAlias())->toBe($this->severityAlias);
});
it('should trim the fields "name" and "alias"', function (): void {
$serviceSeverity = new NewServiceSeverity(
$nameWithSpaces = ' my-name ',
$aliasWithSpaces = ' my-alias ',
$this->level,
$this->iconId
);
expect($serviceSeverity->getName())->toBe(trim($nameWithSpaces))
->and($serviceSeverity->getAlias())->toBe(trim($aliasWithSpaces));
});
it('should throw an exception when service severity name is empty', function (): void {
new NewServiceSeverity('', $this->severityAlias, $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::minLength('', 0, NewServiceSeverity::MIN_NAME_LENGTH, 'NewServiceSeverity::name')
->getMessage()
);
it('should throw an exception when service severity name is too long', function (): void {
new NewServiceSeverity(
str_repeat('a', NewServiceSeverity::MAX_NAME_LENGTH + 1),
$this->severityAlias,
$this->level,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewServiceSeverity::MAX_NAME_LENGTH + 1),
NewServiceSeverity::MAX_NAME_LENGTH + 1,
NewServiceSeverity::MAX_NAME_LENGTH,
'NewServiceSeverity::name'
)->getMessage()
);
it('should throw an exception when service severity alias is empty', function (): void {
new NewServiceSeverity($this->severityName, '', $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::minLength('', 0, NewServiceSeverity::MIN_ALIAS_LENGTH, 'NewServiceSeverity::alias')
->getMessage()
);
it('should throw an exception when service severity alias is too long', function (): void {
new NewServiceSeverity(
$this->severityName,
str_repeat('a', NewServiceSeverity::MAX_ALIAS_LENGTH + 1),
$this->level,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewServiceSeverity::MAX_ALIAS_LENGTH + 1),
NewServiceSeverity::MAX_ALIAS_LENGTH + 1,
NewServiceSeverity::MAX_ALIAS_LENGTH,
'NewServiceSeverity::alias'
)->getMessage()
);
it('should throw an exception when service severity level is too high', function (): void {
$serviceSeverity = new NewServiceSeverity(
$this->severityName,
$this->severityAlias,
NewServiceSeverity::MAX_LEVEL_VALUE + 1,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::max(
NewServiceSeverity::MAX_LEVEL_VALUE + 1,
NewServiceSeverity::MAX_LEVEL_VALUE,
'NewServiceSeverity::level'
)->getMessage()
);
it('should throw an exception when service severity level is too low', function (): void {
$serviceSeverity = new NewServiceSeverity(
$this->severityName,
$this->severityAlias,
NewServiceSeverity::MIN_LEVEL_VALUE - 1,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::min(
NewServiceSeverity::MIN_LEVEL_VALUE - 1,
NewServiceSeverity::MIN_LEVEL_VALUE,
'NewServiceSeverity::level'
)->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/ServiceSeverity/Domain/Model/ServiceSeverityTest.php | centreon/tests/php/Core/ServiceSeverity/Domain/Model/ServiceSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\ServiceSeverity\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\ServiceSeverity\Domain\Model\ServiceSeverity;
beforeEach(function (): void {
$this->severityName = 'service-name';
$this->severityAlias = 'service-alias';
$this->level = 1;
$this->iconId = 2;
});
it('should return properly set service severity instance', function (): void {
$serviceSeverity = new ServiceSeverity(1, $this->severityName, $this->severityAlias, $this->level, $this->iconId);
expect($serviceSeverity->getId())->toBe(1)
->and($serviceSeverity->getName())->toBe($this->severityName)
->and($serviceSeverity->getAlias())->toBe($this->severityAlias);
});
it('should trim the fields "name" and "alias"', function (): void {
$serviceSeverity = new ServiceSeverity(
1,
$nameWithSpaces = ' my-name ',
$aliasWithSpaces = ' my-alias ',
$this->level,
$this->iconId
);
expect($serviceSeverity->getName())->toBe(trim($nameWithSpaces))
->and($serviceSeverity->getAlias())->toBe(trim($aliasWithSpaces));
});
it('should throw an exception when service severity name is empty', function (): void {
new ServiceSeverity(1, '', $this->severityAlias, $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('ServiceSeverity::name')
->getMessage()
);
it('should throw an exception when service severity name is too long', function (): void {
new ServiceSeverity(1, str_repeat('a', ServiceSeverity::MAX_NAME_LENGTH + 1), $this->severityAlias, $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', ServiceSeverity::MAX_NAME_LENGTH + 1),
ServiceSeverity::MAX_NAME_LENGTH + 1,
ServiceSeverity::MAX_NAME_LENGTH,
'ServiceSeverity::name'
)->getMessage()
);
it('should throw an exception when service severity alias is empty', function (): void {
new ServiceSeverity(1, $this->severityName, '', $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEMptyString('ServiceSeverity::alias')
->getMessage()
);
it('should throw an exception when service severity alias is too long', function (): void {
new ServiceSeverity(1, $this->severityName, str_repeat('a', ServiceSeverity::MAX_ALIAS_LENGTH + 1), $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', ServiceSeverity::MAX_ALIAS_LENGTH + 1),
ServiceSeverity::MAX_ALIAS_LENGTH + 1,
ServiceSeverity::MAX_ALIAS_LENGTH,
'ServiceSeverity::alias'
)->getMessage()
);
it('should throw an exception when service severity level is too high', function (): void {
$serviceSeverity = new ServiceSeverity(
1,
$this->severityName,
$this->severityAlias,
ServiceSeverity::MAX_LEVEL_VALUE + 1,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::max(ServiceSeverity::MAX_LEVEL_VALUE + 1, ServiceSeverity::MAX_LEVEL_VALUE, 'ServiceSeverity::level')
->getMessage()
);
it('should throw an exception when service severity level is too low', function (): void {
$serviceSeverity = new ServiceSeverity(
1,
$this->severityName,
$this->severityAlias,
ServiceSeverity::MIN_LEVEL_VALUE - 1,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::min(ServiceSeverity::MIN_LEVEL_VALUE - 1, ServiceSeverity::MIN_LEVEL_VALUE, 'ServiceSeverity::level')
->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/Resources/Application/UseCase/CountResources/CountResourcesPresenterStub.php | centreon/tests/php/Core/Resources/Application/UseCase/CountResources/CountResourcesPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Application\UseCase\CountResources;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Resources\Application\UseCase\CountResources\CountResourcesPresenterInterface;
use Core\Resources\Application\UseCase\CountResources\CountResourcesResponse;
/**
* Class
*
* @class CountResourcesPresenterStub
* @package Tests\Core\Resources\Application\UseCase\CountResources
*/
class CountResourcesPresenterStub implements CountResourcesPresenterInterface
{
/** @var CountResourcesResponse|ResponseStatusInterface */
public CountResourcesResponse|ResponseStatusInterface $response;
/**
* @param ResponseStatusInterface|CountResourcesResponse $response
*
* @return void
*/
public function presentResponse(ResponseStatusInterface|CountResourcesResponse $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/Resources/Application/UseCase/CountResources/CountResourcesTest.php | centreon/tests/php/Core/Resources/Application/UseCase/CountResources/CountResourcesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Application\UseCase\CountResources;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Resources\Application\Repository\ReadResourceRepositoryInterface;
use Core\Resources\Application\UseCase\CountResources\CountResources;
use Core\Resources\Application\UseCase\CountResources\CountResourcesRequest;
use Core\Resources\Application\UseCase\CountResources\CountResourcesResponse;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Mockery;
beforeEach(function (): void {
$this->filters = Mockery::mock(ResourceFilter::class);
$this->resourcesRepository = Mockery::mock(ReadResourceRepositoryInterface::class);
$this->contactRepository = Mockery::mock(ReadAccessGroupRepositoryInterface::class);
$this->presenter = new CountResourcesPresenterStub();
});
it('count resources with an invalid contact_id should throw an InvalidArgumentException', function (): void {
$request = new CountResourcesRequest(
resourceFilter: $this->filters,
allPages: true,
contactId: 0,
isAdmin: true
);
})->throws(\InvalidArgumentException::class);
it('count resources with an error from repository should throw an ErrorResponse', function (): void {
$this->resourcesRepository
->shouldReceive('countResourcesByFilter')
->andThrow(Mockery::mock(RepositoryException::class));
$request = new CountResourcesRequest(
resourceFilter: $this->filters,
allPages: true,
contactId: 1,
isAdmin: true
);
$useCase = new CountResources($this->resourcesRepository, $this->contactRepository);
$useCase($request, $this->presenter);
expect($this->presenter->response)->toBeInstanceOf(ErrorResponse::class);
});
it('count resources with admin mode should throw a response with all resources', function (): void {
$this->resourcesRepository
->shouldReceive('countResourcesByFilter')
->with($this->filters, true)
->andReturn(2);
$this->resourcesRepository
->shouldReceive('countAllResources')
->withNoArgs()
->andReturn(10);
$request = new CountResourcesRequest(
resourceFilter: $this->filters,
allPages: true,
contactId: 1,
isAdmin: true
);
$useCase = new CountResources($this->resourcesRepository, $this->contactRepository);
$useCase($request, $this->presenter);
expect($this->presenter->response)->toBeInstanceOf(CountResourcesResponse::class)
->and($this->presenter->response->getTotalFilteredResources())->toBe(2)
->and($this->presenter->response->getTotalResources())->toBe(10);
});
it('count resources with acl should throw a response with allowed resources', function (): void {
$this->contactRepository
->shouldReceive('findByContactId')
->andReturn(AccessGroupCollection::create([new AccessGroup(1, 'test', 'test')]));
$this->resourcesRepository
->shouldReceive('countResourcesByFilterAndAccessGroupIds')
->with($this->filters, true, [1])
->andReturn(2);
$this->resourcesRepository
->shouldReceive('countAllResourcesByAccessGroupIds')
->with([1])
->andReturn(10);
$request = new CountResourcesRequest(
resourceFilter: $this->filters,
allPages: true,
contactId: 1,
isAdmin: false
);
$useCase = new CountResources($this->resourcesRepository, $this->contactRepository);
$useCase($request, $this->presenter);
expect($this->presenter->response)->toBeInstanceOf(CountResourcesResponse::class)
->and($this->presenter->response->getTotalFilteredResources())->toBe(2)
->and($this->presenter->response->getTotalResources())->toBe(10);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Resources/Application/UseCase/FindResources/FindResourcesPresenterStub.php | centreon/tests/php/Core/Resources/Application/UseCase/FindResources/FindResourcesPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Application\UseCase\FindResources;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Resources\Application\UseCase\FindResources\FindResourcesPresenterInterface;
use Core\Resources\Application\UseCase\FindResources\FindResourcesResponse;
class FindResourcesPresenterStub implements FindResourcesPresenterInterface
{
public FindResourcesResponse|ResponseStatusInterface $data;
public function presentResponse(FindResourcesResponse|ResponseStatusInterface $response): void
{
$this->data = $response;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Resources/Application/UseCase/FindResources/FindResourcesTest.php | centreon/tests/php/Core/Resources/Application/UseCase/FindResources/FindResourcesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Application\UseCase\FindResources;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Resources\Application\Exception\ResourceException;
use Core\Resources\Application\Repository\ReadResourceRepositoryInterface;
use Core\Resources\Application\UseCase\FindResources\FindResources;
use Core\Resources\Application\UseCase\FindResources\FindResourcesResponse;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Mockery;
beforeEach(function (): void {
$this->presenter = new FindResourcesPresenterStub();
$this->useCase = new FindResources(
$this->resourcesRepository = Mockery::mock(ReadResourceRepositoryInterface::class),
$this->contact = Mockery::mock(ContactInterface::class),
$this->accessGroupRepository = Mockery::mock(ReadAccessGroupRepositoryInterface::class),
new \ArrayObject([])
);
});
it(
'should send an ErrorResponse if something bad happen',
function (): void {
$this->contact->shouldReceive('isAdmin')->twice()->andReturn(true);
$this->contact->shouldReceive('getId')->once()->andReturn(1);
$this->resourcesRepository
->shouldReceive('findResources')
->andThrow(Mockery::mock(RepositoryException::class));
($this->useCase)($this->presenter, new ResourceFilter());
expect($this->presenter->data)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->data->getMessage())
->toBe(ResourceException::errorWhileSearching()->getMessage());
}
);
it(
'should retrieve a valid FindResourcesResponse querying the repository with an admin contact',
function (): void {
$this->contact->shouldReceive('isAdmin')->once()->andReturn(true);
$this->resourcesRepository
->shouldReceive('findResources')
->andReturn([]);
$this->accessGroupRepository->shouldReceive('findByContact')->never();
($this->useCase)($this->presenter, new ResourceFilter());
expect($this->presenter->data)->toBeInstanceOf(FindResourcesResponse::class);
}
);
it(
'should retrieve a valid FindResourcesResponse querying the repository with a normal contact',
function (): void {
$this->contact->shouldReceive('isAdmin')->once()->andReturn(false);
$this->accessGroupRepository
->shouldReceive('findByContact')
->andReturn([]);
$this->resourcesRepository
->shouldReceive('findResourcesByAccessGroupIds')
->andReturn([]);
($this->useCase)($this->presenter, new ResourceFilter());
expect($this->presenter->data)->toBeInstanceOf(FindResourcesResponse::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/Resources/Application/UseCase/ExportResources/ExportResourcesPresenterStub.php | centreon/tests/php/Core/Resources/Application/UseCase/ExportResources/ExportResourcesPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Application\UseCase\ExportResources;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Resources\Application\UseCase\ExportResources\ExportResourcesPresenterInterface;
use Core\Resources\Application\UseCase\ExportResources\ExportResourcesResponse;
/**
* Class
*
* @class ExportResourcesPresenterStub
* @package Tests\Core\Resources\Application\UseCase\ExportResources
*/
class ExportResourcesPresenterStub implements ExportResourcesPresenterInterface
{
/** @var ExportResourcesResponse|ResponseStatusInterface */
public ExportResourcesResponse|ResponseStatusInterface $response;
/**
* @param ResponseStatusInterface|ExportResourcesResponse $response
*
* @return void
*/
public function presentResponse(ResponseStatusInterface|ExportResourcesResponse $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/Resources/Application/UseCase/ExportResources/ExportResourcesTest.php | centreon/tests/php/Core/Resources/Application/UseCase/ExportResources/ExportResourcesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Application\UseCase\ExportResources;
use Centreon\Domain\Monitoring\Resource;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Domain\Collection\StringCollection;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Resources\Application\Repository\ReadResourceRepositoryInterface;
use Core\Resources\Application\UseCase\ExportResources\ExportResources;
use Core\Resources\Application\UseCase\ExportResources\ExportResourcesRequest;
use Core\Resources\Application\UseCase\ExportResources\ExportResourcesResponse;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Mockery;
beforeEach(function (): void {
$this->filters = Mockery::mock(ResourceFilter::class);
$this->resourcesRepository = Mockery::mock(ReadResourceRepositoryInterface::class);
$this->contactRepository = Mockery::mock(ReadAccessGroupRepositoryInterface::class);
$this->presenter = new ExportResourcesPresenterStub();
});
it('test export resources with an invalid contact_id should throw an InvalidArgumentException', function (): void {
$request = new ExportResourcesRequest(
exportedFormat: 'csv',
resourceFilter: $this->filters,
allPages: false,
maxResults: 0,
columns: new StringCollection(),
contactId: 0,
isAdmin: true
);
})->throws(\InvalidArgumentException::class);
it('test export resources with an invalid format should throw an InvalidArgumentException', function (): void {
$request = new ExportResourcesRequest(
exportedFormat: 'invalid',
resourceFilter: $this->filters,
allPages: false,
maxResults: 0,
columns: new StringCollection(),
contactId: 1,
isAdmin: true
);
})->throws(\InvalidArgumentException::class);
it('export all resources without max results should throw an InvalidArgumentException', function (): void {
$request = new ExportResourcesRequest(
exportedFormat: 'csv',
resourceFilter: $this->filters,
allPages: true,
maxResults: 0,
columns: new StringCollection(),
contactId: 1,
isAdmin: true
);
})->throws(\InvalidArgumentException::class);
it('export all resources with max results greater than 10000 should throw an InvalidArgumentException', function (): void {
$request = new ExportResourcesRequest(
exportedFormat: 'csv',
resourceFilter: $this->filters,
allPages: true,
maxResults: 12000,
columns: new StringCollection(),
contactId: 1,
isAdmin: true
);
})->throws(\InvalidArgumentException::class);
it('export resources with an error from repository should throw an ErrorResponse', function (): void {
$this->resourcesRepository
->shouldReceive('iterateResources')
->once()
->andThrow(Mockery::mock(RepositoryException::class));
$request = new ExportResourcesRequest(
exportedFormat: 'csv',
resourceFilter: $this->filters,
allPages: false,
maxResults: 0,
columns: new StringCollection(),
contactId: 1,
isAdmin: true
);
$useCase = new ExportResources($this->resourcesRepository, $this->contactRepository);
$useCase($request, $this->presenter);
expect($this->presenter->response)->toBeInstanceOf(ErrorResponse::class);
});
it('export resources with admin mode should throw a response with all resources', function (): void {
$this->resourcesRepository
->shouldReceive('iterateResources')
->once()
->andReturn(new \ArrayObject([Mockery::mock(Resource::class)]));
$request = new ExportResourcesRequest(
exportedFormat: 'csv',
resourceFilter: $this->filters,
allPages: false,
maxResults: 0,
columns: StringCollection::create(['columns1', 'columns2']),
contactId: 1,
isAdmin: true
);
$useCase = new ExportResources($this->resourcesRepository, $this->contactRepository);
$useCase($request, $this->presenter);
expect($this->presenter->response)->toBeInstanceOf(ExportResourcesResponse::class)
->and($this->presenter->response->getResources())->toBeInstanceOf(\ArrayObject::class)
->and($this->presenter->response->getExportedFormat())->toBe('csv')
->and($this->presenter->response->getFilteredColumns()->toArray())->toBe(['columns1', 'columns2']);
});
it('export resources with acl should throw a response with allowed resources', function (): void {
$this->contactRepository
->shouldReceive('findByContactId')
->once()
->andReturn(new AccessGroupCollection([new AccessGroup(1, 'test', 'test')]));
$this->resourcesRepository
->shouldReceive('iterateResourcesByAccessGroupIds')
->once()
->andReturn(new \ArrayObject([Mockery::mock(Resource::class)]));
$request = new ExportResourcesRequest(
exportedFormat: 'csv',
resourceFilter: $this->filters,
allPages: false,
maxResults: 0,
columns: StringCollection::create(['columns1', 'columns2']),
contactId: 1,
isAdmin: false
);
$useCase = new ExportResources($this->resourcesRepository, $this->contactRepository);
$useCase($request, $this->presenter);
expect($this->presenter->response)->toBeInstanceOf(ExportResourcesResponse::class)
->and($this->presenter->response->getResources())->toBeInstanceOf(\ArrayObject::class)
->and($this->presenter->response->getExportedFormat())->toBe('csv')
->and($this->presenter->response->getFilteredColumns()->toArray())->toBe(['columns1', 'columns2']);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Resources/Infrastructure/API/CountResources/CountResourcesInputTest.php | centreon/tests/php/Core/Resources/Infrastructure/API/CountResources/CountResourcesInputTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Infrastructure\API\CountResources;
use Core\Resources\Infrastructure\API\CountResources\CountResourcesInput;
use Symfony\Component\Validator\Validation;
beforeEach(function (): void {
$this->validator = Validation::createValidatorBuilder()
->enableAttributeMapping()
->getValidator();
});
// search parameter
it('test count resources input validation with no search', function (): void {
$input = new CountResourcesInput(null, false, 1, 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('search parameter is required');
});
it('test count resources input validation with an empty search', function (): void {
$input = new CountResourcesInput('', false, 1, 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('search parameter is required');
});
it('test count resources input validation with search with an invalid value', function (): void {
$input = new CountResourcesInput('toto', false, 1, 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('search parameter must be a valid JSON');
});
it('test count resources input validation with search with an invalid json', function (): void {
$input = new CountResourcesInput('{$and:[]}', false, 1, 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('search parameter must be a valid JSON');
});
it('test count resources input validation with search with a valid json', function (): void {
$input = new CountResourcesInput('{"$and":[]}', false, 1, 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
});
// all_pages parameter without limit and page
it('test count resources input validation with no all_pages', function (): void {
$input = new CountResourcesInput('{"$and":[]}', null, null, null);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('all_pages parameter is required');
});
it('test count resources input validation with an empty all_pages', function (): void {
$input = new CountResourcesInput('{"$and":[]}', '', null, null);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('all_pages parameter must be a boolean');
});
it('test count resources input validation with all_pages with an invalid value', function (): void {
$input = new CountResourcesInput('{"$and":[]}', 'toto', null, null);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('all_pages parameter must be a boolean');
});
it('test count resources input validation with a correct all_pages', function (): void {
$input = new CountResourcesInput('{"$and":[]}', true, null, null);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
});
// all_pages parameter with limit and page
it('test count resources input validation for pagination with no page', function (): void {
$input = new CountResourcesInput('{"$and":[]}', false, null, 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('page parameter is required when all_pages is false');
});
it('test count resources input validation for pagination with an empty page', function (): void {
$input = new CountResourcesInput('{"$and":[]}', false, '', 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('page parameter is required when all_pages is false');
});
it('test count resources input validation for pagination with page with invalid type', function (): void {
$input = new CountResourcesInput('{"$and":[]}', false, 'toto', 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('page parameter must be an integer');
});
it('test count resources input validation for pagination with page lower than 1', function (): void {
$input = new CountResourcesInput('{"$and":[]}', false, 0, 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('page parameter must be greater than 1');
});
it('test count resources input validation for pagination with no limit', function (): void {
$input = new CountResourcesInput('{"$and":[]}', false, 1, null);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('limit parameter is required when all_pages is false');
});
it('test count resources input validation for pagination with an empty limit', function (): void {
$input = new CountResourcesInput('{"$and":[]}', false, 1, '');
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(2)
->and($errors[0]->getMessage())->toBe('limit parameter is required when all_pages is false')
->and($errors[1]->getMessage())->toBe('limit parameter must be an integer');
});
it('test count resources input validation for pagination with limit with invalid type', function (): void {
$input = new CountResourcesInput('{"$and":[]}', false, 1, 'toto');
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('limit parameter must be an integer');
});
it('test count resources input validation for pagination with success', function (): void {
$input = new CountResourcesInput('{"$and":[]}', false, 1, 10);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Resources/Infrastructure/API/CountResources/CountResourcesRequestTransformerTest.php | centreon/tests/php/Core/Resources/Infrastructure/API/CountResources/CountResourcesRequestTransformerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Infrastructure\API\CountResources;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Resources\Infrastructure\API\CountResources\CountResourcesInput;
use Core\Resources\Infrastructure\API\CountResources\CountResourcesRequestTransformer;
use Mockery;
beforeEach(function (): void {
$this->filter = Mockery::mock(ResourceFilter::class);
$this->contact = new Contact();
$this->contact->setId(1);
});
it('test transform inputs to request to count resources as admin with pagination', function (): void {
$this->contact->setAdmin(true);
$input = new CountResourcesInput('{"$and":[]}', false, 1, 10);
$request = CountResourcesRequestTransformer::transform($input, $this->filter, $this->contact);
expect($request->contactId)->toBe(1)
->and($request->isAdmin)->toBeTrue()
->and($request->allPages)->toBeFalse()
->and($request->resourceFilter)->toBe($this->filter);
});
it('test transform inputs to request to count resources as admin without pagination', function (): void {
$this->contact->setAdmin(true);
$input = new CountResourcesInput('{"$and":[]}', true, null, null);
$request = CountResourcesRequestTransformer::transform($input, $this->filter, $this->contact);
expect($request->contactId)->toBe(1)
->and($request->isAdmin)->toBeTrue()
->and($request->allPages)->toBeTrue()
->and($request->resourceFilter)->toBe($this->filter);
});
it('test transform inputs to request to count resources as no admin with pagination', function (): void {
$this->contact->setAdmin(false);
$input = new CountResourcesInput('{"$and":[]}', false, 1, 10);
$request = CountResourcesRequestTransformer::transform($input, $this->filter, $this->contact);
expect($request->contactId)->toBe(1)
->and($request->isAdmin)->toBeFalse()
->and($request->allPages)->toBeFalse()
->and($request->resourceFilter)->toBe($this->filter);
});
it('test transform inputs to request to count resources as no admin without pagination', function (): void {
$this->contact->setAdmin(false);
$input = new CountResourcesInput('{"$and":[]}', true, null, null);
$request = CountResourcesRequestTransformer::transform($input, $this->filter, $this->contact);
expect($request->contactId)->toBe(1)
->and($request->isAdmin)->toBeFalse()
->and($request->allPages)->toBeTrue()
->and($request->resourceFilter)->toBe($this->filter);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Resources/Infrastructure/API/FindResources/FindResourcesRequestValidatorTest.php | centreon/tests/php/Core/Resources/Infrastructure/API/FindResources/FindResourcesRequestValidatorTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Infrastructure\API\FindResources;
use Core\Domain\RealTime\ResourceTypeInterface;
use Core\Resources\Infrastructure\API\FindResources\FindResourcesRequestValidator as Validator;
$fakeProviderName = 'awesomeProvider';
beforeEach(function () use ($fakeProviderName): void {
$this->expectInvalidArgumentException = function (callable $function, int $expectedCode): void {
$unexpected = 'It was expected to raise an ' . \InvalidArgumentException::class . " with code {$expectedCode}";
try {
$function();
$this->fail($unexpected);
} catch (\InvalidArgumentException $exception) {
if ($expectedCode === $exception->getCode()) {
// We expect exactly this InvalidArgumentException with this code.
expect(true)->toBeTrue();
return;
}
$this->fail($unexpected . ' but got a code ' . $exception->getCode());
} catch (\Throwable $exception) {
$this->fail($unexpected . ' but got a ' . $exception::class);
}
};
$this->fakeProvider = $this->createMock(ResourceTypeInterface::class);
$this->fakeProvider->method('getName')->willReturn($fakeProviderName);
$this->fakeValidator = new Validator(new \ArrayIterator([$this->fakeProvider]));
});
// ——— FAILING tests ———
it(
'should fail if there are no providers',
function (): void {
($this->expectInvalidArgumentException)(
fn () => new Validator(new \EmptyIterator()),
Validator::ERROR_NO_PROVIDERS
);
}
);
$dataset = [
['not_a_valid_field', Validator::ERROR_UNKNOWN_PARAMETER, null],
[Validator::PARAM_RESOURCE_TYPE, Validator::ERROR_NOT_A_RESOURCE_TYPE, ['foo']],
[Validator::PARAM_RESOURCE_TYPE, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_RESOURCE_TYPE, Validator::ERROR_NOT_AN_ARRAY, 'bar'],
[Validator::PARAM_STATES, Validator::ERROR_NOT_A_STATE, ['foo']],
[Validator::PARAM_STATES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_STATES, Validator::ERROR_NOT_AN_ARRAY, 'bar'],
[Validator::PARAM_STATUSES, Validator::ERROR_NOT_A_STATUS, ['foo']],
[Validator::PARAM_STATUSES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_STATUSES, Validator::ERROR_NOT_AN_ARRAY, 'bar'],
[Validator::PARAM_HOSTGROUP_NAMES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_SERVICEGROUP_NAMES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_MONITORING_SERVER_NAMES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_SERVICE_CATEGORY_NAMES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_HOST_CATEGORY_NAMES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_SERVICE_SEVERITY_NAMES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_HOST_SEVERITY_NAMES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_HOST_SEVERITY_LEVELS, Validator::ERROR_NOT_AN_ARRAY_OF_INTEGER, ['foo']],
[Validator::PARAM_SERVICE_SEVERITY_LEVELS, Validator::ERROR_NOT_AN_ARRAY_OF_INTEGER, ['foo']],
[Validator::PARAM_STATUS_TYPES, Validator::ERROR_NOT_A_STATUS_TYPE, ['foo']],
[Validator::PARAM_STATUS_TYPES, Validator::ERROR_NOT_AN_ARRAY_OF_STRING, [123]],
[Validator::PARAM_STATUS_TYPES, Validator::ERROR_NOT_AN_ARRAY, 'bar'],
[Validator::PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY, Validator::ERROR_NOT_A_BOOLEAN, 42],
[Validator::PARAM_OPEN_TICKET_RULE_ID, Validator::ERROR_NOT_A_INT, true],
[Validator::PARAM_RESOURCES_WITH_OPENED_TICKETS, Validator::ERROR_NOT_A_BOOLEAN, 42],
];
foreach ($dataset as [$field, $expectedCode, $value]) {
$message = match ($expectedCode) {
Validator::ERROR_UNKNOWN_PARAMETER => 'is an unknown parameter',
Validator::ERROR_NOT_A_RESOURCE_TYPE => 'is not a resource type',
Validator::ERROR_NOT_A_STATUS => 'is not a status',
Validator::ERROR_NOT_A_STATE => 'is not a state',
Validator::ERROR_NOT_A_STATUS_TYPE => 'is not a status_type',
Validator::ERROR_NOT_AN_ARRAY_OF_STRING => 'is not an array of string',
Validator::ERROR_NOT_AN_ARRAY_OF_INTEGER => 'is not an array of integer',
Validator::ERROR_NOT_AN_ARRAY => 'is not an array',
Validator::ERROR_NOT_A_BOOLEAN => 'is not a boolean',
Validator::ERROR_NO_PROVIDERS => 'has no providers',
default => 'is not valid',
};
it(
"should fail if the field '{$field}' {$message}",
function () use ($field, $expectedCode, $value): void {
($this->expectInvalidArgumentException)(
fn () => $this->fakeValidator->validateAndRetrieveRequestParameters([$field => $value]),
$expectedCode
);
}
);
}
// ——— SUCCESS tests ———
$datasetGenerator = function () use ($fakeProviderName): \Generator {
$dataset = [
[Validator::PARAM_RESOURCE_TYPE, [$fakeProviderName]],
[Validator::PARAM_STATES, Validator::ALLOWED_STATES],
[Validator::PARAM_STATES, [Validator::ALLOWED_STATES[0]]],
[Validator::PARAM_STATES, []],
[Validator::PARAM_STATUSES, Validator::ALLOWED_STATUSES],
[Validator::PARAM_STATUSES, [Validator::ALLOWED_STATUSES[0]]],
[Validator::PARAM_STATUSES, []],
[Validator::PARAM_HOSTGROUP_NAMES, ['foo', 'bar']],
[Validator::PARAM_HOSTGROUP_NAMES, []],
[Validator::PARAM_SERVICEGROUP_NAMES, ['foo', 'bar']],
[Validator::PARAM_SERVICEGROUP_NAMES, []],
[Validator::PARAM_MONITORING_SERVER_NAMES, ['foo', 'bar']],
[Validator::PARAM_MONITORING_SERVER_NAMES, []],
[Validator::PARAM_SERVICE_CATEGORY_NAMES, ['foo', 'bar']],
[Validator::PARAM_SERVICE_CATEGORY_NAMES, []],
[Validator::PARAM_HOST_CATEGORY_NAMES, ['foo', 'bar']],
[Validator::PARAM_HOST_CATEGORY_NAMES, []],
[Validator::PARAM_SERVICE_SEVERITY_NAMES, ['foo', 'bar']],
[Validator::PARAM_SERVICE_SEVERITY_NAMES, []],
[Validator::PARAM_HOST_SEVERITY_NAMES, ['foo', 'bar']],
[Validator::PARAM_HOST_SEVERITY_NAMES, []],
[Validator::PARAM_HOST_SEVERITY_LEVELS, [1, 2, 3]],
[Validator::PARAM_HOST_SEVERITY_LEVELS, [1, 2, 3], ['1', '2', '3']], // autocast int
[Validator::PARAM_HOST_SEVERITY_LEVELS, []],
[Validator::PARAM_SERVICE_SEVERITY_LEVELS, [1, 2, 3]],
[Validator::PARAM_SERVICE_SEVERITY_LEVELS, [1, 2, 3], ['1', '2', '3']], // autocast int
[Validator::PARAM_SERVICE_SEVERITY_LEVELS, []],
[Validator::PARAM_STATUS_TYPES, Validator::ALLOWED_STATUS_TYPES],
[Validator::PARAM_STATUS_TYPES, [Validator::ALLOWED_STATUS_TYPES[0]]],
[Validator::PARAM_STATUS_TYPES, []],
[Validator::PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY, true],
[Validator::PARAM_RESOURCES_ON_PERFORMANCE_DATA_AVAILABILITY, false],
[Validator::PARAM_RESOURCES_WITH_OPENED_TICKETS, true],
[Validator::PARAM_RESOURCES_WITH_OPENED_TICKETS, false],
[Validator::PARAM_OPEN_TICKET_RULE_ID, 42],
];
foreach ($dataset as $args) {
[$field, $expected, $value] = [$args[0], $args[1], $args[2] ?? $args[1]];
yield $field . ' = ' . json_encode($value) => [$field, $expected, $value];
}
};
it(
'should validate',
function ($field, $expected, $value): void {
$validated = $this->fakeValidator->validateAndRetrieveRequestParameters([$field => $value]);
expect($validated[$field] ?? null)->toBe($expected);
}
)->with($datasetGenerator());
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesInputTest.php | centreon/tests/php/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesInputTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Infrastructure\API\ExportResources;
use Core\Resources\Infrastructure\API\ExportResources\ExportResourcesInput;
use Symfony\Component\Validator\Validation;
beforeEach(function (): void {
$this->validator = Validation::createValidatorBuilder()
->enableAttributeMapping()
->getValidator();
});
// format parameter
it('test export resources input validation with no format', function (): void {
$input = new ExportResourcesInput(
null,
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('format parameter is required');
});
it('test export resources input validation with an empty format', function (): void {
$input = new ExportResourcesInput(
'',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(2)
->and($errors[0]->getMessage())->toBe('format parameter is required')
->and($errors[1]->getMessage())->toBe('format parameter must be one of the following: "csv"');
});
it('test export resources input validation with an invalid type for format', function (): void {
$input = new ExportResourcesInput(
0,
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('format parameter must be one of the following: "csv"');
});
it('test export resources input validation with an invalid value for format', function (): void {
$input = new ExportResourcesInput(
'pdf',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('format parameter must be one of the following: "csv"');
});
it('test export resources input validation with a valid format', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
});
// sort_by parameter
it('test export resources input validation with no sort_by', function (): void {
$input = new ExportResourcesInput('csv', false, null, null, 1, 100, null, '{"$and":[]}');
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('sort_by parameter is required');
});
it('test export resources input validation with an empty sort_by', function (): void {
$input = new ExportResourcesInput('csv', false, null, null, 1, 100, '', '{"$and":[]}');
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('sort_by parameter is required');
});
it('test export resources input validation with an invalid value for sort_by', function (): void {
$input = new ExportResourcesInput('csv', false, null, null, 1, 100, 'toto', '{"$and":[]}');
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('sort_by parameter must be a valid JSON');
});
it('test export resources input validation with sort_by with an invalid json', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{status_severity_code:"desc",last_status_change:"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('sort_by parameter must be a valid JSON');
});
it('test export resources input validation with a valid json for sort_by', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
});
// search parameter
it('test export resources input validation with no search', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
null
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('search parameter is required');
});
it('test export resources input validation with an empty search', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
''
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('search parameter is required');
});
it('test export resources input validation with search with an invalid value', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'toto'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('search parameter must be a valid JSON');
});
it('test export resources input validation with search with an invalid json', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{$and:[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('search parameter must be a valid JSON');
});
it('test export resources input validation with search with a valid json', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
});
// all_pages parameter
it('test export resources input validation with no all_pages', function (): void {
$input = new ExportResourcesInput(
'csv',
null,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('all_pages parameter is required');
});
it('test export resources input validation with an empty all_pages', function (): void {
$input = new ExportResourcesInput(
'csv',
'',
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('all_pages parameter must be a boolean');
});
it('test export resources input validation with an invalid type for all_pages', function (): void {
$input = new ExportResourcesInput(
'csv',
'toto',
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('all_pages parameter must be a boolean');
});
it('test export resources input validation with all_pages equals to false without page and limit', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
null,
null,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(2)
->and($errors[0]->getMessage())->toBe('page parameter is required when all_pages is false')
->and($errors[1]->getMessage())->toBe('limit parameter is required when all_pages is false');
});
it('test export resources input validation with all_pages equals to false with page and without limit', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
null,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('limit parameter is required when all_pages is false');
});
it('test export resources input validation with all_pages equals to false with limit and without page', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
null,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('page parameter is required when all_pages is false');
});
it(
'test export resources input validation with all_pages equals to false with limit and page with an invalid format for limit',
function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
'toto',
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('limit parameter must be an integer');
}
);
it(
'test export resources input validation with all_pages equals to false with limit and page with an invalid format for page',
function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
'toto',
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('page parameter must be an integer');
}
);
it(
'test export resources input validation with all_pages equals to false with limit and page = 0',
function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
0,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('page parameter must be greater than 1');
}
);
it('test export resources input validation with all_pages equals to false with valid limit and page', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
});
it(
'test export resources input validation with all_pages equals to true without pagination and without max_lines',
function (): void {
$input = new ExportResourcesInput(
'csv',
true,
null,
null,
null,
null,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('max_lines parameter is required when all_pages is true');
}
);
it(
'test export resources input validation with all_pages equals to true without pagination and with an invalid max_lines',
function (): void {
$input = new ExportResourcesInput(
'csv',
true,
null,
'toto',
null,
null,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('max_lines parameter must be an integer');
}
);
it(
'test export resources input validation with all_pages equals to true without pagination and with a max_lines greather than 10000',
function (): void {
$input = new ExportResourcesInput(
'csv',
true,
null,
12000,
null,
null,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe('max_lines parameter must be between 1 and 10000');
}
);
it(
'test export resources input validation with all_pages equals to true without pagination and with a valid max_lines',
function (): void {
$input = new ExportResourcesInput(
'csv',
true,
null,
100,
null,
null,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
}
);
it(
'test export resources input validation with all_pages equals to true with pagination (should be ignored) and with a valid max_lines',
function (): void {
$input = new ExportResourcesInput(
'csv',
true,
null,
100,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
}
);
// columns parameter
it('test export resources input validation with no columns', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
null,
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
});
it('test export resources input validation with an empty columns', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
'',
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(2)
->and($errors[0]->getMessage())->toBe('columns parameter must be an array')
->and($errors[1]->getMessage())->toBe('This value should be of type iterable.');
});
it('test export resources input validation with an invalid columns', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
'toto',
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(2)
->and($errors[0]->getMessage())->toBe('columns parameter must be an array')
->and($errors[1]->getMessage())->toBe('This value should be of type iterable.');
});
it('test export resources input validation with columns with an empty value', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
[''],
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(2)
->and($errors[0]->getMessage())->toBe('columns parameter value must not be empty')
->and($errors[1]->getMessage())->toBe(
'columns parameter must be one of the following: "resource", "status", "parent_resource", "duration", "last_check", "information", "tries", "severity", "notes_url", "action_url", "state", "alias", "parent_alias", "fqdn", "monitoring_server_name", "notification", "checks"'
);
});
it('test export resources input validation with columns with an invalid value', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
['toto'],
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(1)
->and($errors[0]->getMessage())->toBe(
'columns parameter must be one of the following: "resource", "status", "parent_resource", "duration", "last_check", "information", "tries", "severity", "notes_url", "action_url", "state", "alias", "parent_alias", "fqdn", "monitoring_server_name", "notification", "checks"'
);
});
it('test export resources input validation with columns with a valid value', function (): void {
$input = new ExportResourcesInput(
'csv',
false,
['status'],
null,
1,
100,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$errors = $this->validator->validate($input);
expect($errors)->toHaveCount(0);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesRequestTransformerTest.php | centreon/tests/php/Core/Resources/Infrastructure/API/ExportResources/ExportResourcesRequestTransformerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Resources\Infrastructure\API\ExportResources;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Monitoring\ResourceFilter;
use Core\Resources\Infrastructure\API\ExportResources\ExportResourcesInput;
use Core\Resources\Infrastructure\API\ExportResources\ExportResourcesRequestTransformer;
use Mockery;
beforeEach(function (): void {
$this->filter = Mockery::mock(ResourceFilter::class);
$this->contact = new Contact();
$this->contact->setId(1);
$this->contact->setAdmin(true);
});
it('test transform inputs to request to export resources with pagination', function (): void {
$input = new ExportResourcesInput(
'csv',
'0',
['status'],
null,
'1',
'100',
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$request = ExportResourcesRequestTransformer::transform($input, $this->filter, $this->contact);
expect($request->exportedFormat)->toBe('csv')
->and($request->allPages)->toBeFalse()
->and($request->maxResults)->toBe(0)
->and($request->columns->toArray())->toBe(['status'])
->and($request->resourceFilter)->toBe($this->filter)
->and($request->contactId)->toBe(1)
->and($request->isAdmin)->toBeTrue();
});
it('test transform inputs to request to export resources without pagination', function (): void {
$input = new ExportResourcesInput(
'csv',
'1',
['status'],
'999',
null,
null,
'{"status_severity_code":"desc","last_status_change":"desc"}',
'{"$and":[]}'
);
$request = ExportResourcesRequestTransformer::transform($input, $this->filter, $this->contact);
expect($request->exportedFormat)->toBe('csv')
->and($request->allPages)->toBeTrue()
->and($request->maxResults)->toBe(999)
->and($request->columns->toArray())->toBe(['status'])
->and($request->resourceFilter)->toBe($this->filter)
->and($request->contactId)->toBe(1)
->and($request->isAdmin)->toBeTrue();
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostCategory/Application/UseCase/FindHostCategories/FindHostCategoriesTest.php | centreon/tests/php/Core/HostCategory/Application/UseCase/FindHostCategories/FindHostCategoriesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Application\UseCase\FindHostCategories;
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\HostCategory\Application\Exception\HostCategoryException;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\UseCase\FindHostCategories\FindHostCategories;
use Core\HostCategory\Application\UseCase\FindHostCategories\FindHostCategoriesResponse;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Exception;
beforeEach(function (): void {
$this->hostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->usecase = new FindHostCategories(
$this->hostCategoryRepository,
$this->accessGroupRepository,
$this->requestParameters,
$this->user,
false
);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->hostCategoryName = 'hc-name';
$this->hostCategoryAlias = 'hc-alias';
$this->hostCategoryComment = 'blablabla';
$this->hostCategory = new HostCategory(1, $this->hostCategoryName, $this->hostCategoryAlias);
$this->hostCategory->setComment($this->hostCategoryComment);
$this->responseArray = [
'id' => 1,
'name' => $this->hostCategoryName,
'alias' => $this->hostCategoryAlias,
'is_activated' => true,
'comment' => $this->hostCategoryComment,
];
$this->accessGroups = [new AccessGroup(1, 'ag-1', 'ag-1-alias')];
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->hostCategoryRepository
->expects($this->once())
->method('findAll')
->willThrowException(new Exception());
($this->usecase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostCategoryException::findHostCategories(new Exception())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has unsufficient rights', function (): void {
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, false],
]
);
($this->usecase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostCategoryException::accessNotAllowed()->getMessage());
});
it('should present a FindHostGroupsResponse when a non-admin user has read only rights', function (): void {
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, true],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, false],
]
);
$this->accessGroupRepository
->expects($this->any())
->method('findByContact')
->willReturn($this->accessGroups);
$this->hostCategoryRepository
->expects($this->once())
->method('hasRestrictedAccessToHostCategories')
->willReturn(true);
$this->hostCategoryRepository
->expects($this->once())
->method('findAllByAccessGroupIds')
->willReturn([$this->hostCategory]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindHostCategoriesResponse::class)
->and($this->presenter->getPresentedData()->hostCategories[0])
->toBe($this->responseArray);
});
it('should present a FindHostGroupsResponse when a non-admin user has read/write rights', function (): void {
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, true],
]
);
$this->accessGroupRepository
->expects($this->any())
->method('findByContact')
->willReturn($this->accessGroups);
$this->hostCategoryRepository
->expects($this->once())
->method('hasRestrictedAccessToHostCategories')
->willReturn(true);
$this->hostCategoryRepository
->expects($this->once())
->method('findAllByAccessGroupIds')
->willReturn([$this->hostCategory]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindHostCategoriesResponse::class)
->and($this->presenter->getPresentedData()->hostCategories[0])
->toBe($this->responseArray);
});
it('should present a FindHostCategoriesResponse with admin user', function (): void {
$this->user
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->hostCategoryRepository
->expects($this->once())
->method('findAll')
->willReturn([$this->hostCategory]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindHostCategoriesResponse::class)
->and($this->presenter->getPresentedData()->hostCategories[0])
->toBe($this->responseArray);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostCategory/Application/UseCase/UpdateHostCategory/UpdateHostCategoryTest.php | centreon/tests/php/Core/HostCategory/Application/UseCase/UpdateHostCategory/UpdateHostCategoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Application\UseCase\UpdateHostCategory;
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\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\HostCategory\Application\Exception\HostCategoryException;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface;
use Core\HostCategory\Application\UseCase\UpdateHostCategory\UpdateHostCategory;
use Core\HostCategory\Application\UseCase\UpdateHostCategory\UpdateHostCategoryRequest;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->writeHostCategoryRepository = $this->createMock(WriteHostCategoryRepositoryInterface::class);
$this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->originalHostCategory = new HostCategory(1, 'hc-name', 'hc-alias');
$this->request = new UpdateHostCategoryRequest();
$this->request->name = 'hc-name-edit';
$this->request->alias = 'hc-alias-edit';
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->useCase = new UpdateHostCategory(
$this->writeHostCategoryRepository,
$this->readHostCategoryRepository,
$this->accessGroupRepository,
$this->user
);
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostCategoryException::UpdateHostCategory(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostCategoryException::writingActionsNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the host category does not exist (with admin user)', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host category not found');
});
it('should present a NotFoundResponse when the host category does not exist (with non-admin user)', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host category not found');
});
it('should present an ErrorResponse if the existing host category cannot be retrieved', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostCategoryException::errorWhileRetrievingObject()->getMessage());
});
it('should present a ConflictResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostCategory);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostCategoryException::hostNameAlreadyExists()->getMessage());
});
it('should present an InvalidArgumentResponse when an assertion fails', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostCategory);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->request->alias = '';
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(InvalidArgumentResponse::class);
});
it('should return created object on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostCategory);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->writeHostCategoryRepository
->expects($this->once())
->method('update');
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostCategory/Application/UseCase/DeleteHostCategory/DeleteHostCategoryTest.php | centreon/tests/php/Core/HostCategory/Application/UseCase/DeleteHostCategory/DeleteHostCategoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Application\UseCase\DeleteHostCategory;
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\HostCategory\Application\Exception\HostCategoryException;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface;
use Core\HostCategory\Application\UseCase\DeleteHostCategory\DeleteHostCategory;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->writeHostCategoryRepository = $this->createMock(WriteHostCategoryRepositoryInterface::class);
$this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->user = $this->createMock(ContactInterface::class);
$this->hostCategory = $this->createMock(HostCategory::class);
$this->hostCategoryId = 1;
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$useCase = new DeleteHostCategory(
$this->writeHostCategoryRepository,
$this->readHostCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->writeHostCategoryRepository
->expects($this->once())
->method('deleteById')
->willThrowException(new \Exception());
$useCase($this->hostCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostCategoryException::deleteHostCategory(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has insufficient rights', function (): void {
$useCase = new DeleteHostCategory(
$this->writeHostCategoryRepository,
$this->readHostCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
$useCase($this->hostCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostCategoryException::deleteNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the host category does not exist (with admin user)', function (): void {
$useCase = new DeleteHostCategory(
$this->writeHostCategoryRepository,
$this->readHostCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$useCase($this->hostCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host category not found');
});
it('should present a NotFoundResponse when the host category does not exist (with non-admin user)', function (): void {
$useCase = new DeleteHostCategory(
$this->writeHostCategoryRepository,
$this->readHostCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(false);
$useCase($this->hostCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host category not found');
});
it('should present a NoContentResponse on success (with admin user)', function (): void {
$useCase = new DeleteHostCategory(
$this->writeHostCategoryRepository,
$this->readHostCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$hostCategoryId = 1;
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->writeHostCategoryRepository
->expects($this->once())
->method('deleteById');
$useCase($hostCategoryId, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
it('should present a NoContentResponse on success (with non-admin user)', function (): void {
$useCase = new DeleteHostCategory(
$this->writeHostCategoryRepository,
$this->readHostCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(true);
$this->writeHostCategoryRepository
->expects($this->once())
->method('deleteById');
$useCase($this->hostCategoryId, $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/HostCategory/Application/UseCase/AddHostCategory/AddHostCategoryTest.php | centreon/tests/php/Core/HostCategory/Application/UseCase/AddHostCategory/AddHostCategoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Application\UseCase\AddHostCategory;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\HostCategory\Application\Exception\HostCategoryException;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\WriteHostCategoryRepositoryInterface;
use Core\HostCategory\Application\UseCase\AddHostCategory\AddHostCategory;
use Core\HostCategory\Application\UseCase\AddHostCategory\AddHostCategoryRequest;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
beforeEach(function (): void {
$this->writeHostCategoryRepository = $this->createMock(WriteHostCategoryRepositoryInterface::class);
$this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->request = new AddHostCategoryRequest();
$this->request->name = 'hc-name';
$this->request->alias = 'hc-alias';
$this->request->comment = null;
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->useCase = new AddHostCategory(
$this->writeHostCategoryRepository,
$this->readHostCategoryRepository,
$this->user
);
$this->hostCategory = new HostCategory(1, $this->request->name, $this->request->alias);
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByName')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostCategoryException::addHostCategory(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostCategoryException::writingActionsNotAllowed()->getMessage());
});
it('should present an InvalidArgumentResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostCategoryException::hostNameAlreadyExists()->getMessage());
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->writeHostCategoryRepository
->expects($this->once())
->method('add')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostCategoryException::addHostCategory(new \Exception())->getMessage());
});
it('should present an ErrorResponse if the newly created host category cannot be retrieved', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->writeHostCategoryRepository
->expects($this->once())
->method('add')
->willReturn(1);
$this->readHostCategoryRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostCategoryException::errorWhileRetrievingObject()->getMessage());
});
it('should return created object on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->writeHostCategoryRepository
->expects($this->once())
->method('add')
->willReturn(1);
$this->readHostCategoryRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostCategory);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getPresentedData())->toBeInstanceOf(CreatedResponse::class);
expect($this->presenter->getPresentedData()->getResourceId())->toBe($this->hostCategory->getId());
$payload = $this->presenter->getPresentedData()->getPayload();
expect($payload->name)
->toBe($this->hostCategory->getName())
->and($payload->alias)
->toBe($this->hostCategory->getAlias())
->and($payload->isActivated)
->toBe($this->hostCategory->isActivated())
->and($payload->comment)
->toBe($this->hostCategory->getComment());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostCategory/Application/UseCase/FindHostCategory/FindHostCategoryTest.php | centreon/tests/php/Core/HostCategory/Application/UseCase/FindHostCategory/FindHostCategoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Application\UseCase\FindHostCategory;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\HostCategory\Application\Exception\HostCategoryException;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\UseCase\FindHostCategory\FindHostCategory;
use Core\HostCategory\Application\UseCase\FindHostCategory\FindHostCategoryResponse;
use Core\HostCategory\Domain\Model\HostCategory;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Exception;
beforeEach(function (): void {
$this->readHostCategoryRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->usecase = new FindHostCategory(
$this->readHostCategoryRepository,
$this->accessGroupRepository,
$this->user
);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->hostCategoryName = 'hc-name';
$this->hostCategoryAlias = 'hc-alias';
$this->hostCategoryComment = 'blablabla';
$this->hostCategory = new HostCategory(1, $this->hostCategoryName, $this->hostCategoryAlias);
$this->hostCategory->setComment($this->hostCategoryComment);
$this->responseArray = [
'id' => 1,
'name' => $this->hostCategoryName,
'alias' => $this->hostCategoryAlias,
'is_activated' => true,
'comment' => $this->hostCategoryComment,
];
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willThrowException(new Exception());
($this->usecase)($this->hostCategory->getId(), $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostCategoryException::findHostCategory(new Exception(), $this->hostCategory->getId())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, false],
]
);
($this->usecase)($this->hostCategory->getId(), $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostCategoryException::accessNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the host category does not exist (with admin user)', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(false);
($this->usecase)($this->hostCategory->getId(), $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host category not found');
});
it('should present a NotFoundResponse when the host category does not exist (with non-admin user)', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(false);
($this->usecase)($this->hostCategory->getId(), $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host category not found');
});
it('should present a FindHostCategoryResponse when a non-admin user has read-only rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, true],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, false],
]
);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostCategory);
($this->usecase)($this->hostCategory->getId(), $this->presenter);
$response = $this->presenter->getPresentedData();
expect($response)
->toBeInstanceOf(FindHostCategoryResponse::class)
->and($response->id)
->toBe($this->responseArray['id'])
->and($response->name)
->toBe($this->responseArray['name'])
->and($response->alias)
->toBe($this->responseArray['alias'])
->and($response->isActivated)
->toBe($this->responseArray['is_activated'])
->and($response->comment)
->toBe($this->responseArray['comment']);
});
it('should present a FindHostCategoryResponse when a non-admin user has read/write rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, true],
]
);
$this->readHostCategoryRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostCategory);
($this->usecase)($this->hostCategory->getId(), $this->presenter);
$response = $this->presenter->getPresentedData();
expect($response)
->toBeInstanceOf(FindHostCategoryResponse::class)
->and($response->id)
->toBe($this->responseArray['id'])
->and($response->name)
->toBe($this->responseArray['name'])
->and($response->alias)
->toBe($this->responseArray['alias'])
->and($response->isActivated)
->toBe($this->responseArray['is_activated'])
->and($response->comment)
->toBe($this->responseArray['comment']);
});
it('should present a FindHostCategoryResponse with admin user', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostCategoryRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostCategory);
($this->usecase)($this->hostCategory->getId(), $this->presenter);
$response = $this->presenter->getPresentedData();
expect($response)
->toBeInstanceOf(FindHostCategoryResponse::class)
->and($response->id)
->toBe($this->responseArray['id'])
->and($response->name)
->toBe($this->responseArray['name'])
->and($response->alias)
->toBe($this->responseArray['alias'])
->and($response->isActivated)
->toBe($this->responseArray['is_activated'])
->and($response->comment)
->toBe($this->responseArray['comment']);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategoriesPresenterStub.php | centreon/tests/php/Core/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategoriesPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Application\UseCase\FindRealTimeHostCategories;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\HostCategory\Application\UseCase\FindRealTimeHostCategories\FindRealTimeHostCategoriesPresenterInterface;
use Core\HostCategory\Application\UseCase\FindRealTimeHostCategories\FindRealTimeHostCategoriesResponse;
class FindRealTimeHostCategoriesPresenterStub extends AbstractPresenter implements FindRealTimeHostCategoriesPresenterInterface
{
public FindRealTimeHostCategoriesResponse|ResponseStatusInterface $response;
public function presentResponse(FindRealTimeHostCategoriesResponse|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/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategoriesTest.php | centreon/tests/php/Core/HostCategory/Application/UseCase/FindRealTimeHostCategories/FindRealTimeHostCategoriesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Application\UseCase\FindRealTimeHostCategories;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\HostCategory\Application\Repository\ReadHostCategoryRepositoryInterface;
use Core\HostCategory\Application\Repository\ReadRealTimeHostCategoryRepositoryInterface;
use Core\HostCategory\Application\UseCase\FindRealTimeHostCategories\FindRealTimeHostCategories;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Core\Tag\RealTime\Domain\Model\Tag;
beforeEach(function (): void {
$this->useCase = new FindRealTimeHostCategories(
$this->user = $this->createMock(ContactInterface::class),
$this->repository = $this->createMock(ReadRealTimeHostCategoryRepositoryInterface::class),
$this->configurationRepository = $this->createMock(ReadHostCategoryRepositoryInterface::class),
$this->requestParameters = $this->createMock(RequestParametersInterface::class),
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class)
);
$this->presenter = new FindRealTimeHostCategoriesPresenterStub($this->createMock(PresenterFormatterInterface::class));
$this->accessGroup = new AccessGroup(1, 'AG-name', 'AG-alias');
$this->category = new Tag(1, 'host-category-name', Tag::SERVICE_CATEGORY_TYPE_ID);
});
it('should find all categories as admin', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->repository->expects($this->once())
->method('findAll')
->willReturn([$this->category]);
($this->useCase)($this->presenter);
expect($this->presenter->response->tags)->toHaveCount(1);
expect($this->presenter->response->tags[0]['id'])->toBe($this->category->getId());
expect($this->presenter->response->tags[0]['name'])->toBe($this->category->getName());
});
it('should find all categories as user with no filters on categories', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([$this->accessGroup]);
$this->configurationRepository
->expects($this->once())
->method('hasRestrictedAccessToHostCategories')
->willReturn(false);
$this->repository->expects($this->once())
->method('findAll')
->willReturn([$this->category]);
($this->useCase)($this->presenter);
expect($this->presenter->response->tags)->toHaveCount(1);
expect($this->presenter->response->tags[0]['id'])->toBe($this->category->getId());
expect($this->presenter->response->tags[0]['name'])->toBe($this->category->getName());
});
it('should find all categories as user with filters on categories', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->accessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([$this->accessGroup]);
$this->configurationRepository
->expects($this->once())
->method('hasRestrictedAccessToHostCategories')
->willReturn(true);
$this->repository->expects($this->once())
->method('findAllByAccessGroupIds')
->willReturn([$this->category]);
($this->useCase)($this->presenter);
expect($this->presenter->response->tags)->toHaveCount(1);
expect($this->presenter->response->tags[0]['id'])->toBe($this->category->getId());
expect($this->presenter->response->tags[0]['name'])->toBe($this->category->getName());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostCategory/Domain/Model/NewHostCategoryTest.php | centreon/tests/php/Core/HostCategory/Domain/Model/NewHostCategoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\HostCategory\Domain\Model\NewHostCategory;
beforeEach(function (): void {
$this->categoryName = 'host-name';
$this->categoryAlias = 'host-alias';
});
it('should return properly set host category instance', function (): void {
$hostCategory = new NewHostCategory($this->categoryName, $this->categoryAlias);
expect($hostCategory->getName())->toBe($this->categoryName)
->and($hostCategory->getAlias())->toBe($this->categoryAlias);
});
it('should throw an exception when host category name is empty', function (): void {
new NewHostCategory('', $this->categoryAlias);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewHostCategory::name')
->getMessage()
);
it('should throw an exception when host category name is too long', function (): void {
new NewHostCategory(str_repeat('a', NewHostCategory::MAX_NAME_LENGTH + 1), $this->categoryAlias);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewHostCategory::MAX_NAME_LENGTH + 1),
NewHostCategory::MAX_NAME_LENGTH + 1,
NewHostCategory::MAX_NAME_LENGTH,
'NewHostCategory::name'
)->getMessage()
);
it('should throw an exception when host category alias is empty', function (): void {
new NewHostCategory($this->categoryName, '');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewHostCategory::alias')
->getMessage()
);
it('should throw an exception when host category alias is too long', function (): void {
new NewHostCategory($this->categoryName, str_repeat('a', NewHostCategory::MAX_ALIAS_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewHostCategory::MAX_ALIAS_LENGTH + 1),
NewHostCategory::MAX_ALIAS_LENGTH + 1,
NewHostCategory::MAX_ALIAS_LENGTH,
'NewHostCategory::alias'
)->getMessage()
);
it('should throw an exception when host category comment is too long', function (): void {
$hostCategory = new NewHostCategory($this->categoryName, $this->categoryAlias);
$hostCategory->setComment(str_repeat('a', NewHostCategory::MAX_COMMENT_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewHostCategory::MAX_COMMENT_LENGTH + 1),
NewHostCategory::MAX_COMMENT_LENGTH + 1,
NewHostCategory::MAX_COMMENT_LENGTH,
'NewHostCategory::comment'
)->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/HostCategory/Domain/Model/HostCategoryTest.php | centreon/tests/php/Core/HostCategory/Domain/Model/HostCategoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostCategory\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\HostCategory\Domain\Model\HostCategory;
beforeEach(function (): void {
$this->categoryName = 'host-name';
$this->categoryAlias = 'host-alias';
});
it('should return properly set host category instance', function (): void {
$hostCategory = new HostCategory(1, $this->categoryName, $this->categoryAlias);
expect($hostCategory->getId())->toBe(1)
->and($hostCategory->getName())->toBe($this->categoryName)
->and($hostCategory->getAlias())->toBe($this->categoryAlias);
});
it('should throw an exception when host category name is empty', function (): void {
new HostCategory(1, '', $this->categoryAlias);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('HostCategory::name')
->getMessage()
);
it('should throw an exception when host category name is too long', function (): void {
new HostCategory(1, str_repeat('a', HostCategory::MAX_NAME_LENGTH + 1), $this->categoryAlias);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostCategory::MAX_NAME_LENGTH + 1),
HostCategory::MAX_NAME_LENGTH + 1,
HostCategory::MAX_NAME_LENGTH,
'HostCategory::name'
)->getMessage()
);
it('should throw an exception when host category name is set empty', function (): void {
$hostCategory = new HostCategory(1, 'HCName', $this->categoryAlias);
$hostCategory->setName('');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('HostCategory::name')
->getMessage()
);
it('should throw an exception when host category name is set too long', function (): void {
$hostCategory = new HostCategory(1, 'HCName', $this->categoryAlias);
$hostCategory->setName(str_repeat('a', HostCategory::MAX_NAME_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostCategory::MAX_NAME_LENGTH + 1),
HostCategory::MAX_NAME_LENGTH + 1,
HostCategory::MAX_NAME_LENGTH,
'HostCategory::name'
)->getMessage()
);
it('should throw an exception when host category alias is empty', function (): void {
new HostCategory(1, $this->categoryName, '');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('HostCategory::alias')
->getMessage()
);
it('should throw an exception when host category alias is too long', function (): void {
new HostCategory(1, $this->categoryName, str_repeat('a', HostCategory::MAX_ALIAS_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostCategory::MAX_ALIAS_LENGTH + 1),
HostCategory::MAX_ALIAS_LENGTH + 1,
HostCategory::MAX_ALIAS_LENGTH,
'HostCategory::alias'
)->getMessage()
);
it('should throw an exception when host category alias is set empty', function (): void {
$hostCategory = new HostCategory(1, $this->categoryName, 'HCAlias');
$hostCategory->setAlias('');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('HostCategory::alias')
->getMessage()
);
it('should throw an exception when host category alias is set too long', function (): void {
$hostCategory = new HostCategory(1, $this->categoryName, 'HCAlias');
$hostCategory->setAlias(str_repeat('a', HostCategory::MAX_ALIAS_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostCategory::MAX_ALIAS_LENGTH + 1),
HostCategory::MAX_ALIAS_LENGTH + 1,
HostCategory::MAX_ALIAS_LENGTH,
'HostCategory::alias'
)->getMessage()
);
it('should throw an exception when host category comment is too long', function (): void {
$hostCategory = new HostCategory(1, $this->categoryName, $this->categoryAlias);
$hostCategory->setComment(str_repeat('a', HostCategory::MAX_COMMENT_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostCategory::MAX_COMMENT_LENGTH + 1),
HostCategory::MAX_COMMENT_LENGTH + 1,
HostCategory::MAX_COMMENT_LENGTH,
'HostCategory::comment'
)->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/Infrastructure/Configuration/User/Api/FindUsers/FindUsersControllerTest.php | centreon/tests/php/Core/Infrastructure/Configuration/User/Api/FindUsers/FindUsersControllerTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Infrastructure\Configuration\User\Api\FindUsers;
use Centreon\Domain\Contact\Contact;
use Core\Application\Configuration\User\UseCase\FindUsers\FindUsers;
use Core\Application\Configuration\User\UseCase\FindUsers\FindUsersPresenterInterface;
use Core\Infrastructure\Configuration\User\Api\FindUsers\FindUsersController;
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 FindUsersControllerTest extends TestCase
{
/** @var FindUsersPresenterInterface&\PHPUnit\Framework\MockObject\MockObject */
private $presenter;
/** @var FindUsers&\PHPUnit\Framework\MockObject\MockObject */
private $useCase;
/** @var ContainerInterface&\PHPUnit\Framework\MockObject\MockObject */
private $container;
public function setUp(): void
{
$this->presenter = $this->createMock(FindUsersPresenterInterface::class);
$this->useCase = $this->createMock(FindUsers::class);
$timezone = new \DateTimeZone('Europe/Paris');
$adminContact = (new Contact())
->setId(1)
->setName('admin')
->setAdmin(true)
->setTimezone($timezone);
/**
* @var AuthorizationCheckerInterface&\PHPUnit\Framework\MockObject\MockObject
*/
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$authorizationChecker->expects($this->once())
->method('isGranted')
->willReturn(true);
/**
* @var TokenInterface&\PHPUnit\Framework\MockObject\MockObject
*/
$token = $this->createMock(TokenInterface::class);
$token->expects($this->any())
->method('getUser')
->willReturn($adminContact);
/**
* @var TokenStorageInterface&\PHPUnit\Framework\MockObject\MockObject
*/
$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__ . '/../../../../../';
}
}
);
}
/**
* Test that the controller calls properly the usecase
*/
public function testFindControllerExecute(): void
{
$controller = new FindUsersController();
$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/Infrastructure/Configuration/User/Api/FindUsers/FindUsersPresenterTest.php | centreon/tests/php/Core/Infrastructure/Configuration/User/Api/FindUsers/FindUsersPresenterTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Infrastructure\Configuration\User\Api\FindUsers;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Configuration\User\UseCase\FindUsers\FindUsersResponse;
use Core\Domain\Configuration\User\Model\User;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Infrastructure\Configuration\User\Api\FindUsers\FindUsersPresenter;
use PHPUnit\Framework\TestCase;
class FindUsersPresenterTest extends TestCase
{
/** @var RequestParametersInterface&\PHPUnit\Framework\MockObject\MockObject */
private $requestParameters;
/** @var PresenterFormatterInterface&\PHPUnit\Framework\MockObject\MockObject */
private $presenterFormatter;
public function setUp(): void
{
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
}
/**
* Test that the controller calls properly the usecase
*/
public function testFindControllerExecute(): void
{
$presenter = new FindUsersPresenter(
$this->requestParameters,
$this->presenterFormatter,
);
$requestParameterValues = [
'page' => 1,
'limit' => 1,
'search' => '',
'sort_by' => '',
'total' => 3,
];
$user = [
'id' => 1,
'alias' => 'alias',
'name' => 'name',
'email' => 'root@localhost',
'is_admin' => true,
];
$userModel = new User(
1,
'alias',
'name',
'root@localhost',
true,
'light',
'compact',
true
);
$this->requestParameters->expects($this->once())
->method('toArray')
->willReturn($requestParameterValues);
$this->presenterFormatter->expects($this->once())
->method('format')
->with(
[
'result' => [$user],
'meta' => $requestParameterValues,
]
);
$response = new FindUsersResponse([$userModel]);
$presenter->present($response);
$presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Infrastructure/Configuration/User/Repository/DbUserFactoryTest.php | centreon/tests/php/Core/Infrastructure/Configuration/User/Repository/DbUserFactoryTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Infrastructure\Configuration\User\Repository;
use Core\Infrastructure\Configuration\User\Repository\DbUserFactory;
use PHPUnit\Framework\TestCase;
class DbUserFactoryTest extends TestCase
{
/** @var array<string, string> */
private array $userRecord;
public function setUp(): void
{
$this->userRecord = [
'contact_id' => '1',
'contact_alias' => 'alias',
'contact_name' => 'name',
'contact_email' => 'root@localhost',
'contact_admin' => '1',
'contact_theme' => 'light',
'user_interface_density' => 'compact',
'user_can_reach_frontend' => '1',
];
}
/**
* Test that user is properly created
*/
public function testUserCreation(): void
{
$user = DbUserFactory::createFromRecord($this->userRecord);
$this->assertEquals(1, $user->getId());
$this->assertEquals('alias', $user->getAlias());
$this->assertEquals(('name'), $user->getName());
$this->assertEquals('root@localhost', $user->getEmail());
$this->assertEquals(true, $user->isAdmin());
$this->assertEquals('light', $user->getTheme());
$this->assertEquals('compact', $user->getUserInterfaceDensity());
$this->assertEquals(true, $user->canReachFrontend());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Infrastructure/Common/Api/HttpUrlTraitTest.php | centreon/tests/php/Core/Infrastructure/Common/Api/HttpUrlTraitTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Infrastructure\Common\Api;
use Core\Infrastructure\Common\Api\HttpUrlTrait;
use Symfony\Component\HttpFoundation\ServerBag;
uses(HttpUrlTrait::class);
beforeEach(function (): void {
$this->httpServerBag = new ServerBag([]);
});
it('returns empty base url when there is no current request', function (): void {
expect($this->getBaseUrl())->toBe('');
});
it('returns empty base uri when there is no current request', function (): void {
expect($this->getBaseUri())->toBe('');
});
it(
'formats properly base uri',
function (
$requestUri,
$baseUri,
): void {
$this->httpServerBag->replace(['REQUEST_URI' => $requestUri]);
expect($this->getBaseUri())->toBe($baseUri);
}
)->with([
['/authentication/providers/configurations/local', ''],
['/monitoring/authentication/providers/configurations/local', '/monitoring'],
['/monitoring/centreon/authentication/providers/configurations/local', '/monitoring/centreon'],
['/administration/authentication/providers/local', ''],
['/my-monitoring/api/v22.04/administration/authentication/providers/local', '/my-monitoring'],
['/api/latest/monitoring/resources', ''],
['/centreon/api/latest/monitoring/resources', '/centreon'],
['/monitoring/authentication/logout', '/monitoring'],
]);
it(
'formats properly base url',
function (
$requestParameters,
$baseUrl,
): void {
$this->httpServerBag->replace([
'HTTPS' => $requestParameters[0],
'SERVER_NAME' => $requestParameters[1],
'SERVER_PORT' => $requestParameters[2],
'REQUEST_URI' => $requestParameters[3],
]);
expect($this->getBaseUrl())->toBe($baseUrl);
}
)->with([
[
[
'off',
'127.0.0.1',
'8080',
'/centreon/api/latest/test',
],
'http://127.0.0.1:8080/centreon',
],
[
[
'on',
'my.monitoring',
'4443',
'/api/latest/test',
],
'https://my.monitoring:4443',
],
[
[
'on',
'test',
'',
'/api/latest/test',
],
'https://test',
],
[
[
'off',
'192.168.0.1',
'',
'/monitoring/centreon/authentication/logout',
],
'http://192.168.0.1/monitoring/centreon',
],
]);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Infrastructure/Common/Api/RouterTest.php | centreon/tests/php/Core/Infrastructure/Common/Api/RouterTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Core\Infrastructure\Common\Api\Router;
beforeEach(function (): void {
$this->router = new Router(
$this->createMock(Symfony\Component\Routing\RouterInterface::class),
$this->createMock(Symfony\Component\Routing\Matcher\RequestMatcherInterface::class)
);
});
it('should return a legacy path without options', function (): void {
$legacyHref = $this->router->generateLegacyHref(60202);
expect($legacyHref)->toBe('/main.php?p=60202');
});
it('should return a legacy path with options', function (): void {
$legacyHref = $this->router->generateLegacyHref(60202, ['foo' => 'bar']);
expect($legacyHref)->toBe('/main.php?p=60202&foo=bar');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Infrastructure/Common/Repository/DbFactoryUtilitiesTraitTest.php | centreon/tests/php/Core/Infrastructure/Common/Repository/DbFactoryUtilitiesTraitTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Infrastructure\Common\Repository;
use Core\Infrastructure\Common\Repository\DbFactoryUtilitiesTrait;
use PHPUnit\Framework\TestCase;
class DbFactoryUtilitiesTraitTest extends TestCase
{
use DbFactoryUtilitiesTrait;
/**
* test createDateTimeImmutableFromTimestamp with null value
*/
public function testCreateDateTimeImmutableFromTimestampWithNull(): void
{
$datetime = self::createDateTimeImmutableFromTimestamp(null);
$this->assertEquals(null, $datetime);
}
/**
* test createDateTimeImmutableFromTimestamp with string value
*/
public function testCreateDateTimeImmutableFromTimestampWithString(): void
{
$timestamp = '127000';
$datetime = self::createDateTimeImmutableFromTimestamp($timestamp);
$this->assertInstanceOf(\DateTimeImmutable::class, $datetime);
$this->assertSame($timestamp, (string) $datetime?->getTimestamp());
}
/**
* test createDateTimeImmutableFromTimestamp with integer value
*/
public function testCreateDateTimeImmutableFromTimestampWithInteger(): void
{
$timestamp = 127000;
$datetime = self::createDateTimeImmutableFromTimestamp($timestamp);
$this->assertInstanceOf(\DateTimeImmutable::class, $datetime);
$this->assertSame($timestamp, $datetime?->getTimestamp());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/CommandMacro/Domain/Model/CommandMacroTest.php | centreon/tests/php/Core/CommandMacro/Domain/Model/CommandMacroTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\CommandMacro\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\CommandMacro\Domain\Model\CommandMacro;
use Core\CommandMacro\Domain\Model\CommandMacroType;
it('should return properly set command macro instance', function (): void {
$macro = new CommandMacro(1, CommandMacroType::Host, 'macroName');
$macro->setDescription('macroDescription');
expect($macro->getCommandId())->toBe(1)
->and($macro->getName())->toBe('macroName')
->and($macro->getType())->toBe(CommandMacroType::Host)
->and($macro->getDescription())->toBe('macroDescription');
});
it('should throw an exception when command macro name is empty', function (): void {
new CommandMacro(1, CommandMacroType::Host, '');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('CommandMacro::name')->getMessage()
);
it('should throw an exception when command macro name is too long', function (): void {
new CommandMacro(1, CommandMacroType::Host, str_repeat('a', CommandMacro::MAX_NAME_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', CommandMacro::MAX_NAME_LENGTH + 1),
CommandMacro::MAX_NAME_LENGTH + 1,
CommandMacro::MAX_NAME_LENGTH,
'CommandMacro::name'
)->getMessage()
);
it('should throw an exception when command macro description is too long', function (): void {
$macro = new CommandMacro(1, CommandMacroType::Host, 'macroName');
$macro->setDescription(str_repeat('a', CommandMacro::MAX_DESCRIPTION_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', CommandMacro::MAX_DESCRIPTION_LENGTH + 1),
CommandMacro::MAX_DESCRIPTION_LENGTH + 1,
CommandMacro::MAX_DESCRIPTION_LENGTH,
'CommandMacro::description'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/CommandMacro/Domain/Model/NewCommandMacroTest.php | centreon/tests/php/Core/CommandMacro/Domain/Model/NewCommandMacroTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\CommandMacro\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\CommandMacro\Domain\Model\CommandMacroType;
use Core\CommandMacro\Domain\Model\NewCommandMacro;
it('should return properly set command macro instance', function (): void {
$macro = new NewCommandMacro(CommandMacroType::Host, 'macroName');
$macro->setDescription('macroDescription');
expect($macro->getName())->toBe('macroName')
->and($macro->getType())->toBe(CommandMacroType::Host)
->and($macro->getDescription())->toBe('macroDescription');
});
it('should throw an exception when command macro name is empty', function (): void {
new NewCommandMacro(CommandMacroType::Host, '');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewCommandMacro::name')->getMessage()
);
it('should throw an exception when command macro name is too long', function (): void {
new NewCommandMacro(CommandMacroType::Host, str_repeat('a', NewCommandMacro::MAX_NAME_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewCommandMacro::MAX_NAME_LENGTH + 1),
NewCommandMacro::MAX_NAME_LENGTH + 1,
NewCommandMacro::MAX_NAME_LENGTH,
'NewCommandMacro::name'
)->getMessage()
);
it('should throw an exception when command macro description is too long', function (): void {
$macro = new NewCommandMacro(CommandMacroType::Host, 'macroName');
$macro->setDescription(str_repeat('a', NewCommandMacro::MAX_DESCRIPTION_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewCommandMacro::MAX_DESCRIPTION_LENGTH + 1),
NewCommandMacro::MAX_DESCRIPTION_LENGTH + 1,
NewCommandMacro::MAX_DESCRIPTION_LENGTH,
'NewCommandMacro::description'
)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Application/UseCase/ExtractResponse.php | centreon/tests/php/Core/TimePeriod/Application/UseCase/ExtractResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Core\TimePeriod\Application\UseCase;
use Core\TimePeriod\Domain\Model\Day;
use Core\TimePeriod\Domain\Model\ExtraTimePeriod;
use Core\TimePeriod\Domain\Model\Template;
use Core\TimePeriod\Domain\Model\TimePeriod;
class ExtractResponse
{
/**
* @param TimePeriod $timePeriod
* @return array
*/
public static function daysToArray(TimePeriod $timePeriod): array
{
return array_map(fn (Day $day) => [
'day' => $day->getDay(),
'time_range' => (string) $day->getTimeRange(),
], $timePeriod->getDays());
}
/**
* @param TimePeriod $timePeriod
* @return array
*/
public static function templatesToArray(TimePeriod $timePeriod): array
{
return array_map(fn (Template $template) => [
'id' => $template->getId(),
'alias' => $template->getAlias(),
], $timePeriod->getTemplates());
}
/**
* @param TimePeriod $timePeriod
* @return array
*/
public static function exceptionsToArray(TimePeriod $timePeriod): array
{
return array_map(fn (ExtraTimePeriod $exception) => [
'id' => $exception->getId(),
'day_range' => $exception->getDayRange(),
'time_range' => (string) $exception->getTimeRange(),
], $timePeriod->getExtraTimePeriods());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodTest.php | centreon/tests/php/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Application\UseCase\AddTimePeriod;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\{ConflictResponse, CreatedResponse, ErrorResponse, ForbiddenResponse};
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\JsonFormatter;
use Core\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\{ReadTimePeriodRepositoryInterface, WriteTimePeriodRepositoryInterface};
use Core\TimePeriod\Application\UseCase\AddTimePeriod\{AddTimePeriod, AddTimePeriodDto};
use Core\TimePeriod\Domain\Model\{Day, ExtraTimePeriod, Template, TimePeriod, TimeRange};
use Tests\Core\TimePeriod\Application\UseCase\ExtractResponse;
beforeEach(function (): void {
$this->readRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class);
$this->writeRepository = $this->createMock(WriteTimePeriodRepositoryInterface::class);
$this->formatter = $this->createMock(JsonFormatter::class);
$this->user = $this->createMock(ContactInterface::class);
$this->timePeriodRequest = new AddTimePeriodDto(
'fake_name',
'fake_alias',
[
['day' => 1, 'time_range' => '00:00-01:00'],
['day' => 2, 'time_range' => '00:00-01:00'],
],
[1],
[
['day_range' => 'monday', 'time_range' => '00:00-01:00'],
['day_range' => 'tuesday', 'time_range' => '00:00-01:00'],
]
);
});
it('should present an ForbiddenResponse whenuser has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
$useCase = new AddTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$presenter = new DefaultPresenter($this->formatter);
$useCase($this->timePeriodRequest, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($presenter->getResponseStatus()?->getMessage())
->toBe(TimePeriodException::editNotAllowed()->getMessage());
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('nameAlreadyExists')
->willThrowException(new \Exception());
$useCase = new AddTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$presenter = new DefaultPresenter($this->formatter);
$useCase($this->timePeriodRequest, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($presenter->getResponseStatus()?->getMessage())
->toBe(TimePeriodException::errorWhenAddingTimePeriod()->getMessage());
});
it('should present an ErrorResponse when the name already exists', function (): void {
$nameToFind = 'fake_name';
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('nameAlreadyExists')
->with($nameToFind, null)
->willReturn(true);
$useCase = new AddTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$presenter = new DefaultPresenter($this->formatter);
$useCase($this->timePeriodRequest, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($presenter->getResponseStatus()?->getMessage())
->toBe(TimePeriodException::nameAlreadyExists($nameToFind)->getMessage());
});
it('should present an ErrorResponse when the new time period cannot be found after creation', function (): void {
$nameToFind = $this->timePeriodRequest->name;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('nameAlreadyExists')
->with($nameToFind, null)
->willReturn(false);
$this->writeRepository
->expects($this->once())
->method('add')
->willReturn(1);
$this->readRepository
->expects($this->once())
->method('findById')
->with(1)
->willReturn(null);
$useCase = new AddTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$presenter = new DefaultPresenter($this->formatter);
$useCase($this->timePeriodRequest, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($presenter->getResponseStatus()?->getMessage())
->toBe(TimePeriodException::errorWhenAddingTimePeriod()->getMessage());
});
it('should present a correct CreatedResponse object after creation', function (): void {
$fakeName = $this->timePeriodRequest->name;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('nameAlreadyExists')
->with($fakeName, null)
->willReturn(false);
$this->writeRepository
->expects($this->once())
->method('add')
->willReturn(1);
$newTimePeriod = new TimePeriod(1, $fakeName, $fakeAlias = 'fake_alias');
$newTimePeriod->addDay(new Day(1, new TimeRange('00:30-04:00')));
$template = new Template(1, 'fake_template');
$newTimePeriod->addTemplate($template);
$extraPeriod = new ExtraTimePeriod(1, 'monday 1', new TimeRange('00:00-01:00'));
$newTimePeriod->addExtraTimePeriod($extraPeriod);
$this->readRepository
->expects($this->once())
->method('findById')
->with(1)
->willReturn($newTimePeriod);
$useCase = new AddTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$presenter = new AddTimePeriodsPresenterStub($this->formatter);
$useCase($this->timePeriodRequest, $presenter);
expect($presenter->response)->toBeInstanceOf(CreatedResponse::class);
expect($presenter->response->getResourceId())->toBe($newTimePeriod->getId());
$payload = $presenter->response->getPayload();
expect($payload->name)
->toBe($newTimePeriod->getName())
->and($payload->alias)
->toBe($newTimePeriod->getAlias())
->and($payload->days)
->toBe(ExtractResponse::daysToArray($newTimePeriod))
->and($payload->templates)
->toBe(ExtractResponse::templatesToArray($newTimePeriod))
->and($payload->exceptions)
->toBe(ExtractResponse::exceptionsToArray($newTimePeriod));
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodsPresenterStub.php | centreon/tests/php/Core/TimePeriod/Application/UseCase/AddTimePeriod/AddTimePeriodsPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Application\UseCase\AddTimePeriod;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Symfony\Component\HttpFoundation\Response;
class AddTimePeriodsPresenterStub extends AbstractPresenter implements PresenterInterface
{
public CreatedResponse $response;
/**
* @param CreatedResponse $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/TimePeriod/Application/UseCase/FindTimePeriods/FindTimePeriodsTest.php | centreon/tests/php/Core/TimePeriod/Application/UseCase/FindTimePeriods/FindTimePeriodsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Application\UseCase\FindTimePeriods;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\{JsonFormatter, PresenterFormatterInterface};
use Core\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\ReadTimePeriodRepositoryInterface;
use Core\TimePeriod\Application\UseCase\FindTimePeriods\{FindTimePeriods, FindTimePeriodsResponse};
use Core\TimePeriod\Domain\Model\{Day, ExtraTimePeriod, Template, TimePeriod, TimeRange};
use Core\TimePeriod\Domain\Rules\Strategies\SimpleDayTimeRangeRuleStrategy;
beforeEach(function (): void {
$this->strategies = [];
foreach ([SimpleDayTimeRangeRuleStrategy::class] as $className) {
$this->strategies[] = new $className();
}
$this->repository = $this->createMock(ReadTimePeriodRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->requestParameter = $this->createMock(RequestParameters::class);
$this->user = $this->createMock(ContactInterface::class);
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ, true],
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE, true],
]
);
$this->repository
->expects($this->once())
->method('findByRequestParameter')
->with($this->requestParameter)
->willThrowException(new \Exception());
$useCase = new FindTimePeriods(
$this->repository,
$this->requestParameter,
$this->user,
new \ArrayObject($this->strategies)
);
$presenter = new DefaultPresenter(
$this->createMock(JsonFormatter::class)
);
$useCase($presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class)
->and($presenter->getResponseStatus()?->getMessage())
->toBe(TimePeriodException::errorWhenSearchingForAllTimePeriods()->getMessage());
});
it('should present an ForbiddenResponse when an user has no rights', function (): void {
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ, false],
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE, false],
]
);
$useCase = new FindTimePeriods(
$this->repository,
$this->requestParameter,
$this->user,
new \ArrayObject($this->strategies)
);
$presenter = new DefaultPresenter(
$this->createMock(JsonFormatter::class)
);
$useCase($presenter);
expect($presenter->getResponseStatus())->toBeInstanceOf(ForbiddenResponse::class)
->and($presenter->getResponseStatus()?->getMessage())
->toBe(TimePeriodException::accessNotAllowed()->getMessage());
});
it('should present a FindTimePeriodsResponse when user has read only rights', function (): void {
$useCase = new FindTimePeriods(
$this->repository,
$this->requestParameter,
$this->user,
new \ArrayObject($this->strategies)
);
$timePeriod = new TimePeriod(
1,
'fakeName',
'fakeAlias'
);
$days = [new Day(1, new TimeRange('00:00-12:00'))];
$timePeriod->setDays($days);
$templates = [
new Template(2, 'fakeAlias2'),
new Template(3, 'fakeAlias3'),
];
$timePeriod->setTemplates($templates);
$exceptions = new ExtraTimePeriod(1, 'monday 1', new TimeRange('06:00-07:00'));
$timePeriod->addExtraTimePeriod($exceptions);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ, true],
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE, false],
]
);
$this->repository
->expects($this->once())
->method('findByRequestParameter')
->with($this->requestParameter)
->willReturn([$timePeriod]);
$presenter = new FindTimePeriodsPresenterStub($this->presenterFormatter);
$useCase($presenter);
expect($presenter->response->timePeriods)->toBeArray()->toHaveCount(1);
/**
* @var TimePeriod $timePeriodToBeExpected
*/
$timePeriodToBeExpected = $presenter->response->timePeriods[0];
expect($presenter->response)
->toBeInstanceOf(FindTimePeriodsResponse::class)
->and($timePeriodToBeExpected)->toBe(
[
'id' => 1,
'name' => 'fakeName',
'alias' => 'fakeAlias',
'days' => [
[
'day' => $timePeriod->getDays()[0]->getDay(),
'time_range' => (string) $timePeriod->getDays()[0]->getTimeRange(),
],
],
'templates' => [
[
'id' => $timePeriod->getTemplates()[0]->getId(),
'alias' => $timePeriod->getTemplates()[0]->getAlias(),
],
[
'id' => $timePeriod->getTemplates()[1]->getId(),
'alias' => $timePeriod->getTemplates()[1]->getAlias(),
],
],
'exceptions' => [
[
'id' => $timePeriod->getExtraTimePeriods()[0]->getId(),
'day_range' => $timePeriod->getExtraTimePeriods()[0]->getDayRange(),
'time_range' => (string) $timePeriod->getExtraTimePeriods()[0]->getTimeRange(),
],
],
'in_period' => $timePeriod->isDateTimeIncludedInPeriod(new \DateTimeImmutable(), $this->strategies),
]
);
});
it('should present a FindTimePeriodsResponse when user has read-write rights', function (): void {
$useCase = new FindTimePeriods(
$this->repository,
$this->requestParameter,
$this->user,
new \ArrayObject($this->strategies)
);
$timePeriod = new TimePeriod(
1,
'fakeName',
'fakeAlias'
);
$days = [new Day(1, new TimeRange('00:00-12:00'))];
$timePeriod->setDays($days);
$templates = [
new Template(2, 'fakeAlias2'),
new Template(3, 'fakeAlias3'),
];
$timePeriod->setTemplates($templates);
$exceptions = new ExtraTimePeriod(1, 'monday 1', new TimeRange('06:00-07:00'));
$timePeriod->addExtraTimePeriod($exceptions);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ, false],
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE, true],
]
);
$this->repository
->expects($this->once())
->method('findByRequestParameter')
->with($this->requestParameter)
->willReturn([$timePeriod]);
$presenter = new FindTimePeriodsPresenterStub($this->presenterFormatter);
$useCase($presenter);
expect($presenter->response->timePeriods)->toBeArray()->toHaveCount(1);
/**
* @var TimePeriod $timePeriodToBeExpected
*/
$timePeriodToBeExpected = $presenter->response->timePeriods[0];
expect($presenter->response)
->toBeInstanceOf(FindTimePeriodsResponse::class)
->and($timePeriodToBeExpected)->toBe(
[
'id' => 1,
'name' => 'fakeName',
'alias' => 'fakeAlias',
'days' => [
[
'day' => $timePeriod->getDays()[0]->getDay(),
'time_range' => (string) $timePeriod->getDays()[0]->getTimeRange(),
],
],
'templates' => [
[
'id' => $timePeriod->getTemplates()[0]->getId(),
'alias' => $timePeriod->getTemplates()[0]->getAlias(),
],
[
'id' => $timePeriod->getTemplates()[1]->getId(),
'alias' => $timePeriod->getTemplates()[1]->getAlias(),
],
],
'exceptions' => [
[
'id' => $timePeriod->getExtraTimePeriods()[0]->getId(),
'day_range' => $timePeriod->getExtraTimePeriods()[0]->getDayRange(),
'time_range' => (string) $timePeriod->getExtraTimePeriods()[0]->getTimeRange(),
],
],
'in_period' => $timePeriod->isDateTimeIncludedInPeriod(new \DateTimeImmutable(), $this->strategies),
]
);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Application/UseCase/FindTimePeriods/FindTimePeriodsPresenterStub.php | centreon/tests/php/Core/TimePeriod/Application/UseCase/FindTimePeriods/FindTimePeriodsPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Application\UseCase\FindTimePeriods;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\TimePeriod\Application\UseCase\FindTimePeriods\FindTimePeriodsResponse;
use Symfony\Component\HttpFoundation\Response;
class FindTimePeriodsPresenterStub extends AbstractPresenter implements PresenterInterface
{
public FindTimePeriodsResponse $response;
/**
* @param FindTimePeriodsResponse $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/TimePeriod/Application/UseCase/DeleteTimePeriod/DeleteTimePeriodTest.php | centreon/tests/php/Core/TimePeriod/Application/UseCase/DeleteTimePeriod/DeleteTimePeriodTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Application\UseCase\DeleteTimePeriod;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\{ErrorResponse, ForbiddenResponse, NoContentResponse, NotFoundResponse};
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\JsonFormatter;
use Core\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\{ReadTimePeriodRepositoryInterface, WriteTimePeriodRepositoryInterface};
use Core\TimePeriod\Application\UseCase\DeleteTimePeriod\DeleteTimePeriod;
beforeEach(function (): void {
$this->readRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class);
$this->writeRepository = $this->createMock(WriteTimePeriodRepositoryInterface::class);
$this->formatter = $this->createMock(JsonFormatter::class);
$this->user = $this->createMock(ContactInterface::class);
});
it('should present a ForbiddenResponse when user has insufficient rights', function (): void {
$timePeriodId = 1;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
$useCase = new DeleteTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$presenter = new DefaultPresenter($this->formatter);
$useCase($timePeriodId, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($presenter->getResponseStatus()->getMessage())
->toBe(TimePeriodException::editNotAllowed()->getMessage());
});
it('should present a NotFoundResponse error when the time period is not found', function (): void {
$timePeriodId = 1;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('exists')
->with($timePeriodId)
->willReturn(false);
$useCase = new DeleteTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$presenter = new DefaultPresenter($this->formatter);
$useCase($timePeriodId, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($presenter->getResponseStatus()->getMessage())
->toBe((new NotFoundResponse('Time period'))->getMessage());
});
it('should present an ErrorResponse response when the exception is raised', function (): void {
$timePeriodId = 1;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('exists')
->with($timePeriodId)
->willReturn(true);
$this->writeRepository
->expects($this->once())
->method('delete')
->willThrowException(new \Exception());
$useCase = new DeleteTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$presenter = new DefaultPresenter($this->formatter);
$useCase($timePeriodId, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($presenter->getResponseStatus()->getMessage())
->toBe(TimePeriodException::errorOnDelete($timePeriodId)->getMessage());
});
it('should present a NoContentResponse response when the time period is deleted', function (): void {
$timePeriodId = 1;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('exists')
->with($timePeriodId)
->willReturn(true);
$useCase = new DeleteTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$presenter = new DefaultPresenter($this->formatter);
$useCase($timePeriodId, $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/TimePeriod/Application/UseCase/FindTimePeriod/FindTimePeriodTest.php | centreon/tests/php/Core/TimePeriod/Application/UseCase/FindTimePeriod/FindTimePeriodTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Application\UseCase\FindTimePeriod;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\{ErrorResponse, ForbiddenResponse, NotFoundResponse};
use Core\Infrastructure\Common\Presenter\JsonFormatter;
use Core\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\{ReadTimePeriodRepositoryInterface, WriteTimePeriodRepositoryInterface};
use Core\TimePeriod\Application\UseCase\FindTimePeriod\{FindTimePeriod, FindTimePeriodResponse};
use Core\TimePeriod\Domain\Model\{Day, ExtraTimePeriod, Template, TimePeriod, TimeRange};
beforeEach(function (): void {
$this->readRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class);
$this->writeRepository = $this->createMock(WriteTimePeriodRepositoryInterface::class);
$this->formatter = $this->createMock(JsonFormatter::class);
$this->user = $this->createMock(ContactInterface::class);
});
it('should present an ErrorResponse response when the exception is raised', function (): void {
$timePeriodId = 1;
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ, true],
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE, true],
]
);
$this->readRepository
->expects($this->once())
->method('findById')
->with($timePeriodId)
->willThrowException(new \Exception());
$useCase = new FindTimePeriod($this->readRepository, $this->user);
$response = $useCase($timePeriodId);
expect($response)
->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())
->toBe(TimePeriodException::errorWhenSearchingForTimePeriod($timePeriodId)->getMessage());
});
it('should present a NotFoundResponse when the time period is not found', function (): void {
$timePeriodId = 1;
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ, true],
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE, true],
]
);
$this->readRepository
->expects($this->once())
->method('findById')
->with($timePeriodId)
->willReturn(null);
$useCase = new FindTimePeriod($this->readRepository, $this->user);
$response = $useCase($timePeriodId);
expect($response)
->toBeInstanceOf(NotFoundResponse::class)
->and($response->getMessage())
->toBe((new NotFoundResponse('Time period'))->getMessage());
});
it('should present an Forbidden response when user has insufficient rights', function (): void {
$timePeriodId = 1;
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ, false],
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE, false],
]
);
$useCase = new FindTimePeriod($this->readRepository, $this->user);
$response = $useCase($timePeriodId);
expect($response)
->toBeInstanceOf(ForbiddenResponse::class)
->and($response->getMessage())
->toBe(TimePeriodException::accessNotAllowed()->getMessage());
});
it('should present a FindTimePeriodResponse if the time response is found and user has read only rigths', function (): void {
$timePeriod = new TimePeriod(1, 'fake_name', 'fake_alias');
$timePeriod->addDay(new Day(1, new TimeRange('00:30-04:00')));
$timePeriod->addTemplate(new Template(1, 'fake_template'));
$timePeriod->addExtraTimePeriod(
new ExtraTimePeriod(1, 'monday 1', new TimeRange('00:00-01:00'))
);
$timePeriodId = 1;
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ, true],
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE, false],
]
);
$this->readRepository
->expects($this->once())
->method('findById')
->with($timePeriodId)
->willReturn($timePeriod);
$useCase = new FindTimePeriod($this->readRepository, $this->user);
/** @var FindTimePeriodResponse $response */
$response = $useCase($timePeriodId);
expect($response)
->toBeInstanceOf(FindTimePeriodResponse::class)
->and($response->timePeriod->getId())
->toBe($timePeriod->getId())
->and($response->timePeriod->getName())
->toBe($timePeriod->getName())
->and($response->timePeriod->getAlias())
->toBe($timePeriod->getAlias())
->and($response->timePeriod->getDays())
->toBe($timePeriod->getDays())
->and($response->timePeriod->getTemplates())
->toBe($timePeriod->getTemplates())
->and($response->timePeriod->getExtraTimePeriods())
->toBe($timePeriod->getExtraTimePeriods());
});
it('should present a FindTimePeriodResponse if the time response is found and user has read-write rigths', function (): void {
$timePeriod = new TimePeriod(1, 'fake_name', 'fake_alias');
$timePeriod->addDay(new Day(1, new TimeRange('00:30-04:00')));
$timePeriod->addTemplate(new Template(1, 'fake_template'));
$timePeriod->addExtraTimePeriod(
new ExtraTimePeriod(1, 'monday 1', new TimeRange('00:00-01:00'))
);
$timePeriodId = 1;
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ, false],
[Contact::ROLE_CONFIGURATION_TIME_PERIODS_READ_WRITE, true],
]
);
$this->readRepository
->expects($this->once())
->method('findById')
->with($timePeriodId)
->willReturn($timePeriod);
$useCase = new FindTimePeriod($this->readRepository, $this->user);
/** @var FindTimePeriodResponse $response */
$response = $useCase($timePeriodId);
expect($response)
->toBeInstanceOf(FindTimePeriodResponse::class)
->and($response->timePeriod->getId())
->toBe($timePeriod->getId())
->and($response->timePeriod->getName())
->toBe($timePeriod->getName())
->and($response->timePeriod->getAlias())
->toBe($timePeriod->getAlias())
->and($response->timePeriod->getDays())
->toBe($timePeriod->getDays())
->and($response->timePeriod->getTemplates())
->toBe($timePeriod->getTemplates())
->and($response->timePeriod->getExtraTimePeriods())
->toBe($timePeriod->getExtraTimePeriods());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Application/UseCase/FindTimePeriod/FindTimePeriodPresenterStub.php | centreon/tests/php/Core/TimePeriod/Application/UseCase/FindTimePeriod/FindTimePeriodPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Application\UseCase\FindTimePeriod;
use Core\Application\Common\UseCase\{AbstractPresenter, PresenterInterface};
use Core\TimePeriod\Application\UseCase\FindTimePeriod\FindTimePeriodResponse;
use Symfony\Component\HttpFoundation\Response;
class FindTimePeriodPresenterStub extends AbstractPresenter implements PresenterInterface
{
public FindTimePeriodResponse $response;
/**
* @param FindTimePeriodResponse $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/TimePeriod/Application/UseCase/UpdateTimePeriod/UpdateTimePeriodTest.php | centreon/tests/php/Core/TimePeriod/Application/UseCase/UpdateTimePeriod/UpdateTimePeriodTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Application\UseCase\UpdateTimePeriod;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\{ConflictResponse, ErrorResponse, NoContentResponse, NotFoundResponse};
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\TimePeriod\Application\Exception\TimePeriodException;
use Core\TimePeriod\Application\Repository\{ReadTimePeriodRepositoryInterface, WriteTimePeriodRepositoryInterface};
use Core\TimePeriod\Application\UseCase\UpdateTimePeriod\{UpdateTimePeriod, UpdateTimePeriodRequest};
use Core\TimePeriod\Domain\Model\TimePeriod;
beforeEach(function (): void {
$this->readRepository = $this->createMock(ReadTimePeriodRepositoryInterface::class);
$this->writeRepository = $this->createMock(WriteTimePeriodRepositoryInterface::class);
$this->formatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
});
it('should present an ErrorResponse when an exception is raised', function (): void {
$request = new UpdateTimePeriodRequest();
$request->id = 1;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findById')
->with($request->id)
->willThrowException(new \Exception());
$presenter = new DefaultPresenter($this->formatter);
$useCase = new UpdateTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$useCase($request, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($presenter->getResponseStatus()->getMessage())
->toBe(TimePeriodException::errorOnUpdate($request->id)->getMessage());
});
it('should present an ForbiddenResponse when user has insufficient rigths', function (): void {
$request = new UpdateTimePeriodRequest();
$request->id = 1;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
$presenter = new DefaultPresenter($this->formatter);
$useCase = new UpdateTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$useCase($request, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($presenter->getResponseStatus()->getMessage())
->toBe(TimePeriodException::editNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the time period to update is not found', function (): void {
$request = new UpdateTimePeriodRequest();
$request->id = 1;
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findById')
->with($request->id)
->willReturn(null);
$presenter = new DefaultPresenter($this->formatter);
$useCase = new UpdateTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$useCase($request, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($presenter->getResponseStatus()->getMessage())
->toBe((new NotFoundResponse('Time period'))->getMessage());
});
it('should present an ErrorResponse when the time period name already exists', function (): void {
$request = new UpdateTimePeriodRequest();
$request->id = 1;
$request->name = 'fake_name';
$request->alias = 'fake_alias';
$timePeriod = new TimePeriod($request->id = 1, $request->name, $request->alias);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findById')
->with($request->id)
->willReturn($timePeriod);
$this->readRepository
->expects($this->once())
->method('nameAlreadyExists')
->with($request->name, $request->id)
->willReturn(true);
$presenter = new DefaultPresenter($this->formatter);
$useCase = new UpdateTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$useCase($request, $presenter);
expect($presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($presenter->getResponseStatus()->getMessage())
->toBe(TimePeriodException::nameAlreadyExists($request->name)->getMessage());
});
it('should present a NoContentResponse after update', function (): void {
$request = new UpdateTimePeriodRequest();
$request->id = 1;
$request->name = 'fake_name';
$request->alias = 'fake_alias';
$timePeriod = new TimePeriod($request->id = 1, $request->name, $request->alias);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readRepository
->expects($this->once())
->method('findById')
->with($request->id)
->willReturn($timePeriod);
$this->readRepository
->expects($this->once())
->method('nameAlreadyExists')
->with($request->name, $request->id)
->willReturn(false);
$presenter = new DefaultPresenter($this->formatter);
$useCase = new UpdateTimePeriod($this->readRepository, $this->writeRepository, $this->user);
$useCase($request, $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/TimePeriod/Domain/Model/DayTest.php | centreon/tests/php/Core/TimePeriod/Domain/Model/DayTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\TimePeriod\Domain\Model\Day;
use Core\TimePeriod\Domain\Model\TimeRange;
it(
'should throw an exception if the day ID is less than 1',
function (): void {
new Day(0, new TimeRange('00:00-12:00'));
}
)->throws(
\InvalidArgumentException::class,
AssertionException::min(
0,
1,
'TimePeriodDay::day'
)->getMessage()
);
it(
'should throw an exception if the day ID is more than 7',
function (): void {
new Day(8, new TimeRange('00:00-12:00'));
}
)->throws(
\InvalidArgumentException::class,
AssertionException::max(
8,
7,
'TimePeriodDay::day'
)->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/TimePeriod/Domain/Model/TimeRangeTest.php | centreon/tests/php/Core/TimePeriod/Domain/Model/TimeRangeTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\TimePeriod\Domain\Exception\TimeRangeException;
use Core\TimePeriod\Domain\Model\TimeRange;
$timeRange = '';
it(
'should throw exception with empty time range',
function () use ($timeRange): void {
new TimeRange($timeRange);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
$timeRange,
mb_strlen($timeRange),
11,
'TimeRange::timeRange'
)->getMessage()
);
it(
'should throw exception with wrong time format',
function (): void {
new TimeRange('00:00-12d00');
}
)->throws(
TimeRangeException::class,
TimeRangeException::badTimeRangeFormat('00:00-12d00')->getMessage()
);
it(
'should throw exception with wrong time ranges format',
function (): void {
new TimeRange('00:00 12:00');
}
)->throws(
TimeRangeException::class,
TimeRangeException::badTimeRangeFormat('00:00 12:00')->getMessage()
);
it(
'should throw exception with wrong time ranges repetition',
function (): void {
new TimeRange('00:00-12:00 13:00-14:00');
}
)->throws(
TimeRangeException::class,
TimeRangeException::badTimeRangeFormat('00:00-12:00 13:00-14:00')->getMessage()
);
it(
'should throw exception when the start of the interval is equal to the end of the interval',
function (): void {
new TimeRange('12:00-12:00');
}
)->throws(
TimeRangeException::class,
TimeRangeException::orderTimeIntervalsNotConsistent()->getMessage()
);
it(
'should throw exception when the start of the interval is greater than the end of the interval',
function (): void {
new TimeRange('12:01-12:00');
}
)->throws(
TimeRangeException::class,
TimeRangeException::orderTimeIntervalsNotConsistent()->getMessage()
);
it(
'should throw exception when the start of the second interval is equal to the end of the first interval',
function (): void {
new TimeRange('00:00-12:00,12:00-14:00');
}
)->throws(
TimeRangeException::class,
TimeRangeException::orderTimeIntervalsNotConsistent()->getMessage()
);
it(
'should throw exception when the start of the second interval is less than the end of the first interval',
function (): void {
new TimeRange('00:00-12:00,11:00-14:00');
}
)->throws(
TimeRangeException::class,
TimeRangeException::orderTimeIntervalsNotConsistent()->getMessage()
);
it('should return a valid single array', function (): void {
$timeRange = new TimeRange('00:00-10:00');
expect($timeRange->getRanges())->toBeArray()->toHaveCount(1);
});
it('should return a valid multiple array', function (): void {
$timeRange = new TimeRange('00:00-10:00,11:00-18:00');
expect($timeRange->getRanges())->toBeArray()->toHaveCount(2);
});
it('should not throw an exception for 00:00-00:00', function (): void {
$timeRange = new TimeRange('00:00-00:00');
expect($timeRange->getRanges())->toBeArray()->toHaveCount(1);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Domain/Model/ExtraTimePeriodTest.php | centreon/tests/php/Core/TimePeriod/Domain/Model/ExtraTimePeriodTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\TimePeriod\Domain\Model\ExtraTimePeriod;
use Core\TimePeriod\Domain\Model\NewExtraTimePeriod;
use Core\TimePeriod\Domain\Model\TimeRange;
$timeRange = new TimeRange('00:01-02:00');
$dayRange = '';
it(
'should throw an exception if ID is less than 1',
function () use ($dayRange, $timeRange): void {
new ExtraTimePeriod(0, $dayRange, $timeRange);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::min(
0,
1,
'ExtraTimePeriod::id'
)->getMessage()
);
$badValue = str_repeat('_', NewExtraTimePeriod::MAX_DAY_RANGE_LENGTH + 1);
it(
'should throw exception with too long day range',
function () use ($timeRange, $badValue): void {
new ExtraTimePeriod(1, $badValue, $timeRange);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::maxLength(
$badValue,
mb_strlen($badValue),
NewExtraTimePeriod::MAX_DAY_RANGE_LENGTH,
'ExtraTimePeriod::dayRange'
)->getMessage()
);
$dayRange = ' ';
it(
'should throw exception if day range consists only of space',
function () use ($dayRange, $timeRange): void {
new ExtraTimePeriod(1, $dayRange, $timeRange);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
NewExtraTimePeriod::MIN_DAY_RANGE_LENGTH,
'ExtraTimePeriod::dayRange'
)->getMessage()
);
$dayRange = '00:00-01:00 ';
it(
'should apply trim on the day range value',
function () use ($dayRange, $timeRange): void {
$extraTimePeriod = new ExtraTimePeriod(1, $dayRange, $timeRange);
expect(trim($dayRange))->toBe($extraTimePeriod->getDayRange());
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Domain/Model/NewTimePeriodTest.php | centreon/tests/php/Core/TimePeriod/Domain/Model/NewTimePeriodTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\TimePeriod\Domain\Model\ {
Day, NewExtraTimePeriod, NewTimePeriod, TimeRange
};
it(
'should throw an exception if alias is empty',
function (): void {
new NewTimePeriod('fake_name', '');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
NewTimePeriod::MIN_NAME_LENGTH,
'NewTimePeriod::alias'
)->getMessage()
);
it(
'should throw an exception if alias consists only of space',
function (): void {
new NewTimePeriod('fake_name', ' ');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
NewTimePeriod::MIN_NAME_LENGTH,
'NewTimePeriod::alias'
)->getMessage()
);
$badAlias = str_repeat('_', NewTimePeriod::MAX_ALIAS_LENGTH + 1);
it(
'should throw an exception if alias is too long',
function () use ($badAlias): void {
new NewTimePeriod('fake_name', $badAlias);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::maxLength(
$badAlias,
mb_strlen($badAlias),
NewTimePeriod::MAX_ALIAS_LENGTH,
'NewTimePeriod::alias'
)->getMessage()
);
it(
'should throw an exception if name is empty',
function (): void {
new NewTimePeriod('', 'fake_alias');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
NewTimePeriod::MIN_NAME_LENGTH,
'NewTimePeriod::name'
)->getMessage()
);
it(
'should throw an exception if name consists only of space',
function (): void {
new NewTimePeriod(' ', 'fake_alias');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
NewTimePeriod::MIN_NAME_LENGTH,
'NewTimePeriod::name'
)->getMessage()
);
$badName = str_repeat('_', NewTimePeriod::MAX_NAME_LENGTH + 1);
it(
'should throw an exception if name is too long',
function () use ($badName): void {
new NewTimePeriod($badName, 'fake_alias');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::maxLength(
$badName,
mb_strlen($badName),
NewTimePeriod::MAX_NAME_LENGTH,
'NewTimePeriod::name'
)->getMessage()
);
it(
'should throw an exception if the given extra periods are not of the right type',
function (): void {
$newTimePeriod = new NewTimePeriod('fake_name', 'fake_alias');
$newTimePeriod->setExtraTimePeriods([
new \stdClass(),
]);
}
)->throws(
\TypeError::class
);
it(
'should throw an exception if the given templates are not of the right type',
function (): void {
$newTimePeriod = new NewTimePeriod('fake_name', 'fake_alias');
$newTimePeriod->setTemplates([
new \stdClass(),
]);
}
)->throws(
\TypeError::class
);
it(
'should throw an exception if the given days are not of the right type',
function (): void {
$newTimePeriod = new NewTimePeriod('fake_name', 'fake_alias');
$newTimePeriod->setDays([
new \stdClass(),
]);
}
)->throws(
\TypeError::class
);
it(
'Properties should be equal between constructor and getter',
function (): void {
$name = ' fake_name ';
$alias = ' fake_alias ';
$newTimePeriod = new NewTimePeriod($name, $alias);
expect($newTimePeriod->getName())->toBe(trim($name));
expect($newTimePeriod->getAlias())->toBe(trim($alias));
$timeRange = new TimeRange('00:00-01:00');
$extra = [new NewExtraTimePeriod('monday 1', $timeRange)];
$newTimePeriod->setExtraTimePeriods($extra);
expect($newTimePeriod->getExtraTimePeriods())->toBe($extra);
$templates = [1];
$newTimePeriod->setTemplates($templates);
expect($newTimePeriod->getTemplates())->toBe($templates);
$days = [new Day(1, $timeRange)];
$newTimePeriod->setDays($days);
expect($newTimePeriod->getDays())->toBe($days);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Domain/Model/NewExtraTimePeriodTest.php | centreon/tests/php/Core/TimePeriod/Domain/Model/NewExtraTimePeriodTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\TimePeriod\Domain\Model\NewExtraTimePeriod;
use Core\TimePeriod\Domain\Model\TimeRange;
beforeEach(function (): void {
$this->timeRange = new TimeRange('00:01-02:00');
});
it(
'should throw exception with empty day range',
function (): void {
new NewExtraTimePeriod('', $this->timeRange);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
NewExtraTimePeriod::MIN_DAY_RANGE_LENGTH,
'NewExtraTimePeriod::dayRange'
)->getMessage()
);
$badValue = str_repeat('_', NewExtraTimePeriod::MAX_DAY_RANGE_LENGTH + 1);
it(
'should throw exception with too long day range',
function () use ($badValue): void {
new NewExtraTimePeriod($badValue, $this->timeRange);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::maxLength(
$badValue,
mb_strlen($badValue),
NewExtraTimePeriod::MAX_DAY_RANGE_LENGTH,
'NewExtraTimePeriod::dayRange'
)->getMessage()
);
it(
'should throw exception if day range consists only of space',
function (): void {
new NewExtraTimePeriod(' ', $this->timeRange);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
NewExtraTimePeriod::MIN_DAY_RANGE_LENGTH,
'NewExtraTimePeriod::dayRange'
)->getMessage()
);
it(
'should apply trim on the day range value',
function (): void {
$dayRange = '00:00-01:00 ';
$extraTimePeriod = new NewExtraTimePeriod($dayRange, $this->timeRange);
expect(trim($dayRange))->toBe($extraTimePeriod->getDayRange());
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Domain/Model/TemplateTest.php | centreon/tests/php/Core/TimePeriod/Domain/Model/TemplateTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\TimePeriod\Domain\Model\Template;
$emptyAlias = '';
it(
'should throw an exception if alias is empty',
function () use ($emptyAlias): void {
new Template(1, $emptyAlias);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
Template::MIN_ALIAS_LENGTH,
'Template::alias'
)->getMessage()
);
$badAlias = str_repeat('_', Template::MAX_ALIAS_LENGTH + 1);
it(
'should throw an exception if alias is too long',
function () use ($badAlias): void {
new Template(1, $badAlias);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::maxLength(
$badAlias,
mb_strlen($badAlias),
Template::MAX_ALIAS_LENGTH,
'Template::alias'
)->getMessage()
);
$emptyAlias = ' ';
it(
'should throw an exception if alias consists only of space',
function () use ($emptyAlias): void {
new Template(1, $emptyAlias);
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
Template::MIN_ALIAS_LENGTH,
'Template::alias'
)->getMessage()
);
it(
'should throw an exception if ID is less than 1',
function (): void {
new Template(0, 'fake_value');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::min(
0,
1,
'Template::id'
)->getMessage()
);
it(
'should apply trim on the alias value',
function (): void {
$fakeAlias = 'fake alias ';
$template = new Template(1, $fakeAlias);
expect(trim($fakeAlias))->toBe($template->getAlias());
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/TimePeriod/Domain/Model/TimePeriodTest.php | centreon/tests/php/Core/TimePeriod/Domain/Model/TimePeriodTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\TimePeriod\Domain\Model\{
Day, ExtraTimePeriod, Template, TimePeriod, TimeRange
};
it(
'should throw an exception if alias is empty',
function (): void {
new TimePeriod(1, 'fake_name', '');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
TimePeriod::MIN_ALIAS_LENGTH,
'TimePeriod::alias'
)->getMessage()
);
it(
'should throw an exception if alias consists only of space',
function (): void {
new TimePeriod(1, 'fake_name', ' ');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
TimePeriod::MIN_ALIAS_LENGTH,
'TimePeriod::alias'
)->getMessage()
);
it(
'should throw an exception if name is empty',
function (): void {
new TimePeriod(1, '', 'fake_alias');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
TimePeriod::MIN_NAME_LENGTH,
'TimePeriod::name'
)->getMessage()
);
it(
'Properties should be equal between constructor and getter',
function (): void {
$id = 1;
$name = ' fake_name ';
$alias = ' fake_alias ';
$timePeriod = new TimePeriod($id, $name, $alias);
expect($timePeriod->getId())->toBe($id);
expect($timePeriod->getName())->toBe(trim($name));
expect($timePeriod->getAlias())->toBe(trim($alias));
$timeRange = new TimeRange('00:00-01:00');
$extra = [new ExtraTimePeriod(1, 'monday 1', $timeRange)];
$timePeriod->setExtraTimePeriods($extra);
expect($timePeriod->getExtraTimePeriods())->toBe($extra);
$templates = [new Template(1, 'fake_template')];
$timePeriod->setTemplates($templates);
expect($timePeriod->getTemplates())->toBe($templates);
$days = [new Day(1, $timeRange)];
$timePeriod->setDays($days);
expect($timePeriod->getDays())->toBe($days);
}
);
it(
'should throw an exception if name consists only of space',
function (): void {
new TimePeriod(1, ' ', 'fake_alias');
}
)->throws(
\InvalidArgumentException::class,
AssertionException::minLength(
'',
0,
TimePeriod::MIN_NAME_LENGTH,
'TimePeriod::name'
)->getMessage()
);
it(
'should throw an exception if the given extra periods are not of the right type',
function (): void {
$timePeriod = new TimePeriod(1, 'fake_name', 'fake_alias');
$timePeriod->setExtraTimePeriods([
new \stdClass(),
]);
}
)->throws(
\TypeError::class
);
it(
'should throw an exception if the given templates are not of the right type',
function (): void {
$timePeriod = new TimePeriod(1, 'fake_name', 'fake_alias');
$timePeriod->setTemplates([
new \stdClass(),
]);
}
)->throws(
\TypeError::class
);
it(
'should throw an exception if the given days are not of the right type',
function (): void {
$timePeriod = new TimePeriod(1, 'fake_name', 'fake_alias');
$timePeriod->setDays([
new \stdClass(),
]);
}
)->throws(
\TypeError::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/TimePeriod/Domain/Rules/SimpleDayTimeRangeRuleStrategyTest.php | centreon/tests/php/Core/TimePeriod/Domain/Rules/SimpleDayTimeRangeRuleStrategyTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\TimePeriod\Domain\Rules;
use Core\TimePeriod\Domain\Rules\Strategies\SimpleDayTimeRangeRuleStrategy;
it('return true if DateTimes are within the time range on the specified day', function (): void {
$ranges = [
['start' => '00:00', 'end' => '09:00'],
['start' => '17:00', 'end' => '24:00'],
];
$day = (int) (new \DateTimeImmutable())->format('N');
$now = new \DateTime();
$now->setTime(8, 30);
$isWithin = (new SimpleDayTimeRangeRuleStrategy())->isIncluded($now, $day, $ranges);
expect($isWithin)->toBe(true);
});
it('return true if DateTimes swapped are within the time range on the specified day', function (): void {
$ranges = [
['start' => '17:00', 'end' => '24:00'],
['start' => '00:00', 'end' => '09:00'],
];
$day = (int) (new \DateTimeImmutable())->format('N');
$now = new \DateTime();
$now->setTime(8, 30);
$isWithin = (new SimpleDayTimeRangeRuleStrategy())->isIncluded($now, $day, $ranges);
expect($isWithin)->toBe(true);
$now->setTime(18, 30);
$isWithin = (new SimpleDayTimeRangeRuleStrategy())->isIncluded($now, $day, $ranges);
expect($isWithin)->toBe(true);
});
it('return false if DateTimes are outside the time range on the specified day', function (): void {
$ranges = [
['start' => '17:00', 'end' => '24:00'],
['start' => '00:00', 'end' => '09:00'],
];
$day = (int) (new \DateTimeImmutable())->format('N');
$now = new \DateTime();
$now->setTime(10, 30);
$isWithin = (new SimpleDayTimeRangeRuleStrategy())->isIncluded($now, $day, $ranges);
expect($isWithin)->toBe(false);
$now->setTime(16, 30);
$isWithin = (new SimpleDayTimeRangeRuleStrategy())->isIncluded($now, $day, $ranges);
expect($isWithin)->toBe(false);
});
it('return false if the day is not today', function (): void {
$ranges = [
['start' => '00:00', 'end' => '09:00'],
['start' => '17:00', 'end' => '24:00'],
];
$yesterday = (new \DateTimeImmutable())->modify('+1 day');
$day = (int) $yesterday->format('N');
$now = new \DateTime();
$now->setTime(8, 30);
$isWithin = (new SimpleDayTimeRangeRuleStrategy())->isIncluded($now, $day, $ranges);
expect($isWithin)->toBe(false);
$now->setTime(18, 30);
$isWithin = (new SimpleDayTimeRangeRuleStrategy())->isIncluded($now, $day, $ranges);
expect($isWithin)->toBe(false);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostSeverity/Application/UseCase/AddHostSeverity/AddHostSeverityTest.php | centreon/tests/php/Core/HostSeverity/Application/UseCase/AddHostSeverity/AddHostSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostSeverity\Application\UseCase\AddHostSeverity;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\CreatedResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\Repository\WriteHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\UseCase\AddHostSeverity\AddHostSeverity;
use Core\HostSeverity\Application\UseCase\AddHostSeverity\AddHostSeverityRequest;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\HostSeverity\Domain\Model\NewHostSeverity;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(function (): void {
$this->writeHostSeverityRepository = $this->createMock(WriteHostSeverityRepositoryInterface::class);
$this->readHostSeverityRepository = $this->createMock(ReadHostSeverityRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->request = new AddHostSeverityRequest();
$this->request->name = 'hc-name';
$this->request->alias = 'hc-alias';
$this->request->comment = null;
$this->request->level = 2;
$this->request->iconId = 1;
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->useCase = new AddHostSeverity(
$this->writeHostSeverityRepository,
$this->readHostSeverityRepository,
$this->readViewImgRepository = $this->createMock(ReadViewImgRepositoryInterface::class),
$this->user
);
$this->hostSeverity = new HostSeverity(
1,
$this->request->name,
$this->request->alias,
$this->request->level,
$this->request->iconId,
);
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByName')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostSeverityException::addHostSeverity(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostSeverityException::writeActionsNotAllowed()->getMessage());
});
it('should present a ConflictResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostSeverityException::hostNameAlreadyExists()->getMessage());
});
it('should present an InvalidArgumentResponse when a field assert failed', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->request->level = NewHostSeverity::MIN_LEVEL_VALUE - 1;
$expectedException = AssertionException::min(
$this->request->level,
NewHostSeverity::MIN_LEVEL_VALUE,
'NewHostSeverity::level'
);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe($expectedException->getMessage());
});
it('should throw a ConflictResponse if the host severity icon does not exist', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostSeverityException::iconDoesNotExist($this->request->iconId)->getMessage());
});
it('should present an ErrorResponse if the newly created host severity cannot be retrieved', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->writeHostSeverityRepository
->expects($this->once())
->method('add')
->willReturn(1);
$this->readHostSeverityRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostSeverityException::errorWhileRetrievingObject()->getMessage());
});
it('should return created object on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->writeHostSeverityRepository
->expects($this->once())
->method('add')
->willReturn(1);
$this->readHostSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostSeverity);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getPresentedData())->toBeInstanceOf(CreatedResponse::class);
expect($this->presenter->getPresentedData()->getResourceId())->toBe($this->hostSeverity->getId());
$payload = $this->presenter->getPresentedData()->getPayload();
expect($payload->name)
->toBe($this->hostSeverity->getName())
->and($payload->alias)
->toBe($this->hostSeverity->getAlias())
->and($payload->isActivated)
->toBe($this->hostSeverity->isActivated())
->and($payload->comment)
->toBe($this->hostSeverity->getComment());
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostSeverity/Application/UseCase/FindHostSeverity/FindHostSeverityTest.php | centreon/tests/php/Core/HostSeverity/Application/UseCase/FindHostSeverity/FindHostSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostSeverity\Application\UseCase\FindHostSeverity;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\UseCase\FindHostSeverity\FindHostSeverity;
use Core\HostSeverity\Application\UseCase\FindHostSeverity\FindHostSeverityResponse;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Exception;
beforeEach(function (): void {
$this->readHostSeverityRepository = $this->createMock(ReadHostSeverityRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->usecase = new FindHostSeverity(
$this->readHostSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->hostSeverityName = 'hs-name';
$this->hostSeverityAlias = 'hs-alias';
$this->hostSeverityComment = 'blablabla';
$this->hostSeverity = new HostSeverity(
1,
$this->hostSeverityName,
$this->hostSeverityAlias,
1,
1
);
$this->hostSeverity->setComment($this->hostSeverityComment);
$this->responseArray = [
'id' => 1,
'name' => $this->hostSeverityName,
'alias' => $this->hostSeverityAlias,
'level' => 1,
'icon_id' => 1,
'is_activated' => true,
'comment' => $this->hostSeverityComment,
];
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willThrowException(new Exception());
($this->usecase)($this->hostSeverity->getId(), $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostSeverityException::findHostSeverity(new Exception(), $this->hostSeverity->getId())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, false],
]
);
($this->usecase)($this->hostSeverity->getId(), $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostSeverityException::accessNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the host severity does not exist (with admin user)', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(false);
($this->usecase)($this->hostSeverity->getId(), $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host severity not found');
});
it('should present a NotFoundResponse when the host severity does not exist (with non-admin user)', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(false);
($this->usecase)($this->hostSeverity->getId(), $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host severity not found');
});
it('should present a FindHostSeverityResponse when a non-admin user has read-only rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, true],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, false],
]
);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostSeverity);
($this->usecase)($this->hostSeverity->getId(), $this->presenter);
$response = $this->presenter->getPresentedData();
expect($response)
->toBeInstanceOf(FindHostSeverityResponse::class)
->and($response->id)
->toBe($this->responseArray['id'])
->and($response->name)
->toBe($this->responseArray['name'])
->and($response->alias)
->toBe($this->responseArray['alias'])
->and($response->isActivated)
->toBe($this->responseArray['is_activated'])
->and($response->level)
->toBe($this->responseArray['level'])
->and($response->iconId)
->toBe($this->responseArray['icon_id'])
->and($response->comment)
->toBe($this->responseArray['comment']);
});
it('should present a FindHostSeverityResponse when a non-admin user has read/write rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, true],
]
);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostSeverity);
($this->usecase)($this->hostSeverity->getId(), $this->presenter);
$response = $this->presenter->getPresentedData();
expect($response)
->toBeInstanceOf(FindHostSeverityResponse::class)
->and($response->id)
->toBe($this->responseArray['id'])
->and($response->name)
->toBe($this->responseArray['name'])
->and($response->alias)
->toBe($this->responseArray['alias'])
->and($response->isActivated)
->toBe($this->responseArray['is_activated'])
->and($response->level)
->toBe($this->responseArray['level'])
->and($response->iconId)
->toBe($this->responseArray['icon_id'])
->and($response->comment)
->toBe($this->responseArray['comment']);
});
it('should present a FindHostSeverityResponse with admin user', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->hostSeverity);
($this->usecase)($this->hostSeverity->getId(), $this->presenter);
$response = $this->presenter->getPresentedData();
expect($response)
->toBeInstanceOf(FindHostSeverityResponse::class)
->and($response->id)
->toBe($this->responseArray['id'])
->and($response->name)
->toBe($this->responseArray['name'])
->and($response->alias)
->toBe($this->responseArray['alias'])
->and($response->isActivated)
->toBe($this->responseArray['is_activated'])
->and($response->level)
->toBe($this->responseArray['level'])
->and($response->iconId)
->toBe($this->responseArray['icon_id'])
->and($response->comment)
->toBe($this->responseArray['comment']);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostSeverity/Application/UseCase/UpdateHostSeverity/UpdateHostSeverityTest.php | centreon/tests/php/Core/HostSeverity/Application/UseCase/UpdateHostSeverity/UpdateHostSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostSeverity\Application\UseCase\UpdateHostSeverity;
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\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\Repository\WriteHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\UseCase\UpdateHostSeverity\UpdateHostSeverity;
use Core\HostSeverity\Application\UseCase\UpdateHostSeverity\UpdateHostSeverityRequest;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\ViewImg\Application\Repository\ReadViewImgRepositoryInterface;
beforeEach(function (): void {
$this->writeHostSeverityRepository = $this->createMock(WriteHostSeverityRepositoryInterface::class);
$this->readHostSeverityRepository = $this->createMock(ReadHostSeverityRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->readViewImgRepository = $this->createMock(ReadViewImgRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->originalHostSeverity = new HostSeverity(1, 'hs-name', 'hs-alias', 1, 1);
$this->request = new UpdateHostSeverityRequest();
$this->request->name = 'hs-name-edit';
$this->request->alias = 'hs-alias-edit';
$this->request->level = 2;
$this->request->iconId = 1;
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->useCase = new UpdateHostSeverity(
$this->writeHostSeverityRepository,
$this->readHostSeverityRepository,
$this->readViewImgRepository,
$this->accessGroupRepository,
$this->user
);
});
it('should present an ErrorResponse when a generic exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willThrowException(new \Exception());
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostSeverityException::UpdateHostSeverity(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostSeverityException::writeActionsNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the host severity does not exist (with admin user)', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host severity not found');
});
it('should present a NotFoundResponse when the host severity does not exist (with non-admin user)', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host severity not found');
});
it('should present an ErrorResponse if the existing host severity cannot be retrieved', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('findById')
->willReturn(null);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostSeverityException::errorWhileRetrievingObject()->getMessage());
});
it('should present a ConflictResponse when name is already used', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostSeverity);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(true);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ConflictResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostSeverityException::hostNameAlreadyExists()->getMessage());
});
it('should present an InvalidArgumentResponse when an assertion fails', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostSeverity);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->request->alias = '';
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(InvalidArgumentResponse::class);
});
it('should return a NoContentResponse on success', function (): void {
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('findById')
->willReturn($this->originalHostSeverity);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByName')
->willReturn(false);
$this->readViewImgRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->writeHostSeverityRepository
->expects($this->once())
->method('update');
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostSeverity/Application/UseCase/FindHostSeverities/FindHostSeveritiesTest.php | centreon/tests/php/Core/HostSeverity/Application/UseCase/FindHostSeverities/FindHostSeveritiesTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostSeverity\Application\UseCase\FindHostSeverities;
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\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\UseCase\FindHostSeverities\FindHostSeverities;
use Core\HostSeverity\Application\UseCase\FindHostSeverities\FindHostSeveritiesResponse;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Exception;
beforeEach(function (): void {
$this->hostSeverityRepository = $this->createMock(ReadHostSeverityRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->user = $this->createMock(ContactInterface::class);
$this->usecase = new FindHostSeverities(
$this->hostSeverityRepository,
$this->accessGroupRepository,
$this->requestParameters,
$this->user
);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->hostSeverity = new HostSeverity(
1,
$this->hostSeverityName = 'hc-name',
$this->hostSeverityAlias = 'hc-alias',
$this->hostSeverityLevel = 2,
$this->hostSeverityIconId = 1
);
$this->hostSeverity->setComment(
$this->hostSeverityComment = 'blablabla'
);
$this->responseArray = [
'id' => 1,
'name' => $this->hostSeverityName,
'alias' => $this->hostSeverityAlias,
'level' => $this->hostSeverityLevel,
'iconId' => $this->hostSeverityIconId,
'isActivated' => true,
'comment' => $this->hostSeverityComment,
];
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->hostSeverityRepository
->expects($this->once())
->method('findAll')
->willThrowException(new Exception());
($this->usecase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostSeverityException::findHostSeverities(new Exception())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has insufficient rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, false],
]
);
($this->usecase)($this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostSeverityException::accessNotAllowed()->getMessage());
});
it('should present a FindHostGroupsResponse when a non-admin user has read only rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, true],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, false],
]
);
$this->hostSeverityRepository
->expects($this->once())
->method('findAllByAccessGroups')
->willReturn([$this->hostSeverity]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindHostSeveritiesResponse::class)
->and($this->presenter->getPresentedData()->hostSeverities[0])
->toBe($this->responseArray);
});
it('should present a FindHostGroupsResponse when a non-admin user has read/write rights', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_CATEGORIES_READ_WRITE, true],
]
);
$this->hostSeverityRepository
->expects($this->once())
->method('findAllByAccessGroups')
->willReturn([$this->hostSeverity]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindHostSeveritiesResponse::class)
->and($this->presenter->getPresentedData()->hostSeverities[0])
->toBe($this->responseArray);
});
it('should present a FindHostSeveritiesResponse with admin user', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->hostSeverityRepository
->expects($this->once())
->method('findAll')
->willReturn([$this->hostSeverity]);
($this->usecase)($this->presenter);
expect($this->presenter->getPresentedData())
->toBeInstanceOf(FindHostSeveritiesResponse::class)
->and($this->presenter->getPresentedData()->hostSeverities[0])
->toBe($this->responseArray);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostSeverity/Application/UseCase/DeleteHostSeverity/DeleteHostSeverityTest.php | centreon/tests/php/Core/HostSeverity/Application/UseCase/DeleteHostSeverity/DeleteHostSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostSeverity\Application\UseCase\DeleteHostSeverity;
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\HostSeverity\Application\Exception\HostSeverityException;
use Core\HostSeverity\Application\Repository\ReadHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\Repository\WriteHostSeverityRepositoryInterface;
use Core\HostSeverity\Application\UseCase\DeleteHostSeverity\DeleteHostSeverity;
use Core\HostSeverity\Domain\Model\HostSeverity;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->writeHostSeverityRepository = $this->createMock(WriteHostSeverityRepositoryInterface::class);
$this->readHostSeverityRepository = $this->createMock(ReadHostSeverityRepositoryInterface::class);
$this->accessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new DefaultPresenter($this->presenterFormatter);
$this->user = $this->createMock(ContactInterface::class);
$this->hostSeverity = $this->createMock(HostSeverity::class);
$this->hostSeverityId = 1;
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$useCase = new DeleteHostSeverity(
$this->writeHostSeverityRepository,
$this->readHostSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->writeHostSeverityRepository
->expects($this->once())
->method('deleteById')
->willThrowException(new \Exception());
$useCase($this->hostSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostSeverityException::deleteHostSeverity(new \Exception())->getMessage());
});
it('should present a ForbiddenResponse when a non-admin user has insufficient rights', function (): void {
$useCase = new DeleteHostSeverity(
$this->writeHostSeverityRepository,
$this->readHostSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
$useCase($this->hostSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(HostSeverityException::deleteNotAllowed()->getMessage());
});
it('should present a NotFoundResponse when the host severity does not exist (with admin user)', function (): void {
$useCase = new DeleteHostSeverity(
$this->writeHostSeverityRepository,
$this->readHostSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$useCase($this->hostSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host severity not found');
});
it('should present a NotFoundResponse when the host severity does not exist (with non-admin user)', function (): void {
$useCase = new DeleteHostSeverity(
$this->writeHostSeverityRepository,
$this->readHostSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(false);
$useCase($this->hostSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Host severity not found');
});
it('should present a NoContentResponse on success (with admin user)', function (): void {
$useCase = new DeleteHostSeverity(
$this->writeHostSeverityRepository,
$this->readHostSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$hostSeverityId = 1;
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('exists')
->willReturn(true);
$this->writeHostSeverityRepository
->expects($this->once())
->method('deleteById');
$useCase($hostSeverityId, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(NoContentResponse::class);
});
it('should present a NoContentResponse on success (with non-admin user)', function (): void {
$useCase = new DeleteHostSeverity(
$this->writeHostSeverityRepository,
$this->readHostSeverityRepository,
$this->accessGroupRepository,
$this->user
);
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->user
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readHostSeverityRepository
->expects($this->once())
->method('existsByAccessGroups')
->willReturn(true);
$this->writeHostSeverityRepository
->expects($this->once())
->method('deleteById');
$useCase($this->hostSeverityId, $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/HostSeverity/Domain/Model/HostSeverityTest.php | centreon/tests/php/Core/HostSeverity/Domain/Model/HostSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostSeverity\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\HostSeverity\Domain\Model\HostSeverity;
beforeEach(function (): void {
$this->severityName = 'host-name';
$this->severityAlias = 'host-alias';
$this->level = 1;
$this->iconId = 2;
});
it('should return properly set host severity instance', function (): void {
$hostSeverity = new HostSeverity(1, $this->severityName, $this->severityAlias, $this->level, $this->iconId);
expect($hostSeverity->getId())->toBe(1)
->and($hostSeverity->getName())->toBe($this->severityName)
->and($hostSeverity->getAlias())->toBe($this->severityAlias);
});
it('should trim the fields "name" and "alias"', function (): void {
$hostSeverity = new HostSeverity(
1,
$nameWithSpaces = ' my-name ',
$aliasWithSpaces = ' my-alias ',
$this->level,
$this->iconId
);
expect($hostSeverity->getName())->toBe(trim($nameWithSpaces))
->and($hostSeverity->getAlias())->toBe(trim($aliasWithSpaces));
});
it('should throw an exception when host severity name is empty', function (): void {
new HostSeverity(1, '', $this->severityAlias, $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('HostSeverity::name')
->getMessage()
);
it('should throw an exception when host severity name is too long', function (): void {
new HostSeverity(1, str_repeat('a', HostSeverity::MAX_NAME_LENGTH + 1), $this->severityAlias, $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostSeverity::MAX_NAME_LENGTH + 1),
HostSeverity::MAX_NAME_LENGTH + 1,
HostSeverity::MAX_NAME_LENGTH,
'HostSeverity::name'
)->getMessage()
);
it('should throw an exception when host severity alias is empty', function (): void {
new HostSeverity(1, $this->severityName, '', $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('HostSeverity::alias')
->getMessage()
);
it('should throw an exception when host severity alias is too long', function (): void {
new HostSeverity(1, $this->severityName, str_repeat('a', HostSeverity::MAX_ALIAS_LENGTH + 1), $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostSeverity::MAX_ALIAS_LENGTH + 1),
HostSeverity::MAX_ALIAS_LENGTH + 1,
HostSeverity::MAX_ALIAS_LENGTH,
'HostSeverity::alias'
)->getMessage()
);
it('should throw an exception when host severity comment is too long', function (): void {
$hostSeverity = new HostSeverity(1, $this->severityName, $this->severityAlias, $this->level, $this->iconId);
$hostSeverity->setComment(str_repeat('a', HostSeverity::MAX_COMMENT_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostSeverity::MAX_COMMENT_LENGTH + 1),
HostSeverity::MAX_COMMENT_LENGTH + 1,
HostSeverity::MAX_COMMENT_LENGTH,
'HostSeverity::comment'
)->getMessage()
);
it('should throw an exception when host severity level is too high', function (): void {
$hostSeverity = new HostSeverity(
1,
$this->severityName,
$this->severityAlias,
HostSeverity::MAX_LEVEL_VALUE + 1,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::max(HostSeverity::MAX_LEVEL_VALUE + 1, HostSeverity::MAX_LEVEL_VALUE, 'HostSeverity::level')
->getMessage()
);
it('should throw an exception when host severity level is too low', function (): void {
$hostSeverity = new HostSeverity(
1,
$this->severityName,
$this->severityAlias,
HostSeverity::MIN_LEVEL_VALUE - 1,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::min(HostSeverity::MIN_LEVEL_VALUE - 1, HostSeverity::MIN_LEVEL_VALUE, 'HostSeverity::level')
->getMessage()
);
it('should throw an exception when host severity name is set empty', function (): void {
$hostSeverity = new HostSeverity(
1,
$this->severityName,
$this->severityAlias,
$this->level,
$this->iconId
);
$hostSeverity->setName('');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('HostSeverity::name')
->getMessage()
);
it('should throw an exception when host severity name is set too long', function (): void {
$hostSeverity = new HostSeverity(
1,
$this->severityName,
$this->severityAlias,
$this->level,
$this->iconId
);
$hostSeverity->setName(str_repeat('a', HostSeverity::MAX_NAME_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostSeverity::MAX_NAME_LENGTH + 1),
HostSeverity::MAX_NAME_LENGTH + 1,
HostSeverity::MAX_NAME_LENGTH,
'HostSeverity::name'
)->getMessage()
);
it('should throw an exception when host severity alias is set empty', function (): void {
$hostSeverity = new HostSeverity(
1,
$this->severityName,
$this->severityAlias,
$this->level,
$this->iconId
);
$hostSeverity->setAlias('');
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('HostSeverity::alias')
->getMessage()
);
it('should throw an exception when host severity alias is set too long', function (): void {
$hostSeverity = new HostSeverity(
1,
$this->severityName,
$this->severityAlias,
$this->level,
$this->iconId
);
$hostSeverity->setAlias(str_repeat('a', HostSeverity::MAX_ALIAS_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', HostSeverity::MAX_ALIAS_LENGTH + 1),
HostSeverity::MAX_ALIAS_LENGTH + 1,
HostSeverity::MAX_ALIAS_LENGTH,
'HostSeverity::alias'
)->getMessage()
);
it('should throw an exception when host severity level is set too high', function (): void {
$hostSeverity = new HostSeverity(
1,
$this->severityName,
$this->severityAlias,
$this->level,
$this->iconId
);
$hostSeverity->setLevel(HostSeverity::MAX_LEVEL_VALUE + 1);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::max(HostSeverity::MAX_LEVEL_VALUE + 1, HostSeverity::MAX_LEVEL_VALUE, 'HostSeverity::level')
->getMessage()
);
it('should throw an exception when host severity level is set too low', function (): void {
$hostSeverity = new HostSeverity(
1,
$this->severityName,
$this->severityAlias,
$this->level,
$this->iconId
);
$hostSeverity->setLevel(HostSeverity::MIN_LEVEL_VALUE - 1);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::min(HostSeverity::MIN_LEVEL_VALUE - 1, HostSeverity::MIN_LEVEL_VALUE, 'HostSeverity::level')
->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/HostSeverity/Domain/Model/NewHostseverityTest.php | centreon/tests/php/Core/HostSeverity/Domain/Model/NewHostseverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostSeverity\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\HostSeverity\Domain\Model\NewHostSeverity;
beforeEach(function (): void {
$this->severityName = 'host-name';
$this->severityAlias = 'host-alias';
$this->level = 1;
$this->iconId = 2;
});
it('should return properly set host severity instance', function (): void {
$hostSeverity = new NewHostSeverity($this->severityName, $this->severityAlias, $this->level, $this->iconId);
expect($hostSeverity->getName())->toBe($this->severityName)
->and($hostSeverity->getAlias())->toBe($this->severityAlias);
});
it('should trim the fields "name" and "alias"', function (): void {
$hostSeverity = new NewHostSeverity(
$nameWithSpaces = ' my-name ',
$aliasWithSpaces = ' my-alias ',
$this->level,
$this->iconId
);
expect($hostSeverity->getName())->toBe(trim($nameWithSpaces))
->and($hostSeverity->getAlias())->toBe(trim($aliasWithSpaces));
});
it('should throw an exception when host severity name is empty', function (): void {
new NewHostSeverity('', $this->severityAlias, $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewHostSeverity::name')
->getMessage()
);
it('should throw an exception when host severity name is too long', function (): void {
new NewHostSeverity(
str_repeat('a', NewHostSeverity::MAX_NAME_LENGTH + 1),
$this->severityAlias,
$this->level,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewHostSeverity::MAX_NAME_LENGTH + 1),
NewHostSeverity::MAX_NAME_LENGTH + 1,
NewHostSeverity::MAX_NAME_LENGTH,
'NewHostSeverity::name'
)->getMessage()
);
it('should throw an exception when host severity alias is empty', function (): void {
new NewHostSeverity($this->severityName, '', $this->level, $this->iconId);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewHostSeverity::alias')
->getMessage()
);
it('should throw an exception when host severity alias is too long', function (): void {
new NewHostSeverity(
$this->severityName,
str_repeat('a', NewHostSeverity::MAX_ALIAS_LENGTH + 1),
$this->level,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewHostSeverity::MAX_ALIAS_LENGTH + 1),
NewHostSeverity::MAX_ALIAS_LENGTH + 1,
NewHostSeverity::MAX_ALIAS_LENGTH,
'NewHostSeverity::alias'
)->getMessage()
);
it('should throw an exception when host severity comment is too long', function (): void {
$hostSeverity = new NewHostSeverity($this->severityName, $this->severityAlias, $this->level, $this->iconId);
$hostSeverity->setComment(str_repeat('a', NewHostSeverity::MAX_COMMENT_LENGTH + 1));
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', NewHostSeverity::MAX_COMMENT_LENGTH + 1),
NewHostSeverity::MAX_COMMENT_LENGTH + 1,
NewHostSeverity::MAX_COMMENT_LENGTH,
'NewHostSeverity::comment'
)->getMessage()
);
it('should throw an exception when host severity level is too high', function (): void {
$hostSeverity = new NewHostSeverity(
$this->severityName,
$this->severityAlias,
NewHostSeverity::MAX_LEVEL_VALUE + 1,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::max(
NewHostSeverity::MAX_LEVEL_VALUE + 1,
NewHostSeverity::MAX_LEVEL_VALUE,
'NewHostSeverity::level'
)->getMessage()
);
it('should throw an exception when host severity level is too low', function (): void {
$hostSeverity = new NewHostSeverity(
$this->severityName,
$this->severityAlias,
NewHostSeverity::MIN_LEVEL_VALUE - 1,
$this->iconId
);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::min(
NewHostSeverity::MIN_LEVEL_VALUE - 1,
NewHostSeverity::MIN_LEVEL_VALUE,
'NewHostSeverity::level'
)->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/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverityPresenterStub.php | centreon/tests/php/Core/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverityPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Severity\RealTime\Application\UseCase\FindSeverity;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Severity\RealTime\Application\UseCase\FindSeverity\FindSeverityPresenterInterface;
use Core\Severity\RealTime\Application\UseCase\FindSeverity\FindSeverityResponse;
use Symfony\Component\HttpFoundation\Response;
class FindSeverityPresenterStub extends AbstractPresenter implements
FindSeverityPresenterInterface
{
/** @var FindSeverityResponse */
public $response;
/**
* @param FindSeverityResponse $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/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverityTest.php | centreon/tests/php/Core/Severity/RealTime/Application/UseCase/FindSeverity/FindSeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Severity\RealTime\Application\UseCase\FindSeverity;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Domain\RealTime\Model\Icon;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Severity\RealTime\Application\Repository\ReadSeverityRepositoryInterface;
use Core\Severity\RealTime\Application\UseCase\FindSeverity\FindSeverity;
use Core\Severity\RealTime\Application\UseCase\FindSeverity\FindSeverityResponse;
use Core\Severity\RealTime\Domain\Model\Severity;
beforeEach(function (): void {
$this->user = $this->createMock(ContactInterface::class);
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->repository = $this->createMock(ReadSeverityRepositoryInterface::class);
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class);
$this->presenter = new FindSeverityPresenterStub($this->presenterFormatter);
$this->icon = (new Icon())
->setId(1)
->setName('icon-name')
->setUrl('ppm/icon-name.png');
$this->severity = new Severity(1, 'name', 50, Severity::HOST_SEVERITY_TYPE_ID, $this->icon);
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->repository
->expects($this->once())
->method('findAllByTypeId')
->with(Severity::HOST_SEVERITY_TYPE_ID)
->willThrowException(new \Exception());
$useCase = new FindSeverity($this->repository, $this->user, $this->readAccessGroupRepository);
$useCase(Severity::HOST_SEVERITY_TYPE_ID, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe('An error occured while retrieving severities');
});
it('should present a FindSeverityResponse as admin', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->repository
->expects($this->once())
->method('findAllByTypeId')
->willReturn([$this->severity]);
$useCase = new FindSeverity($this->repository, $this->user, $this->readAccessGroupRepository);
$useCase(Severity::HOST_SEVERITY_TYPE_ID, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindSeverityResponse::class)
->and($this->presenter->response->severities[0])->toBe(
[
'id' => 1,
'name' => 'name',
'level' => 50,
'type' => 'host',
'icon' => [
'id' => 1,
'name' => 'icon-name',
'url' => 'ppm/icon-name.png',
],
]
);
});
it('should present a FindSeverityResponse as non-admin', function (): void {
$this->user
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([]);
$this->repository
->expects($this->once())
->method('findAllByTypeIdAndAccessGroups')
->willReturn([$this->severity]);
$useCase = new FindSeverity($this->repository, $this->user, $this->readAccessGroupRepository);
$useCase(Severity::HOST_SEVERITY_TYPE_ID, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(FindSeverityResponse::class)
->and($this->presenter->response->severities[0])->toBe(
[
'id' => 1,
'name' => 'name',
'level' => 50,
'type' => 'host',
'icon' => [
'id' => 1,
'name' => 'icon-name',
'url' => 'ppm/icon-name.png',
],
]
);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Severity/RealTime/Domain/Model/SeverityTest.php | centreon/tests/php/Core/Severity/RealTime/Domain/Model/SeverityTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Severity\RealTime\Domain\Model;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\RealTime\Model\Icon;
use Core\Severity\RealTime\Domain\Model\Severity;
beforeEach(function (): void {
$this->icon = (new Icon())
->setName('icon-name')
->setUrl('ppm/icon-name.png');
});
it('should throw an exception when severity name is empty', function (): void {
new Severity(1, '', 50, Severity::HOST_SEVERITY_TYPE_ID, $this->icon);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmpty('Severity::name')
->getMessage()
);
it('should throw an exception when severity name is too long', function (): void {
new Severity(1, str_repeat('a', Severity::MAX_NAME_LENGTH + 1), 50, Severity::HOST_SEVERITY_TYPE_ID, $this->icon);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::maxLength(
str_repeat('a', Severity::MAX_NAME_LENGTH + 1),
Severity::MAX_NAME_LENGTH + 1,
Severity::MAX_NAME_LENGTH,
'Severity::name'
)->getMessage()
);
it('should throw an exception when severity level is lower than 0', function (): void {
new Severity(1, 'name', -1, Severity::HOST_SEVERITY_TYPE_ID, $this->icon);
})->throws(\Assert\InvalidArgumentException::class, AssertionException::min(-1, 0, 'Severity::level')->getMessage());
it('should throw an exception when severity level is greater than 100', function (): void {
new Severity(1, 'name', 200, Severity::HOST_SEVERITY_TYPE_ID, $this->icon);
})->throws(\Assert\InvalidArgumentException::class, AssertionException::max(200, 100, 'Severity::level')->getMessage());
it('should throw an exception when severity type is not handled', function (): void {
new Severity(1, 'name', 60, 2, $this->icon);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::inArray(
2,
[Severity::HOST_SEVERITY_TYPE_ID, Severity::SERVICE_SEVERITY_TYPE_ID],
'Severity::type'
)->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/HostGroup/Application/UseCase/GetHostGroup/GetHostGroupTest.php | centreon/tests/php/Core/HostGroup/Application/UseCase/GetHostGroup/GetHostGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostGroup\Application\UseCase\GetHostGroup;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Contact\Application\Repository\ReadContactGroupRepositoryInterface;
use Core\Contact\Domain\AdminResolver;
use Core\Domain\Common\GeoCoords;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\HostGroup\Application\Exceptions\HostGroupException;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\UseCase\GetHostGroup\GetHostGroup;
use Core\HostGroup\Application\UseCase\GetHostGroup\GetHostGroupResponse;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\Media\Application\Repository\ReadMediaRepositoryInterface;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\TinyRule;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new GetHostGroup(
$this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
$this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readResourceAccessRepository = $this->createMock(ReadResourceAccessRepositoryInterface::class),
$this->readMediaRepository = $this->createMock(ReadMediaRepositoryInterface::class),
$this->readContactGroupRepository = $this->createMock(ReadContactGroupRepositoryInterface::class),
false,
$this->user = $this->createMock(ContactInterface::class),
$this->adminResolver = $this->createMock(AdminResolver::class),
);
$this->useCaseSaas = new GetHostGroup(
$this->readHostGroupRepository,
$this->readHostRepository,
$this->readAccessGroupRepository,
$this->readResourceAccessRepository,
$this->readMediaRepository,
$this->readContactGroupRepository,
true,
$this->user,
$this->adminResolver
);
$this->hostGroup = new HostGroup(
id: 1,
name: 'hg-name',
alias: 'hg-alias',
geoCoords: GeoCoords::fromString('-2,100'),
);
$this->host = new SimpleEntity(
id: 1,
name: new TrimmedString('host-name'),
objectName: 'Host',
);
$this->ruleA = new TinyRule(
id: 1,
name: 'rule-A',
);
$this->ruleB = new TinyRule(
id: 2,
name: 'rule-B',
);
$this->ruleC = new TinyRule(
id: 3,
name: 'rule-C',
);
$this->ruleA_bis = new TinyRule(
id: 1,
name: 'rule-A',
);
});
it(
'should present an ErrorResponse when an exception is thrown',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn($this->hostGroup);
$this->readHostRepository
->expects($this->once())
->method('findByHostGroup')
->willThrowException(new \Exception());
$response = ($this->useCase)($this->hostGroup->getId());
expect($response)
->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())
->toBe(HostGroupException::errorWhileRetrieving()->getMessage());
}
);
it(
'should present a NotFoundResponse when no host group is found',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn(null);
$response = ($this->useCase)($this->hostGroup->getId());
expect($response)
->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should present a GetHostGroupResponse as admin (OnPrem)',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn($this->hostGroup);
$this->readHostRepository
->expects($this->once())
->method('findByHostGroup')
->willReturn([]);
$response = ($this->useCase)($this->hostGroup->getId());
expect($response)
->toBeInstanceOf(GetHostGroupResponse::class)
->and($response->hostgroup)
->toBe($this->hostGroup);
}
);
it(
'should present a GetHostGroupResponse as non-admin user (OnPrem)',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([]);
$this->readHostGroupRepository
->expects($this->once())
->method('findOneByAccessGroups')
->willReturn($this->hostGroup);
$this->readHostRepository
->expects($this->once())
->method('findByHostGroupAndAccessGroups')
->willReturn([$this->host]);
$response = ($this->useCase)($this->hostGroup->getId());
expect($response)
->toBeInstanceOf(GetHostGroupResponse::class)
->and($response->hostgroup)
->toBe($this->hostGroup)
->and($response->hosts)
->toBe([$this->host]);
}
);
it(
'should present a GetHostGroupResponse as non-admin user (Saas)',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->once())
->method('findByContact')
->willReturn([]);
$this->readHostGroupRepository
->expects($this->once())
->method('findOneByAccessGroups')
->willReturn($this->hostGroup);
$this->readHostRepository
->expects($this->once())
->method('findByHostGroupAndAccessGroups')
->willReturn([$this->host]);
$this->readResourceAccessRepository
->expects($this->once())
->method('findRuleByResourceIdAndContactId')
->willReturn([$this->ruleA, $this->ruleB]);
$this->readResourceAccessRepository
->expects($this->once())
->method('findRuleByResourceIdAndContactGroups')
->willReturn([$this->ruleA_bis, $this->ruleC]);
$response = ($this->useCaseSaas)($this->hostGroup->getId());
expect($response)
->toBeInstanceOf(GetHostGroupResponse::class)
->and($response->hostgroup)
->toBe($this->hostGroup)
->and($response->hosts)
->toBe([$this->host])
->and($response->rules)
->toBe([0 => $this->ruleA, 1 => $this->ruleB, 3 => $this->ruleC]);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostGroup/Application/UseCase/AddHostGroup/AddHostGroupTest.php | centreon/tests/php/Core/HostGroup/Application/UseCase/AddHostGroup/AddHostGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostGroup\Application\UseCase\AddHostGroup;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Domain\Common\GeoCoords;
use Core\Domain\Exception\InvalidGeoCoordException;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\HostGroup\Application\Exceptions\HostGroupException;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostGroup\Application\UseCase\AddHostGroup\AddHostGroup;
use Core\HostGroup\Application\UseCase\AddHostGroup\AddHostGroupRequest;
use Core\HostGroup\Application\UseCase\AddHostGroup\AddHostGroupResponse;
use Core\HostGroup\Application\UseCase\AddHostGroup\AddHostGroupValidator;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\HostGroup\Domain\Model\HostGroupRelation;
use Core\ResourceAccess\Application\Exception\RuleException;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilter;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterRelation;
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\Application\Repository\WriteAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new AddHostGroup(
$this->contact = $this->createMock(ContactInterface::class),
$this->validator = $this->createMock(AddHostGroupValidator::class),
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->isCloudPlatform = true,
$this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
$this->readResourceAccessRepository = $this->createMock(ReadResourceAccessRepositoryInterface::class),
$this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->writeHostGroupRepository = $this->createMock(WriteHostGroupRepositoryInterface::class),
$this->writeResourceAccessRepository = $this->createMock(WriteResourceAccessRepositoryInterface::class),
$this->writeAccessGroupRepository = $this->createMock(WriteAccessGroupRepositoryInterface::class),
);
$this->addHostGroupRequest = new AddHostGroupRequest();
$this->addHostGroupRequest->name = 'HG1';
$this->addHostGroupRequest->alias = 'HG_Alias';
$this->addHostGroupRequest->geoCoords = '-10,10';
$this->addHostGroupRequest->comment = 'A New Hostgroup';
$this->addHostGroupRequest->hosts = [1, 2];
$this->addHostGroupRequest->resourceAccessRules = [1, 2, 3];
$this->addHostGroupRequest->iconId = 1;
$this->datasetFilterValidator = $this->createMock(DatasetFilterValidator::class);
});
it(
'Should return an InvalidArgumentResponse When an hostgroup already exists with this name',
function (): void {
$this->validator
->expects($this->once())
->method('assertNameDoesNotAlreadyExists')
->willThrowException(HostGroupException::nameAlreadyExists($this->addHostGroupRequest->name));
$response = ($this->useCase)($this->addHostGroupRequest);
expect($response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(HostGroupException::nameAlreadyExists($this->addHostGroupRequest->name)->getMessage());
}
);
it(
"Should return an InvalidArgumentResponse When a given host doesn't exist",
function (): void {
$this->validator
->expects($this->once())
->method('assertHostsExist')
->willThrowException(HostException::idsDoNotExist('hosts', [2]));
$response = ($this->useCase)($this->addHostGroupRequest);
expect($response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(HostException::idsDoNotExist('hosts', [2])->getMessage());
}
);
it(
"Should return an InvalidArgumentResponse When a given Resource Access Rule doesn't exist",
function (): void {
$this->validator
->expects($this->once())
->method('assertResourceAccessRulesExist')
->willThrowException(RuleException::idsDoNotExist('rules', [2]));
$response = ($this->useCase)($this->addHostGroupRequest);
expect($response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(RuleException::idsDoNotExist('rules', [2])->getMessage());
}
);
it(
'should present an InvalidArgumentResponse when the "geoCoords" field value is not valid',
function (): void {
$this->addHostGroupRequest->geoCoords = 'this,is,wrong';
$response = ($this->useCase)($this->addHostGroupRequest);
expect($response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(InvalidGeoCoordException::invalidFormat()->getMessage());
}
);
it(
'should present an ErrorResponse when an error occured while creating the host group',
function (): void {
$this->writeHostGroupRepository
->expects($this->once())
->method('add')
->willThrowException(new \Exception());
$response = ($this->useCase)($this->addHostGroupRequest);
expect($response)
->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())
->toBe(HostGroupException::errorWhileAdding()->getMessage());
}
);
it(
'should present an AddHostGroupResponse When everything is good',
function (): void {
$this->writeHostGroupRepository
->expects($this->once())
->method('add')
->willReturn(7);
$this->writeHostGroupRepository
->expects($this->once())
->method('addHostLinks');
$this->readResourceAccessRepository
->expects($this->once())
->method('findLastLevelDatasetFilterByRuleIdsAndType')
->willReturn([
new DatasetFilterRelation(
datasetFilterId: 1,
datasetFilterType: 'hostgroup',
parentId: null,
resourceAccessGroupId: 1,
aclGroupId: 1,
resourceIds: [1, 2, 3]
),
new DatasetFilterRelation(
datasetFilterId: 2,
datasetFilterType: 'hostgroup',
parentId: null,
resourceAccessGroupId: 2,
aclGroupId: 2,
resourceIds: [4, 5, 6]
),
]);
$this->writeResourceAccessRepository
->expects($this->exactly(2))
->method('updateDatasetResources');
$hostGroup = new HostGroup(
id: 7,
name: $this->addHostGroupRequest->name,
alias: $this->addHostGroupRequest->alias,
iconId: null,
geoCoords: GeoCoords::fromString($this->addHostGroupRequest->geoCoords),
comment: $this->addHostGroupRequest->comment,
isActivated: true
);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn($hostGroup);
$this->readHostRepository
->expects($this->once())
->method('findByHostGroup')
->willReturn([
new SimpleEntity(1, new TrimmedString('host1'), 'Host'),
new SimpleEntity(2, new TrimmedString('host2'), 'Host'),
]);
$filterTypes = [];
foreach ([
HostFilterType::class,
HostGroupFilterType::class,
HostCategoryFilterType::class,
ServiceFilterType::class,
ServiceGroupFilterType::class,
ServiceCategoryFilterType::class,
MetaServiceFilterType::class,
] as $className) {
$filterTypes[] = new $className();
}
$validator = new DatasetFilterValidator(new \ArrayObject($filterTypes));
$this->readResourceAccessRepository
->expects($this->exactly(3))
->method('findById')
->willReturnOnConsecutiveCalls(
new Rule(
id: 1,
name: 'rule1',
applyToAllContacts: true,
datasets: [new DatasetFilter('hostgroup', [1, 2, 3, 7], $validator)]
),
new Rule(
id: 2,
name: 'rule2',
applyToAllContacts: true,
datasets: [new DatasetFilter('hostgroup', [1, 2, 3, 7], $validator)]
),
new Rule(
id: 3,
name: 'rule3',
applyToAllContacts: true,
datasets: [new DatasetFilter('hostgroup', [1, 2, 3, 7], $validator)]
),
);
$response = ($this->useCase)($this->addHostGroupRequest);
expect($response)
->toBeInstanceOf(AddHostGroupResponse::class)
->and($response->getData())
->toBeInstanceOf(HostGroupRelation::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/HostGroup/Application/UseCase/FindHostGroups/FindHostGroupsTest.php | centreon/tests/php/Core/HostGroup/Application/UseCase/FindHostGroups/FindHostGroupsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostGroup\Application\UseCase\FindHostGroups;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Domain\Common\GeoCoords;
use Core\HostGroup\Application\Exceptions\HostGroupException;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\UseCase\FindHostGroups\FindHostGroups;
use Core\HostGroup\Application\UseCase\FindHostGroups\FindHostGroupsResponse;
use Core\HostGroup\Application\UseCase\FindHostGroups\HostGroupResponse;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\HostGroup\Domain\Model\HostGroupRelationCount;
use Core\Media\Application\Repository\ReadMediaRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
beforeEach(function (): void {
$this->useCase = new FindHostGroups(
$this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readMediaRepository = $this->createMock(ReadMediaRepositoryInterface::class),
$this->createMock(RequestParametersInterface::class),
$this->contact = $this->createMock(ContactInterface::class),
$this->adminResolver = $this->createMock(AdminResolver::class),
);
$this->hostCounts = new HostGroupRelationCount(1, 2);
$this->hostGroup = new HostGroup(
id: 1,
name: 'hg-name',
alias: 'hg-alias',
geoCoords: $this->geoCoords = GeoCoords::fromString('-2,100'),
);
$this->hostGroupResponse = new HostGroupResponse(
$this->hostGroup,
$this->hostCounts,
);
});
it(
'should present an ErrorResponse when an exception is thrown',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findAll')
->willThrowException(new \Exception());
$response = ($this->useCase)();
expect($response)
->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())
->toBe(HostGroupException::errorWhileSearching()->getMessage());
}
);
it(
'should present a FindHostGroupsResponse as admin',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findAll')
->willReturn(new \ArrayIterator([$this->hostGroup]));
$this->readHostGroupRepository
->expects($this->once())
->method('findHostsCountByIds')
->willReturn([$this->hostGroup->getId() => $this->hostCounts]);
$response = ($this->useCase)();
expect($response)
->toBeInstanceOf(FindHostGroupsResponse::class)
->and($response->hostgroups[0]->hostgroup)
->toBe($this->hostGroup)
->and($response->hostgroups[0]->hostsCount)
->toBe($this->hostCounts);
}
);
it(
'should present a FindHostGroupsResponse as non-admin',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->any())
->method('findByContact')
->willReturn([new AccessGroup(id: 1, name: 'testName', alias: 'testAlias')]);
$this->readHostGroupRepository
->expects($this->once())
->method('hasAccessToAllHostGroups')
->willReturn(false);
$this->readHostGroupRepository
->expects($this->once())
->method('findAllByAccessGroupIds')
->willReturn(new \ArrayIterator([$this->hostGroup]));
$this->readHostGroupRepository
->expects($this->once())
->method('findHostsCountByAccessGroupsIds')
->willReturn([$this->hostGroup->getId() => $this->hostCounts]);
$response = ($this->useCase)();
expect($response)
->toBeInstanceOf(FindHostGroupsResponse::class)
->and($response->hostgroups[0]->hostgroup)
->toBe($this->hostGroup)
->and($response->hostgroups[0]->hostsCount)
->toBe($this->hostCounts);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroupsTest.php | centreon/tests/php/Core/HostGroup/Application/UseCase/DuplicateHostGroups/DuplicateHostGroupsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
namespace Tests\Core\HostGroup\Application\UseCase\DuplicateHostGroups;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Domain\ResponseCodeEnum;
use Core\Contact\Domain\AdminResolver;
use Core\HostGroup\Application\Exceptions\HostGroupException;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostGroup\Application\UseCase\DuplicateHostGroups\DuplicateHostGroups;
use Core\HostGroup\Application\UseCase\DuplicateHostGroups\DuplicateHostGroupsRequest;
use Core\HostGroup\Application\UseCase\DuplicateHostGroups\DuplicateHostGroupsResponse;
use Core\HostGroup\Domain\Model\HostGroupNamesById;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\WriteAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
beforeEach(function (): void {
$this->useCase = new DuplicateHostGroups(
$this->contact = $this->createMock(ContactInterface::class),
$this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
$this->writeHostGroupRepository = $this->createMock(WriteHostGroupRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->writeAccessGroupRepository = $this->createMock(WriteAccessGroupRepositoryInterface::class),
$this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
$this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class),
$this->adminResolver = $this->createMock(AdminResolver::class)
);
$this->accessGroups = [$this->createMock(AccessGroup::class)];
$this->request = new DuplicateHostGroupsRequest([1, 2], 1);
$this->hostGroupNames = $this->createMock(HostGroupNamesById::class);
$this->hostGroupNames->method('getName')->willReturn('test_hg');
});
it('should handle host group not found', function (): void {
$this->adminResolver
->expects($this->exactly(1))
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('existsOne')
->willReturn(false);
$response = ($this->useCase)($this->request);
expect($response)->toBeInstanceOf(DuplicateHostGroupsResponse::class)
->and($response->getData()[0]->status)->toBe(ResponseCodeEnum::NotFound)
->and($response->getData()[0]->message)->toBe((new NotFoundResponse('Host Group'))->getMessage());
});
it('should handle exception during duplication', function (): void {
$this->adminResolver
->expects($this->exactly(1))
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('existsOne')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('findNames')
->willReturn($this->hostGroupNames);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('nameAlreadyExists')
->willReturn(false);
$this->writeHostGroupRepository
->expects($this->exactly(2))
->method('duplicate')
->willThrowException(new \Exception('Database error'));
$response = ($this->useCase)($this->request);
expect($response)->toBeInstanceOf(DuplicateHostGroupsResponse::class)
->and($response->getData()[0]->status)->toBe(ResponseCodeEnum::Error)
->and($response->getData()[0]->message)->toBe(HostGroupException::errorWhileDuplicating()->getMessage());
});
it('should successfully duplicate host group as admin', function (): void {
$this->adminResolver
->expects($this->atLeastOnce())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('existsOne')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('findNames')
->willReturn($this->hostGroupNames);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('nameAlreadyExists')
->willReturn(false);
$this->writeHostGroupRepository
->expects($this->exactly(2))
->method('duplicate')
->willReturn(100);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('findLinkedHosts')
->willReturn([1, 2]);
$this->readMonitoringServerRepository
->expects($this->exactly(2))
->method('findByHostsIds')
->willReturn([10]);
$this->writeMonitoringServerRepository
->expects($this->exactly(2))
->method('notifyConfigurationChanges')
->with([10]);
$this->writeAccessGroupRepository
->expects($this->exactly(2))
->method('updateAclResourcesFlag');
$this->writeAccessGroupRepository
->expects($this->never())
->method('addLinksBetweenHostGroupAndAccessGroups');
$response = ($this->useCase)($this->request);
expect($response)->toBeInstanceOf(DuplicateHostGroupsResponse::class)
->and($response->getData()[0]->status)->toBe(ResponseCodeEnum::OK);
});
it('should successfully duplicate host group as non-admin', function (): void {
$this->adminResolver
->expects($this->atLeastOnce())
->method('isAdmin')
->willReturn(false);
$this->readAccessGroupRepository
->expects($this->atLeastOnce())
->method('findByContact')
->willReturn($this->accessGroups);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('existsOneByAccessGroups')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('findNames')
->willReturn($this->hostGroupNames);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('nameAlreadyExistsByAccessGroups')
->willReturn(false);
$this->writeHostGroupRepository
->expects($this->exactly(2))
->method('duplicate')
->willReturn(100);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('findLinkedHosts')
->willReturn([1, 2]);
// Non-admin users should call duplicateContactAclResources
$this->writeAccessGroupRepository
->expects($this->exactly(2))
->method('addLinksBetweenHostGroupAndAccessGroups')
->with(100, $this->accessGroups);
$this->readMonitoringServerRepository
->expects($this->exactly(2))
->method('findByHostsIds')
->willReturn([10]);
$this->writeMonitoringServerRepository
->expects($this->exactly(2))
->method('notifyConfigurationChanges');
$this->writeAccessGroupRepository
->expects($this->exactly(2))
->method('updateAclGroupsFlag')
->with($this->accessGroups);
$this->readAccessGroupRepository
->expects($this->exactly(2))
->method('findAclResourcesByHostGroupId')
->willReturn([]);
$response = ($this->useCase)($this->request);
expect($response)->toBeInstanceOf(DuplicateHostGroupsResponse::class)
->and($response->getData()[0]->status)->toBe(ResponseCodeEnum::OK);
});
it('should duplicate multiple host groups', function (): void {
$this->request = new DuplicateHostGroupsRequest([62, 63], 1);
$this->adminResolver
->expects($this->atLeastOnce())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('existsOne')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('findNames')
->willReturn($this->hostGroupNames);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('nameAlreadyExists')
->willReturn(false);
$this->writeHostGroupRepository
->expects($this->exactly(2))
->method('duplicate')
->willReturnOnConsecutiveCalls(100, 101);
$response = ($this->useCase)($this->request);
expect($response)->toBeInstanceOf(DuplicateHostGroupsResponse::class)
->and($response->getData())->toHaveCount(2)
->and($response->getData()[0]->status)->toBe(ResponseCodeEnum::OK)
->and($response->getData()[1]->status)->toBe(ResponseCodeEnum::OK);
});
it('should create multiple duplicates when requested', function (): void {
$this->request = new DuplicateHostGroupsRequest([62], 2);
$this->adminResolver
->expects($this->atLeastOnce())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findNames')
->willReturn($this->hostGroupNames);
$this->readHostGroupRepository
->expects($this->exactly(2))
->method('nameAlreadyExists')
->willReturn(false);
$this->writeHostGroupRepository
->expects($this->exactly(2))
->method('duplicate')
->with(62, $this->anything())
->willReturnOnConsecutiveCalls(100, 101);
$response = ($this->useCase)($this->request);
expect($response)->toBeInstanceOf(DuplicateHostGroupsResponse::class)
->and($response->getData())->toHaveCount(1)
->and($response->getData()[0]->status)->toBe(ResponseCodeEnum::OK);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostGroup/Application/UseCase/DeleteHostGroup/DeleteHostGroupTest.php | centreon/tests/php/Core/HostGroup/Application/UseCase/DeleteHostGroup/DeleteHostGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostGroup\Application\UseCase\DeleteHostGroup;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Contact\Domain\AdminResolver;
use Core\Domain\Common\GeoCoords;
use Core\HostGroup\Application\Exceptions\HostGroupException;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostGroup\Application\UseCase\DeleteHostGroup\DeleteHostGroup;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class);
$this->writeHostGroupRepository = $this->createMock(WriteHostGroupRepositoryInterface::class);
$this->contact = $this->createMock(ContactInterface::class);
$this->adminResolver = $this->createMock(AdminResolver::class);
$this->presenter = new DefaultPresenter($this->createMock(PresenterFormatterInterface::class));
$this->useCase = new DeleteHostGroup(
$this->readHostGroupRepository,
$this->writeHostGroupRepository,
$this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->contact,
$this->adminResolver
);
$this->testedHostGroup = new HostGroup(
id: $this->hostgroupId = 1,
name: 'hg-name',
alias: 'hg-alias',
iconId: null,
geoCoords: GeoCoords::fromString('-2,100'),
comment: '',
isActivated: true
);
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('existsOne')
->willThrowException(new \Exception());
($this->useCase)($this->hostgroupId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostGroupException::errorWhileDeleting()->getMessage());
});
it('should present a ForbiddenResponse when the user does not have the correct role', function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ_WRITE, false],
]
);
($this->useCase)($this->hostgroupId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()?->getMessage())
->toBe(HostGroupException::accessNotAllowedForWriting()->getMessage());
});
it('should present a NoContentResponse as admin', function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('existsOne')
->willReturn(true);
($this->useCase)($this->hostgroupId, $this->presenter);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NoContentResponse::class);
});
it('should present a ForbiddenResponse as allowed READ user', function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ, true],
[Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ_WRITE, false],
]
);
$this->readHostGroupRepository
->expects($this->never())
->method('findOneByAccessGroups');
($this->useCase)($this->hostgroupId, $this->presenter);
expect($this->presenter->getResponseStatus())->toBeInstanceOf(ForbiddenResponse::class);
});
it('should present a NoContentResponse as allowed READ_WRITE user', function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(false);
$this->contact
->expects($this->atMost(2))
->method('hasTopologyRole')
->willReturnMap(
[
[Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ, false],
[Contact::ROLE_CONFIGURATION_HOSTS_HOST_GROUPS_READ_WRITE, true],
]
);
$this->readHostGroupRepository
->expects($this->once())
->method('existsOneByAccessGroups')
->willReturn(true);
($this->useCase)($this->hostgroupId, $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/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroupsTest.php | centreon/tests/php/Core/HostGroup/Application/UseCase/EnableDisableHostGroups/EnableDisableHostGroupsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Contact\Domain\AdminResolver;
use Core\HostGroup\Application\Exceptions\HostGroupException;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostGroup\Application\UseCase\EnableDisableHostGroups\EnableDisableHostGroups;
use Core\HostGroup\Application\UseCase\EnableDisableHostGroups\EnableDisableHostGroupsRequest;
use Core\HostGroup\Application\UseCase\EnableDisableHostGroups\EnableDisableHostGroupsResponse;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new EnableDisableHostGroups(
$this->contact = $this->createMock(ContactInterface::class),
$this->storageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
$this->writeRepository = $this->createMock(WriteHostGroupRepositoryInterface::class),
$this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
$this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class),
$this->adminResolver = $this->createMock(AdminResolver::class),
);
$this->request = new EnableDisableHostGroupsRequest([1, 2, 3], true);
});
it('should check that HostGroups exists as admin', function (): void {
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readRepository
->expects($this->exactly(3))
->method('existsOne');
($this->useCase)($this->request);
});
it('should check that HostGroups exists as user', function (): void {
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->readRepository
->expects($this->exactly(3))
->method('existsOneByAccessGroups');
($this->useCase)($this->request);
});
it('should return a EnableDisableHostGroupsResponse', function (): void {
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readRepository
->expects($this->exactly(3))
->method('existsOne')
->willReturnOnConsecutiveCalls(true, false, true);
$ex = new Exception('Error while enabling a HostGroup');
$this->writeRepository
->expects($this->exactly(2))
->method('enableDisableHostGroup')
->will($this->onConsecutiveCalls(null, $this->throwException($ex)));
$response = ($this->useCase)($this->request);
expect($response)->toBeInstanceOf(EnableDisableHostGroupsResponse::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('Host Group'))->getMessage())
->and($response->getData()[2]->id)->toBe(3)
->and($response->getData()[2]->status)->toBe(ResponseCodeEnum::Error)
->and($response->getData()[2]->message)->toBe(HostGroupException::errorWhileEnablingDisabling()->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/HostGroup/Application/UseCase/UpdateHostGroup/UpdateHostGroupTest.php | centreon/tests/php/Core/HostGroup/Application/UseCase/UpdateHostGroup/UpdateHostGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostGroup\Application\UseCase\UpdateHostGroup;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Common\Domain\SimpleEntity;
use Core\Common\Domain\TrimmedString;
use Core\Contact\Domain\AdminResolver;
use Core\Domain\Common\GeoCoords;
use Core\Host\Application\Exception\HostException;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\HostGroup\Application\Exceptions\HostGroupException;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostGroup\Application\UseCase\UpdateHostGroup\UpdateHostGroup;
use Core\HostGroup\Application\UseCase\UpdateHostGroup\UpdateHostGroupRequest;
use Core\HostGroup\Application\UseCase\UpdateHostGroup\UpdateHostGroupValidator;
use Core\HostGroup\Domain\Model\HostGroup;
use Core\MonitoringServer\Application\Repository\ReadMonitoringServerRepositoryInterface;
use Core\MonitoringServer\Application\Repository\WriteMonitoringServerRepositoryInterface;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface;
use Core\ResourceAccess\Domain\Model\DatasetFilter\DatasetFilterRelation;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\WriteAccessGroupRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new UpdateHostGroup(
$this->user = $this->createMock(ContactInterface::class),
$this->validator = $this->createMock(UpdateHostGroupValidator::class),
$this->storageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->isCloudPlatform = true,
$this->readHostGroupRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
$this->readHostRepository = $this->createMock(ReadHostRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readResourceAccessRepository = $this->createMock(ReadResourceAccessRepositoryInterface::class),
$this->readMonitoringServerRepository = $this->createMock(ReadMonitoringServerRepositoryInterface::class),
$this->writeHostGroupRepository = $this->createMock(WriteHostGroupRepositoryInterface::class),
$this->writeResourceAccessRepository = $this->createMock(WriteResourceAccessRepositoryInterface::class),
$this->writeMonitoringServerRepository = $this->createMock(WriteMonitoringServerRepositoryInterface::class),
$this->writeAccessGroupRepository = $this->createMock(WriteAccessGroupRepositoryInterface::class),
$this->adminResolver = $this->createMock(AdminResolver::class),
);
$this->updateHostGroupRequest = new UpdateHostGroupRequest(
id: 1,
name: 'name update',
alias: 'alias update',
geoCoords: '-10,10',
comment: 'comment',
hosts: [1, 2],
resourceAccessRules: [1, 2]
);
});
it(
'should present a NotFoundResponse when the hostgroup does not exists',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn(null);
$response = ($this->useCase)($this->updateHostGroupRequest);
expect($response)
->toBeInstanceOf(NotFoundResponse::class);
}
);
it(
'should return an InvalidArgumentResponse When an hostgroup already exists with this name',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn(new HostGroup(
id: 1,
name: 'name',
alias: 'alias',
geoCoords: GeoCoords::fromString('-10,10'),
comment: 'comment',
));
$this->validator
->expects($this->once())
->method('assertNameDoesNotAlreadyExists')
->willThrowException(HostGroupException::nameAlreadyExists($this->updateHostGroupRequest->name));
$response = ($this->useCase)($this->updateHostGroupRequest);
expect($response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(HostGroupException::nameAlreadyExists($this->updateHostGroupRequest->name)->getMessage());
}
);
it(
"should return an InvalidArgumentResponse When a given host doesn't exist",
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn(new HostGroup(
id: 1,
name: 'name',
alias: 'alias',
geoCoords: GeoCoords::fromString('-10,10'),
comment: 'comment',
));
$this->validator
->expects($this->once())
->method('assertHostsExist')
->willThrowException(HostException::idsDoNotExist('hosts', [2]));
$response = ($this->useCase)($this->updateHostGroupRequest);
expect($response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(HostException::idsDoNotExist('hosts', [2])->getMessage());
}
);
it(
'should return an InvalidArgumentResponse When a given resource access rule does not exist',
function (): void {
$this->adminResolver
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn(new HostGroup(
id: 1,
name: 'name',
alias: 'alias',
geoCoords: GeoCoords::fromString('-10,10'),
comment: 'comment',
));
$this->validator
->expects($this->once())
->method('assertResourceAccessRulesExist')
->willThrowException(HostException::idsDoNotExist('resourceAccessRules', [2]));
$response = ($this->useCase)($this->updateHostGroupRequest);
expect($response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($response->getMessage())
->toBe(HostException::idsDoNotExist('resourceAccessRules', [2])->getMessage());
}
);
it(
'should update the host group configuration',
function (): void {
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn(new HostGroup(
id: 1,
name: 'name',
alias: 'alias',
geoCoords: GeoCoords::fromString('-10,10'),
comment: 'comment',
));
$this->writeHostGroupRepository
->expects($this->once())
->method('update')
->with(new HostGroup(
id: 1,
name: 'name update',
alias: 'alias update',
geoCoords: GeoCoords::fromString('-10,10'),
comment: 'comment',
));
$response = ($this->useCase)($this->updateHostGroupRequest);
expect($response)
->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should update the hosts of the host group',
function (): void {
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn(new HostGroup(
id: 1,
name: 'name',
alias: 'alias',
geoCoords: GeoCoords::fromString('-10,10'),
comment: 'comment',
));
$this->readHostRepository
->expects($this->once())
->method('findByHostGroup')
->willReturn([
new SimpleEntity(
id: 1,
name: new TrimmedString('host'),
objectName: 'Host',
),
]);
$this->writeHostGroupRepository
->expects($this->once())
->method('deleteHostLinks')
->with($this->updateHostGroupRequest->id, [1]);
$this->writeHostGroupRepository
->expects($this->once())
->method('addHostLinks')
->with($this->updateHostGroupRequest->id, [1, 2]);
$response = ($this->useCase)($this->updateHostGroupRequest);
expect($response)
->toBeInstanceOf(NoContentResponse::class);
}
);
it(
'should update the resource access rules of the host group',
function (): void {
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readHostGroupRepository
->expects($this->once())
->method('findOne')
->willReturn(new HostGroup(
id: 1,
name: 'name',
alias: 'alias',
geoCoords: GeoCoords::fromString('-10,10'),
comment: 'comment',
));
$this->readResourceAccessRepository
->expects($this->once())
->method('existByTypeAndResourceId')
->willReturn([
1, 2, 3,
]);
$this->readResourceAccessRepository
->expects($this->exactly(2))
->method('findLastLevelDatasetFilterByRuleIdsAndType')
->willReturnOnConsecutiveCalls(
[
new DatasetFilterRelation(
datasetFilterId: 1,
datasetFilterType: 'hostgroup',
parentId: null,
resourceAccessGroupId: 1,
aclGroupId: 1,
resourceIds: [1, 2, 3]
),
new DatasetFilterRelation(
datasetFilterId: 2,
datasetFilterType: 'hostgroup',
parentId: null,
resourceAccessGroupId: 2,
aclGroupId: 2,
resourceIds: [1, 5, 6]
),
],
[]
);
$this->writeResourceAccessRepository
->expects($this->exactly(2))
->method('updateDatasetResources');
$response = ($this->useCase)($this->updateHostGroupRequest);
dump($response);
expect($response)
->toBeInstanceOf(NoContentResponse::class);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroupsTest.php | centreon/tests/php/Core/HostGroup/Application/UseCase/DeleteHostGroups/DeleteHostGroupsTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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\Contact\Domain\AdminResolver;
use Core\HostGroup\Application\Exceptions\HostGroupException;
use Core\HostGroup\Application\Repository\ReadHostGroupRepositoryInterface;
use Core\HostGroup\Application\Repository\WriteHostGroupRepositoryInterface;
use Core\HostGroup\Application\UseCase\DeleteHostGroups\DeleteHostGroups;
use Core\HostGroup\Application\UseCase\DeleteHostGroups\DeleteHostGroupsRequest;
use Core\HostGroup\Application\UseCase\DeleteHostGroups\DeleteHostGroupsResponse;
use Core\Notification\Application\Repository\ReadNotificationRepositoryInterface;
use Core\Notification\Application\Repository\WriteNotificationRepositoryInterface;
use Core\ResourceAccess\Application\Repository\ReadResourceAccessRepositoryInterface;
use Core\ResourceAccess\Application\Repository\WriteResourceAccessRepositoryInterface;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Service\Application\Repository\ReadServiceRepositoryInterface;
use Core\Service\Application\Repository\WriteServiceRepositoryInterface;
beforeEach(function (): void {
$this->useCase = new DeleteHostGroups(
$this->contact = $this->createMock(ContactInterface::class),
$this->writeRepository = $this->createMock(WriteHostGroupRepositoryInterface::class),
$this->readRepository = $this->createMock(ReadHostGroupRepositoryInterface::class),
$this->readAccessGroupRepository = $this->createMock(ReadAccessGroupRepositoryInterface::class),
$this->readNotificationRepository = $this->createMock(ReadNotificationRepositoryInterface::class),
$this->writeNotificationRepository = $this->createMock(WriteNotificationRepositoryInterface::class),
$this->readServiceRepository = $this->createMock(ReadServiceRepositoryInterface::class),
$this->writeServiceRepository = $this->createMock(WriteServiceRepositoryInterface::class),
$this->readResourceAccessRepository = $this->createMock(ReadResourceAccessRepositoryInterface::class),
$this->writeResourceAccessRepository = $this->createMock(WriteResourceAccessRepositoryInterface::class),
$this->storageEngine = $this->createMock(DataStorageEngineInterface::class),
$this->isCloudPlatform = false,
$this->adminResolver = $this->createMock(AdminResolver::class)
);
$this->request = new DeleteHostGroupsRequest([1, 2, 3]);
});
it('should check that HostGroups exists as admin', function (): void {
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readRepository
->expects($this->exactly(3))
->method('existsOne');
($this->useCase)($this->request);
});
it('should check that HostGroups exists as user', function (): void {
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->willReturn(false);
$this->readRepository
->expects($this->exactly(3))
->method('existsOneByAccessGroups');
($this->useCase)($this->request);
});
it('should return a DeleteHostGroupsResponse', function (): void {
$this->adminResolver
->expects($this->any())
->method('isAdmin')
->willReturn(true);
$this->readRepository
->expects($this->exactly(3))
->method('existsOne')
->willReturnOnConsecutiveCalls(true, false, true);
$ex = new Exception('Error while deleting a HostGroup configuration');
$this->writeRepository
->expects($this->exactly(2))
->method('deleteHostGroup')
->will($this->onConsecutiveCalls(null, $this->throwException($ex)));
$response = ($this->useCase)($this->request);
expect($response)->toBeInstanceOf(DeleteHostGroupsResponse::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('Host Group'))->getMessage())
->and($response->getData()[2]->id)->toBe(3)
->and($response->getData()[2]->status)->toBe(ResponseCodeEnum::Error)
->and($response->getData()[2]->message)->toBe(HostGroupException::errorWhileDeleting()->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/HostGroup/Domain/Model/NewHostGroupTest.php | centreon/tests/php/Core/HostGroup/Domain/Model/NewHostGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostGroup\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\Common\GeoCoords;
use Core\HostGroup\Domain\Model\NewHostGroup;
beforeEach(function (): void {
$this->createHostGroup = static fn (array $fields = []): NewHostGroup => new NewHostGroup(
...[
'name' => 'host-name',
'alias' => 'host-alias',
'iconId' => 2,
'geoCoords' => GeoCoords::fromString('-90.0,180.0'),
'comment' => '',
'isActivated' => true,
...$fields,
]
);
});
it('should return properly set host group instance', function (): void {
$hostGroup = ($this->createHostGroup)();
expect($hostGroup->getIconId())->toBe(2)
->and((string) $hostGroup->getGeoCoords())->toBe('-90.0,180.0')
->and($hostGroup->getName())->toBe('host-name')
->and($hostGroup->getAlias())->toBe('host-alias');
});
// mandatory fields
it(
'should throw an exception when host group name is an empty string',
fn () => ($this->createHostGroup)(['name' => ''])
)->throws(
InvalidArgumentException::class,
AssertionException::minLength('', 0, NewHostGroup::MIN_NAME_LENGTH, 'NewHostGroup::name')->getMessage()
);
// string field trimmed
foreach (
[
'name',
'alias',
'comment',
] as $field
) {
it(
"should return trim the field {$field} after construct",
function () use ($field): void {
$hostGroup = ($this->createHostGroup)([$field => ' abcd ']);
$valueFromGetter = $hostGroup->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => NewHostGroup::MAX_NAME_LENGTH,
'alias' => NewHostGroup::MAX_ALIAS_LENGTH,
// We have skipped the comment max size test because it costs ~1 second
// to run it, so more than 10 times the time of all the other tests.
// At this moment, I didn't find any explanation, and considering
// this is a non-critical field ... I prefer skipping it.
// 'comment' => NewHostGroup::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when host group {$field} is too long",
fn () => ($this->createHostGroup)([$field => $tooLong])
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "NewHostGroup::{$field}")->getMessage()
);
}
// FK fields : int = 0 forbidden
foreach (['iconId'] as $field) {
it(
"should throw an exception when host group {$field} is an empty integer",
fn () => ($this->createHostGroup)([$field => 0])
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(0, "NewHostGroup::{$field}")->getMessage()
);
}
// FK fields : int < 0 forbidden
foreach (['iconId'] as $field) {
it(
"should throw an exception when host group {$field} is a negative integer",
fn () => ($this->createHostGroup)([$field => -1])
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(-1, "NewHostGroup::{$field}")->getMessage()
);
}
// geoCoords field
it(
'should return a valid host group if the "geoCoords" field is valid',
function (): void {
$hostGroup = ($this->createHostGroup)();
expect($hostGroup->getGeoCoords())->toBeInstanceOf(GeoCoords::class);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/HostGroup/Domain/Model/HostGroupTest.php | centreon/tests/php/Core/HostGroup/Domain/Model/HostGroupTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\HostGroup\Domain\Model;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Domain\Common\GeoCoords;
use Core\HostGroup\Domain\Model\HostGroup;
beforeEach(function (): void {
$this->createHostGroup = static fn (array $fields = []): HostGroup => new HostGroup(
...[
'id' => 1,
'name' => 'host-name',
'alias' => 'host-alias',
'iconId' => 2,
'geoCoords' => GeoCoords::fromString('-90.0,180.0'),
'comment' => '',
'isActivated' => true,
...$fields,
]
);
});
it('should return properly set host group instance', function (): void {
$hostGroup = ($this->createHostGroup)();
expect($hostGroup->getId())->toBe(1)
->and($hostGroup->getIconId())->toBe(2)
->and((string) $hostGroup->getGeoCoords())->toBe('-90.0,180.0')
->and($hostGroup->getName())->toBe('host-name')
->and($hostGroup->getAlias())->toBe('host-alias');
});
// mandatory fields
it(
'should throw an exception when host group name is an empty string',
fn () => ($this->createHostGroup)(['name' => ''])
)->throws(
InvalidArgumentException::class,
AssertionException::minLength('', 0, HostGroup::MIN_NAME_LENGTH, 'HostGroup::name')->getMessage()
);
// string field trimmed
foreach (
[
'name',
'alias',
'comment',
] as $field
) {
it(
"should return trim the field {$field} after construct",
function () use ($field): void {
$hostGroup = ($this->createHostGroup)([$field => ' abcd ']);
$valueFromGetter = $hostGroup->{'get' . $field}();
expect($valueFromGetter)->toBe('abcd');
}
);
}
// too long fields
foreach (
[
'name' => HostGroup::MAX_NAME_LENGTH,
'alias' => HostGroup::MAX_ALIAS_LENGTH,
// We have skipped the comment max size test because it costs ~1 second
// to run it, so more than 10 times the time of all the other tests.
// At this moment, I didn't find any explanation, and considering
// this is a non-critical field ... I prefer skipping it.
// 'comment' => HostGroup::MAX_COMMENT_LENGTH,
] as $field => $length
) {
$tooLong = str_repeat('a', $length + 1);
it(
"should throw an exception when host group {$field} is too long",
fn () => ($this->createHostGroup)([$field => $tooLong])
)->throws(
InvalidArgumentException::class,
AssertionException::maxLength($tooLong, $length + 1, $length, "HostGroup::{$field}")->getMessage()
);
}
foreach (['iconId'] as $field) {
it(
"should throw an exception when host group {$field} is an empty integer",
fn () => ($this->createHostGroup)([$field => 0])
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(0, "HostGroup::{$field}")->getMessage()
);
}
foreach (['iconId'] as $field) {
it(
"should throw an exception when host group {$field} is a negative integer",
fn () => ($this->createHostGroup)([$field => -1])
)->throws(
InvalidArgumentException::class,
AssertionException::positiveInt(-1, "HostGroup::{$field}")->getMessage()
);
}
// geoCoords field
it(
'should return a valid host group if the "geoCoords" field is valid',
function (): void {
$hostGroup = ($this->createHostGroup)();
expect($hostGroup->getGeoCoords())->toBeInstanceOf(GeoCoords::class);
}
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Media/Application/UseCase/FindImageFolders/FindImageFoldersTest.php | centreon/tests/php/Core/Media/Application/UseCase/FindImageFolders/FindImageFoldersTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Application\UseCase\FindImageFolders;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Media\Application\Repository\ReadImageFolderRepositoryInterface;
use Core\Media\Application\UseCase\FindImageFolders\FindImageFolders;
use Core\Media\Domain\Model\ImageFolder\ImageFolder;
use Core\Media\Domain\Model\ImageFolder\ImageFolderDescription;
use Core\Media\Domain\Model\ImageFolder\ImageFolderId;
use Core\Media\Domain\Model\ImageFolder\ImageFolderName;
use Core\Security\AccessGroup\Application\Repository\ReadAccessGroupRepositoryInterface;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
final class FindImageFoldersTest extends TestCase
{
private ContactInterface&MockObject $user;
private RequestParametersInterface&MockObject $requestParameters;
private ReadAccessGroupRepositoryInterface&MockObject $accessGroupReader;
private ReadImageFolderRepositoryInterface&MockObject $imageFolderReader;
protected function setUp(): void
{
$this->user = $this->createMock(ContactInterface::class);
$this->requestParameters = $this->createMock(RequestParametersInterface::class);
$this->accessGroupReader = $this->createMock(ReadAccessGroupRepositoryInterface::class);
$this->imageFolderReader = $this->createMock(ReadImageFolderRepositoryInterface::class);
}
public function testInvokeAsAdminReturnsAllFolders(): void
{
$this->user->method('isAdmin')->willReturn(true);
$folders = [
$this->createImageFolder(1, 'Folder 1', 'alias1', 'desc1'),
$this->createImageFolder(2, 'Folder 2', null, null),
];
$this->imageFolderReader
->expects($this->once())
->method('findByRequestParameters')
->with($this->requestParameters)
->willReturn($folders);
$useCase = new FindImageFolders(
$this->user,
$this->requestParameters,
$this->accessGroupReader,
$this->imageFolderReader
);
$response = $useCase();
$resultFolders = $response->imageFolders;
$this->assertCount(2, $resultFolders);
$this->assertSame('Folder 1', $resultFolders[0]->name()->value);
$this->assertSame('alias1', $resultFolders[0]->alias()->value);
$this->assertSame('desc1', $resultFolders[0]->description()->value);
$this->assertNull($resultFolders[1]->alias()?->value);
}
public function testInvokeAsUserWithFullAccessReturnsAllFolders(): void
{
$this->user->method('isAdmin')->willReturn(false);
$accessGroups = [
new AccessGroup(1, 'group1', 'group1'),
];
$folders = [
$this->createImageFolder(3, 'User Folder'),
];
$this->accessGroupReader
->method('findByContact')
->with($this->user)
->willReturn($accessGroups);
$this->imageFolderReader
->method('hasAccessToAllImageFolders')
->with($accessGroups)
->willReturn(true);
$this->imageFolderReader
->method('findByRequestParameters')
->with($this->requestParameters)
->willReturn($folders);
$useCase = new FindImageFolders(
$this->user,
$this->requestParameters,
$this->accessGroupReader,
$this->imageFolderReader
);
$response = $useCase();
$resultFolders = $response->imageFolders;
$this->assertCount(1, $resultFolders);
$this->assertSame('User Folder', $resultFolders[0]->name()->value);
}
public function testInvokeAsUserWithNoFullAccessReturnsFilteredFolders(): void
{
$this->user->method('isAdmin')->willReturn(false);
$accessGroups = [
new AccessGroup(1, 'group1', 'group1'),
];
$folders = [
$this->createImageFolder(3, 'User Folder'),
];
$this->accessGroupReader
->method('findByContact')
->with($this->user)
->willReturn($accessGroups);
$this->imageFolderReader
->method('hasAccessToAllImageFolders')
->with($accessGroups)
->willReturn(false);
$this->imageFolderReader
->method('findByRequestParametersAndAccessGroups')
->with($this->requestParameters, $accessGroups)
->willReturn($folders);
$useCase = new FindImageFolders(
$this->user,
$this->requestParameters,
$this->accessGroupReader,
$this->imageFolderReader
);
$response = $useCase();
$resultFolders = $response->imageFolders;
$this->assertCount(1, $resultFolders);
$this->assertSame('User Folder', $resultFolders[0]->name()->value);
}
private function createImageFolder(int $id, string $name, ?string $alias = null, ?string $description = null): ImageFolder
{
$folder = new ImageFolder(
new ImageFolderId($id),
new ImageFolderName($name)
);
$folder->setAlias($alias ? new ImageFolderName($alias) : null);
$folder->setDescription($description ? new ImageFolderDescription($description) : null);
return $folder;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Media/Application/UseCase/AddMedia/AddMediaTest.php | centreon/tests/php/Core/Media/Application/UseCase/AddMedia/AddMediaTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Application\UseCase\AddMedia;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Media\Application\Exception\MediaException;
use Core\Media\Application\Repository\ReadMediaRepositoryInterface;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Media\Application\UseCase\AddMedia\AddMedia;
use Core\Media\Application\UseCase\AddMedia\AddMediaRequest;
use Core\Media\Application\UseCase\AddMedia\AddMediaResponse;
use enshrined\svgSanitize\Sanitizer;
use Tests\Core\Media\Infrastructure\API\AddMedia\AddMediaPresenterStub;
beforeEach(function (): void {
$this->writeMediaRepository = $this->createMock(WriteMediaRepositoryInterface::class);
$this->readMediaRepository = $this->createMock(ReadMediaRepositoryInterface::class);
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class);
$this->svgSanitizer = $this->createMock(Sanitizer::class);
$this->presenter = new AddMediaPresenterStub(
$this->createMock(PresenterFormatterInterface::class)
);
$this->useCase = new AddMedia(
$this->writeMediaRepository,
$this->readMediaRepository,
$this->dataStorageEngine,
$this->svgSanitizer,
);
$this->imagePath = realpath(__DIR__ . '/../../../Infrastructure/API/AddMedia/logo.jpg');
$this->mediaGenerator = new class ($this->imagePath) implements \Iterator {
private int $counter = 0;
public function __construct(readonly private string $imagePath)
{
}
public function current(): mixed
{
return file_get_contents($this->imagePath);
}
public function next(): void
{
$this->counter++;
}
public function key(): mixed
{
return 'logo.jpg';
}
public function valid(): bool
{
return $this->counter < 1;
}
public function rewind(): void
{
$this->counter = 0;
}
};
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->writeMediaRepository
->expects($this->once())
->method('add')
->willThrowException(new \Exception());
$request = new AddMediaRequest($this->mediaGenerator);
$request->directory = 'filepath';
($this->useCase)($request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(MediaException::errorWhileAddingMedia()->getMessage());
});
it('should present an InvalidArgumentResponse when a field assert of NewMedia fails', function (): void {
$request = new AddMediaRequest($this->mediaGenerator);
$request->directory = 'badfilepath^$';
($this->useCase)($request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(InvalidArgumentResponse::class)
->and($this->presenter->response->getMessage())
->toBe(AssertionException::matchRegex(
$request->directory,
'/^[a-zA-Z0-9_-]+$/',
'NewMedia::directory',
)->getMessage());
});
it('should present an AddMediaResponse with an empty response when the media already exists', function (): void {
$this->readMediaRepository
->expects($this->once())
->method('existsByPath')
->willReturn(true);
$request = new AddMediaRequest($this->mediaGenerator);
$request->directory = 'filepath';
($this->useCase)($request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(AddMediaResponse::class)
->and($this->presenter->response->mediasRecorded)
->toBeEmpty();
});
it('should present an AddMediaResponse when the media does not exist', function (): void {
$this->readMediaRepository
->expects($this->once())
->method('existsByPath')
->willReturn(false);
$this->writeMediaRepository
->expects($this->once())
->method('add')
->willReturn(1);
$request = new AddMediaRequest($this->mediaGenerator);
$request->directory = 'filepath';
($this->useCase)($request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(AddMediaResponse::class)
->and($this->presenter->response->mediasRecorded)
->toHaveCount(1)
->and($this->presenter->response->mediasRecorded[0]['id'])->toEqual(1)
->and($this->presenter->response->mediasRecorded[0]['filename'])->toEqual('logo.jpg')
->and($this->presenter->response->mediasRecorded[0]['directory'])->toEqual('filepath')
->and($this->presenter->response->mediasRecorded[0]['md5'])->toEqual(md5(file_get_contents($this->imagePath)));
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Media/Application/UseCase/UpdateMedia/UpdateMediaTest.php | centreon/tests/php/Core/Media/Application/UseCase/UpdateMedia/UpdateMediaTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Application\UseCase\UpdateMedia;
use Centreon\Domain\Repository\Interfaces\DataStorageEngineInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Media\Application\Exception\MediaException;
use Core\Media\Application\Repository\ReadMediaRepositoryInterface;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMedia;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMediaRequest;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMediaResponse;
use Core\Media\Domain\Model\Media;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Tests\Core\Media\Infrastructure\API\UpdateMedia\UpdateMediaPresenterStub;
beforeEach(function (): void {
$this->writeMediaRepository = $this->createMock(WriteMediaRepositoryInterface::class);
$this->readMediaRepository = $this->createMock(ReadMediaRepositoryInterface::class);
$this->dataStorageEngine = $this->createMock(DataStorageEngineInterface::class);
$this->presenter = new UpdateMediaPresenterStub(
$this->createMock(PresenterFormatterInterface::class)
);
$this->useCase = new UpdateMedia(
$this->writeMediaRepository,
$this->readMediaRepository,
$this->dataStorageEngine,
);
$this->imagePath = __DIR__ . '/../../../Infrastructure/API/UpdateMedia/logo.jpg';
$this->uploadedFile = new UploadedFile(
$this->imagePath,
'logo.jpg',
'image/jpg',
);
});
it('should present an NotFoundResponse when the media to update does not exist', function (): void {
$this->readMediaRepository
->expects($this->once())
->method('findById')
->willReturn(null);
$request = new UpdateMediaRequest(
$this->uploadedFile->getClientOriginalName(),
$this->uploadedFile->getContent()
);
($this->useCase)(1, $request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->response->getMessage())
->toBe('Media not found');
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->readMediaRepository
->expects($this->once())
->method('findById')
->willReturn(new Media(1, 'filename', 'directory', null, null));
$this->writeMediaRepository
->expects($this->once())
->method('update')
->willThrowException(new \Exception());
$request = new UpdateMediaRequest(
$this->uploadedFile->getClientOriginalName(),
$this->uploadedFile->getContent()
);
($this->useCase)(1, $request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(MediaException::errorWhileUpdatingMedia()->getMessage());
});
it('should present an UpdateMediaResponse when the media has been updated', function (): void {
$this->readMediaRepository
->expects($this->once())
->method('findById')
->willReturn(new Media(1, 'logo.jpg', 'directory', null, null));
$this->writeMediaRepository
->expects($this->once())
->method('update');
$request = new UpdateMediaRequest(
$this->uploadedFile->getClientOriginalName(),
$this->uploadedFile->getContent()
);
($this->useCase)(1, $request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(UpdateMediaResponse::class)
->and($this->presenter->response->updatedMedia)
->and($this->presenter->response->updatedMedia['id'])->toEqual(1)
->and($this->presenter->response->updatedMedia['filename'])->toEqual('logo.jpg')
->and($this->presenter->response->updatedMedia['directory'])->toEqual('directory')
->and($this->presenter->response->updatedMedia['md5'])->toEqual(md5(file_get_contents($this->imagePath)));
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Media/Application/UseCase/MigrateAllMedias/MigrateAllMediasTest.php | centreon/tests/php/Core/Media/Application/UseCase/MigrateAllMedias/MigrateAllMediasTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Application\UseCase\MigrateAllMedias;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Media\Application\Exception\MediaException;
use Core\Media\Application\Repository\ReadMediaRepositoryInterface;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrateAllMedias;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrateAllMediasRequest;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrationAllMediasResponse;
use Core\Media\Domain\Model\Media;
use Tests\Core\Media\Infrastructure\Command\MigrateAllMedias\MigrateAllMediasPresenterStub;
beforeEach(function (): void {
$this->readMediaRepository = $this->createMock(ReadMediaRepositoryInterface::class);
$this->writeMediaRepository = $this->createMock(WriteMediaRepositoryInterface::class);
$this->useCase = new MigrateAllMedias($this->readMediaRepository, $this->writeMediaRepository);
$this->presenter = new MigrateAllMediasPresenterStub();
$this->contact = $this->createMock(ContactInterface::class);
$this->request = new MigrateAllMediasRequest();
$this->request->contact = $this->contact;
});
it('should present an Exception if the user is not an administrator', function (): void {
$this->request->contact
->expects($this->once())
->method('isAdmin')
->willReturn(false);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->response->getMessage())
->toBe(MediaException::operationRequiresAdminUser()->getMessage());
});
it('should present a MigrateAllMediasResponse when the user is an admin', function (): void {
$this->request->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$mediaWithoutData = new Media(1, 'media1.png', 'img', null, null);
$mediaWithData = new Media(2, 'media2.png', 'img', null, 'fake data');
$medias = new \ArrayIterator([$mediaWithoutData, $mediaWithData]);
$this->readMediaRepository
->expects($this->once())
->method('findAll')
->willReturn($medias);
($this->useCase)($this->request, $this->presenter);
expect($this->presenter->response)->toBeInstanceOf(MigrationAllMediasResponse::class);
$check = [
$mediaWithoutData->getFilename() => 0,
$mediaWithData->getFilename() => 0,
];
foreach ($this->presenter->response->results as $responseMedia) {
if ($responseMedia->filename === $mediaWithoutData->getFilename()) {
$check[$mediaWithoutData->getFilename()]++;
expect($responseMedia->directory)
->tobe('img')
->and($responseMedia->reason)
->tobe('The file img/media1.png does not exist');
}
if ($responseMedia->filename === $mediaWithData->getFilename()) {
$check[$mediaWithData->getFilename()]++;
expect($responseMedia->directory)
->tobe('img')
->and($responseMedia->md5)
->tobe(md5($mediaWithData->getData() ?? ''));
}
}
expect($check[$mediaWithoutData->getFilename()])->toBe(1);
expect($check[$mediaWithData->getFilename()])->toBe(1);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Media/Domain/NewMediaTest.php | centreon/tests/php/Core/Media/Domain/NewMediaTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Domain;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Media\Domain\Model\NewMedia;
beforeEach(function (): void {
$this->createMedia = fn (array $arguments = []): NewMedia => new NewMedia(...[
'filename' => 'filename',
'directory' => 'directory',
'data' => 'data',
...$arguments,
]);
});
it('should throw an exception when the filename property is empty', function (): void {
($this->createMedia)(['filename' => '']);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewMedia::filename')->getMessage()
);
it('should throw an exception when the directory property is empty', function (): void {
($this->createMedia)(['directory' => '']);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('NewMedia::directory')->getMessage()
);
it('should replace space characters by \'_\' in the filename property', function (): void {
$newMedia = ($this->createMedia)(['filename' => ' new filename.jpg ']);
expect($newMedia->getFilename())->toBe('new_filename.jpg');
});
it('should remove the space characters in the path property', function (): void {
$newMedia = ($this->createMedia)(['directory' => ' new path ']);
expect($newMedia->getDirectory())->toBe('newpath');
});
it('should remove the space characters in the comment property', function (): void {
$newMedia = ($this->createMedia)([]);
$newMedia->setComment(' comments ');
expect($newMedia->getComment())->toBe('comments');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Media/Domain/MediaTest.php | centreon/tests/php/Core/Media/Domain/MediaTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Domain;
use Centreon\Domain\Common\Assertion\AssertionException;
use Core\Media\Domain\Model\Media;
beforeEach(function (): void {
$this->createMedia = fn (array $arguments = []): Media => new Media(...[
'id' => 1,
'filename' => 'filename',
'directory' => 'directory',
'comment' => null,
'data' => 'data',
...$arguments,
]);
});
it('should throw an exception when the ID property is lower than 1', function (): void {
($this->createMedia)(['id' => 0]);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::positiveInt(0, 'Media::id')->getMessage()
);
it('should throw an exception when the filename property is empty', function (): void {
($this->createMedia)(['filename' => '']);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Media::filename')->getMessage()
);
it('should throw an exception when the directory property is empty', function (): void {
($this->createMedia)(['directory' => '']);
})->throws(
\Assert\InvalidArgumentException::class,
AssertionException::notEmptyString('Media::directory')->getMessage()
);
it('should replace space characters by \'_\' in the filename property', function (): void {
$media = ($this->createMedia)(['filename' => ' new filename.jpg ']);
expect($media->getFilename())->toBe('new_filename.jpg');
});
it('should remove the space characters in the path property', function (): void {
$media = ($this->createMedia)(['directory' => ' new path ']);
expect($media->getDirectory())->toBe('newpath');
});
it('should remove the space characters in the comment property', function (): void {
$media = ($this->createMedia)(['comment' => ' some comments ']);
expect($media->getComment())->toBe('some comments');
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Media/Domain/ImageFolder/ImageFolderTest.php | centreon/tests/php/Core/Media/Domain/ImageFolder/ImageFolderTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Domain\ImageFolder;
use Core\Media\Domain\Model\ImageFolder\ImageFolder;
use Core\Media\Domain\Model\ImageFolder\ImageFolderDescription;
use Core\Media\Domain\Model\ImageFolder\ImageFolderId;
use Core\Media\Domain\Model\ImageFolder\ImageFolderName;
use PHPUnit\Framework\TestCase;
final class ImageFolderTest extends TestCase
{
public function testValidImageFolderIsCreatedCorrectly(): void
{
$id = new ImageFolderId(1);
$name = new ImageFolderName('Main Folder');
$folder = new ImageFolder($id, $name);
$this->assertSame($id, $folder->id());
$this->assertSame($name, $folder->name());
$this->assertNull($folder->alias());
$this->assertNull($folder->description());
}
public function testIdThrowsWhenNull(): void
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Id of "Core\Media\Domain\Model\ImageFolder\ImageFolder" is not defined');
$folder = new ImageFolder(null, new ImageFolderName('No ID'));
$folder->id(); // Should throw
}
public function testSetAliasAndDescription(): void
{
$folder = new ImageFolder(new ImageFolderId(2), new ImageFolderName('Folder'));
$alias = new ImageFolderName('Alias Name');
$desc = new ImageFolderDescription('Description here');
$folder->setAlias($alias)->setDescription($desc);
$this->assertSame($alias, $folder->alias());
$this->assertSame($desc, $folder->description());
}
public function testSetAliasAndDescriptionToNull(): void
{
$folder = new ImageFolder(new ImageFolderId(3), new ImageFolderName('Another Folder'));
$folder->setAlias(null)->setDescription(null);
$this->assertNull($folder->alias());
$this->assertNull($folder->description());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Media/Infrastructure/API/AddMedia/AddMediaPresenterStub.php | centreon/tests/php/Core/Media/Infrastructure/API/AddMedia/AddMediaPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Infrastructure\API\AddMedia;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Media\Application\UseCase\AddMedia\AddMediaPresenterInterface;
use Core\Media\Application\UseCase\AddMedia\AddMediaResponse;
class AddMediaPresenterStub extends AbstractPresenter implements AddMediaPresenterInterface
{
public AddMediaResponse|ResponseStatusInterface $response;
public function presentResponse(AddMediaResponse|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/Media/Infrastructure/API/UpdateMedia/UpdateMediaPresenterStub.php | centreon/tests/php/Core/Media/Infrastructure/API/UpdateMedia/UpdateMediaPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Infrastructure\API\UpdateMedia;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMediaPresenterInterface;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMediaResponse;
class UpdateMediaPresenterStub extends AbstractPresenter implements UpdateMediaPresenterInterface
{
public UpdateMediaResponse|ResponseStatusInterface $response;
public function presentResponse(UpdateMediaResponse|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/Media/Infrastructure/Command/MigrateAllMedias/MigrateAllMediasPresenterStub.php | centreon/tests/php/Core/Media/Infrastructure/Command/MigrateAllMedias/MigrateAllMediasPresenterStub.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Tests\Core\Media\Infrastructure\Command\MigrateAllMedias;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrateAllMediasPresenterInterface;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrationAllMediasResponse;
class MigrateAllMediasPresenterStub implements MigrateAllMediasPresenterInterface
{
public ResponseStatusInterface|MigrationAllMediasResponse $response;
public function presentResponse(MigrationAllMediasResponse|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/Token/Application/UseCase/FindTokens/FindTokensTest.php | centreon/tests/php/Core/Security/Token/Application/UseCase/FindTokens/FindTokensTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License 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\FindTokens;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Domain\TrimmedString;
use Core\Security\Token\Application\Exception\TokenException;
use Core\Security\Token\Application\UseCase\FindTokens\FindTokens;
use Core\Security\Token\Application\UseCase\FindTokens\FindTokensResponse;
use Core\Security\Token\Domain\Model\ApiToken;
use Core\Security\Token\Domain\Model\JwtToken;
use Core\Security\Token\Infrastructure\Repository\DbReadTokenRepository;
beforeEach(closure: function (): void {
$this->useCase = new FindTokens(
$this->repository = $this->createMock(DbReadTokenRepository::class),
$this->user = $this->createMock(ContactInterface::class),
);
});
it('should present an ErrorResponse when an exception is thrown', function (): void {
$this->user
->expects($this->once())
->method('hasRole')
->with(Contact::ROLE_MANAGE_TOKENS)
->willReturn(true);
$this->repository
->expects($this->once())
->method('findByRequestParameters')
->willThrowException(new \Exception());
$response = ($this->useCase)();
expect($response)
->toBeInstanceOf(ErrorResponse::class)
->and($response->getMessage())
->toBe(TokenException::errorWhileSearching(new \Exception())->getMessage());
});
it('should present a FindTokensResponse when a non-admin user has read rights', function (): void {
$this->user
->method('hasRole')
->with(Contact::ROLE_MANAGE_TOKENS)
->willReturn(false);
$creationDate = new \DateTime();
$expirationDate = $creationDate->add(\DateInterval::createFromDateString('1 day'));
$this->repository
->expects($this->once())
->method('findByUserIdAndRequestParameters')
->willReturn([
new ApiToken(
name: new TrimmedString('fake'),
userId: 1,
userName: new TrimmedString('non-admin'),
creatorId: 1,
creatorName: new TrimmedString('non-admin'),
creationDate: $creationDate,
expirationDate: $expirationDate,
isRevoked: false
),
]);
$response = ($this->useCase)();
expect($response)
->toBeInstanceOf(FindTokensResponse::class)
->and($response->tokens)
->toHaveCount(1)
->and(serialize($response->tokens[0]))
->toBe(
serialize(
new ApiToken(
name: new TrimmedString('fake'),
userId: 1,
userName: new TrimmedString('non-admin'),
creatorId: 1,
creatorName: new TrimmedString('non-admin'),
creationDate: $creationDate,
expirationDate: $expirationDate,
isRevoked: false
),
)
);
});
it('should present a FindTokensResponse when user is an admin', function (): void {
$this->user
->method('hasTopologyRole')
->with(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_TOKENS_RW)
->willReturn(true);
$this->user
->method('hasRole')
->with(Contact::ROLE_MANAGE_TOKENS)
->willReturn(true);
$creationDate = new \DateTime();
$expirationDate = $creationDate->add(\DateInterval::createFromDateString('1 day'));
$this->repository
->expects($this->once())
->method('findByRequestParameters')
->willReturn([
new JwtToken(
name: new TrimmedString('fake'),
creatorId: 1,
creatorName: new TrimmedString('non-admin'),
creationDate: $creationDate,
expirationDate: $expirationDate,
isRevoked: false
),
]);
$response = ($this->useCase)();
expect($response)
->toBeInstanceOf(FindTokensResponse::class)
->and($response->tokens)
->toHaveCount(1)
->and(serialize($response->tokens[0]))
->toBe(
serialize(
new JwtToken(
name: new TrimmedString('fake'),
creatorId: 1,
creatorName: new TrimmedString('non-admin'),
creationDate: $creationDate,
expirationDate: $expirationDate,
isRevoked: false,
),
)
);
});
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/tests/php/Core/Security/Token/Application/UseCase/PartialUpdateToken/PartialUpdateTokenTest.php | centreon/tests/php/Core/Security/Token/Application/UseCase/PartialUpdateToken/PartialUpdateTokenTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License 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\PartialUpdate;
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\PartialUpdateToken\PartialUpdateToken;
use Core\Security\Token\Application\UseCase\PartialUpdateToken\PartialUpdateTokenRequest;
use Core\Security\Token\Domain\Model\ApiToken;
beforeEach(function (): void {
$this->presenter = new DefaultPresenter(
$this->presenterFormatter = $this->createMock(PresenterFormatterInterface::class)
);
$this->useCase = new PartialUpdateToken(
$this->contact = $this->createMock(ContactInterface::class),
$this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class),
$this->writeTokenRepository = $this->createMock(WriteTokenRepositoryInterface::class),
);
$this->request = new PartialUpdateTokenRequest(true);
$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->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readTokenRepository
->expects($this->once())
->method('findByNameAndUserId')
->willReturn($this->token);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->writeTokenRepository
->expects($this->once())
->method('update')
->willThrowException(new \Exception());
$this->request->isRevoked = false;
($this->useCase)($this->request, $this->presenter, $this->token->getName(), $this->linkedUser['id']);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ErrorResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(TokenException::errorWhilePartiallyUpdatingToken()->getMessage());
});
it('should present a ForbiddenResponse when the user does not have sufficient rights', function (): void {
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(false);
($this->useCase)($this->request, $this->presenter, $this->token->getName(), $this->linkedUser['id']);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(ForbiddenResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe(TokenException::notAllowedToPartiallyUpdateToken()->getMessage());
});
it('should present a NotFoundResponse when no token exists for a given name and/or user ID', function (): void {
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readTokenRepository
->expects($this->once())
->method('findByNameAndUserId')
->willReturn(null);
($this->useCase)($this->request, $this->presenter, $this->token->getName(), $this->linkedUser['id']);
expect($this->presenter->getResponseStatus())
->toBeInstanceOf(NotFoundResponse::class)
->and($this->presenter->getResponseStatus()->getMessage())
->toBe('Token not found');
});
it('should present a NoContentResponse when token is successfully revoked', function (): void {
$this->contact
->expects($this->once())
->method('hasTopologyRole')
->willReturn(true);
$this->readTokenRepository
->expects($this->once())
->method('findByNameAndUserId')
->willReturn($this->token);
$this->contact
->expects($this->once())
->method('isAdmin')
->willReturn(true);
$this->writeTokenRepository
->expects($this->once())
->method('update');
($this->useCase)($this->request, $this->presenter, $this->token->getName(), $this->linkedUser['id']);
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/Application/UseCase/AddToken/AddTokenValidationTest.php | centreon/tests/php/Core/Security/Token/Application/UseCase/AddToken/AddTokenValidationTest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License 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\AddTokenValidation;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Security\Token\Application\Exception\TokenException;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Application\UseCase\AddToken\AddTokenValidation;
beforeEach(function (): void {
$this->validation = new AddTokenValidation(
$this->readTokenRepository = $this->createMock(ReadTokenRepositoryInterface::class),
$this->readContactRepository = $this->createMock(ReadContactRepositoryInterface::class),
$this->user = $this->createMock(ContactInterface::class)
);
});
it('throws an exception when name is already used', function (): void {
$this->readTokenRepository
->expects($this->once())
->method('existsByNameAndUserId')
->willReturn(true);
$this->validation->assertIsValidName(' name test ', 1);
})->throws(
TokenException::class,
TokenException::nameAlreadyExists(trim('name test'))->getMessage()
);
it('throws an exception when user is not allowed to manage other\'s token', function (): void {
$this->user
->expects($this->once())
->method('getId')
->willReturn(2);
$this->user
->expects($this->once())
->method('hasRole')
->willReturn(false);
$this->validation->assertIsValidUser(1);
})->throws(
TokenException::class,
TokenException::notAllowedToCreateTokenForUser(1)->getMessage()
);
it('throws an exception when user ID does not exist', function (): void {
$this->user
->expects($this->once())
->method('getId')
->willReturn(2);
$this->user
->expects($this->once())
->method('hasRole')
->willReturn(true);
$this->readContactRepository
->expects($this->once())
->method('exists')
->willReturn(false);
$this->validation->assertIsValidUser(1);
})->throws(
TokenException::class,
TokenException::invalidUserId(1)->getMessage()
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.