cs: Fix code style (safe rules only).

This commit is contained in:
Pol Dellaiera
2021-11-23 14:06:38 +01:00
parent 149d7ce991
commit 8f96a1121d
1223 changed files with 65199 additions and 64625 deletions

View File

@@ -1,11 +1,22 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Security\Authorization;
use Chill\MainBundle\Security\ParentRoleHelper;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* @internal
* @coversNothing
*/
class ParentRoleHelperTest extends KernelTestCase
{
private ParentRoleHelper $parentRoleHelper;

View File

@@ -1,36 +1,35 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Controller;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Repository\AddressRepository;
use Chill\MainBundle\Test\PrepareClientTrait;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
/**
* @internal
* @coversNothing
*/
class AddressControllerTest extends \Symfony\Bundle\FrameworkBundle\Test\WebTestCase
{
private KernelBrowser $client;
use PrepareClientTrait;
private KernelBrowser $client;
public function setUp()
{
self::bootKernel();
$this->client = $this->getClientAuthenticated();
}
/**
* @dataProvider generateAddressIds
* @param int $addressId
*/
public function testDuplicate(int $addressId)
{
$this->client->request('POST', "/api/1.0/main/address/$addressId/duplicate.json");
$this->assertResponseIsSuccessful('test that duplicate is successful');
}
public function generateAddressIds()
{
self::bootKernel();
@@ -43,7 +42,17 @@ class AddressControllerTest extends \Symfony\Bundle\FrameworkBundle\Test\WebTest
->getResult();
foreach ($addresses as $a) {
yield [ $a->getId() ];
yield [$a->getId()];
}
}
/**
* @dataProvider generateAddressIds
*/
public function testDuplicate(int $addressId)
{
$this->client->request('POST', "/api/1.0/main/address/{$addressId}/duplicate.json");
$this->assertResponseIsSuccessful('test that duplicate is successful');
}
}

View File

@@ -1,52 +1,71 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
* @coversNothing
*/
class CenterControllerTest extends WebTestCase
{
public function testCompleteScenario()
{
// Create a new client to browse the application
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR'
));
$client = static::createClient([], [
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR',
]);
// Create a new entry in the database
$crawler = $client->request('GET', '/fr/admin/center/');
$this->assertEquals(200, $client->getResponse()->getStatusCode(),
"Unexpected HTTP status code for GET /fr/admin/center/");
$this->assertEquals(
200,
$client->getResponse()->getStatusCode(),
'Unexpected HTTP status code for GET /fr/admin/center/'
);
$crawler = $client->click($crawler->selectLink('Créer un nouveau centre')->link());
// Fill in the form and submit it
$form = $crawler->selectButton('Créer')->form(array(
'chill_mainbundle_center[name]' => 'Test center',
));
$form = $crawler->selectButton('Créer')->form([
'chill_mainbundle_center[name]' => 'Test center',
]);
$client->submit($form);
$crawler = $client->followRedirect();
// Check data in the show view
$this->assertGreaterThan(0,
$crawler->filter('td:contains("Test center")')->count(),
'Missing element td:contains("Test center")');
$this->assertGreaterThan(
0,
$crawler->filter('td:contains("Test center")')->count(),
'Missing element td:contains("Test center")'
);
// Edit the entity
$crawler = $client->click($crawler->selectLink('Modifier')->link());
$form = $crawler->selectButton('Mettre à jour')->form(array(
'chill_mainbundle_center[name]' => 'Foo',
));
$form = $crawler->selectButton('Mettre à jour')->form([
'chill_mainbundle_center[name]' => 'Foo',
]);
$client->submit($form);
$crawler = $client->followRedirect();
// Check the element contains an attribute with value equals "Foo"
$this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(),
'Missing element [value="Foo"]');
$this->assertGreaterThan(
0,
$crawler->filter('[value="Foo"]')->count(),
'Missing element [value="Foo"]'
);
$crawler = $client->request('GET', '/fr/admin/center/');

View File

@@ -1,20 +1,10 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Controller;
@@ -22,24 +12,26 @@ namespace Chill\MainBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Test the export
* Test the export.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class ExportControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR'
));
$client = static::createClient([], [
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR',
]);
$client->request('GET', '/fr/exports/');
$this->assertTrue($client->getResponse()->isSuccessful(),
"assert the list is shown");
$this->assertTrue(
$client->getResponse()->isSuccessful(),
'assert the list is shown'
);
}
}

View File

@@ -1,10 +1,21 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;
/**
* @internal
* @coversNothing
*/
class LoginControllerTest extends WebTestCase
{
public function testLogin()
@@ -14,47 +25,44 @@ class LoginControllerTest extends WebTestCase
//load login page and submit form
$crawler = $client->request('GET', '/login');
$this->assertTrue($client->getResponse()->isSuccessful());
$buttonCrawlerNode = $crawler->selectButton('login');
$form = $buttonCrawlerNode->form();
$client->submit($form, array(
'_username' => 'center a_social',
'_password' => 'password'
));
$client->submit($form, [
'_username' => 'center a_social',
'_password' => 'password',
]);
//the response is a redirection
$this->assertTrue($client->getResponse()->isRedirect());
//the response is not a login page, but on a new page
$this->assertNotRegExp('/\/login$/', $client->getResponse()
->headers
->get('location'));
->headers
->get('location'));
//on the home page, there must be a logout link
$client->followRedirects(true);
$crawler = $client->request('GET', '/');
$this->assertRegExp('/center a_social/', $client->getResponse()
->getContent());
->getContent());
$logoutLinkFilter = $crawler->filter('a:contains("Se déconnecter")');
//check there is > 0 logout link
$this->assertGreaterThan(0, $logoutLinkFilter->count(), 'check that a logout link is present');
//click on logout link
$client->followRedirects(false);
$client->click($crawler->selectLink('Se déconnecter')->link());
$this->assertTrue($client->getResponse()->isRedirect());
$client->followRedirect(); #redirect to login page
$client->followRedirect(); //redirect to login page
//check we are back on login page
$this->assertRegExp('/\/login$/', $client->getResponse()
->headers
->get('location'));
->headers
->get('location'));
}
}

View File

@@ -1,15 +1,27 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
* @coversNothing
*/
class PermissionsGroupControllerTest extends WebTestCase
{
public function testEmpty()
{
$this->markTestSkipped();
}
/*
public function testCompleteScenario()
{
@@ -55,5 +67,5 @@ class PermissionsGroupControllerTest extends WebTestCase
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
*/
}

View File

@@ -1,30 +1,44 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
* @coversNothing
*/
class ScopeControllerTest extends WebTestCase
{
public function testCompleteScenario()
{
// Create a new client to browse the application
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR'
));
$client = static::createClient([], [
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR',
]);
// Create a new entry in the database
$crawler = $client->request('GET', '/fr/admin/scope/');
$this->assertEquals(200, $client->getResponse()->getStatusCode(),
"Unexpected HTTP status code for GET /fr/admin/scope/");
$this->assertEquals(
200,
$client->getResponse()->getStatusCode(),
'Unexpected HTTP status code for GET /fr/admin/scope/'
);
$crawler = $client->click($crawler->selectLink('Créer un nouveau cercle')->link());
// Fill in the form and submit it
$form = $crawler->selectButton('Créer')->form(array(
'chill_mainbundle_scope[name][fr]' => 'Test en fr',
'chill_mainbundle_scope[name][en]' => 'Test en en'
));
$form = $crawler->selectButton('Créer')->form([
'chill_mainbundle_scope[name][fr]' => 'Test en fr',
'chill_mainbundle_scope[name][en]' => 'Test en en',
]);
$client->submit($form/*, array(
'chill_mainbundle_scope' => array(
@@ -36,25 +50,26 @@ class ScopeControllerTest extends WebTestCase
)
)*/);
$crawler = $client->followRedirect();
// Check data in the show view
$this->assertGreaterThan(0, $crawler->filter('td:contains("Test en fr")')->count(),
'Missing element td:contains("Test en fr")');
$this->assertGreaterThan(
0,
$crawler->filter('td:contains("Test en fr")')->count(),
'Missing element td:contains("Test en fr")'
);
// Edit the entity
$crawler = $client->click($crawler->selectLink('Modifier')->link());
$form = $crawler->selectButton('Mettre à jour')->form(array(
'chill_mainbundle_scope[name][fr]' => 'Foo',
'chill_mainbundle_scope[name][en]' => 'Foo en',
));
$form = $crawler->selectButton('Mettre à jour')->form([
'chill_mainbundle_scope[name][fr]' => 'Foo',
'chill_mainbundle_scope[name][en]' => 'Foo en',
]);
$client->submit($form);
$crawler = $client->followRedirect();
// Check the element contains an attribute with value equals "Foo"
$this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]');
}
}

View File

@@ -1,15 +1,37 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Bundle\ChillMainBundle\Tests\Controller;
use Chill\MainBundle\Test\PrepareClientTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
/**
* @internal
* @coversNothing
*/
class SearchApiControllerTest extends WebTestCase
{
use PrepareClientTrait;
public function generateSearchData()
{
yield ['per', ['person', 'thirdparty']];
yield ['per', ['thirdparty']];
yield ['per', ['person']];
yield ['fjklmeqjfkdqjklrmefdqjklm', ['person', 'thirdparty']];
}
/**
* @dataProvider generateSearchData
*/
@@ -20,17 +42,9 @@ class SearchApiControllerTest extends WebTestCase
$client->request(
Request::METHOD_GET,
'/api/1.0/search.json',
[ 'q' => $pattern, 'type' => $types ]
['q' => $pattern, 'type' => $types]
);
$this->assertResponseIsSuccessful();
}
public function generateSearchData()
{
yield ['per', ['person', 'thirdparty'] ];
yield ['per', ['thirdparty'] ];
yield ['per', ['person'] ];
yield ['fjklmeqjfkdqjklrmefdqjklm', ['person', 'thirdparty'] ];
}
}

View File

@@ -1,102 +1,98 @@
<?php
/*
/**
* Chill is a software for social workers
* Copyright (C) 2015 Champs-Libres Coopérative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Chill\MainBundle\Search\SearchInterface;
/**
* Test the search controller
* Test the search controller.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class SearchControllerTest extends WebTestCase
{
public function testDomainUnknow()
{
$client = $this->getAuthenticatedClient();
$crawler = $client->request('GET', '/fr/search', ['q' => '@unknow domain']);
$this->assertTrue(
$client->getResponse()->isSuccessful(),
'The page is loaded without errors'
);
$this->assertGreaterThan(
0,
$crawler->filter('*:contains("Le domaine de recherche "unknow" est inconnu.")')->count(),
'Message domain unknow is shown'
);
}
public function testParsingIncorrect()
{
$client = $this->getAuthenticatedClient();
$crawler = $client->request(
'GET',
'/fr/search',
['q' => '@domaine @domain double domaine']
);
$this->assertGreaterThan(0, $crawler->filter('*:contains("Recherche invalide")')
->count());
}
/**
* Test the behaviour when no domain is provided in the search pattern :
* the default search should be enabled
* Test the behaviour when no domain is provided in the search pattern :
* the default search should be enabled.
*/
public function testSearchPath()
{
$client = $this->getAuthenticatedClient();
$crawler = $client->request('GET', '/fr/search', array('q' => 'default search'));
$this->assertTrue($client->getResponse()->isSuccessful(),
"The page is loaded without errors");
$crawler = $client->request('GET', '/fr/search', ['q' => 'default search']);
$this->assertTrue(
$client->getResponse()->isSuccessful(),
'The page is loaded without errors'
);
}
public function testSearchPathEmpty()
{
$client = $this->getAuthenticatedClient();
$crawler = $client->request('GET', '/fr/search?q=');
$this->assertGreaterThan(0, $crawler->filter('*:contains("Merci de fournir des termes de recherche.")')->count());
}
public function testDomainUnknow()
{
$client = $this->getAuthenticatedClient();
$crawler = $client->request('GET', '/fr/search', array('q' => '@unknow domain'));
$this->assertTrue($client->getResponse()->isSuccessful(),
"The page is loaded without errors");
$this->assertGreaterThan(0, $crawler->filter('*:contains("Le domaine de recherche "unknow" est inconnu.")')->count(),
"Message domain unknow is shown");
}
public function testParsingIncorrect()
{
$client = $this->getAuthenticatedClient();
$crawler = $client->request('GET', '/fr/search',
array('q' => '@domaine @domain double domaine'));
$this->assertGreaterThan(0, $crawler->filter('*:contains("Recherche invalide")')
->count());
}
public function testUnknowName()
{
$client = $this->getAuthenticatedClient();
$client->request('GET', '/fr/search',
array('q' => 'default search', 'name' => 'unknow'));
$client->request(
'GET',
'/fr/search',
['q' => 'default search', 'name' => 'unknow']
);
$this->assertTrue($client->getResponse()->isNotFound());
}
private function getAuthenticatedClient()
{
return static::createClient(array(), array(
'PHP_AUTH_USER' => 'center b_social',
'PHP_AUTH_PW' => 'password',
));
return static::createClient([], [
'PHP_AUTH_USER' => 'center b_social',
'PHP_AUTH_PW' => 'password',
]);
}
}

