Added the commit with the tests introduction.

pull/316/head
Ruslan Baidan 2020-04-14 11:57:21 +02:00
parent ad74b357f1
commit 9757525c73
No known key found for this signature in database
GPG Key ID: 4B7724C136BF1D89
13 changed files with 351 additions and 5404 deletions

View File

@ -43,8 +43,8 @@
"php": "^7.1",
"ext-json": "*",
"ext-pdo": "*",
"monarc/frontoffice": "^2.9.15",
"monarc/core": "^2.9.15",
"monarc/frontoffice": "dev-feature/stats",
"monarc/core": "dev-feature/stats as 2.9.17",
"laminas/laminas-mvc": "^3.1",
"laminas/laminas-di": "^3.1",
"laminas/laminas-permissions-rbac": "^3.0",
@ -54,7 +54,14 @@
"laminas/laminas-dependency-plugin": "^1.0"
},
"require-dev": {
"roave/security-advisories": "dev-master"
"roave/security-advisories": "dev-master",
"phpunit/phpunit": "^8.3",
"laminas/laminas-test": "^3.4"
},
"autoload-dev": {
"psr-4": {
"MonarcAppFo\\Tests\\": "tests/"
}
},
"config": {
"bin-dir": "bin/"

5399
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -6,9 +6,11 @@
* @see https://github.com/zendframework/ZFTool
*/
$env = getenv('APPLICATION_ENV') ?: 'production';
$appConfDir = getenv('APP_CONF_DIR') ?? '';
$appConfDir = getenv('APP_CONF_DIR') ?: null;
if ($env !== 'testing') {
$confPaths = ['config/autoload/{,*.}{global,local}.php'];
}
$dataPath = 'data';
if (!empty($appConfDir)) {
$confPaths[] = $appConfDir . '/local.php';

36
phpunit.xml Normal file
View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/bootstrap.php"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutTodoAnnotatedTests="true"
forceCoversAnnotation="true"
verbose="true">
<testsuites>
<testsuite name="Functional">
<directory suffix="Test.php">tests/Functional</directory>
</testsuite>
<testsuite name="Integration">
<directory suffix="Test.php">tests/Integration</directory>
</testsuite>
<testsuite name="Unit">
<directory suffix="Test.php">tests/Unit</directory>
</testsuite>
</testsuites>
<!--
<logging>
<log type="coverage-html" target="coverage"/>
</logging>
-->
<filter>
<whitelist>
<directory suffix=".php">module/Monarc/Core/src</directory>
<directory suffix=".php">module/Monarc/FrontOffice/src</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,38 @@
<?php declare(strict_types=1);
namespace MonarcAppFo\Tests\Functional;
use Laminas\ServiceManager\ServiceManager;
use Laminas\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
abstract class AbstractFunctionalTestCase extends AbstractHttpControllerTestCase
{
protected function setUp(): void
{
$this->setApplicationConfig(require dirname(__DIR__) . '/../config/application.config.php');
parent::setUp();
$this->configureServiceManager($this->getApplicationServiceLocator());
}
protected function tearDown(): void
{
// TODO: clear the db data.
}
public static function setUpBeforeClass(): void
{
// Creates the DB with initial data, executes all the migrations.
shell_exec(getenv('TESTS_DIR') . '/scripts/setup_db.sh');
}
public static function tearDownAfterClass(): void
{
// TODO: drop the database or clear the phinxlog table and all the data.
}
protected function configureServiceManager(ServiceManager $serviceManager)
{
}
}

View File

@ -0,0 +1,136 @@
<?php declare(strict_types=1);
namespace MonarcAppFo\Tests\Functional\Controller;
use Monarc\Core\Model\Table\UserTable;
use Monarc\Core\Service\AuthenticationService;
use Monarc\Core\Service\ConnectedUserService;
use Monarc\Core\Model\Entity\UserRole;
use Monarc\FrontOffice\Controller\ApiAdminUsersController;
use Monarc\FrontOffice\Model\Entity\User;
use MonarcAppFo\Tests\Functional\AbstractFunctionalTestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Laminas\Http\Header\HeaderInterface;
use Laminas\ServiceManager\ServiceManager;
class ApiAdminUsersControllerTest extends AbstractFunctionalTestCase
{
//protected $traceError = false;
/** @var ConnectedUserService */
private $connectedUserService;
/** @var AuthenticationService|MockObject */
private $authenticationService;
protected function configureServiceManager(ServiceManager $serviceManager)
{
$serviceManager->setAllowOverride(true);
$this->connectedUserService = $this->createMock(ConnectedUserService::class);
$serviceManager->setService(ConnectedUserService::class, $this->connectedUserService);
$this->authenticationService = $this->createMock(AuthenticationService::class);
$serviceManager->setService(AuthenticationService::class, $this->authenticationService);
$serviceManager->setAllowOverride(false);
}
public function testUserCreationByAdminUser()
{
$user = $this->createMock(User::class);
$user->method('getRoles')->willReturn([UserRole::SUPER_ADMIN_FO]);
$user->method('getId')->willReturn(1);
$this->connectedUserService->method('getConnectedUser')->willReturn($user);
$header = $this->createMock(HeaderInterface::class);
$header->method('getFieldName')->willReturn('token');
$header->method('getFieldValue')->willReturn('token-value');
$this->getRequest()->getHeaders()->addHeader($header);
$this->authenticationService
->expects($this->once())
->method('checkConnect')
->with(['token' => 'token-value'])
->willReturn(true);
$email = 'testlast@gmail.com';
$this->dispatch('/api/users', 'POST', [
'firstname' => 'test',
'lastname' => 'testlast',
'email' => $email,
'role' => [UserRole::USER_FO],
], true);
$this->assertModuleName('Monarc');
$this->assertControllerName(ApiAdminUsersController::class);
$this->assertMatchedRouteName('monarc_api_admin_users');
$this->assertResponseStatusCode(200);
$this->assertEquals('{"status":"ok"}', $this->getResponse()->getContent());
$this->removeTestUser($email);
}
public function testUserCreationFailsWhenEmailIsAlreadyExist()
{
$user = $this->createMock(User::class);
$user->method('getRoles')->willReturn([UserRole::SUPER_ADMIN_FO]);
$user->method('getId')->willReturn(1);
$this->connectedUserService->method('getConnectedUser')->willReturn($user);
$header = $this->createMock(HeaderInterface::class);
$header->method('getFieldName')->willReturn('token');
$header->method('getFieldValue')->willReturn('token-value');
$this->getRequest()->getHeaders()->addHeader($header);
$this->authenticationService
->expects($this->once())
->method('checkConnect')
->with(['token' => 'token-value'])
->willReturn(true);
$email = 'testlast@gmail.com';
$this->createTestUser($email);
$this->dispatch('/api/users', 'POST', [
'firstname' => 'test',
'lastname' => 'testlast',
'email' => $email,
'role' => [UserRole::USER_FO],
], true);
$this->assertModuleName('Monarc');
$this->assertControllerName(ApiAdminUsersController::class);
$this->assertMatchedRouteName('monarc_api_admin_users');
$this->assertResponseStatusCode(400);
$this->assertStringContainsString('This email is already used', $this->getResponse()->getContent());
$this->removeTestUser($email);
}
protected function createTestUser(string $email): User
{
/** @var UserTable $userTable */
$userTable = $this->getApplicationServiceLocator()->get(UserTable::class);
$user = new User([
'email' => $email,
'firstname' => 'firstname',
'lastname' => 'lastname',
'language' => 'fr',
'creator' => 'Test',
'role' => [],
]);
$userTable->saveEntity($user);
return $user;
}
protected function removeTestUser(string $email): void
{
/** @var UserTable $userTable */
$userTable = $this->getApplicationServiceLocator()->get(UserTable::class);
$userTable->deleteEntity($userTable->findByEmail($email));
}
}

13
tests/bootstrap.php Normal file
View File

@ -0,0 +1,13 @@
<?php declare(strict_types=1);
chdir(dirname(__DIR__));
if (date_default_timezone_get() !== ini_get('date.timezone')) {
date_default_timezone_set('Europe/Luxembourg');
}
putenv('APP_CONF_DIR=' . dirname(__DIR__) . '/tests/config');
putenv('TESTS_DIR=' . dirname(__DIR__) . '/tests');
putenv('APPLICATION_ENV=testing');
require dirname(__DIR__) . '/vendor/autoload.php';

0
tests/config/data/cache/.gitkeep vendored Normal file
View File

85
tests/config/local.php Normal file
View File

@ -0,0 +1,85 @@
<?php
use Doctrine\DBAL\Driver\PDOSqlite\Driver;
$appdir = dirname(__DIR__);
return [
'doctrine' => [
'connection' => [
'orm_default' => [
'params' => array(
'host' => 'localhost',
'user' => 'sqlmonarcuser',
'password' => 'sqlmonarcuser',
'dbname' => 'monarc_common_test',
'port' => 3306,
),
],
'orm_cli' => [
'params' => array(
'host' => 'localhost',
'user' => 'sqlmonarcuser',
'password' => 'sqlmonarcuser',
'dbname' => 'monarc_cli_test',
'port' => 3306,
),
],
],
'entitymanager' => [
'orm_default' => [
'connection' => 'orm_default',
'configuration' => 'orm_default'
],
'orm_cli' => [
'connection' => 'orm_cli',
'configuration' => 'orm_cli',
],
],
'configuration' => [
'orm_default' => [
'metadata_cache' => 'array',
'query_cache' => 'array',
'result_cache' => 'array',
'driver' => 'orm_default',
'generate_proxies' => false,
'filters' => [],
'datetime_functions' => [],
'string_functions' => [],
'numeric_functions' => [],
'second_level_cache' => [],
],
'orm_cli' => [
'metadata_cache' => 'array',
'query_cache' => 'array',
'result_cache' => 'array',
'driver' => 'orm_cli',
'generate_proxies' => false,
'filters' => [],
'datetime_functions' => [],
'string_functions' => [],
'numeric_functions' => [],
'second_level_cache' => [],
],
],
],
'activeLanguages' => ['fr', 'en', 'de', 'nl',],
'appVersion' => '3.0.0',
'checkVersion' => false,
'appCheckingURL' => 'https://version.monarc.lu/check/MONARC',
'email' => [
'name' => 'MONARC',
'from' => 'info@monarc.lu',
],
'mospApiUrl' => 'https://objects.monarc.lu/api/v1/',
'monarc' => [
'ttl' => 60,
'salt' => '',
],
];

17
tests/scripts/setup_db.sh Normal file
View File

@ -0,0 +1,17 @@
#!/bin/bash
DBUSER_MONARC='sqlmonarcuser'
DBPASSWORD_MONARC="sqlmonarcuser"
mysql -u $DBUSER_MONARC -p$DBPASSWORD_MONARC -e "CREATE DATABASE IF NOT EXISTS monarc_cli_test DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;" > /dev/null
# Check if the database is already exist we don't need to create the structure and import the data.
if ! mysql -u $DBUSER_MONARC -p$DBPASSWORD_MONARC -e 'use monarc_common_test'; then
mysql -u $DBUSER_MONARC -p$DBPASSWORD_MONARC -e "CREATE DATABASE monarc_common_test DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;" > /dev/null
mysql -u $DBUSER_MONARC -p$DBPASSWORD_MONARC monarc_common_test < db-bootstrap/monarc_structure.sql > /dev/null
mysql -u $DBUSER_MONARC -p$DBPASSWORD_MONARC monarc_common_test < db-bootstrap/monarc_data.sql > /dev/null
fi
php bin/phinx migrate -c tests/migrations/phinx_core.php
php bin/phinx migrate -c tests/migrations/phinx_frontoffice.php

View File

@ -37,3 +37,11 @@ The username is *admin@admin.localhost* and the password is *admin*.
You can now edit the source code with your favorite editor and test it in your
browser. The only thing is to not forget to restart Apache in the VM after a
modification.
------------------------------
Run tests.
The test can be run from Monarc root folder (/home/ubuntu/monarc) of your vagrant VM (params in square brackets are optional):
sudo ./bin/phpunit [--testsuite Functional | --testsuite Integration | --testsuite Unit]
In case of changing the DB configuration (tests/local.php) you can run them from your host machine.

View File

@ -18,6 +18,10 @@ post_max_size=50M
max_execution_time=100
max_input_time=223
memory_limit=512M
# session expires in 1 week:
session.gc_maxlifetime=604800
session.gc_probability=1
session.gc_divisor=1000
PHP_INI=/etc/php/7.2/apache2/php.ini
X_DEBUG_CFG=/etc/php/7.2/apache2/conf.d/20-xdebug.ini
MARIA_DB_CFG=/etc/mysql/mariadb.conf.d/50-server.cnf