Covered fetching stats and filter with the test cases.

pull/316/head
Ruslan Baidan 2020-07-03 15:00:32 +02:00
commit 69894d9806
No known key found for this signature in database
GPG Key ID: 4B7724C136BF1D89
6 changed files with 380 additions and 119 deletions

141
composer.lock generated
View File

@ -394,71 +394,6 @@
], ],
"time": "2020-06-14T02:01:05+00:00" "time": "2020-06-14T02:01:05+00:00"
}, },
{
"name": "composer/package-versions-deprecated",
"version": "1.8.0",
"source": {
"type": "git",
"url": "https://github.com/composer/package-versions-deprecated.git",
"reference": "98df7f1b293c0550bd5b1ce6b60b59bdda23aa47"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/composer/package-versions-deprecated/zipball/98df7f1b293c0550bd5b1ce6b60b59bdda23aa47",
"reference": "98df7f1b293c0550bd5b1ce6b60b59bdda23aa47",
"shasum": ""
},
"require": {
"composer-plugin-api": "^1.1.0 || ^2.0",
"php": "^7"
},
"replace": {
"ocramius/package-versions": "1.2 - 1.8.99"
},
"require-dev": {
"composer/composer": "^1.9.3 || ^2.0@dev",
"ext-zip": "^1.13",
"phpunit/phpunit": "^6.5 || ^7"
},
"type": "composer-plugin",
"extra": {
"class": "PackageVersions\\Installer",
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"autoload": {
"psr-4": {
"PackageVersions\\": "src/PackageVersions"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Marco Pivetta",
"email": "ocramius@gmail.com"
},
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be"
}
],
"description": "Composer plugin that provides efficient querying for installed package versions (no runtime IO)",
"funding": [
{
"url": "https://packagist.com",
"type": "custom"
},
{
"url": "https://tidelift.com/funding/github/packagist/composer/composer",
"type": "tidelift"
}
],
"time": "2020-04-23T11:49:37+00:00"
},
{ {
"name": "container-interop/container-interop", "name": "container-interop/container-interop",
"version": "1.2.0", "version": "1.2.0",
@ -4052,12 +3987,12 @@
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/monarc-project/zm-core.git", "url": "https://github.com/monarc-project/zm-core.git",
"reference": "5338a9caaab59a8be2e8a70e5c33ae7beb6514af" "reference": "0f8b08580ca4b2b4467715ebc4543e42323a1022"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/monarc-project/zm-core/zipball/5338a9caaab59a8be2e8a70e5c33ae7beb6514af", "url": "https://api.github.com/repos/monarc-project/zm-core/zipball/0f8b08580ca4b2b4467715ebc4543e42323a1022",
"reference": "5338a9caaab59a8be2e8a70e5c33ae7beb6514af", "reference": "0f8b08580ca4b2b4467715ebc4543e42323a1022",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -4131,7 +4066,7 @@
} }
], ],
"description": "Core for monarc/monarc application", "description": "Core for monarc/monarc application",
"time": "2020-07-02T10:36:58+00:00" "time": "2020-07-02T13:38:58+00:00"
}, },
{ {
"name": "monarc/frontoffice", "name": "monarc/frontoffice",
@ -4139,12 +4074,12 @@
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/monarc-project/zm-client.git", "url": "https://github.com/monarc-project/zm-client.git",
"reference": "11b1912a489964534f20ff6e1169124037026623" "reference": "8990aadf0ceeb332cd53aa4a00c75f58a83868b2"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/monarc-project/zm-client/zipball/11b1912a489964534f20ff6e1169124037026623", "url": "https://api.github.com/repos/monarc-project/zm-client/zipball/8990aadf0ceeb332cd53aa4a00c75f58a83868b2",
"reference": "11b1912a489964534f20ff6e1169124037026623", "reference": "8990aadf0ceeb332cd53aa4a00c75f58a83868b2",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -4219,7 +4154,7 @@
} }
], ],
"description": "Frontoffice for monarc/monarc application", "description": "Frontoffice for monarc/monarc application",
"time": "2020-06-30T19:17:13+00:00" "time": "2020-07-03T12:44:45+00:00"
}, },
{ {
"name": "monarc/phpword", "name": "monarc/phpword",
@ -4324,6 +4259,56 @@
], ],
"time": "2019-09-12T12:23:28+00:00" "time": "2019-09-12T12:23:28+00:00"
}, },
{
"name": "ocramius/package-versions",
"version": "1.4.2",
"source": {
"type": "git",
"url": "https://github.com/Ocramius/PackageVersions.git",
"reference": "44af6f3a2e2e04f2af46bcb302ad9600cba41c7d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Ocramius/PackageVersions/zipball/44af6f3a2e2e04f2af46bcb302ad9600cba41c7d",
"reference": "44af6f3a2e2e04f2af46bcb302ad9600cba41c7d",
"shasum": ""
},
"require": {
"composer-plugin-api": "^1.0.0",
"php": "^7.1.0"
},
"require-dev": {
"composer/composer": "^1.6.3",
"doctrine/coding-standard": "^5.0.1",
"ext-zip": "*",
"infection/infection": "^0.7.1",
"phpunit/phpunit": "^7.5.17"
},
"type": "composer-plugin",
"extra": {
"class": "PackageVersions\\Installer",
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"psr-4": {
"PackageVersions\\": "src/PackageVersions"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Marco Pivetta",
"email": "ocramius@gmail.com"
}
],
"description": "Composer plugin that provides efficient querying for installed package versions (no runtime IO)",
"time": "2019-11-15T16:17:10+00:00"
},
{ {
"name": "ocramius/proxy-manager", "name": "ocramius/proxy-manager",
"version": "2.2.3", "version": "2.2.3",
@ -7081,12 +7066,12 @@
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/Roave/SecurityAdvisories.git", "url": "https://github.com/Roave/SecurityAdvisories.git",
"reference": "6d2e5ab854782830911ddd33b7d4649b9f18c10f" "reference": "9ec84501a85a3b0c7b260042ae81a8efb2f234ce"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/Roave/SecurityAdvisories/zipball/6d2e5ab854782830911ddd33b7d4649b9f18c10f", "url": "https://api.github.com/repos/Roave/SecurityAdvisories/zipball/9ec84501a85a3b0c7b260042ae81a8efb2f234ce",
"reference": "6d2e5ab854782830911ddd33b7d4649b9f18c10f", "reference": "9ec84501a85a3b0c7b260042ae81a8efb2f234ce",
"shasum": "" "shasum": ""
}, },
"conflict": { "conflict": {
@ -7181,7 +7166,7 @@
"monolog/monolog": ">=1.8,<1.12", "monolog/monolog": ">=1.8,<1.12",
"namshi/jose": "<2.2", "namshi/jose": "<2.2",
"nzo/url-encryptor-bundle": ">=4,<4.3.2|>=5,<5.0.1", "nzo/url-encryptor-bundle": ">=4,<4.3.2|>=5,<5.0.1",
"october/october": ">=1.0.319,<1.0.466", "october/october": ">=1.0.319,<1.0.467",
"onelogin/php-saml": "<2.10.4", "onelogin/php-saml": "<2.10.4",
"oneup/uploader-bundle": "<1.9.3|>=2,<2.1.5", "oneup/uploader-bundle": "<1.9.3|>=2,<2.1.5",
"openid/php-openid": "<2.3", "openid/php-openid": "<2.3",
@ -7358,7 +7343,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2020-06-19T13:23:43+00:00" "time": "2020-07-02T17:01:23+00:00"
}, },
{ {
"name": "sebastian/code-unit-reverse-lookup", "name": "sebastian/code-unit-reverse-lookup",

View File

@ -0,0 +1,33 @@
vercomp () {
if [[ $1 == $2 ]]
then
return 1
fi
local IFS=.
local i ver1=($1) ver2=($2)
# fill empty fields in ver1 with zeros
for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
do
ver1[i]=0
done
for ((i=0; i<${#ver1[@]}; i++))
do
if [[ -z ${ver2[i]} ]]
then
# fill empty fields in ver2 with zeros
ver2[i]=0
fi
if ((10#${ver1[i]} > 10#${ver2[i]}))
then
return 1
fi
done
return 0
}
php_version_string=`php -v | grep -Eow '^PHP [^ ]+' | grep -Eow '[0-9\.]{1,3}'`
echo Your php version is $php_version_string
if [[ $(vercomp $php_version_string 7.4; echo $?) -eq 1 ]]; then
composer require "ocramius/proxy-manager: ^2.8" --ignore-platform-reqs
fi

View File

@ -2,15 +2,15 @@
namespace MonarcAppFo\Tests\Functional\Controller; namespace MonarcAppFo\Tests\Functional\Controller;
use Laminas\Http\Header\HeaderInterface;
use Laminas\ServiceManager\ServiceManager;
use Monarc\Core\Model\Table\UserTable; use Monarc\Core\Model\Table\UserTable;
use Monarc\Core\Service\AuthenticationService; use Monarc\Core\Service\AuthenticationService;
use Monarc\Core\Service\ConnectedUserService; use Monarc\Core\Service\ConnectedUserService;
use Monarc\Core\Model\Entity\UserRole;
use Monarc\FrontOffice\Controller\ApiAdminUsersController; use Monarc\FrontOffice\Controller\ApiAdminUsersController;
use Monarc\FrontOffice\Model\Entity\User; use Monarc\FrontOffice\Model\Entity\User;
use Monarc\FrontOffice\Model\Entity\UserRole;
use MonarcAppFo\Tests\Functional\AbstractFunctionalTestCase; use MonarcAppFo\Tests\Functional\AbstractFunctionalTestCase;
use Laminas\Http\Header\HeaderInterface;
use Laminas\ServiceManager\ServiceManager;
class ApiAdminUsersControllerTest extends AbstractFunctionalTestCase class ApiAdminUsersControllerTest extends AbstractFunctionalTestCase
{ {

View File

@ -3,9 +3,18 @@
namespace MonarcAppFo\Tests\Integration\Service; namespace MonarcAppFo\Tests\Integration\Service;
use DateTime; use DateTime;
use DateTimeImmutable;
use Doctrine\Common\Collections\ArrayCollection;
use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
use Laminas\ServiceManager\ServiceManager; use Laminas\ServiceManager\ServiceManager;
use Monarc\Core\Service\ConnectedUserService;
use Monarc\FrontOffice\Model\Entity\Anr;
use Monarc\FrontOffice\Model\Entity\UserAnr;
use Monarc\FrontOffice\Model\Entity\UserRole;
use Monarc\FrontOffice\Exception\AccessForbiddenException;
use Monarc\FrontOffice\Exception\UserNotAuthorizedException;
use Monarc\FrontOffice\Model\Entity\User;
use Monarc\FrontOffice\Model\Table\AnrTable; use Monarc\FrontOffice\Model\Table\AnrTable;
use Monarc\FrontOffice\Model\Table\SettingTable; use Monarc\FrontOffice\Model\Table\SettingTable;
use Monarc\FrontOffice\Stats\DataObject\StatsDataObject; use Monarc\FrontOffice\Stats\DataObject\StatsDataObject;
@ -13,15 +22,22 @@ use Monarc\FrontOffice\Stats\Exception\StatsAlreadyCollectedException;
use Monarc\FrontOffice\Stats\Provider\StatsApiProvider; use Monarc\FrontOffice\Stats\Provider\StatsApiProvider;
use Monarc\FrontOffice\Stats\Service\StatsAnrService; use Monarc\FrontOffice\Stats\Service\StatsAnrService;
use MonarcAppFo\Tests\Integration\AbstractIntegrationTestCase; use MonarcAppFo\Tests\Integration\AbstractIntegrationTestCase;
use PHPUnit\Framework\MockObject\MockObject;
class StatsAnrServiceTest extends AbstractIntegrationTestCase class StatsAnrServiceTest extends AbstractIntegrationTestCase
{ {
/** @var MockHandler */ /** @var MockHandler */
private $mockHandler; private $statsApiMockHandler;
/** @var array */ /** @var array */
private $currentDateParams; private $currentDateParams;
/** @var StatsAnrService */
private $statsAnrService;
/** @var ConnectedUserService|MockObject */
private $connectedUserService;
public static function setUpBeforeClass(): void public static function setUpBeforeClass(): void
{ {
parent::setUpBeforeClass(); parent::setUpBeforeClass();
@ -34,20 +50,24 @@ class StatsAnrServiceTest extends AbstractIntegrationTestCase
parent::setUp(); parent::setUp();
$this->currentDateParams = $this->getCurrentDateParams(); $this->currentDateParams = $this->getCurrentDateParams();
$this->statsAnrService = $this->getApplicationServiceLocator()->get(StatsAnrService::class);
} }
protected function configureServiceManager(ServiceManager $serviceManager) protected function configureServiceManager(ServiceManager $serviceManager)
{ {
$serviceManager->setAllowOverride(true); $serviceManager->setAllowOverride(true);
$this->mockHandler = new MockHandler(); $this->statsApiMockHandler = new MockHandler();
$statsApiProvider = new StatsApiProvider( $statsApiProvider = new StatsApiProvider(
$serviceManager->get(SettingTable::class), $serviceManager->get(SettingTable::class),
[], [],
$this->mockHandler $this->statsApiMockHandler
); );
$serviceManager->setService(StatsApiProvider::class, $statsApiProvider); $serviceManager->setService(StatsApiProvider::class, $statsApiProvider);
$this->connectedUserService = $this->createMock(ConnectedUserService::class);
$serviceManager->setService(ConnectedUserService::class, $this->connectedUserService);
$serviceManager->setAllowOverride(false); $serviceManager->setAllowOverride(false);
} }
@ -56,12 +76,12 @@ class StatsAnrServiceTest extends AbstractIntegrationTestCase
$this->expectException(StatsAlreadyCollectedException::class); $this->expectException(StatsAlreadyCollectedException::class);
$this->expectExceptionMessage('The stats is already collected for today.'); $this->expectExceptionMessage('The stats is already collected for today.');
$this->mockHandler->append(new Response(200, [], $this->getStatsResponse([ $this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse([
[ new StatsDataObject([
'type' => StatsDataObject::TYPE_RISK, 'type' => StatsDataObject::TYPE_RISK,
'anr' => '1232-31abcd-213efgh-123klmp',
'data' => [ 'data' => [
'category' => 'ANR 1', 'total' => [
'series' => [
[ [
'label' => 'Low risks', 'label' => 'Low risks',
'value' => 50, 'value' => 50,
@ -79,23 +99,19 @@ class StatsAnrServiceTest extends AbstractIntegrationTestCase
], ],
], ],
], ],
], ])
]))); ])));
/** @var StatsAnrService $statsAnrService */ $this->statsAnrService->collectStats();
$statsAnrService = $this->getApplicationServiceLocator()->get(StatsAnrService::class);
$statsAnrService->collectStats();
} }
public function testItDoesNotSendTheStatsWhenTheDataIsEmpty() public function testItDoesNotSendTheStatsWhenTheDataIsEmpty()
{ {
$this->mockHandler->append(new Response(200, [], $this->getStatsResponse())); $this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
/** @var StatsAnrService $statsAnrService */ $this->statsAnrService->collectStats([99, 78]);
$statsAnrService = $this->getApplicationServiceLocator()->get(StatsAnrService::class);
$statsAnrService->collectStats([99, 78]);
$this->assertEquals('GET', $this->mockHandler->getLastRequest()->getMethod()); $this->assertEquals('GET', $this->statsApiMockHandler->getLastRequest()->getMethod());
} }
public function testItCanGenerateTheStatsForAllTheAnrs() public function testItCanGenerateTheStatsForAllTheAnrs()
@ -108,16 +124,14 @@ class StatsAnrServiceTest extends AbstractIntegrationTestCase
$anrUuids[] = $anr->getUuid(); $anrUuids[] = $anr->getUuid();
} }
$this->mockHandler->append(new Response(200, [], $this->getStatsResponse())); $this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$this->mockHandler->append(new Response(201, [], '{"status": "ok"}')); $this->statsApiMockHandler->append(new Response(201, [], '{"status": "ok"}'));
/** @var StatsAnrService $statsAnrService */ $this->statsAnrService->collectStats();
$statsAnrService = $this->getApplicationServiceLocator()->get(StatsAnrService::class);
$statsAnrService->collectStats();
$this->assertJsonStringEqualsJsonString( $this->assertJsonStringEqualsJsonString(
$this->getExpectedStatsDataJson($anrUuids), $this->getExpectedStatsDataJson($anrUuids),
$this->mockHandler->getLastRequest()->getBody()->getContents() $this->statsApiMockHandler->getLastRequest()->getBody()->getContents()
); );
} }
@ -135,53 +149,234 @@ class StatsAnrServiceTest extends AbstractIntegrationTestCase
$this->assertCount(\count($anrIdsToGenerateTheStats), $anrUuids); $this->assertCount(\count($anrIdsToGenerateTheStats), $anrUuids);
$this->mockHandler->append(new Response(200, [], $this->getStatsResponse())); $this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$this->mockHandler->append(new Response(201, [], '{"status": "ok"}')); $this->statsApiMockHandler->append(new Response(201, [], '{"status": "ok"}'));
/** @var StatsAnrService $statsAnrService */ $this->statsAnrService->collectStats($anrIdsToGenerateTheStats);
$statsAnrService = $this->getApplicationServiceLocator()->get(StatsAnrService::class);
$statsAnrService->collectStats($anrIdsToGenerateTheStats);
$this->assertJsonStringEqualsJsonString( $this->assertJsonStringEqualsJsonString(
$this->getExpectedStatsDataJson($anrUuids), $this->getExpectedStatsDataJson($anrUuids),
$this->mockHandler->getLastRequest()->getBody()->getContents() $this->statsApiMockHandler->getLastRequest()->getBody()->getContents()
); );
} }
/*
public function testItThrowsTheExceptionIfUserIsNotLoggedIn() public function testItThrowsTheExceptionIfUserIsNotLoggedIn()
{ {
$this->expectException(UserNotAuthorizedException::class);
$this->expectExceptionMessage('User not authorized.');
$this->statsAnrService->getStats([]);
} }
public function testItThrowsTheExceptionIfUserDoesNotHaveTheRightsToGetTheStats() public function testItThrowsTheExceptionIfUserDoesNotHaveTheRightsToGetTheStats()
{ {
$this->expectException(AccessForbiddenException::class);
$this->expectExceptionMessage('User does not have an access to the action.');
$user = $this->createMock(User::class);
$user->expects($this->once())->method('hasRole')->with(UserRole::USER_ROLE_CEO)->willReturn(false);
$user->method('getUserAnrs')->willReturn(new ArrayCollection());
$this->connectedUserService
->expects($this->once())
->method('getConnectedUser')
->willReturn($user);
$this->statsAnrService->getStats([]);
} }
public function testItAddsToTheFilterAllowedForTheUserAnrUuids() public function testItAddsToTheFilterAllowedForTheUserAnrUuids()
{ {
$user = $this->createMock(User::class);
$user->expects($this->exactly(2))->method('hasRole')->with(UserRole::USER_ROLE_CEO)->willReturn(false);
/** @var Anr $anr1 */
$anr1 = (new Anr())->setId(1);
/** @var Anr $anr2 */
$anr2 = (new Anr())->setId(2);
/** @var Anr $anr3 */
$anr3 = (new Anr())->setId(3);
$user->method('getUserAnrs')->willReturn(new ArrayCollection([
(new UserAnr())->setAnr($anr1->generateAndSetUuid()),
(new UserAnr())->setAnr($anr2->generateAndSetUuid()),
(new UserAnr())->setAnr($anr3->generateAndSetUuid()),
]));
$this->connectedUserService->expects($this->exactly(2))->method('getConnectedUser')->willReturn($user);
$this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$stats = $this->statsAnrService->getStats([]);
$this->assertEmpty($stats);
$defaultDates = [
'dateFrom' => (new DateTime())->modify('-' . StatsAnrService::DEFAULT_STATS_DATES_RANGE)->format('Y-m-d'),
'dateTo' => (new DateTime())->format('Y-m-d'),
];
$queryParams = [];
parse_str($this->statsApiMockHandler->getLastRequest()->getUri()->getQuery(), $queryParams);
$this->assertEquals(
array_merge(['anrs' => [$anr1->getUuid(), $anr2->getUuid(), $anr3->getUuid()]], $defaultDates),
$queryParams
);
$statsResponse = $this->getStatsResponse([
new StatsDataObject([
'type' => StatsDataObject::TYPE_RISK,
'anr' => '1232-31abcd-213efgh-123klmp',
'data' => [
'total' => [
[
'label' => 'Low risks',
'value' => 50,
],
[
'label' => 'Medium risks',
'value' => 30,
],
[
'label' => 'High risks',
'value' => 10,
],
],
],
])
]);
$this->statsApiMockHandler->append(new Response(200, [], $statsResponse));
$stats = $this->statsAnrService->getStats(['anrs' => [1, 3, 7]]);
$this->assertEquals($this->getStatsResponse($stats), $statsResponse);
parse_str($this->statsApiMockHandler->getLastRequest()->getUri()->getQuery(), $queryParams);
$this->assertEquals(
array_merge(['anrs' => [$anr1->getUuid(), $anr3->getUuid()]], $defaultDates),
$queryParams
);
} }
public function testItAllowsToFilterBySpecificAnrsForCeoRole() public function testItAllowsToFilterBySpecificAnrsForCeoRoleOrGetItWithoutLimitations()
{ {
$user = $this->createMock(User::class);
$user->expects($this->exactly(2))->method('hasRole')->with(UserRole::USER_ROLE_CEO)->willReturn(true);
$user->expects($this->never())->method('getUserAnrs');
$this->connectedUserService->expects($this->exactly(2))->method('getConnectedUser')->willReturn($user);
/** @var AnrTable $anrTable */
$anrTable = $this->getApplicationServiceLocator()->get(AnrTable::class);
$anrUuids = [];
foreach ($anrTable->findByIds([1, 2, 3]) as $anr) {
$anrUuids[] = $anr->getUuid();
} }
public function testItAllowsToGetStatsWithoutAnrsLimitationForCeoRole() $defaultDates = [
{ 'dateFrom' => (new DateTime())->modify('-' . StatsAnrService::DEFAULT_STATS_DATES_RANGE)->format('Y-m-d'),
'dateTo' => (new DateTime())->format('Y-m-d'),
];
$this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$this->statsAnrService->getStats([
'anrs' => [1, 2, 3, 99] // anr ID = 99 is not in thew db.
]);
parse_str($this->statsApiMockHandler->getLastRequest()->getUri()->getQuery(), $queryParams);
$this->assertEquals(array_merge(['anrs' => $anrUuids], $defaultDates), $queryParams);
$this->statsAnrService->getStats([]);
parse_str($this->statsApiMockHandler->getLastRequest()->getUri()->getQuery(), $queryParams);
$this->assertEquals($defaultDates, $queryParams);
} }
public function testItCanSendDifferentAggregationParamsToGetTheStats() public function testItCanSendDifferentParamsToGetTheStats()
{ {
$user = $this->createMock(User::class);
$user->expects($this->exactly(2))->method('hasRole')->with(UserRole::USER_ROLE_CEO)->willReturn(true);
$user->expects($this->never())->method('getUserAnrs');
$this->connectedUserService->expects($this->exactly(2))->method('getConnectedUser')->willReturn($user);
/** @var AnrTable $anrTable */
$anrTable = $this->getApplicationServiceLocator()->get(AnrTable::class);
$anrUuids = [];
foreach ($anrTable->findByIds([1, 2, 3, 4]) as $anr) {
$anrUuids[] = $anr->getUuid();
}
$datesRange = [
'dateFrom' => (new DateTime())->modify('-1 year')->format('Y-m-d'),
'dateTo' => (new DateTime())->format('Y-m-d'),
];
$this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$this->statsAnrService->getStats(array_merge([
'anrs' => [1, 2, 3, 4],
'aggregationPeriod' => 'month',
'type' => StatsDataObject::TYPE_COMPLIANCE
], $datesRange));
parse_str($this->statsApiMockHandler->getLastRequest()->getUri()->getQuery(), $queryParams);
$this->assertEquals(array_merge([
'anrs' => $anrUuids,
'aggregationPeriod' => 'month',
'type' => StatsDataObject::TYPE_COMPLIANCE
], $datesRange), $queryParams);
$this->statsAnrService->getStats(array_merge([
'aggregationPeriod' => 'week',
'type' => StatsDataObject::TYPE_VULNERABILITY
], $datesRange));
parse_str($this->statsApiMockHandler->getLastRequest()->getUri()->getQuery(), $queryParams);
$this->assertEquals(array_merge([
'aggregationPeriod' => 'week',
'type' => StatsDataObject::TYPE_VULNERABILITY
], $datesRange), $queryParams);
} }
public function testItFetchesStatsForDefaultPeriodIfFromAndToDatesAreNotPassed() public function testItFetchesStatsForDefaultPeriodIfFromAndToDatesAreNotPassed()
{ {
$user = $this->createMock(User::class);
$user->expects($this->exactly(3))->method('hasRole')->with(UserRole::USER_ROLE_CEO)->willReturn(true);
$user->expects($this->never())->method('getUserAnrs');
$this->connectedUserService->expects($this->exactly(3))->method('getConnectedUser')->willReturn($user);
$defaultDates = [
'dateFrom' => (new DateTime())->modify('-' . StatsAnrService::DEFAULT_STATS_DATES_RANGE)->format('Y-m-d'),
'dateTo' => (new DateTime())->format('Y-m-d'),
];
$this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$this->statsApiMockHandler->append(new Response(200, [], $this->getStatsResponse()));
$this->statsAnrService->getStats([]);
parse_str($this->statsApiMockHandler->getLastRequest()->getUri()->getQuery(), $queryParams);
$this->assertEquals($defaultDates, $queryParams);
$this->statsAnrService->getStats(['dateFrom' => (new DateTime())->modify('-6 months')->format('Y-m-d')]);
parse_str($this->statsApiMockHandler->getLastRequest()->getUri()->getQuery(), $queryParams);
$this->assertEquals([
'dateFrom' => (new DateTime())->modify('-6 months')->format('Y-m-d'),
'dateTo' => $defaultDates['dateTo']
], $queryParams);
$dateTo = (new DateTimeImmutable())->modify('-6 months');
$this->statsAnrService->getStats(['dateTo' => $dateTo->format('Y-m-d')]);
parse_str($this->statsApiMockHandler->getLastRequest()->getUri()->getQuery(), $queryParams);
$this->assertEquals([
'dateFrom' => $dateTo->modify('-' . StatsAnrService::DEFAULT_STATS_DATES_RANGE)->format('Y-m-d'),
'dateTo' => $dateTo->format('Y-m-d')
], $queryParams);
} }
*/
private function getStatsResponse(array $results = []): string private function getStatsResponse(array $results = []): string
{ {
return json_encode([ return json_encode([

View File

@ -0,0 +1,10 @@
<?php declare(strict_types=1);
namespace MonarcAppFo\Tests\Unit;
use PHPUnit\Framework\TestCase;
class AbstractUnitTestCase extends TestCase
{
}

View File

@ -7,6 +7,7 @@ use Laminas\InputFilter\InputFilter;
use Monarc\FrontOffice\Model\Entity\Anr; use Monarc\FrontOffice\Model\Entity\Anr;
use Monarc\FrontOffice\Model\Table\AnrTable; use Monarc\FrontOffice\Model\Table\AnrTable;
use Monarc\FrontOffice\Stats\DataObject\StatsDataObject; use Monarc\FrontOffice\Stats\DataObject\StatsDataObject;
use Monarc\FrontOffice\Stats\Service\StatsAnrService;
use Monarc\FrontOffice\Stats\Validator\GetStatsQueryParamsValidator; use Monarc\FrontOffice\Stats\Validator\GetStatsQueryParamsValidator;
use Monarc\FrontOffice\Validator\FieldValidator\AnrExistenceValidator; use Monarc\FrontOffice\Validator\FieldValidator\AnrExistenceValidator;
use MonarcAppFo\Tests\Unit\AbstractUnitTestCase; use MonarcAppFo\Tests\Unit\AbstractUnitTestCase;
@ -72,7 +73,13 @@ class GetStatsQueryParamsValidatorTest extends AbstractUnitTestCase
static::assertEmpty($this->getStatsQueryParamsValidator->getErrorMessages()); static::assertEmpty($this->getStatsQueryParamsValidator->getErrorMessages());
static::assertEquals( static::assertEquals(
['dateFrom' => '2019-12-01', 'dateTo' => '2020-06-01', 'anrs' => [], 'type' => StatsDataObject::TYPE_RISK], [
'dateFrom' => '2019-12-01',
'dateTo' => '2020-06-01',
'anrs' => [],
'type' => StatsDataObject::TYPE_RISK,
'aggregationPeriod' => null
],
$this->getStatsQueryParamsValidator->getValidData() $this->getStatsQueryParamsValidator->getValidData()
); );
@ -84,7 +91,13 @@ class GetStatsQueryParamsValidatorTest extends AbstractUnitTestCase
static::assertEmpty($this->getStatsQueryParamsValidator->getErrorMessages()); static::assertEmpty($this->getStatsQueryParamsValidator->getErrorMessages());
static::assertEquals( static::assertEquals(
['dateFrom' => '2019-12-01', 'dateTo' => '2019-12-01', 'anrs' => [], 'type' => StatsDataObject::TYPE_RISK], [
'dateFrom' => '2019-12-01',
'dateTo' => '2019-12-01',
'anrs' => [],
'type' => StatsDataObject::TYPE_RISK,
'aggregationPeriod' => null
],
$this->getStatsQueryParamsValidator->getValidData() $this->getStatsQueryParamsValidator->getValidData()
); );
} }
@ -124,11 +137,36 @@ class GetStatsQueryParamsValidatorTest extends AbstractUnitTestCase
static::assertEquals( static::assertEquals(
[ [
'type' => [ 'type' => [
'notInArray' => 'Type should be one of the values: ' 'notInArray' => 'Should be one of the values: '
. implode(', ', StatsDataObject::getAvailableTypes()) . implode(', ', StatsDataObject::getAvailableTypes())
] ]
], ],
$this->getStatsQueryParamsValidator->getErrorMessages() $this->getStatsQueryParamsValidator->getErrorMessages()
); );
} }
public function testItIsNotValidOnlyWhenPassedWrongAggregationPeriod()
{
static::assertFalse($this->getStatsQueryParamsValidator->isValid([
'type' => StatsDataObject::TYPE_RISK,
'aggregationPeriod' => 'not-existed-period'
]));
static::assertEquals(
[
'aggregationPeriod' => [
'notInArray' => 'Should be one of the values: '
. implode(', ', StatsAnrService::AVAILABLE_AGGREGATION_FIELDS)
]
],
$this->getStatsQueryParamsValidator->getErrorMessages()
);
static::assertTrue($this->getStatsQueryParamsValidator->isValid([
'type' => StatsDataObject::TYPE_RISK,
]));
static::assertTrue($this->getStatsQueryParamsValidator->isValid([
'type' => StatsDataObject::TYPE_RISK,
'aggregationType' => 'week',
]));
}
} }