View File

@@ -1,15 +1,42 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Controller;
use Chill\MainBundle\Test\PrepareClientTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
use function array_key_exists;
use function json_decode;
/**
* @internal
* @coversNothing
*/
class UserApiControllerTest extends WebTestCase
{
use PrepareClientTrait;
/**
* @depends testIndex
*
* @param mixed $existingUser
*/
public function testEntity($existingUser)
{
$client = $this->getClientAuthenticated();
$client->request(Request::METHOD_GET, '/api/1.0/main/user/' . $existingUser['id'] . '.json');
$this->assertResponseIsSuccessful();
}
public function testIndex()
{
$client = $this->getClientAuthenticated();
@@ -18,26 +45,14 @@ class UserApiControllerTest extends WebTestCase
$this->assertResponseIsSuccessful();
$data = \json_decode($client->getResponse()->getContent(), true);
$this->assertTrue(\array_key_exists('count', $data));
$data = json_decode($client->getResponse()->getContent(), true);
$this->assertTrue(array_key_exists('count', $data));
$this->assertGreaterThan(0, $data['count']);
$this->assertTrue(\array_key_exists('results', $data));
$this->assertTrue(array_key_exists('results', $data));
return $data['results'][0];
}
/**
* @depends testIndex
*/
public function testEntity($existingUser)
{
$client = $this->getClientAuthenticated();
$client->request(Request::METHOD_GET, '/api/1.0/main/user/'.$existingUser['id'].'.json');
$this->assertResponseIsSuccessful();
}
public function testWhoami()
{
$client = $this->getClientAuthenticated();

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Controller;
use Chill\MainBundle\Entity\User;
@@ -7,6 +14,10 @@ use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
/**
* @internal
* @coversNothing
*/
class UserControllerTest extends WebTestCase
{
private $client;
@@ -17,102 +28,11 @@ class UserControllerTest extends WebTestCase
{
self::bootKernel();
$this->client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR'
));
}
public function testList()
{
// get the list
$crawler = $this->client->request('GET', '/fr/admin/main/user');
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(),
"Unexpected HTTP status code for GET /admin/main/user");
}
public function testNew()
{
$crawler = $this->client->request('GET', '/fr/admin/main/user/new');
$username = 'Test_user'. uniqid();
$password = 'Password1234!';
// Fill in the form and submit it
$form = $crawler->selectButton('Créer')->form(array(
'chill_mainbundle_user[username]' => $username,
'chill_mainbundle_user[plainPassword][first]' => $password,
'chill_mainbundle_user[plainPassword][second]' => $password,
'chill_mainbundle_user[email]' => $username.'@gmail.com',
'chill_mainbundle_user[label]' => $username,
));
$this->client->submit($form);
$crawler = $this->client->followRedirect();
// Check data in the show view
$this->assertGreaterThan(0, $crawler->filter('td:contains("Test_user")')->count(),
'Missing element td:contains("Test user")');
//test the auth of the new client
$this->isPasswordValid($username, $password);
}
protected function isPasswordValid($username, $password)
{
/* @var $passwordEncoder \Symfony\Component\Security\Core\Encoder\UserPasswordEncoder */
$passwordEncoder = self::$container
->get(UserPasswordEncoderInterface::class);
$user = self::$kernel->getContainer()
->get('doctrine.orm.entity_manager')
->getRepository('ChillMainBundle:User')
->findOneBy(array('username' => $username));
$this->assertTrue($passwordEncoder->isPasswordValid($user, $password));
}
/**
*
* @dataProvider dataGenerateUserId
*/
public function testUpdate(int $userId, string $username)
{
$crawler = $this->client->request('GET', "/fr/admin/main/user/$userId/edit");
$username = 'Foo bar '.uniqid();
$form = $crawler->selectButton('Enregistrer & fermer')->form(array(
'chill_mainbundle_user[username]' => $username,
));
$this->client->submit($form);
$crawler = $this->client->followRedirect();
// Check the element contains an attribute with value equals "Foo"
$this->assertGreaterThan(0, $crawler->filter('[data-username="'.$username.'"]')->count(),
'Missing element [data-username="Foo bar"]');
}
/**
*
* @dataProvider dataGenerateUserId
*/
public function testUpdatePassword(int $userId, $username)
{
$crawler = $this->client->request('GET', "/fr/admin/user/$userId/edit_password");
$newPassword = '1234Password!';
$form = $crawler->selectButton('Changer le mot de passe')->form(array(
'chill_mainbundle_user_password[new_password][first]' => $newPassword,
'chill_mainbundle_user_password[new_password][second]' => $newPassword,
));
$this->client->submit($form);
$this->assertTrue($this->client->getResponse()->isRedirect(),
"the response is a redirection");
$this->isPasswordValid($username, $newPassword);
$this->client = static::createClient([], [
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR',
]);
}
protected function tearDown()
@@ -120,7 +40,7 @@ class UserControllerTest extends WebTestCase
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
foreach ($this->toDelete as list($class, $id)) {
foreach ($this->toDelete as [$class, $id]) {
$obj = $em->getRepository($class)->find($id);
$em->remove($obj);
}
@@ -134,15 +54,118 @@ class UserControllerTest extends WebTestCase
$em = self::$container->get(EntityManagerInterface::class);
$user = new User();
$user->setUsername('Test_user '.uniqid());
$user->setPassword(self::$container->get(UserPasswordEncoderInterface::class)->encodePassword($user,
'password'));
$user->setUsername('Test_user ' . uniqid());
$user->setPassword(self::$container->get(UserPasswordEncoderInterface::class)->encodePassword(
$user,
'password'
));
$em->persist($user);
$em->flush();
$this->toDelete[] = [User::class, $user->getId()];
yield [ $user->getId(), $user->getUsername() ];
yield [$user->getId(), $user->getUsername()];
}
public function testList()
{
// get the list
$crawler = $this->client->request('GET', '/fr/admin/main/user');
$this->assertEquals(
200,
$this->client->getResponse()->getStatusCode(),
'Unexpected HTTP status code for GET /admin/main/user'
);
}
public function testNew()
{
$crawler = $this->client->request('GET', '/fr/admin/main/user/new');
$username = 'Test_user' . uniqid();
$password = 'Password1234!';
// Fill in the form and submit it
$form = $crawler->selectButton('Créer')->form([
'chill_mainbundle_user[username]' => $username,
'chill_mainbundle_user[plainPassword][first]' => $password,
'chill_mainbundle_user[plainPassword][second]' => $password,
'chill_mainbundle_user[email]' => $username . '@gmail.com',
'chill_mainbundle_user[label]' => $username,
]);
$this->client->submit($form);
$crawler = $this->client->followRedirect();
// Check data in the show view
$this->assertGreaterThan(
0,
$crawler->filter('td:contains("Test_user")')->count(),
'Missing element td:contains("Test user")'
);
//test the auth of the new client
$this->isPasswordValid($username, $password);
}
/**
* @dataProvider dataGenerateUserId
*/
public function testUpdate(int $userId, string $username)
{
$crawler = $this->client->request('GET', "/fr/admin/main/user/{$userId}/edit");
$username = 'Foo bar ' . uniqid();
$form = $crawler->selectButton('Enregistrer & fermer')->form([
'chill_mainbundle_user[username]' => $username,
]);
$this->client->submit($form);
$crawler = $this->client->followRedirect();
// Check the element contains an attribute with value equals "Foo"
$this->assertGreaterThan(
0,
$crawler->filter('[data-username="' . $username . '"]')->count(),
'Missing element [data-username="Foo bar"]'
);
}
/**
* @dataProvider dataGenerateUserId
*
* @param mixed $username
*/
public function testUpdatePassword(int $userId, $username)
{
$crawler = $this->client->request('GET', "/fr/admin/user/{$userId}/edit_password");
$newPassword = '1234Password!';
$form = $crawler->selectButton('Changer le mot de passe')->form([
'chill_mainbundle_user_password[new_password][first]' => $newPassword,
'chill_mainbundle_user_password[new_password][second]' => $newPassword,
]);
$this->client->submit($form);
$this->assertTrue(
$this->client->getResponse()->isRedirect(),
'the response is a redirection'
);
$this->isPasswordValid($username, $newPassword);
}
protected function isPasswordValid($username, $password)
{
/* @var $passwordEncoder \Symfony\Component\Security\Core\Encoder\UserPasswordEncoder */
$passwordEncoder = self::$container
->get(UserPasswordEncoderInterface::class);
$user = self::$kernel->getContainer()
->get('doctrine.orm.entity_manager')
->getRepository('ChillMainBundle:User')
->findOneBy(['username' => $username]);
$this->assertTrue($passwordEncoder->isPasswordValid($user, $password));
}
}

View File

@@ -1,49 +1,73 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Doctrine\Model;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Chill\MainBundle\Doctrine\Model\Point;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* Test the point model methods
* Test the point model methods.
*
* @author Julien Minet <julien.minet@champs-libres.coop>
* @internal
* @coversNothing
*/
class ExportControllerTest extends KernelTestCase
{
public function testToWKT()
public function testFromArrayGeoJson()
{
$array = [
'type' => 'Point',
'coordinates' => [4.8634, 50.47382],
];
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);
$this->assertEquals($point->toWKT(),'SRID=4326;POINT(4.8634 50.47382)');
$this->assertEquals($point, Point::fromArrayGeoJson($array));
}
public function testToGeojson()
public function testFromGeoJson()
{
$geojson = '{"type":"Point","coordinates":[4.8634,50.47382]}';
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);
$this->assertEquals($point->toGeoJson(),'{"type":"Point","coordinates":[4.8634,50.47382]}');
$this->assertEquals($point, Point::fromGeoJson($geojson));
}
public function testToArrayGeoJson()
public function testFromLonLat()
{
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);
$this->assertEquals(
$point->toArrayGeoJson(),
[
'type' => 'Point',
'coordinates' => [4.8634, 50.47382]
]
);
$this->assertEquals($point, Point::fromLonLat($lon, $lat));
}
public function testGetLat()
{
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);
$this->assertEquals($lat, $point->getLat());
}
public function testGetLon()
{
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);
$this->assertEquals($lon, $point->getLon());
}
public function testJsonSerialize()
@@ -56,64 +80,46 @@ class ExportControllerTest extends KernelTestCase
$point->jsonSerialize(),
[
'type' => 'Point',
'coordinates' => [4.8634, 50.47382]
'coordinates' => [4.8634, 50.47382],
]
);
}
public function testFromGeoJson()
public function testToArrayGeoJson()
{
$geojson = '{"type":"Point","coordinates":[4.8634,50.47382]}';
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);;
$point = $this->preparePoint($lon, $lat);
$this->assertEquals($point, Point::fromGeoJson($geojson));
$this->assertEquals(
$point->toArrayGeoJson(),
[
'type' => 'Point',
'coordinates' => [4.8634, 50.47382],
]
);
}
public function testFromLonLat()
public function testToGeojson()
{
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);;
$point = $this->preparePoint($lon, $lat);
$this->assertEquals($point, Point::fromLonLat($lon, $lat));
$this->assertEquals($point->toGeoJson(), '{"type":"Point","coordinates":[4.8634,50.47382]}');
}
public function testFromArrayGeoJson()
{
$array = [
'type' => 'Point',
'coordinates' => [4.8634, 50.47382]
];
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);;
$this->assertEquals($point, Point::fromArrayGeoJson($array));
}
public function testGetLat()
public function testToWKT()
{
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);;
$point = $this->preparePoint($lon, $lat);
$this->assertEquals($lat, $point->getLat());
}
public function testGetLon()
{
$lon = 4.8634;
$lat = 50.47382;
$point = $this->preparePoint($lon, $lat);;
$this->assertEquals($lon, $point->getLon());
$this->assertEquals($point->toWKT(), 'SRID=4326;POINT(4.8634 50.47382)');
}
private function preparePoint($lon, $lat)
{
return Point::fromLonLat($lon, $lat);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,83 +1,26 @@
<?php
/*
* Copyright (C) 2015 Julien Fastré <julien.fastre@champs-libres.coop>
/**
* Chill is a software for social workers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Form\Type;
use Symfony\Component\Form\Test\TypeTestCase;
use Chill\MainBundle\Form\Type\CenterType;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\GroupCenter;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Chill\MainBundle\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Test\TypeTestCase;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class CenterTypeTest extends TypeTestCase
{
/**
* Test that a user which can reach only one center
* render as an hidden field
*/
public function testUserCanReachSingleCenter()
{
$this->markTestSkipped();
//prepare user
$center = $this->prepareCenter(1, 'center');
$groupCenter = (new GroupCenter())
->setCenter($center)
;
$user = (new User())
->addGroupCenter($groupCenter);
$type = $this->prepareType($user);
$this->assertEquals(HiddenType::class, $type->getParent());
}
/**
* Test that a user which can reach only one center
* render as an hidden field
*/
public function testUserCanReachMultipleSameCenter()
{
$this->markTestSkipped();
//prepare user
$center = $this->prepareCenter(1, 'center');
$groupCenterA = (new GroupCenter())
->setCenter($center)
;
$groupCenterB = (new GroupCenter())
->setCenter($center)
;
$user = (new User())
->addGroupCenter($groupCenterA)
->addGroupCenter($groupCenterB);
$type = $this->prepareType($user);
$this->assertEquals(HiddenType::class, $type->getParent());
}
/**
* Test that a user which can reach multiple center
* make CenterType render as "entity" type.
@@ -89,15 +32,12 @@ class CenterTypeTest extends TypeTestCase
$centerA = $this->prepareCenter(1, 'centerA');
$centerB = $this->prepareCenter(2, 'centerB');
$groupCenterA = (new GroupCenter())
->setCenter($centerA)
;
->setCenter($centerA);
$groupCenterB = (new GroupCenter())
->setCenter($centerB)
;
->setCenter($centerB);
$user = (new User())
->addGroupCenter($groupCenterA)
->addGroupCenter($groupCenterB)
;
->addGroupCenter($groupCenterA)
->addGroupCenter($groupCenterB);
$type = $this->prepareType($user);
@@ -105,15 +45,57 @@ class CenterTypeTest extends TypeTestCase
}
/**
* prepare a mocked center, with and id and name given
* Test that a user which can reach only one center
* render as an hidden field.
*/
public function testUserCanReachMultipleSameCenter()
{
$this->markTestSkipped();
//prepare user
$center = $this->prepareCenter(1, 'center');
$groupCenterA = (new GroupCenter())
->setCenter($center);
$groupCenterB = (new GroupCenter())
->setCenter($center);
$user = (new User())
->addGroupCenter($groupCenterA)
->addGroupCenter($groupCenterB);
$type = $this->prepareType($user);
$this->assertEquals(HiddenType::class, $type->getParent());
}
/**
* Test that a user which can reach only one center
* render as an hidden field.
*/
public function testUserCanReachSingleCenter()
{
$this->markTestSkipped();
//prepare user
$center = $this->prepareCenter(1, 'center');
$groupCenter = (new GroupCenter())
->setCenter($center);
$user = (new User())
->addGroupCenter($groupCenter);
$type = $this->prepareType($user);
$this->assertEquals(HiddenType::class, $type->getParent());
}
/**
* prepare a mocked center, with and id and name given.
*
* @param int $id
* @param string $name
*
* @return \Chill\MainBundle\Entity\Center
*/
private function prepareCenter($id, $name)
{
$prophet = new \Prophecy\Prophet;
$prophet = new \Prophecy\Prophet();
$prophecyCenter = $prophet->prophesize();
$prophecyCenter->willExtend('\Chill\MainBundle\Entity\Center');
@@ -123,36 +105,35 @@ class CenterTypeTest extends TypeTestCase
return $prophecyCenter->reveal();
}
/**
* prepare the type with mocked center transformer and token storage
* prepare the type with mocked center transformer and token storage.
*
* @param User $user the user for wich the form will be prepared
*
* @return CenterType
*/
private function prepareType(User $user)
{
$prophet = new \Prophecy\Prophet;
$prophet = new \Prophecy\Prophet();
//create a center transformer
$centerTransformerProphecy = $prophet->prophesize();
$centerTransformerProphecy
->willExtend('Chill\MainBundle\Form\Type\DataTransformer\CenterTransformer');
->willExtend('Chill\MainBundle\Form\Type\DataTransformer\CenterTransformer');
$transformer = $centerTransformerProphecy->reveal();
$tokenProphecy = $prophet->prophesize();
$tokenProphecy
->willImplement('\Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
->willImplement('\Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
$tokenProphecy->getUser()->willReturn($user);
$token = $tokenProphecy->reveal();
$tokenStorageProphecy = $prophet->prophesize();
$tokenStorageProphecy
->willExtend('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage');
->willExtend('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage');
$tokenStorageProphecy->getToken()->willReturn($token);
$tokenStorage = $tokenStorageProphecy->reveal();
return new CenterType($tokenStorage, $transformer);
}
}

View File

@@ -1,148 +1,135 @@
<?php
/*
/**
* Chill is a software for social workers
* Copyright (C) 2016 Champs-Libres Coopérative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Pagination;
use Chill\MainBundle\Pagination\Page;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Chill\MainBundle\Pagination\Page;
/**
* Test the Page class
* Test the Page class.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
* @internal
* @coversNothing
*/
class PageTest extends KernelTestCase
{
protected $paginator;
protected $prophet;
public function setUp() {
$this->prophet = new \Prophecy\Prophet;
public function setUp()
{
$this->prophet = new \Prophecy\Prophet();
}
/**
*
* @param int $maxResult
* @param int $itemPerPage
* @param string $route
* @param array $routeParameters
* @return Page
*/
protected function generatePage(
$number = 1,
$itemPerPage = 10,
$route = 'route',
array $routeParameters = array(),
$totalItems = 100
) {
$urlGenerator = $this->prophet->prophesize();
$urlGenerator->willImplement(UrlGeneratorInterface::class);
return new Page(
$number,
$itemPerPage,
$urlGenerator->reveal(),
$route,
$routeParameters,
$totalItems
);
}
public function testPageNumber() {
$page = $this->generatePage(1);
$this->assertEquals(1, $page->getNumber());
}
/**
* return a set of element to testGetFirstItemNumber
*
* the set contains :
* return a set of element to testGetFirstItemNumber.
*
* the set contains :
* - the page number ;
* - the number of item per page ;
* - the expected first item number
*
*
* @return array
*/
public function generateGetFirstItemNumber() {
return array(
[1, 10, 0],
[2, 10, 10]
);
public function generateGetFirstItemNumber()
{
return [
[1, 10, 0],
[2, 10, 10],
];
}
/**
* return a set of element to testGetLastItemNumber.
*
* the set contains :
* - the page number ;
* - the number of item per page ;
* - the expected last item number
*
* @return array
*/
public function generateGetLastItemNumber()
{
return [
[1, 10, 9],
[2, 10, 19],
];
}
/**
*
* @param int $number
* @param int $itemPerPage
* @param int $expectedItemPerPage
* @dataProvider generateGetFirstItemNumber
*/
public function testGetFirstItemNumber(
$number,
$itemPerPage,
$expectedItemPerPage
$number,
$itemPerPage,
$expectedItemPerPage
) {
$page = $this->generatePage($number, $itemPerPage);
$this->assertEquals($expectedItemPerPage, $page->getFirstItemNumber());
}
/**
* return a set of element to testGetLastItemNumber
*
* the set contains :
* - the page number ;
* - the number of item per page ;
* - the expected last item number
*
* @return array
*/
public function generateGetLastItemNumber() {
return array(
[1, 10, 9],
[2, 10, 19]
);
}
/**
*
* @param int $number
* @param int $itemPerPage
* @param int $expectedItemPerPage
* @dataProvider generateGetLastItemNumber
*/
public function testGetLastItemNumber(
$number,
$itemPerPage,
$expectedItemPerPage
$number,
$itemPerPage,
$expectedItemPerPage
) {
$page = $this->generatePage($number, $itemPerPage);
$this->assertEquals($expectedItemPerPage, $page->getLastItemNumber());
}
public function testPageNumber()
{
$page = $this->generatePage(1);
$this->assertEquals(1, $page->getNumber());
}
/**
* @param int $itemPerPage
* @param string $route
* @param mixed $number
* @param mixed $totalItems
*
* @return Page
*/
protected function generatePage(
$number = 1,
$itemPerPage = 10,
$route = 'route',
array $routeParameters = [],
$totalItems = 100
) {
$urlGenerator = $this->prophet->prophesize();
$urlGenerator->willImplement(UrlGeneratorInterface::class);
return new Page(
$number,
$itemPerPage,
$urlGenerator->reveal(),
$route,
$routeParameters,
$totalItems
);
}
}

View File

@@ -1,133 +1,110 @@
<?php
/*
/**
* Chill is a software for social workers
* Copyright (C) 2016 Champs-Libres Coopérative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Pagination;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Chill\MainBundle\Pagination\Paginator;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Test the paginator class
* Test the paginator class.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
* @internal
* @coversNothing
*/
class PaginatorTest extends KernelTestCase
{
protected $paginator;
protected $prophet;
public function setUp()
public function setUp()
{
$this->prophet = new \Prophecy\Prophet;
$this->prophet = new \Prophecy\Prophet();
}
/**
*
* @param int $maxResult
* @param int $itemPerPage
* @param string $route
* @param array $routeParameters
* @return Paginator
*/
protected function generatePaginator(
$totalItems,
$itemPerPage,
$currentPageNumber = 1,
$route = '',
array $routeParameters = array()
) {
$urlGenerator = $this->prophet->prophesize();
$urlGenerator->willImplement(UrlGeneratorInterface::class);
return new Paginator(
$totalItems,
$itemPerPage,
$currentPageNumber,
$route,
$routeParameters,
$urlGenerator->reveal(),
'page',
'item_per_page'
);
}
/**
* generate a set of pages with different maxItem, itemPerPage, and
* expected page number
*
* @return array
*/
public function generatePageNumber()
{
return array(
[12, 10, 2],
[20, 10, 2],
[21, 10, 3],
[19, 10, 2],
[1, 10, 1],
[0, 10, 1],
[10, 10, 1]
);
}
/**
* Test that the countPages method (and his alias `count`) return
* valid results.
*
* @param int $totalItems
* @param int $itemPerPage
* @param int $expectedPageNumber
* @dataProvider generatePageNumber
*/
public function testPageNumber($totalItems, $itemPerPage, $expectedPageNumber)
{
$paginator = $this->generatePaginator($totalItems, $itemPerPage);
$this->assertEquals($expectedPageNumber, $paginator->countPages());
$this->assertEquals($expectedPageNumber, count($paginator));
}
/**
* generate an array with a set of page with :
* - total items ;
* - item per page ;
* - current page number ;
* - expected hasNextPage result
*
* - expected hasNextPage result.
*
* @return array
*/
public function generateHasNextPage()
public function generateHasNextPage()
{
return array(
[10, 10, 1, false],
[20, 10, 1, true],
[12, 10, 1, true],
[12, 10, 2, false]
);
return [
[10, 10, 1, false],
[20, 10, 1, true],
[12, 10, 1, true],
[12, 10, 2, false],
];
}
public function generateHasPage()
{
return [
[10, 10, -1, false],
[12, 10, 1, true],
[12, 10, 2, true],
[12, 10, 3, false],
];
}
/**
* generate an array with a set of page with :
* - total items ;
* - item per page ;
* - current page number ;
* - expected hasPreviousPage result.
*
* @return array
*/
public function generateHasPreviousPage()
{
return [
[10, 10, 1, false],
[20, 10, 1, false],
[12, 10, 1, false],
[12, 10, 2, true],
];
}
/**
* generate a set of pages with different maxItem, itemPerPage, and
* expected page number.
*
* @return array
*/
public function generatePageNumber()
{
return [
[12, 10, 2],
[20, 10, 2],
[21, 10, 3],
[19, 10, 2],
[1, 10, 1],
[0, 10, 1],
[10, 10, 1],
];
}
public function testGetPage()
{
$paginator = $this->generatePaginator(105, 10);
$this->assertEquals(5, $paginator->getPage(5)->getNumber());
}
/**
*
* @param int $totalItems
* @param int $itemPerPage
* @param int $currentPage
@@ -135,103 +112,123 @@ class PaginatorTest extends KernelTestCase
* @dataProvider generateHasNextPage
*/
public function testHasNextPage(
$totalItems,
$itemPerPage,
$currentPage,
$expectedHasNextPage
$totalItems,
$itemPerPage,
$currentPage,
$expectedHasNextPage
) {
$paginator = $this->generatePaginator($totalItems, $itemPerPage, $currentPage);
$this->assertEquals($expectedHasNextPage, $paginator->hasNextPage());
}
/**
* generate an array with a set of page with :
* - total items ;
* - item per page ;
* - current page number ;
* - expected hasPreviousPage result
*
* @return array
*/
public function generateHasPreviousPage()
{
return array(
[10, 10, 1, false],
[20, 10, 1, false],
[12, 10, 1, false],
[12, 10, 2, true],
);
}
/**
*
* @param int $totalItems
* @param int $itemPerPage
* @param int $currentPage
* @param bool $expectedHasPreviousPage
* @dataProvider generateHasPreviousPage
*/
public function testHasPreviousPage(
$totalItems,
$itemPerPage,
$currentPage,
$expectedHasNextPage
) {
$paginator = $this->generatePaginator($totalItems, $itemPerPage, $currentPage);
$this->assertEquals($expectedHasNextPage, $paginator->hasPreviousPage());
}
public function generateHasPage()
{
return array(
[10, 10, -1, false],
[12, 10, 1, true],
[12, 10, 2, true],
[12, 10, 3, false]
);
}
/**
* test the HasPage function
*
*
* test the HasPage function.
*
* @param int $totalItems
* @param int $itemPerpage
* @param int $pageNumber
* @param bool $expectedHasPage
* @dataProvider generateHasPage
*/
public function testHasPage($totalItems, $itemPerpage, $pageNumber,
$expectedHasPage)
public function testHasPage(
$totalItems,
$itemPerpage,
$pageNumber,
$expectedHasPage
)
{
$paginator = $this->generatePaginator($totalItems, $itemPerpage);
$this->assertEquals($expectedHasPage, $paginator->hasPage($pageNumber));
}
public function testGetPage()
{
$paginator = $this->generatePaginator(105, 10);
$this->assertEquals(5, $paginator->getPage(5)->getNumber());
/**
* @param int $totalItems
* @param int $itemPerPage
* @param int $currentPage
* @param mixed $expectedHasNextPage
* @dataProvider generateHasPreviousPage
*/
public function testHasPreviousPage(
$totalItems,
$itemPerPage,
$currentPage,
$expectedHasNextPage
) {
$paginator = $this->generatePaginator($totalItems, $itemPerPage, $currentPage);
$this->assertEquals($expectedHasNextPage, $paginator->hasPreviousPage());
}
/**
* Test that the countPages method (and his alias `count`) return
* valid results.
*
* @param int $totalItems
* @param int $itemPerPage
* @param int $expectedPageNumber
* @dataProvider generatePageNumber
*/
public function testPageNumber($totalItems, $itemPerPage, $expectedPageNumber)
{
$paginator = $this->generatePaginator($totalItems, $itemPerPage);
$this->assertEquals($expectedPageNumber, $paginator->countPages());
$this->assertEquals($expectedPageNumber, count($paginator));
}
public function testPagesGenerator()
{
$paginator = $this->generatePaginator(105, 10);
$generator = $paginator->getPagesGenerator();
$i = 1;
foreach($generator as $page) {
$this->assertEquals($i, $page->getNumber(),
"assert that the current page number is $i");
$i++;
foreach ($generator as $page) {
$this->assertEquals(
$i,
$page->getNumber(),
"assert that the current page number is {$i}"
);
++$i;
}
$this->assertEquals(11, $page->getNumber(),
"assert that the last page number is 11");
$this->assertEquals(
11,
$page->getNumber(),
'assert that the last page number is 11'
);
}
/**
* @param int $itemPerPage
* @param string $route
* @param mixed $totalItems
* @param mixed $currentPageNumber
*
* @return Paginator
*/
protected function generatePaginator(
$totalItems,
$itemPerPage,
$currentPageNumber = 1,
$route = '',
array $routeParameters = []
) {
$urlGenerator = $this->prophet->prophesize();
$urlGenerator->willImplement(UrlGeneratorInterface::class);
return new Paginator(
$totalItems,
$itemPerPage,
$currentPageNumber,
$route,
$routeParameters,
$urlGenerator->reveal(),
'page',
'item_per_page'
);
}
}

View File

@@ -1,52 +1,39 @@
<?php
/*
/**
* Chill is a software for social workers
* Copyright (C) 2015 Champs-Libres Coopérative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Routing\Loader;
use Chill\MainBundle\Routing\Loader\ChillRoutesLoader;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* Test the route loader
* Test the route loader.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class RouteLoaderTest extends KernelTestCase
{
private $router;
public function setUp()
{
static::bootKernel();
$this->router = static::$kernel->getContainer()->get('router');
}
/**
* Test that the route loader loads at least homepage
* Test that the route loader loads at least homepage.
*/
public function testRouteFromMainBundleAreLoaded()
{
$homepage = $this->router->getRouteCollection()->get('chill_main_homepage');
$this->assertNotNull($homepage);
}
}

View File

@@ -1,29 +1,19 @@
<?php
/*
* Chill is a suite of a modules, Chill is a software for social workers
* Copyright (C) 2014, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Search;
/**
* Description of AbstractSearch
* Description of AbstractSearch.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class AbstractSearchTest extends \PHPUnit\Framework\TestCase
{
@@ -31,22 +21,21 @@ class AbstractSearchTest extends \PHPUnit\Framework\TestCase
* @var \Chill\MainBundle\Search\AbstractSearch
*/
private $stub;
public function setUp()
{
$this->stub = $this->getMockForAbstractClass('Chill\MainBundle\Search\AbstractSearch');
}
public function testParseDateRegular()
{
$date = $this->stub->parseDate('2014-05-01');
$this->assertEquals('2014', $date->format('Y'));
$this->assertEquals('05', $date->format('m'));
$this->assertEquals('01', $date->format('d'));
}
public function testRecompose()
{
$this->markTestSkipped();

View File

@@ -1,12 +1,39 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Search;
use Chill\MainBundle\Search\SearchApiQuery;
use PHPUnit\Framework\TestCase;
use function is_string;
/**
* @internal
* @coversNothing
*/
class SearchApiQueryTest extends TestCase
{
public function testBuildParams()
{
$q = new SearchApiQuery();
$q
->addSelectClause('bada', ['one', 'two'])
->addSelectClause('boum', ['three', 'four'])
->setWhereClauses('mywhere', ['six', 'seven']);
$params = $q->buildParameters();
$this->assertEquals(['six', 'seven'], $q->buildParameters(true));
$this->assertEquals(['one', 'two', 'three', 'four', 'six', 'seven'], $q->buildParameters());
}
public function testMultipleWhereClauses()
{
$q = new SearchApiQuery();
@@ -14,9 +41,8 @@ class SearchApiQueryTest extends TestCase
->setSelectKey('bim')
->setSelectPertinence('?', ['gamma'])
->setFromClause('badaboum')
->andWhereClause('foo', [ 'alpha' ])
->andWhereClause('bar', [ 'beta' ])
;
->andWhereClause('foo', ['alpha'])
->andWhereClause('bar', ['beta']);
$query = $q->buildQuery();
@@ -35,27 +61,9 @@ class SearchApiQueryTest extends TestCase
$q->setSelectJsonbMetadata('boum')
->setSelectKey('bim')
->setSelectPertinence('1')
->setFromClause('badaboum')
;
->setFromClause('badaboum');
$this->assertTrue(\is_string($q->buildQuery()));
$this->assertTrue(is_string($q->buildQuery()));
$this->assertEquals([], $q->buildParameters());
}
public function testBuildParams()
{
$q = new SearchApiQuery();
$q
->addSelectClause('bada', [ 'one', 'two' ])
->addSelectClause('boum', ['three', 'four'])
->setWhereClauses('mywhere', [ 'six', 'seven'])
;
$params = $q->buildParameters();
$this->assertEquals(['six', 'seven'], $q->buildParameters(true));
$this->assertEquals(['one', 'two', 'three', 'four', 'six', 'seven'], $q->buildParameters());
}
}

View File

@@ -1,34 +1,25 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2014, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Test\Search;
use Chill\MainBundle\Search\SearchProvider;
use Chill\MainBundle\Search\SearchInterface;
use Chill\MainBundle\Search\SearchProvider;
use PHPUnit\Framework\TestCase;
/**
* @internal
* @coversNothing
*/
class SearchProviderTest extends TestCase
{
/**
*
* @var SearchProvider
*/
private $search;
@@ -39,85 +30,14 @@ class SearchProviderTest extends TestCase
//add a default service
$this->addSearchService(
$this->createDefaultSearchService('I am default', 10), 'default'
);
$this->createDefaultSearchService('I am default', 10),
'default'
);
//add a domain service
$this->addSearchService(
$this->createNonDefaultDomainSearchService('I am domain bar', 20, FALSE), 'bar'
);
}
/**
* @expectedException \Chill\MainBundle\Search\UnknowSearchNameException
*/
public function testInvalidSearchName()
{
$this->search->getByName("invalid name");
}
public function testSimplePattern()
{
$terms = $this->p("@person birthdate:2014-01-02 name:\"my name\" is not my name");
$this->assertEquals(array(
'_domain' => 'person',
'birthdate' => '2014-01-02',
'_default' => 'is not my name',
'name' => 'my name'
), $terms);
}
public function testWithoutDomain()
{
$terms = $this->p('foo:bar residual');
$this->assertEquals(array(
'_domain' => null,
'foo' => 'bar',
'_default' => 'residual'
), $terms);
}
public function testWithoutDefault()
{
$terms = $this->p('@person foo:bar');
$this->assertEquals(array(
'_domain' => 'person',
'foo' => 'bar',
'_default' => ''
), $terms);
}
public function testCapitalLetters()
{
$terms = $this->p('Foo:Bar LOL marCi @PERSON');
$this->assertEquals(array(
'_domain' => 'person',
'_default' => 'lol marci',
'foo' => 'bar'
), $terms);
}
/**
* @expectedException Chill\MainBundle\Search\ParsingException
*/
public function testMultipleDomainError()
{
$term = $this->p("@person @report");
}
public function testDoubleParenthesis()
{
$terms = $this->p('@papamobile name:"my beautiful name" residual surname:"i love techno"');
$this->assertEquals(array(
'_domain' => 'papamobile',
'name' => 'my beautiful name',
'_default' => 'residual',
'surname' => 'i love techno'
), $terms);
$this->createNonDefaultDomainSearchService('I am domain bar', 20, false),
'bar'
);
}
public function testAccentued()
@@ -126,10 +46,10 @@ class SearchProviderTest extends TestCase
$terms = $this->p('manço bélier aztèque à saloù ê');
$this->assertEquals(array(
'_domain' => NULL,
'_default' => 'manco belier azteque a salou e'
), $terms);
$this->assertEquals([
'_domain' => null,
'_default' => 'manco belier azteque a salou e',
], $terms);
}
public function testAccentuedCapitals()
@@ -138,47 +58,65 @@ class SearchProviderTest extends TestCase
$terms = $this->p('MANÉÀ oÛ lÎ À');
$this->assertEquals(array(
'_domain' => null,
'_default' => 'manea ou li a'
), $terms);
}
public function testTrimInParenthesis()
{
$terms = $this->p('foo:"bar "');
$this->assertEquals(array(
'_domain' => null,
'foo' => 'bar',
'_default' => ''
), $terms);
}
public function testTrimInDefault()
{
$terms = $this->p(' foo bar ');
$this->assertEquals(array(
'_domain' => null,
'_default' => 'foo bar'
), $terms);
$this->assertEquals([
'_domain' => null,
'_default' => 'manea ou li a',
], $terms);
}
public function testArgumentNameWithTrait()
{
$terms = $this->p('date-from:2016-05-04');
$this->assertEquals(array(
$this->assertEquals([
'_domain' => null,
'date-from' => '2016-05-04',
'_default' => ''
), $terms);
'_default' => '',
], $terms);
}
public function testCapitalLetters()
{
$terms = $this->p('Foo:Bar LOL marCi @PERSON');
$this->assertEquals([
'_domain' => 'person',
'_default' => 'lol marci',
'foo' => 'bar',
], $terms);
}
public function testDoubleParenthesis()
{
$terms = $this->p('@papamobile name:"my beautiful name" residual surname:"i love techno"');
$this->assertEquals([
'_domain' => 'papamobile',
'name' => 'my beautiful name',
'_default' => 'residual',
'surname' => 'i love techno',
], $terms);
}
/**
* @expectedException \Chill\MainBundle\Search\UnknowSearchNameException
*/
public function testInvalidSearchName()
{
$this->search->getByName('invalid name');
}
/**
* @expectedException \Chill\MainBundle\Search\ParsingException
*/
public function testMultipleDomainError()
{
$term = $this->p('@person @report');
}
/**
* Test the behaviour when no domain is provided in the search pattern :
* the default search should be enabled
* the default search should be enabled.
*/
public function testSearchResultDefault()
{
@@ -186,9 +124,24 @@ class SearchProviderTest extends TestCase
//$this->markTestSkipped();
$this->assertEquals(array(
"I am default"
), $response);
$this->assertEquals([
'I am default',
], $response);
}
public function testSearchResultDomainSearch()
{
//add a search service which will be supported
$this->addSearchService(
$this->createNonDefaultDomainSearchService('I am domain foo', 100, true),
'foo'
);
$response = $this->search->getSearchResults('@foo default search');
$this->assertEquals([
'I am domain foo',
], $response);
}
/**
@@ -199,35 +152,19 @@ class SearchProviderTest extends TestCase
$response = $this->search->getSearchResults('@unknow domain');
//$this->markTestSkipped();
}
public function testSearchResultDomainSearch()
{
//add a search service which will be supported
$this->addSearchService(
$this->createNonDefaultDomainSearchService("I am domain foo", 100, TRUE), 'foo'
);
$response = $this->search->getSearchResults('@foo default search');
$this->assertEquals(array(
"I am domain foo"
), $response);
}
public function testSearchWithinSpecificSearchName()
{
//add a search service which will be supported
$this->addSearchService(
$this->createNonDefaultDomainSearchService("I am domain foo", 100, TRUE), 'foo'
);
$this->createNonDefaultDomainSearchService('I am domain foo', 100, true),
'foo'
);
$response = $this->search->getResultByName('@foo search', 'foo');
$this->assertEquals('I am domain foo', $response);
}
/**
@@ -236,52 +173,94 @@ class SearchProviderTest extends TestCase
public function testSearchWithinSpecificSearchNameInConflictWithSupport()
{
$response = $this->search->getResultByName('@foo default search', 'bar');
}
/**
* shortcut for executing parse method
*
* @param unknown $pattern
* @return string[]
*/
private function p($pattern)
public function testSimplePattern()
{
return $this->search->parse($pattern);
$terms = $this->p('@person birthdate:2014-01-02 name:"my name" is not my name');
$this->assertEquals([
'_domain' => 'person',
'birthdate' => '2014-01-02',
'_default' => 'is not my name',
'name' => 'my name',
], $terms);
}
public function testTrimInDefault()
{
$terms = $this->p(' foo bar ');
$this->assertEquals([
'_domain' => null,
'_default' => 'foo bar',
], $terms);
}
public function testTrimInParenthesis()
{
$terms = $this->p('foo:"bar "');
$this->assertEquals([
'_domain' => null,
'foo' => 'bar',
'_default' => '',
], $terms);
}
public function testWithoutDefault()
{
$terms = $this->p('@person foo:bar');
$this->assertEquals([
'_domain' => 'person',
'foo' => 'bar',
'_default' => '',
], $terms);
}
public function testWithoutDomain()
{
$terms = $this->p('foo:bar residual');
$this->assertEquals([
'_domain' => null,
'foo' => 'bar',
'_default' => 'residual',
], $terms);
}
/**
* Add a search service to the chill.main.search_provider
* Add a search service to the chill.main.search_provider.
*
* Useful for mocking the SearchInterface
*
* @param SearchInterface $search
* @param string $name
*/
private function addSearchService(SearchInterface $search, $name)
private function addSearchService(SearchInterface $search, $name)
{
$this->search
->addSearchService($search, $name);
->addSearchService($search, $name);
}
private function createDefaultSearchService($result, $order)
{
$mock = $this
->getMockForAbstractClass('Chill\MainBundle\Search\AbstractSearch');
->getMockForAbstractClass('Chill\MainBundle\Search\AbstractSearch');
//set the mock as default
$mock->expects($this->any())
->method('isActiveByDefault')
->will($this->returnValue(TRUE));
->method('isActiveByDefault')
->will($this->returnValue(true));
$mock->expects($this->any())
->method('getOrder')
->will($this->returnValue($order));
->method('getOrder')
->will($this->returnValue($order));
//set the return value
$mock->expects($this->any())
->method('renderResult')
->will($this->returnValue($result));
->method('renderResult')
->will($this->returnValue($result));
return $mock;
}
@@ -289,26 +268,38 @@ class SearchProviderTest extends TestCase
private function createNonDefaultDomainSearchService($result, $order, $domain)
{
$mock = $this
->getMockForAbstractClass('Chill\MainBundle\Search\AbstractSearch');
->getMockForAbstractClass('Chill\MainBundle\Search\AbstractSearch');
//set the mock as default
$mock->expects($this->any())
->method('isActiveByDefault')
->will($this->returnValue(FALSE));
->method('isActiveByDefault')
->will($this->returnValue(false));
$mock->expects($this->any())
->method('getOrder')
->will($this->returnValue($order));
->method('getOrder')
->will($this->returnValue($order));
$mock->expects($this->any())
->method('supports')
->will($this->returnValue($domain));
->method('supports')
->will($this->returnValue($domain));
//set the return value
$mock->expects($this->any())
->method('renderResult')
->will($this->returnValue($result));
->method('renderResult')
->will($this->returnValue($result));
return $mock;
}
/**
* shortcut for executing parse method.
*
* @param unknown $pattern
*
* @return string[]
*/
private function p($pattern)
{
return $this->search->parse($pattern);
}
}

View File

@@ -1,12 +1,41 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Search\Utils;
use Chill\MainBundle\Search\Utils\ExtractDateFromPattern;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
use function array_map;
/**
* @internal
* @coversNothing
*/
class ExtractDateFromPatternTest extends TestCase
{
public function provideSubjects()
{
yield ['15/06/1981', '', 1, '1981-06-15'];
yield ['15/06/1981 30/12/1987', '', 2, '1981-06-15', '1987-12-30'];
yield ['diallo 15/06/1981', 'diallo', 1, '1981-06-15'];
yield ['diallo 31/03/1981', 'diallo', 1, '1981-03-31'];
yield ['diallo 15-06-1981', 'diallo', 1, '1981-06-15'];
yield ['diallo 1981-12-08', 'diallo', 1, '1981-12-08'];
yield ['diallo', 'diallo', 0];
}
/**
* @dataProvider provideSubjects
@@ -18,28 +47,17 @@ class ExtractDateFromPatternTest extends TestCase
$this->assertCount($count, $result->getFound());
$this->assertEquals($filtered, $result->getFilteredSubject());
$this->assertContainsOnlyInstancesOf(\DateTimeImmutable::class, $result->getFound());
$this->assertContainsOnlyInstancesOf(DateTimeImmutable::class, $result->getFound());
$dates = \array_map(
function (\DateTimeImmutable $d) {
$dates = array_map(
function (DateTimeImmutable $d) {
return $d->format('Y-m-d');
}, $result->getFound()
},
$result->getFound()
);
foreach ($datesSearched as $date) {
$this->assertContains($date, $dates);
}
}
public function provideSubjects()
{
yield ["15/06/1981", "", 1, '1981-06-15'];
yield ["15/06/1981 30/12/1987", "", 2, '1981-06-15', '1987-12-30'];
yield ["diallo 15/06/1981", "diallo", 1, '1981-06-15'];
yield ["diallo 31/03/1981", "diallo", 1, '1981-03-31'];
yield ["diallo 15-06-1981", "diallo", 1, '1981-06-15'];
yield ["diallo 1981-12-08", "diallo", 1, '1981-12-08'];
yield ["diallo", "diallo", 0];
}
}

View File

@@ -1,14 +1,46 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Search\Utils;
use Chill\MainBundle\Search\Utils\ExtractPhonenumberFromPattern;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* @internal
* @coversNothing
*/
class ExtractPhonenumberFromPatternTest extends KernelTestCase
{
public function provideData()
{
yield ['Diallo', 0, [], 'Diallo', 'no phonenumber'];
yield ['Diallo 15/06/2021', 0, [], 'Diallo 15/06/2021', 'no phonenumber and a date'];
yield ['Diallo 0486 123 456', 1, ['+32486123456'], 'Diallo', 'a phonenumber and a name'];
yield ['Diallo 123 456', 1, ['123456'], 'Diallo', 'a number and a name, without leadiing 0'];
yield ['123 456', 1, ['123456'], '', 'only phonenumber'];
yield ['0123 456', 1, ['+32123456'], '', 'only phonenumber with a leading 0'];
}
/**
* @dataProvider provideData
*
* @param mixed $subject
* @param mixed $expectedCount
* @param mixed $expected
* @param mixed $filteredSubject
* @param mixed $msg
*/
public function testExtract($subject, $expectedCount, $expected, $filteredSubject, $msg)
{
@@ -19,15 +51,4 @@ class ExtractPhonenumberFromPatternTest extends KernelTestCase
$this->assertEquals($filteredSubject, $result->getFilteredSubject());
$this->assertEquals($expected, $result->getFound());
}
public function provideData()
{
yield ['Diallo', 0, [], 'Diallo', "no phonenumber"];
yield ['Diallo 15/06/2021', 0, [], 'Diallo 15/06/2021', "no phonenumber and a date"];
yield ['Diallo 0486 123 456', 1, ['+32486123456'], 'Diallo', "a phonenumber and a name"];
yield ['Diallo 123 456', 1, ['123456'], 'Diallo', "a number and a name, without leadiing 0"];
yield ['123 456', 1, ['123456'], '', "only phonenumber"];
yield ['0123 456', 1, ['+32123456'], '', "only phonenumber with a leading 0"];
}
}

View File

@@ -1,58 +1,50 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Tests\PasswordRecover;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Chill\MainBundle\Security\PasswordRecover\TokenManager;
use Chill\MainBundle\Entity\User;
/**
*
* Chill is a software for social workers
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\PasswordRecover;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\PasswordRecover\TokenManager;
use DateInterval;
use DateTimeImmutable;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* @internal
* @coversNothing
*/
class TokenManagerTest extends KernelTestCase
{
protected $tokenManager;
public static function setUpBefore()
{
}
public function setUp()
{
self::bootKernel();
$logger = self::$container
->get('logger');
$this->tokenManager = new TokenManager('secret', $logger);
}
public function testGenerate()
public static function setUpBefore()
{
}
public function testGenerate()
{
$tokenManager = $this->tokenManager;
$user = (new User())->setUsernameCanonical('test');
$expiration = new \DateTimeImmutable('tomorrow');
$expiration = new DateTimeImmutable('tomorrow');
$tokens = $tokenManager->generate($user, $expiration);
$this->assertInternalType('array', $tokens);
$this->assertArrayHasKey('h', $tokens);
$this->assertArrayHasKey('t', $tokens);
@@ -60,57 +52,57 @@ class TokenManagerTest extends KernelTestCase
$this->assertNotEmpty($tokens['t']);
$this->assertEquals($user->getUsernameCanonical(), $tokens['u']);
}
/**
* @expectedException \UnexpectedValueException
*/
public function testGenerateEmptyUsernameCanonical()
public function testGenerateEmptyUsernameCanonical()
{
$tokenManager = $this->tokenManager;
// set a username, but not a username canonical
$user = (new User())->setUsername('test');
$expiration = new \DateTimeImmutable('tomorrow');
$expiration = new DateTimeImmutable('tomorrow');
$tokenManager->generate($user, $expiration);
}
public function testVerify()
{
$tokenManager = $this->tokenManager;
$user = (new User())->setUsernameCanonical('test');
$expiration = new \DateTimeImmutable('tomorrow');
$expiration = new DateTimeImmutable('tomorrow');
$tokens = $tokenManager->generate($user, $expiration);
$hash = $tokens[TokenManager::HASH];
$token = $tokens[TokenManager::TOKEN];
$timestamp = $tokens[TokenManager::TIMESTAMP];
$verification = $tokenManager->verify($hash, $token, $user, $timestamp);
$this->assertTrue($verification);
// test with altering token
$this->assertFalse($tokenManager->verify($hash.'5', $token, $user, $timestamp));
$this->assertFalse($tokenManager->verify($hash, $token.'25', $user, $timestamp));
$this->assertFalse($tokenManager->verify($hash . '5', $token, $user, $timestamp));
$this->assertFalse($tokenManager->verify($hash, $token . '25', $user, $timestamp));
$this->assertFalse($tokenManager->verify($hash, $token, $user->setUsernameCanonical('test2'), $timestamp));
$this->assertFalse($tokenManager->verify($hash, $token, $user, $timestamp+1));
$this->assertFalse($tokenManager->verify($hash, $token, $user, $timestamp + 1));
}
public function testVerifyExpiredFails()
{
$tokenManager = $this->tokenManager;
$user = (new User())->setUsernameCanonical('test');
$expiration = (new \DateTimeImmutable('now'))->sub(new \DateInterval('PT1S'));
$expiration = (new DateTimeImmutable('now'))->sub(new DateInterval('PT1S'));
$tokens = $tokenManager->generate($user, $expiration);
$hash = $tokens[TokenManager::HASH];
$token = $tokens[TokenManager::TOKEN];
$timestamp = $tokens[TokenManager::TIMESTAMP];
$verification = $tokenManager->verify($hash, $token, $user, $timestamp);
$this->assertFalse($verification);
}
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Tests\Security\Resolver;
@@ -9,6 +16,10 @@ use Chill\MainBundle\Security\Resolver\CenterResolverDispatcher;
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcherInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* @internal
* @coversNothing
*/
class CenterResolverDispatcherTest extends KernelTestCase
{
private CenterResolverDispatcherInterface $dispatcher;
@@ -21,10 +32,10 @@ class CenterResolverDispatcherTest extends KernelTestCase
public function testResolveCenter()
{
$center = new Center();
$center = new Center();
$resolved = $this->dispatcher->resolveCenter($center);
$resolved = $this->dispatcher->resolveCenter($center);
$this->assertSame($center, $resolved);
$this->assertSame($center, $resolved);
}
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Security\Resolver;
use Chill\MainBundle\Entity\HasScopeInterface;
@@ -8,6 +15,10 @@ use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Security\Resolver\DefaultScopeResolver;
use PHPUnit\Framework\TestCase;
/**
* @internal
* @coversNothing
*/
class DefaultScopeResolverTest extends TestCase
{
private DefaultScopeResolver $scopeResolver;
@@ -21,8 +32,8 @@ class DefaultScopeResolverTest extends TestCase
{
$scope = new Scope();
$entity = new class($scope) implements HasScopeInterface {
public function __construct(Scope $scope) {
public function __construct(Scope $scope)
{
$this->scope = $scope;
}
@@ -30,7 +41,6 @@ class DefaultScopeResolverTest extends TestCase
{
return $this->scope;
}
};
$this->assertTrue($this->scopeResolver->supports($entity));
@@ -41,8 +51,8 @@ class DefaultScopeResolverTest extends TestCase
public function testHasScopesInterface()
{
$entity = new class($scopeA = new Scope(), $scopeB = new Scope()) implements HasScopesInterface {
public function __construct(Scope $scopeA, Scope $scopeB) {
public function __construct(Scope $scopeA, Scope $scopeB)
{
$this->scopes = [$scopeA, $scopeB];
}
@@ -58,5 +68,4 @@ class DefaultScopeResolverTest extends TestCase
$this->assertSame($scopeA, $this->scopeResolver->resolveScope($entity)[0]);
$this->assertSame($scopeB, $this->scopeResolver->resolveScope($entity)[1]);
}
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Security\Resolver;
use Chill\MainBundle\Entity\HasScopeInterface;
@@ -9,6 +16,10 @@ use Chill\MainBundle\Security\Resolver\DefaultScopeResolver;
use Chill\MainBundle\Security\Resolver\ScopeResolverDispatcher;
use PHPUnit\Framework\TestCase;
/**
* @internal
* @coversNothing
*/
class DefaultScopeResolverDispatcherTest extends TestCase
{
private ScopeResolverDispatcher $scopeResolverDispatcher;
@@ -22,8 +33,8 @@ class DefaultScopeResolverDispatcherTest extends TestCase
{
$scope = new Scope();
$entity = new class($scope) implements HasScopeInterface {
public function __construct(Scope $scope) {
public function __construct(Scope $scope)
{
$this->scope = $scope;
}
@@ -31,7 +42,6 @@ class DefaultScopeResolverDispatcherTest extends TestCase
{
return $this->scope;
}
};
$this->assertTrue($this->scopeResolverDispatcher->isConcerned($entity));
@@ -41,8 +51,8 @@ class DefaultScopeResolverDispatcherTest extends TestCase
public function testHasScopesInterface()
{
$entity = new class($scopeA = new Scope(), $scopeB = new Scope()) implements HasScopesInterface {
public function __construct(Scope $scopeA, Scope $scopeB) {
public function __construct(Scope $scopeA, Scope $scopeB)
{
$this->scopes = [$scopeA, $scopeB];
}

View File

@@ -1,14 +1,29 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Serializer\Normalizer;
use Chill\MainBundle\Serializer\Normalizer\DateNormalizer;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Prophecy\Prophet;
use stdClass;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* @internal
* @coversNothing
*/
class DateNormalizerTest extends KernelTestCase
{
private Prophet $prophet;
@@ -18,34 +33,71 @@ class DateNormalizerTest extends KernelTestCase
$this->prophet = new Prophet();
}
public function testSupports()
public function generateDataNormalize()
{
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(new \DateTime(), 'json'));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(new \DateTimeImmutable(), 'json'));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(new \DateTime(), 'docgen'));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(new \DateTimeImmutable(), 'docgen'));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(null, 'docgen', ['docgen:expects' => \DateTimeImmutable::class]));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(null, 'docgen', ['docgen:expects' => \DateTimeInterface::class]));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(null, 'docgen', ['docgen:expects' => \DateTime::class]));
$this->assertFalse($this->buildDateNormalizer()->supportsNormalization(new \stdClass(), 'docgen'));
$this->assertFalse($this->buildDateNormalizer()->supportsNormalization(new \DateTime(), 'xml'));
$datetime = DateTime::createFromFormat('Y-m-d H:i:sO', '2021-06-05 15:05:01+02:00');
$date = DateTime::createFromFormat('Y-m-d H:i:sO', '2021-06-05 00:00:00+02:00');
yield [
['datetime' => '2021-06-05T15:05:01+0200'],
$datetime, 'json', null, 'simple normalization to json',
];
yield [
['long' => '5 juin 2021', 'short' => '05/06/2021'],
$date, 'docgen', 'fr', 'normalization to docgen for a date, with current request',
];
yield [
['long' => '5 juin 2021', 'short' => '05/06/2021'],
$date, 'docgen', null, 'normalization to docgen for a date, without current request',
];
yield [
['long' => '5 juin 2021 à 15:05', 'short' => '05/06/2021 15:05'],
$datetime, 'docgen', null, 'normalization to docgen for a datetime, without current request',
];
yield [
['long' => '', 'short' => ''],
null, 'docgen', null, 'normalization to docgen for a null datetime',
];
}
/**
* @dataProvider generateDataNormalize
*
* @param mixed $expected
* @param mixed $date
* @param mixed $format
* @param mixed $locale
* @param mixed $msg
*/
public function testNormalize($expected, $date, $format, $locale, $msg)
{
$this->assertEquals($expected, $this->buildDateNormalizer($locale)->normalize($date, $format, []), $msg);
}
private function buildDateNormalizer(string $locale = null): DateNormalizer
public function testSupports()
{
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(new DateTime(), 'json'));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(new DateTimeImmutable(), 'json'));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(new DateTime(), 'docgen'));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(new DateTimeImmutable(), 'docgen'));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(null, 'docgen', ['docgen:expects' => DateTimeImmutable::class]));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(null, 'docgen', ['docgen:expects' => DateTimeInterface::class]));
$this->assertTrue($this->buildDateNormalizer()->supportsNormalization(null, 'docgen', ['docgen:expects' => DateTime::class]));
$this->assertFalse($this->buildDateNormalizer()->supportsNormalization(new stdClass(), 'docgen'));
$this->assertFalse($this->buildDateNormalizer()->supportsNormalization(new DateTime(), 'xml'));
}
private function buildDateNormalizer(?string $locale = null): DateNormalizer
{
$requestStack = $this->prophet->prophesize(RequestStack::class);
$parameterBag = new ParameterBag();
$parameterBag->set('kernel.default_locale', 'fr');
if ($locale === null) {
if (null === $locale) {
$requestStack->getCurrentRequest()->willReturn(null);
} else {
$request = $this->prophet->prophesize(Request::class);
@@ -55,34 +107,4 @@ class DateNormalizerTest extends KernelTestCase
return new DateNormalizer($requestStack->reveal(), $parameterBag);
}
public function generateDataNormalize()
{
$datetime = \DateTime::createFromFormat('Y-m-d H:i:sO', '2021-06-05 15:05:01+02:00');
$date = \DateTime::createFromFormat('Y-m-d H:i:sO', '2021-06-05 00:00:00+02:00');
yield [
['datetime' => '2021-06-05T15:05:01+0200'],
$datetime, 'json', null, 'simple normalization to json'
];
yield [
['long' => '5 juin 2021', 'short' => '05/06/2021'],
$date, 'docgen', 'fr', 'normalization to docgen for a date, with current request'
];
yield [
['long' => '5 juin 2021', 'short' => '05/06/2021'],
$date, 'docgen', null, 'normalization to docgen for a date, without current request'
];
yield [
['long' => '5 juin 2021 à 15:05', 'short' => '05/06/2021 15:05'],
$datetime, 'docgen', null, 'normalization to docgen for a datetime, without current request'
];
yield [
['long' => '', 'short' => ''],
null, 'docgen', null, 'normalization to docgen for a null datetime'
];
}
}

View File

@@ -1,14 +1,24 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Serializer\Normalizer;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Serializer\Normalizer\DoctrineExistingEntityNormalizer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Chill\MainBundle\Entity\User;
/**
* @internal
* @coversNothing
*/
class DoctrineExistingEntityNormalizerTest extends KernelTestCase
{
protected DoctrineExistingEntityNormalizer $normalizer;
@@ -16,23 +26,12 @@ class DoctrineExistingEntityNormalizerTest extends KernelTestCase
protected function setUp()
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$em = self::$container->get(EntityManagerInterface::class);
$serializerFactory = self::$container->get(ClassMetadataFactoryInterface::class);
$this->normalizer = new DoctrineExistingEntityNormalizer($em, $serializerFactory);
}
/**
* @dataProvider dataProviderUserId
*/
public function testGetMappedClass($userId)
{
$data = [ 'type' => 'user', 'id' => $userId];
$supports = $this->normalizer->supportsDenormalization($data, User::class);
$this->assertTrue($supports);
}
public function dataProviderUserId()
{
self::bootKernel();
@@ -43,9 +42,21 @@ class DoctrineExistingEntityNormalizerTest extends KernelTestCase
->select('u.id')
->setMaxResults(1)
->getQuery()
->getResult()
;
->getResult();
yield [ $userIds[0]['id'] ];
yield [$userIds[0]['id']];
}
/**
* @dataProvider dataProviderUserId
*
* @param mixed $userId
*/
public function testGetMappedClass($userId)
{
$data = ['type' => 'user', 'id' => $userId];
$supports = $this->normalizer->supportsDenormalization($data, User::class);
$this->assertTrue($supports);
}
}

View File

@@ -1,46 +1,51 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Services;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Routing\RouteCollection;
/**
* This class provide functional test for MenuComposer
* This class provide functional test for MenuComposer.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class MenuComposerTest extends KernelTestCase
{
/**
*
* @var \Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader;
*/
private $loader;
/**
*
* @var \Chill\MainBundle\DependencyInjection\Services\MenuComposer;
*/
private $menuComposer;
public function setUp()
{
self::bootKernel(array('environment' => 'test'));
self::bootKernel(['environment' => 'test']);
$this->menuComposer = static::$container
->get('chill.main.menu_composer');
->get('chill.main.menu_composer');
}
/**
* @covers \Chill\MainBundle\Routing\MenuComposer
*/
public function testMenuComposer()
{
$collection = new RouteCollection();
$routes = $this->menuComposer->getRoutesFor('dummy0');
$this->assertInternalType('array', $routes);
}
}

View File

@@ -1,76 +1,69 @@
<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2014-2021, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Tests\Templating;
use PHPUnit\Framework\TestCase;
use Chill\MainBundle\Templating\ChillMarkdownRenderExtension;
/**
* Test the service ChillMarkdownRenderExtension
*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Templating;
use Chill\MainBundle\Templating\ChillMarkdownRenderExtension;
use PHPUnit\Framework\TestCase;
/**
* Test the service ChillMarkdownRenderExtension.
*
* @internal we do not want to test the markdown transformation. We just want to
* test that the markdown is correctly transformed into html, and that the html
* test that the markdown is correctly transformed into html, and that the html
* is safe.
* @coversNothing
*/
class ChillMarkdownRenderExtensionTest extends TestCase
{
private const SIMPLE_MARKDOWN = <<<MD
# test
private const SIMPLE_HTML = <<<'HTML'
<h1>test</h1>
<p>Text.</p>
HTML;
private const SIMPLE_MARKDOWN = <<<'MD'
# test
Text.
MD;
private const UNAUTHORIZED_HTML = <<<'HTML'
<p>&lt;script&gt;alert(&quot;ok&quot;);&lt;/script&gt;</p>
HTML;
private const UNAUTHORIZED_MARKDOWN = <<<'MD'
<script>alert("ok");</script>
MD;
Text.
MD;
private const SIMPLE_HTML = <<<HTML
<h1>test</h1>
<p>Text.</p>
HTML;
private const UNAUTHORIZED_MARKDOWN = <<<MD
<script>alert("ok");</script>
MD;
private const UNAUTHORIZED_HTML = <<<HTML
<p>&lt;script&gt;alert(&quot;ok&quot;);&lt;/script&gt;</p>
HTML;
/**
* Test that the markdown input is transformed into html
* Test that the markdown input is transformed into html.
*/
public function testRendering()
{
$extension = new ChillMarkdownRenderExtension();
$this->assertEquals(self::SIMPLE_HTML,
$extension->renderMarkdownToHtml(self::SIMPLE_MARKDOWN));
$this->assertEquals(
self::SIMPLE_HTML,
$extension->renderMarkdownToHtml(self::SIMPLE_MARKDOWN)
);
}
/**
* Test that the output of the markdown content is sanitized
* Test that the output of the markdown content is sanitized.
*/
public function testSecurity()
{
$extension = new ChillMarkdownRenderExtension();
$this->assertEquals(self::UNAUTHORIZED_HTML,
$extension->renderMarkdownToHtml(self::UNAUTHORIZED_MARKDOWN));
$this->assertEquals(
self::UNAUTHORIZED_HTML,
$extension->renderMarkdownToHtml(self::UNAUTHORIZED_MARKDOWN)
);
}
}

View File

@@ -1,22 +1,51 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Templating\Entity;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\Country;
use Chill\MainBundle\Entity\PostalCode;
use Chill\MainBundle\Templating\Entity\AddressRender;
use Chill\MainBundle\Entity\Address;
use Iterator;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Templating\EngineInterface;
/**
* @internal
* @coversNothing
*/
class AddressRenderTest extends KernelTestCase
{
protected function setUp()
{
self::bootKernel();
}
public function addressDataProvider(): Iterator
{
$addr = new Address();
$country = (new Country())
->setName(['fr' => 'Pays'])
->setCountryCode('BE');
$postCode = new PostalCode();
$postCode->setName('Locality')
->setCode('012345')
->setCountry($country);
$addr->setStreet('Rue ABC')
->setStreetNumber('5')
->setPostcode($postCode);
yield [$addr, 'Rue ABC, 5 - 012345 Locality'];
}
/**
* @dataProvider addressDataProvider
*/
@@ -26,30 +55,8 @@ class AddressRenderTest extends KernelTestCase
$renderer = new AddressRender($engine);
$this->assertEquals($expectedString, $renderer->renderString($addr, []));
return;
$this->assertIsString($renderer->renderBox($addr, []));
}
public function addressDataProvider(): \Iterator
{
$addr = new Address();
$country = (new Country())
->setName([ "fr" => "Pays" ])
->setCountryCode("BE")
;
$postCode = new PostalCode();
$postCode->setName("Locality")
->setCode("012345")
->setCountry($country)
;
$addr->setStreet("Rue ABC")
->setStreetNumber("5")
->setPostcode($postCode)
;
yield[ $addr, "Rue ABC, 5 - 012345 Locality"];
}
}

View File

@@ -1,21 +1,10 @@
<?php
/*
/**
* Chill is a software for social workers
* Copyright (C) 2015 Champs Libres <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests;
@@ -23,25 +12,26 @@ namespace Chill\MainBundle\Tests;
use Symfony\Component\BrowserKit\Client;
/**
* Provide useful methods for tests
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
* Provide useful methods for tests.
*/
class TestHelper
{
/**
* create a client authenticated with an user
*
* @param WebTestCase $testCase
* create a client authenticated with an user.
*
* @param mixed $username
* @param mixed $password
*
* @return \Symfony\Component\BrowserKit\Client authenticated client
*/
public static function getAuthenticatedClientOptions($username = 'center a_social',
$password = 'password')
public static function getAuthenticatedClientOptions(
$username = 'center a_social',
$password = 'password'
)
{
return array(
'PHP_AUTH_USER' => $username,
'PHP_AUTH_PW' => $password,
);
return [
'PHP_AUTH_USER' => $username,
'PHP_AUTH_PW' => $password,
];
}
}

View File

@@ -1,48 +1,58 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Util;
use PHPUnit\Framework\TestCase;
use Chill\MainBundle\Util\CountriesInfo;
use PHPUnit\Framework\TestCase;
/**
* tests for CountriesInfos
* tests for CountriesInfos.
*
* @author julien.fastre@champs-libre.coop
* @internal
* @coversNothing
*/
class CountriesInfoTest extends TestCase {
public function testGetCountryData()
class CountriesInfoTest extends TestCase
{
public function getGetContinentsCodes()
{
$raw = CountriesInfo::getCountriesData();
$this->assertStringStartsWith("AS AF AFG 004 Afghanistan, Islamic Republic of",
$raw);
$continents = CountriesInfo::getContinentsCodes();
$this->assertContains('EU', $continents);
}
public function testGetArrayCountriesData()
public function testGetArrayCountriesData()
{
$data = CountriesInfo::getArrayCountriesData();
$this->assertNotNull($data);
$this->assertContains(array(
"AS", "AF", "AFG", "004", "Afghanistan, Islamic Republic of"
), $data);
$this->assertContains([
'AS', 'AF', 'AFG', '004', 'Afghanistan, Islamic Republic of',
], $data);
}
public function testGetCountryCodeByContinents()
{
$countries = CountriesInfo::getCountriesCodeByContinent('EU');
$this->assertContains('BE', $countries);
$this->assertContains('FR', $countries);
$this->assertContains('GB', $countries);
}
public function getGetContinentsCodes()
public function testGetCountryData()
{
$continents = CountriesInfo::getContinentsCodes();
$this->assertContains('EU', $continents);
$raw = CountriesInfo::getCountriesData();
$this->assertStringStartsWith(
'AS AF AFG 004 Afghanistan, Islamic Republic of',
$raw
);
}
}

View File

@@ -1,35 +1,47 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Tests\Util;
use Chill\MainBundle\Util\DateRangeCovering;
use DateTime;
use DateTimeZone;
use PHPUnit\Framework\TestCase;
use function usort;
/**
* @internal
* @coversNothing
*/
class DateRangeCoveringTest extends TestCase
{
public function testCoveringWithMinCover1()
{
$cover = new DateRangeCovering(1, new \DateTimeZone('Europe/Brussels'));
$cover = new DateRangeCovering(1, new DateTimeZone('Europe/Brussels'));
$cover
->add(new \DateTime('2010-01-01'), new \DateTime('2010-12-01'), 1)
->add(new \DateTime('2010-06-01'), new \DateTime('2011-06-01'), 2)
->add(new \DateTime('2019-06-01'), new \DateTime('2019-06-01'), 3)
->compute()
;
->add(new DateTime('2010-01-01'), new DateTime('2010-12-01'), 1)
->add(new DateTime('2010-06-01'), new DateTime('2011-06-01'), 2)
->add(new DateTime('2019-06-01'), new DateTime('2019-06-01'), 3)
->compute();
$this->assertTrue($cover->hasIntersections());
$this->assertIsArray($cover->getIntersections());
$this->assertCount(1, $cover->getIntersections());
$this->assertEquals(
new \DateTime('2010-06-01'),
new DateTime('2010-06-01'),
$cover->getIntersections()[0][0],
"assert date start are the intersection"
'assert date start are the intersection'
);
$this->assertEquals(
new \DateTime('2010-12-01'),
new DateTime('2010-12-01'),
$cover->getIntersections()[0][1],
"assert date end are the intersection"
'assert date end are the intersection'
);
$this->assertIsArray($cover->getIntersections()[0][2]);
$this->assertContains(1, $cover->getIntersections()[0][2]);
@@ -37,28 +49,26 @@ class DateRangeCoveringTest extends TestCase
$this->assertNotContains(3, $cover->getIntersections()[0][2]);
}
public function testCoveringWithMinCover1_NoCoveringWithNullDates()
public function testCoveringWithMinCover1NoCoveringWithNullDates()
{
$cover = new DateRangeCovering(1, new \DateTimeZone('Europe/Brussels'));
$cover = new DateRangeCovering(1, new DateTimeZone('Europe/Brussels'));
$cover
->add(new \DateTime('2021-10-05'), new \DateTime('2021-10-18'), 521)
->add(new \DateTime('2021-10-26'), null, 663)
->compute()
;
->add(new DateTime('2021-10-05'), new DateTime('2021-10-18'), 521)
->add(new DateTime('2021-10-26'), null, 663)
->compute();
$this->assertFalse($cover->hasIntersections());
}
public function testCoveringWithMinCover1WithTwoIntersections()
{
$cover = new DateRangeCovering(1, new \DateTimeZone('Europe/Brussels'));
$cover = new DateRangeCovering(1, new DateTimeZone('Europe/Brussels'));
$cover
->add(new \DateTime('2010-01-01'), new \DateTime('2010-12-01'), 1)
->add(new \DateTime('2010-06-01'), new \DateTime('2011-06-01'), 2)
->add(new \DateTime('2019-01-01'), new \DateTime('2019-12-01'), 3)
->add(new \DateTime('2019-06-01'), new \DateTime('2020-06-01'), 4)
->compute()
;
->add(new DateTime('2010-01-01'), new DateTime('2010-12-01'), 1)
->add(new DateTime('2010-06-01'), new DateTime('2011-06-01'), 2)
->add(new DateTime('2019-01-01'), new DateTime('2019-12-01'), 3)
->add(new DateTime('2019-06-01'), new DateTime('2020-06-01'), 4)
->compute();
$this->assertTrue($cover->hasIntersections());
$this->assertIsArray($cover->getIntersections());
@@ -67,7 +77,7 @@ class DateRangeCoveringTest extends TestCase
$intersections = $cover->getIntersections();
// sort the intersections to compare them in expected order
\usort($intersections, function($a, $b) {
usort($intersections, function ($a, $b) {
if ($a[0] === $b[0]) {
return $a[1] <=> $b[1];
}
@@ -77,14 +87,14 @@ class DateRangeCoveringTest extends TestCase
// first intersection
$this->assertEquals(
new \DateTime('2010-06-01'),
new DateTime('2010-06-01'),
$intersections[0][0],
"assert date start are the intersection"
'assert date start are the intersection'
);
$this->assertEquals(
new \DateTime('2010-12-01'),
new DateTime('2010-12-01'),
$intersections[0][1],
"assert date end are the intersection"
'assert date end are the intersection'
);
$this->assertIsArray($intersections[0][2]);
$this->assertContains(1, $intersections[0][2]);
@@ -94,14 +104,14 @@ class DateRangeCoveringTest extends TestCase
// second intersection
$this->assertEquals(
new \DateTime('2019-06-01'),
new DateTime('2019-06-01'),
$intersections[1][0],
"assert date start are the intersection"
'assert date start are the intersection'
);
$this->assertEquals(
new \DateTime('2019-12-01'),
new DateTime('2019-12-01'),
$intersections[1][1],
"assert date end are the intersection"
'assert date end are the intersection'
);
$this->assertIsArray($intersections[1][2]);
$this->assertContains(3, $intersections[1][2]);
@@ -112,28 +122,27 @@ class DateRangeCoveringTest extends TestCase
public function testCoveringWithMinCover2()
{
$cover = new DateRangeCovering(2, new \DateTimeZone('Europe/Brussels'));
$cover = new DateRangeCovering(2, new DateTimeZone('Europe/Brussels'));
$cover
->add(new \DateTime('2010-01-01'), new \DateTime('2010-10-01'), 1)
->add(new \DateTime('2010-06-01'), new \DateTime('2010-09-01'), 2)
->add(new \DateTime('2010-04-01'), new \DateTime('2010-12-01'), 3)
->add(new \DateTime('2019-01-01'), new \DateTime('2019-10-01'), 4)
->add(new \DateTime('2019-06-01'), new \DateTime('2019-09-01'), 5)
->compute()
;
->add(new DateTime('2010-01-01'), new DateTime('2010-10-01'), 1)
->add(new DateTime('2010-06-01'), new DateTime('2010-09-01'), 2)
->add(new DateTime('2010-04-01'), new DateTime('2010-12-01'), 3)
->add(new DateTime('2019-01-01'), new DateTime('2019-10-01'), 4)
->add(new DateTime('2019-06-01'), new DateTime('2019-09-01'), 5)
->compute();
$this->assertTrue($cover->hasIntersections());
$this->assertIsArray($cover->getIntersections());
$this->assertCount(1, $cover->getIntersections());
$this->assertEquals(
new \DateTime('2010-06-01'),
new DateTime('2010-06-01'),
$cover->getIntersections()[0][0],
"assert date start are the intersection"
'assert date start are the intersection'
);
$this->assertEquals(
new \DateTime('2010-09-01'),
new DateTime('2010-09-01'),
$cover->getIntersections()[0][1],
"assert date end are the intersection"
'assert date end are the intersection'
);
$this->assertIsArray($cover->getIntersections()[0][2]);
$this->assertContains(1, $cover->getIntersections()[0][2]);
@@ -145,30 +154,29 @@ class DateRangeCoveringTest extends TestCase
public function testCoveringWithMinCover2AndThreePeriodsCovering()
{
$cover = new DateRangeCovering(2, new \DateTimeZone('Europe/Brussels'));
$cover = new DateRangeCovering(2, new DateTimeZone('Europe/Brussels'));
$cover
->add(new \DateTime('2010-01-01'), new \DateTime('2010-10-01'), 1)
->add(new \DateTime('2010-06-01'), new \DateTime('2010-09-01'), 2)
->add(new \DateTime('2010-04-01'), new \DateTime('2010-12-01'), 3)
->add(new \DateTime('2009-01-01'), new \DateTime('2010-09-15'), 4)
->add(new \DateTime('2019-01-01'), new \DateTime('2019-10-01'), 5)
->add(new \DateTime('2019-06-01'), new \DateTime('2019-09-01'), 6)
->compute()
;
->add(new DateTime('2010-01-01'), new DateTime('2010-10-01'), 1)
->add(new DateTime('2010-06-01'), new DateTime('2010-09-01'), 2)
->add(new DateTime('2010-04-01'), new DateTime('2010-12-01'), 3)
->add(new DateTime('2009-01-01'), new DateTime('2010-09-15'), 4)
->add(new DateTime('2019-01-01'), new DateTime('2019-10-01'), 5)
->add(new DateTime('2019-06-01'), new DateTime('2019-09-01'), 6)
->compute();
$this->assertTrue($cover->hasIntersections());
$this->assertIsArray($cover->getIntersections());
$this->assertCount(1, $cover->getIntersections());
$this->assertEquals(
new \DateTime('2010-04-01'),
new DateTime('2010-04-01'),
$cover->getIntersections()[0][0],
"assert date start are the intersection"
'assert date start are the intersection'
);
$this->assertEquals(
new \DateTime('2010-09-15'),
new DateTime('2010-09-15'),
$cover->getIntersections()[0][1],
"assert date end are the intersection"
'assert date end are the intersection'
);
$this->assertIsArray($cover->getIntersections()[0][2]);
$this->assertContains(1, $cover->getIntersections()[0][2]);
@@ -181,46 +189,43 @@ class DateRangeCoveringTest extends TestCase
public function testCoveringWithMinCover2AndThreePeriodsCoveringWithNullMetadata()
{
$cover = new DateRangeCovering(2, new \DateTimeZone('Europe/Brussels'));
$cover = new DateRangeCovering(2, new DateTimeZone('Europe/Brussels'));
$cover
->add(new \DateTime('2010-01-01'), new \DateTime('2010-10-01'), null)
->add(new \DateTime('2010-06-01'), new \DateTime('2010-09-01'), null)
->add(new \DateTime('2010-04-01'), new \DateTime('2010-12-01'), null)
->add(new \DateTime('2009-01-01'), new \DateTime('2010-09-15'), null)
->add(new \DateTime('2019-01-01'), new \DateTime('2019-10-01'), null)
->add(new \DateTime('2019-06-01'), new \DateTime('2019-09-01'), null)
->compute()
;
->add(new DateTime('2010-01-01'), new DateTime('2010-10-01'), null)
->add(new DateTime('2010-06-01'), new DateTime('2010-09-01'), null)
->add(new DateTime('2010-04-01'), new DateTime('2010-12-01'), null)
->add(new DateTime('2009-01-01'), new DateTime('2010-09-15'), null)
->add(new DateTime('2019-01-01'), new DateTime('2019-10-01'), null)
->add(new DateTime('2019-06-01'), new DateTime('2019-09-01'), null)
->compute();
$this->assertTrue($cover->hasIntersections());
$this->assertIsArray($cover->getIntersections());
$this->assertCount(1, $cover->getIntersections());
$this->assertEquals(
new \DateTime('2010-04-01'),
new DateTime('2010-04-01'),
$cover->getIntersections()[0][0],
"assert date start are the intersection"
'assert date start are the intersection'
);
$this->assertEquals(
new \DateTime('2010-09-15'),
new DateTime('2010-09-15'),
$cover->getIntersections()[0][1],
"assert date end are the intersection"
'assert date end are the intersection'
);
$this->assertIsArray($cover->getIntersections()[0][2]);
}
public function testCoveringWithMinCover3Absent()
{
$cover = new DateRangeCovering(3, new \DateTimeZone('Europe/Brussels'));
$cover = new DateRangeCovering(3, new DateTimeZone('Europe/Brussels'));
$cover
->add(new \DateTime('2010-01-01'), new \DateTime('2010-10-01'), 1)
->add(new \DateTime('2010-06-01'), new \DateTime('2010-09-01'), 2)
->add(new \DateTime('2010-04-01'), new \DateTime('2010-12-01'), 3)
->add(new \DateTime('2019-01-01'), new \DateTime('2019-10-01'), 4)
->add(new \DateTime('2019-06-01'), new \DateTime('2019-09-01'), 5)
->compute()
;
->add(new DateTime('2010-01-01'), new DateTime('2010-10-01'), 1)
->add(new DateTime('2010-06-01'), new DateTime('2010-09-01'), 2)
->add(new DateTime('2010-04-01'), new DateTime('2010-12-01'), 3)
->add(new DateTime('2019-01-01'), new DateTime('2019-10-01'), 4)
->add(new DateTime('2019-06-01'), new DateTime('2019-09-01'), 5)
->compute();
$this->assertFalse($cover->hasIntersections());
$this->assertIsArray($cover->getIntersections());
$this->assertCount(0, $cover->getIntersections());

View File

@@ -1,8 +1,14 @@
<?php
if (!is_file($autoloadFile = __DIR__.'/../vendor/autoload.php')) {
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
if (!is_file($autoloadFile = __DIR__ . '/../vendor/autoload.php')) {
throw new \LogicException('Could not find autoload.php in vendor/. Did you run "composer install --dev"?');
}
require $autoloadFile;