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,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\PersonBundle\Tests\Controller;
use Chill\MainBundle\Entity\Center;
@@ -7,9 +14,17 @@ use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Test\PrepareClientTrait;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Iterator;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use function array_pop;
use function preg_match;
/**
* @internal
* @coversNothing
*/
class AccompanyingCourseControllerTest extends WebTestCase
{
use PrepareClientTrait;
@@ -21,34 +36,60 @@ class AccompanyingCourseControllerTest extends WebTestCase
$this->client = $this->getClientAuthenticated();
}
public function dataGenerateRandomUsers(): Iterator
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$period = new AccompanyingPeriod(new DateTime('1 week ago'));
$user = $em->getRepository(User::class)
->findOneByUsernameCanonical('center a_social');
$period->setCreatedBy($user);
//$period->setCreatedAt(new \DateTime('yesterday'));
$center = $em->getRepository(Center::class)
->findOneBy(['name' => 'Center A']);
$personIds = $em->createQuery('SELECT p.id FROM ' .
Person::class . ' p ' .
' WHERE p.center = :center')
->setParameter('center', $center)
->setMaxResults(100)
->getScalarResult();
yield [array_pop($personIds), array_pop($personIds)];
}
public function testNewWithoutUsers()
{
$this->client->request('GET', '/fr/person/parcours/new');
$this->client->request('GET', '/fr/person/parcours/new');
$this->assertResponseRedirects();
$location = $this->client->getResponse()->headers->get('Location');
$this->assertEquals(1, \preg_match("|^\/[^\/]+\/parcours/([\d]+)/edit$|", $location));
$this->assertEquals(1, preg_match('|^\\/[^\\/]+\\/parcours/([\\d]+)/edit$|', $location));
}
/**
* @dataProvider dataGenerateRandomUsers
*
* @param mixed $personId0
* @param mixed $personId1
*/
public function testWithNewUsers($personId0, $personId1)
{
$this->client->request('GET', '/fr/person/parcours/new', [
'person_id' => [
$personId0,
$personId1
]
]);
$personId0,
$personId1,
],
]);
$this->assertResponseRedirects();
$location = $this->client->getResponse()->headers->get('Location');
$matches = [];
$this->assertEquals(1, \preg_match("|^\/[^\/]+\/parcours/([\d]+)/edit$|", $location, $matches));
$this->assertEquals(1, preg_match('|^\\/[^\\/]+\\/parcours/([\\d]+)/edit$|', $location, $matches));
$id = $matches[1];
$period = self::$container->get(EntityManagerInterface::class)
@@ -59,30 +100,4 @@ class AccompanyingCourseControllerTest extends WebTestCase
$this->assertEquals(2, count($period->getParticipations()));
}
public function dataGenerateRandomUsers(): \Iterator
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$period = new AccompanyingPeriod(new \DateTime('1 week ago'));
$user = $em->getRepository(User::class)
->findOneByUsernameCanonical('center a_social');
$period->setCreatedBy($user);
//$period->setCreatedAt(new \DateTime('yesterday'));
$center = $em->getRepository(Center::class)
->findOneBy(array('name' => 'Center A'));
$personIds = $em->createQuery("SELECT p.id FROM ".
Person::class." p ".
" WHERE p.center = :center")
->setParameter('center', $center)
->setMaxResults(100)
->getScalarResult();
yield [ \array_pop($personIds), \array_pop($personIds) ];
}
}

View File

@@ -1,78 +1,77 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>, <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\PersonBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use DateTime;
use Doctrine\Common\Collections\Criteria;
use LogicalException;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Test the creation or deletion of accompanying periods
*
* The person on which the test is done has a (current) period opened (and not
* Test the creation or deletion of accompanying periods.
*
* The person on which the test is done has a (current) period opened (and not
* closed) starting the 2015-01-05.
*
* @internal
* @coversNothing
*/
class AccompanyingPeriodControllerTest extends WebTestCase
{
/** @var \Symfony\Component\BrowserKit\Client */
protected $client;
/** @var Person The person on which the form is applied*/
protected $person;
/** @var \Doctrine\ORM\EntityManagerInterface */
protected static $em;
const OPENING_INPUT = 'chill_personbundle_accompanyingperiod[openingDate]';
const CLOSING_INPUT = 'chill_personbundle_accompanyingperiod[closingDate]';
const CLOSING_MOTIVE_INPUT = 'chill_personbundle_accompanyingperiod[closingMotive]';
public const CLOSING_INPUT = 'chill_personbundle_accompanyingperiod[closingDate]';
public const CLOSING_MOTIVE_INPUT = 'chill_personbundle_accompanyingperiod[closingMotive]';
public const OPENING_INPUT = 'chill_personbundle_accompanyingperiod[openingDate]';
/**
* Setup before the first test of this class (see phpunit doc)
* @var \Symfony\Component\BrowserKit\Client
*/
protected $client;
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
protected static $em;
/**
* @var Person The person on which the form is applied
*/
protected $person;
/**
* Setup before the first test of this class (see phpunit doc).
*/
public static function setUpBeforeClass()
{
static::bootKernel();
static::$em = static::$kernel->getContainer()
->get('doctrine.orm.entity_manager');
->get('doctrine.orm.entity_manager');
}
/**
* Setup before each test method (see phpunit doc)
* Setup before each test method (see phpunit doc).
*/
public function setUp()
{
$this->client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
));
$this->client = static::createClient([], [
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
]);
$center = static::$em->getRepository('ChillMainBundle:Center')
->findOneBy(array('name' => 'Center A'));
$this->person = (new Person(new \DateTime('2015-01-05')))
->findOneBy(['name' => 'Center A']);
$this->person = (new Person(new DateTime('2015-01-05')))
->setFirstName('Roland')
->setLastName('Gallorime')
->setCenter($center)
@@ -81,139 +80,21 @@ class AccompanyingPeriodControllerTest extends WebTestCase
static::$em->persist($this->person);
static::$em->flush();
}
/**
* TearDown after each test method (see phpunit doc)
/**
* TearDown after each test method (see phpunit doc).
*/
public function tearDown()
{
static::$em->refresh($this->person);
static::$em->remove($this->person);
static::$em->flush();
}
/**
* Given an array of periods (key openingDate, closingDate (optioal),
* closingMotive) generate the periods in the db.
*/
protected function generatePeriods(array $periods)
{
foreach ($periods as $periodDef) {
$period = new AccompanyingPeriod(new \DateTime($periodDef['openingDate']));
if (array_key_exists('closingDate', $periodDef)) {
if (!array_key_exists('closingMotive', $periodDef)) {
throw new \LogicalException('you must define a closing '
. 'motive into your periods fixtures');
}
$period->setClosingDate(new \DateTime($periodDef['closingDate']))
->setClosingMotive($periodDef['closingMotive']);
}
$this->person->addAccompanyingPeriod($period);
static::$em->persist($period);
}
static::$em->refresh($this->person);
static::$em->remove($this->person);
static::$em->flush();
}
/**
* Get the last value of a closing motive
* @var \Symfony\Component\DomCrawler\Form The form
* @return Chill\PersonBundle\Entity\AccompanyingPeriod The last value of closing
* motive
*/
protected function getLastValueOnClosingMotive(\Symfony\Component\DomCrawler\Form $form)
{
$values = $form->get(self::CLOSING_MOTIVE_INPUT)
->availableOptionValues();
return end($values);
}
/**
* Get a random closing motive
* @return Chill\PersonBundle\Entity\AccompanyingPeriod The last closing motive
*/
protected function getRandomClosingMotive()
{
$motives = static::$em
->getRepository('ChillPersonBundle:AccompanyingPeriod\ClosingMotive')
->findAll();
return end($motives);
}
/**
* Test the closing of a periods
*
* Given that a person as an accompanying period opened since 2015-01-05
* and we fill the close form (at /fr/person/[id]/accompanying-period/close
* with : dateClosing: 2015-02-01
* with : the last closing motive in list
* Then the response should redirect to period view
* And the next page should have a `.alert-danger` element present in page
*
* @todo
*/
public function testClosingCurrentPeriod()
{
$crawler = $this->client->request('GET', '/fr/person/'
.$this->person->getId().'/accompanying-period/close');
$form = $crawler->selectButton('Clôre la période')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue((new \DateTime('2015-02-01'))->format('d-m-Y'));
$cr = $this->client->submit($form);
$this->assertTrue($this->client->getResponse()->isRedirect(
'/fr/person/'.$this->person->getId().'/accompanying-period'),
'the server redirects to /accompanying-period page');
$this->assertGreaterThan(0, $this->client->followRedirect()
->filter('.alert-success')->count(),
"a 'success' element is shown");
}
/**
* Test the closing of a periods
*
* Given that a person as an accompanying period opened since 2015-01-05
* and we fill the close form (at /fr/person/[id]/accompanying-period/close
* with : dateClosing: 2014-01-01
* with : the last closing motive in list
* Then the response should redirect to period view
* And the next page should have a `.alert-danger` element present in page
*
* @todo
*/
public function testClosingCurrentPeriodWithDateClosingBeforeOpeningFails()
{
$crawler = $this->client->request('GET', '/fr/person/'
.$this->person->getId().'/accompanying-period/close');
$form = $crawler->selectButton('Clôre la période')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue((new \DateTime('2014-01-01'))->format('d-m-Y'));
$crawlerResponse = $this->client->submit($form);
$this->assertFalse($this->client->getResponse()->isRedirect(),
'the server stays on the /close page');
$this->assertGreaterThan(0, $crawlerResponse
->filter('.alert-danger')->count(),
"an '.alert-danger' element is shown");
}
/**
* Test the creation of a new period
*
* Test the creation of a new period.
*
* Given that a person as an accompanying period opened since 2015-01-05
* and we create a new period
* with : dateClosing: 2014-12-31
@@ -224,29 +105,160 @@ class AccompanyingPeriodControllerTest extends WebTestCase
public function testAddNewPeriodBeforeActual()
{
$crawler = $this->client->request('GET', '/fr/person/'
.$this->person->getId().'/accompanying-period/create');
. $this->person->getId() . '/accompanying-period/create');
$form = $crawler->selectButton('Créer une période d\'accompagnement')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('31-12-2014');
->setValue('31-12-2014');
$form->get(self::OPENING_INPUT)
->setValue('01-01-2014');
->setValue('01-01-2014');
$this->client->submit($form);
$this->assertTrue($this->client->getResponse()->isRedirect(
'/fr/person/'.$this->person->getId().'/accompanying-period'),
'the server redirects to /accompanying-period page');
$this->assertGreaterThan(0, $this->client->followRedirect()
->filter('.alert-success')->count(),
"a 'success' element is shown");
$this->assertTrue(
$this->client->getResponse()->isRedirect(
'/fr/person/' . $this->person->getId() . '/accompanying-period'
),
'the server redirects to /accompanying-period page'
);
$this->assertGreaterThan(
0,
$this->client->followRedirect()
->filter('.alert-success')->count(),
"a 'success' element is shown"
);
}
/**
* Create a period with closing after current fails
*
* Test the closing of a periods.
*
* Given that a person as an accompanying period opened since 2015-01-05
* and we fill the close form (at /fr/person/[id]/accompanying-period/close
* with : dateClosing: 2015-02-01
* with : the last closing motive in list
* Then the response should redirect to period view
* And the next page should have a `.alert-danger` element present in page
*
* @todo
*/
public function testClosingCurrentPeriod()
{
$crawler = $this->client->request('GET', '/fr/person/'
. $this->person->getId() . '/accompanying-period/close');
$form = $crawler->selectButton('Clôre la période')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue((new DateTime('2015-02-01'))->format('d-m-Y'));
$cr = $this->client->submit($form);
$this->assertTrue(
$this->client->getResponse()->isRedirect(
'/fr/person/' . $this->person->getId() . '/accompanying-period'
),
'the server redirects to /accompanying-period page'
);
$this->assertGreaterThan(
0,
$this->client->followRedirect()
->filter('.alert-success')->count(),
"a 'success' element is shown"
);
}
/**
* Test the closing of a periods.
*
* Given that a person as an accompanying period opened since 2015-01-05
* and we fill the close form (at /fr/person/[id]/accompanying-period/close
* with : dateClosing: 2014-01-01
* with : the last closing motive in list
* Then the response should redirect to period view
* And the next page should have a `.alert-danger` element present in page
*
* @todo
*/
public function testClosingCurrentPeriodWithDateClosingBeforeOpeningFails()
{
$crawler = $this->client->request('GET', '/fr/person/'
. $this->person->getId() . '/accompanying-period/close');
$form = $crawler->selectButton('Clôre la période')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue((new DateTime('2014-01-01'))->format('d-m-Y'));
$crawlerResponse = $this->client->submit($form);
$this->assertFalse(
$this->client->getResponse()->isRedirect(),
'the server stays on the /close page'
);
$this->assertGreaterThan(
0,
$crawlerResponse
->filter('.alert-danger')->count(),
"an '.alert-danger' element is shown"
);
}
/**
* create a period with date closing and date opening inside another period
* fails.
*
* Given that a person as an accompanying period opened since 2015-01-05
* and that this person has another accompanying period between 2014-01-01 and 2014-12-31
* and we create a new period
* with : dateClosing: 2014-02-01
* with : dateOpening: 2014-03-01
* with : the last closing motive in list
* Then the response should not redirect
* and a error element is shown on the response page
*/
public function testCreatePeriodAfterOpeningFails()
{
$this->generatePeriods([
[
'openingDate' => '2014-01-01',
'closingDate' => '2014-12-31',
'closingMotive' => $this->getRandomClosingMotive(),
],
]);
$crawler = $this->client->request('GET', '/fr/person/'
. $this->person->getId() . '/accompanying-period/create');
$form = $crawler->selectButton('Créer une période d\'accompagnement')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('2014-02-01');
$form->get(self::OPENING_INPUT)
->setValue('01-03-2014');
$crawlerResponse = $this->client->submit($form);
$this->assertFalse(
$this->client->getResponse()->isRedirect(),
'the server stay on form page'
);
$this->assertGreaterThan(
0,
$crawlerResponse->filter('.alert-danger')->count(),
"an 'error' element is shown"
);
}
/**
* Create a period with closing after current fails.
*
* Given that a person as an accompanying period opened since 2015-01-05
* and we create a new period
* with : dateClosing: 2015-02-01 (after 2015-01-05)
@@ -257,31 +269,164 @@ class AccompanyingPeriodControllerTest extends WebTestCase
*/
public function testCreatePeriodWithClosingAfterCurrentFails()
{
$this->markTestSkipped("Multiple period may now cover. This test is kept ".
"in case of a configuration may add this feature again");
$this->markTestSkipped('Multiple period may now cover. This test is kept ' .
'in case of a configuration may add this feature again');
$crawler = $this->client->request('GET', '/fr/person/'
.$this->person->getId().'/accompanying-period/create');
. $this->person->getId() . '/accompanying-period/create');
$form = $crawler->selectButton("Créer une période d'accompagnement")->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('01-02-2015');
->setValue('01-02-2015');
$form->get(self::OPENING_INPUT)
->setValue('31-12-2014');
->setValue('31-12-2014');
$crawler = $this->client->submit($form);
$this->assertFalse($this->client->getResponse()->isRedirect(),
'the server stay on form page');
$this->assertGreaterThan(0, $crawler->filter('.alert-danger')->count(),
"an 'error' element is shown");
$this->assertFalse(
$this->client->getResponse()->isRedirect(),
'the server stay on form page'
);
$this->assertGreaterThan(
0,
$crawler->filter('.alert-danger')->count(),
"an 'error' element is shown"
);
}
/**
* Create a period after a current opened period fails
*
* create a period with date closing after opening fails.
*
* Given that a person as an accompanying period opened since 2015-01-05
* and we create a new period
* with : dateClosing: 2014-01-01 (before opening)
* with : dateOpening: 2015-01-01
* with : the last closing motive in list
* Then the response should redirect to period view
*/
public function testCreatePeriodWithClosingBeforeOpeningFails()
{
$crawler = $this->client->request('GET', '/fr/person/'
. $this->person->getId() . '/accompanying-period/create');
$form = $crawler->selectButton('Créer une période d\'accompagnement')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('01-01-2014');
$form->get(self::OPENING_INPUT)
->setValue('01-01-2015');
$crawler = $this->client->submit($form);
$this->assertFalse(
$this->client->getResponse()->isRedirect(),
'the server stay on form page'
);
$this->assertGreaterThan(
0,
$crawler->filter('.alert-danger')->count(),
"an 'error' element is shown"
);
}
/**
* create a period with date end between another period must fails.
*
* Given that a person as an accompanying period opened since 2015-01-05
* and that this person has another accompanying period between 2014-01-01 and 2014-12-31
* and we create a new period
* with : dateClosing: 2014-16-01
* with : dateOpening: 2013-01-01
* with : the last closing motive in list
* Then the response should not redirect
* and a error element is shown on the response page
*/
public function testCreatePeriodWithDateEndBetweenAnotherPeriodFails()
{
$this->generatePeriods([
[
'openingDate' => '2014-01-01',
'closingDate' => '2014-12-31',
'closingMotive' => $this->getRandomClosingMotive(),
],
]);
$crawler = $this->client->request('GET', '/fr/person/'
. $this->person->getId() . '/accompanying-period/create');
$form = $crawler->selectButton('Créer une période d\'accompagnement')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('31-12-2014');
$form->get(self::OPENING_INPUT)
->setValue('01-02-2015');
$crawlerResponse = $this->client->submit($form);
$this->assertFalse(
$this->client->getResponse()->isRedirect(),
'the server stay on form page'
);
$this->assertGreaterThan(
0,
$crawlerResponse->filter('.alert-danger')->count(),
"an 'error' element is shown"
);
}
/**
* Create a period with dateOpening between another period must fails.
*
* Given that a person as an accompanying period opened since 2015-01-05
* and that this person has another accompanying period between 2014-01-01 and 2014-12-31
* and we create a new period
* with : dateClosing: 2015-01-01
* with : dateOpening: 2014-06-01
* with : the last closing motive in list
* Then the response should not redirect
* and a error element is shown on the response page
*/
public function testCreatePeriodWithDateOpeningBetweenAnotherPeriodFails()
{
$this->generatePeriods([
[
'openingDate' => '2014-01-01',
'closingDate' => '2014-12-31',
'closingMotive' => $this->getRandomClosingMotive(),
],
]);
$crawler = $this->client->request('GET', '/fr/person/'
. $this->person->getId() . '/accompanying-period/create');
$form = $crawler->selectButton('Créer une période d\'accompagnement')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('2015-01-01');
$form->get(self::OPENING_INPUT)
->setValue('01-06-2014');
$crawlerResponse = $this->client->submit($form);
$this->assertFalse(
$this->client->getResponse()->isRedirect(),
'the server stay on form page'
);
$this->assertGreaterThan(
0,
$crawlerResponse->filter('.alert-danger')->count(),
"an 'error' element is shown"
);
}
/**
* Create a period after a current opened period fails.
*
* Given that a person as an accompanying period opened since 2015-01-05
* and we create a new period
* with : dateClosing: 2015-03-01
@@ -292,212 +437,66 @@ class AccompanyingPeriodControllerTest extends WebTestCase
*/
public function testCreatePeriodWithOpeningAndClosingAfterCurrentFails()
{
$this->markTestSkipped("Multiple period may now cover. This test is kept ".
"in case of a configuration may add this feature again");
$this->markTestSkipped('Multiple period may now cover. This test is kept ' .
'in case of a configuration may add this feature again');
$crawler = $this->client->request('GET', '/fr/person/'
.$this->person->getId().'/accompanying-period/create');
. $this->person->getId() . '/accompanying-period/create');
$form = $crawler->selectButton("Créer une période d'accompagnement")->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('01-03-2015');
->setValue('01-03-2015');
$form->get(self::OPENING_INPUT)
->setValue('01-02-2015');
->setValue('01-02-2015');
$crawler = $this->client->submit($form);
$this->assertFalse($this->client->getResponse()->isRedirect(),
'the server stay on form page');
$this->assertGreaterThan(0, $crawler->filter('.alert-danger')->count(),
"an 'error' element is shown");
$this->assertFalse(
$this->client->getResponse()->isRedirect(),
'the server stay on form page'
);
$this->assertGreaterThan(
0,
$crawler->filter('.alert-danger')->count(),
"an 'error' element is shown"
);
}
/**
* create a period with date end between another period must fails
*
* Given that a person as an accompanying period opened since 2015-01-05
* and that this person has another accompanying period between 2014-01-01 and 2014-12-31
* and we create a new period
* with : dateClosing: 2014-16-01
* with : dateOpening: 2013-01-01
* with : the last closing motive in list
* Then the response should not redirect
* and a error element is shown on the response page
*/
public function testCreatePeriodWithDateEndBetweenAnotherPeriodFails()
{
$this->generatePeriods(array(
[
'openingDate' => '2014-01-01',
'closingDate' => '2014-12-31',
'closingMotive' => $this->getRandomClosingMotive()
]
));
$crawler = $this->client->request('GET', '/fr/person/'
.$this->person->getId().'/accompanying-period/create');
$form = $crawler->selectButton('Créer une période d\'accompagnement')->form();;
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('31-12-2014');
$form->get(self::OPENING_INPUT)
->setValue('01-02-2015');
$crawlerResponse = $this->client->submit($form);
$this->assertFalse($this->client->getResponse()->isRedirect(),
'the server stay on form page');
$this->assertGreaterThan(0, $crawlerResponse->filter('.alert-danger')->count(),
"an 'error' element is shown");
}
/**
* create a period with date closing after opening fails
*
* Given that a person as an accompanying period opened since 2015-01-05
* and we create a new period
* with : dateClosing: 2014-01-01 (before opening)
* with : dateOpening: 2015-01-01
* with : the last closing motive in list
* Then the response should redirect to period view
*/
public function testCreatePeriodWithClosingBeforeOpeningFails()
{
$crawler = $this->client->request('GET', '/fr/person/'
.$this->person->getId().'/accompanying-period/create');
$form = $crawler->selectButton('Créer une période d\'accompagnement')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('01-01-2014');
$form->get(self::OPENING_INPUT)
->setValue('01-01-2015');
$crawler = $this->client->submit($form);
$this->assertFalse($this->client->getResponse()->isRedirect(),
'the server stay on form page');
$this->assertGreaterThan(0, $crawler->filter('.alert-danger')->count(),
"an 'error' element is shown");
}
/**
* create a period with date closing and date opening inside another period
* fails
*
* Given that a person as an accompanying period opened since 2015-01-05
* and that this person has another accompanying period between 2014-01-01 and 2014-12-31
* and we create a new period
* with : dateClosing: 2014-02-01
* with : dateOpening: 2014-03-01
* with : the last closing motive in list
* Then the response should not redirect
* and a error element is shown on the response page
*/
public function testCreatePeriodAfterOpeningFails()
{
$this->generatePeriods(array(
[
'openingDate' => '2014-01-01',
'closingDate' => '2014-12-31',
'closingMotive' => $this->getRandomClosingMotive()
]
));
$crawler = $this->client->request('GET', '/fr/person/'
.$this->person->getId().'/accompanying-period/create');
$form = $crawler->selectButton('Créer une période d\'accompagnement')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('2014-02-01');
$form->get(self::OPENING_INPUT)
->setValue('01-03-2014');
$crawlerResponse = $this->client->submit($form);
$this->assertFalse($this->client->getResponse()->isRedirect(),
'the server stay on form page');
$this->assertGreaterThan(0, $crawlerResponse->filter('.alert-danger')->count(),
"an 'error' element is shown");
}
/**
* Create a period with dateOpening between another period must fails
*
* Given that a person as an accompanying period opened since 2015-01-05
* and that this person has another accompanying period between 2014-01-01 and 2014-12-31
* and we create a new period
* with : dateClosing: 2015-01-01
* with : dateOpening: 2014-06-01
* with : the last closing motive in list
* Then the response should not redirect
* and a error element is shown on the response page
*/
public function testCreatePeriodWithDateOpeningBetweenAnotherPeriodFails()
{
$this->generatePeriods(array(
[
'openingDate' => '2014-01-01',
'closingDate' => '2014-12-31',
'closingMotive' => $this->getRandomClosingMotive()
]
));
$crawler = $this->client->request('GET', '/fr/person/'
.$this->person->getId().'/accompanying-period/create');
$form = $crawler->selectButton('Créer une période d\'accompagnement')->form();
$form->get(self::CLOSING_MOTIVE_INPUT)
->setValue($this->getLastValueOnClosingMotive($form));
$form->get(self::CLOSING_INPUT)
->setValue('2015-01-01');
$form->get(self::OPENING_INPUT)
->setValue('01-06-2014');
$crawlerResponse = $this->client->submit($form);
$this->assertFalse($this->client->getResponse()->isRedirect(),
'the server stay on form page');
$this->assertGreaterThan(0, $crawlerResponse->filter('.alert-danger')->count(),
"an 'error' element is shown");
}
/**
* @group reopening
*/
public function testReOpeningPeriod()
{
// test that re-opening a period which is opened does not work
$this->client->request('GET',
sprintf(
'/fr/person/%d/accompanying-period/%d/re-open',
$this->person->getId(),
$this->person->getOpenedAccompanyingPeriod()->getId()
)
);
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"Test an error is returned on a period which cannot be reopened");
$this->client->request(
'GET',
sprintf(
'/fr/person/%d/accompanying-period/%d/re-open',
$this->person->getId(),
$this->person->getOpenedAccompanyingPeriod()->getId()
)
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'Test an error is returned on a period which cannot be reopened'
);
// close the current period
$period = $this->person->getOpenedAccompanyingPeriod();
$period->setClosingDate(new \DateTime('2015-02-05'));
$period->setClosingDate(new DateTime('2015-02-05'));
$this->person->close($period);
$this->generatePeriods(array(
$this->generatePeriods([
[
'openingDate' => '2014-01-01',
'closingDate' => '2014-12-31',
'closingMotive' => $this->getRandomClosingMotive()
]
));
'closingMotive' => $this->getRandomClosingMotive(),
],
]);
$periods = $this->person->getAccompanyingPeriodsOrdered();
/* @var $criteria Criteria */
$criteria = Criteria::create();
@@ -505,29 +504,91 @@ class AccompanyingPeriodControllerTest extends WebTestCase
$firstPeriod = reset($periods);
$lastPeriod = end($periods);
$this->markTestSkipped("From here, the test should be rewritten");
$this->markTestSkipped('From here, the test should be rewritten');
// test that it is not possible to open the first period in the list
$this->client->request('GET',
sprintf('/fr/person/%d/accompanying-period/%d/re-open', $this->person->getId(), reset($periods)->getId())
);
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"Test an error is returned on the first period in the list");
$this->client->request(
'GET',
sprintf('/fr/person/%d/accompanying-period/%d/re-open', $this->person->getId(), reset($periods)->getId())
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'Test an error is returned on the first period in the list'
);
// test that re-opening the last closed period works
$crawler = $this->client->request('GET',
sprintf('/fr/person/%d/accompanying-period/%d/re-open', $this->person->getId(), end($periods)->getId())
);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
$links = $crawler->selectLink('Confirmer');
$this->assertEquals(1, $links->count(), "test the link 'confirmer' is present");
$this->client->click($links->link());
$this->assertTrue($this->client->getResponse()->isRedirect(),
"Test the response is a redirection => the period is re-opened");
$crawler = $this->client->request(
'GET',
sprintf('/fr/person/%d/accompanying-period/%d/re-open', $this->person->getId(), end($periods)->getId())
);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
$links = $crawler->selectLink('Confirmer');
$this->assertEquals(1, $links->count(), "test the link 'confirmer' is present");
$this->client->click($links->link());
$this->assertTrue(
$this->client->getResponse()->isRedirect(),
'Test the response is a redirection => the period is re-opened'
);
}
/**
* Given an array of periods (key openingDate, closingDate (optioal),
* closingMotive) generate the periods in the db.
*/
protected function generatePeriods(array $periods)
{
foreach ($periods as $periodDef) {
$period = new AccompanyingPeriod(new DateTime($periodDef['openingDate']));
if (array_key_exists('closingDate', $periodDef)) {
if (!array_key_exists('closingMotive', $periodDef)) {
throw new LogicalException('you must define a closing '
. 'motive into your periods fixtures');
}
$period->setClosingDate(new DateTime($periodDef['closingDate']))
->setClosingMotive($periodDef['closingMotive']);
}
$this->person->addAccompanyingPeriod($period);
static::$em->persist($period);
}
static::$em->flush();
}
/**
* Get the last value of a closing motive.
*
* @var \Symfony\Component\DomCrawler\Form The form
*
* @return Chill\PersonBundle\Entity\AccompanyingPeriod The last value of closing
* motive
*/
protected function getLastValueOnClosingMotive(\Symfony\Component\DomCrawler\Form $form)
{
$values = $form->get(self::CLOSING_MOTIVE_INPUT)
->availableOptionValues();
return end($values);
}
/**
* Get a random closing motive.
*
* @return Chill\PersonBundle\Entity\AccompanyingPeriod The last closing motive
*/
protected function getRandomClosingMotive()
{
$motives = static::$em
->getRepository('ChillPersonBundle:AccompanyingPeriod\ClosingMotive')
->findAll();
return end($motives);
}
}

View File

@@ -1,79 +1,52 @@
<?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\PersonBundle\Tests\Controller;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\AddressReference;
use Chill\MainBundle\Entity\Center;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\MainBundle\Test\PrepareClientTrait;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Household\HouseholdMember;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\HttpFoundation\Request;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
use function array_map;
use function array_pop;
use function random_int;
use function shuffle;
/**
* @internal
* @coversNothing
*/
class HouseholdApiControllerTest extends WebTestCase
{
use PrepareClientTrait;
private array $toDelete = [];
/**
* @dataProvider generatePersonId
*/
public function testSuggestByAccompanyingPeriodParticipation(int $personId)
protected function tearDown()
{
$client = $this->getClientAuthenticated();
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$client->request(
Request::METHOD_GET,
"/api/1.0/person/household/suggest/by-person/{$personId}/through-accompanying-period-participation.json"
);
foreach ($this->toDelete as [$class, $id]) {
$obj = $em->getRepository($class)->find($id);
$em->remove($obj);
}
$this->assertResponseIsSuccessful();
}
/**
* @dataProvider generateHouseholdId
*/
public function testSuggestAddressByHousehold(int $householdId)
{
$client = $this->getClientAuthenticated();
$client->request(
Request::METHOD_GET,
"/api/1.0/person/address/suggest/by-household/{$householdId}.json"
);
$this->assertResponseIsSuccessful();
}
/**
* @dataProvider generateHouseholdAssociatedWithAddressReference
*/
public function testFindHouseholdByAddressReference(int $addressReferenceId, int $expectedHouseholdId)
{
$client = $this->getClientAuthenticated();
$client->request(
Request::METHOD_GET,
"/api/1.0/person/household/by-address-reference/$addressReferenceId.json"
);
$this->assertResponseIsSuccessful();
$data = json_decode($client->getResponse()->getContent(), true);
$this->assertArrayHasKey('count', $data);
$this->assertArrayHasKey('results', $data);
$householdIds = \array_map(function($r) {
return $r['id'];
}, $data['results']);
$this->assertContains($expectedHouseholdId, $householdIds);
$em->flush();
}
public function generateHouseholdAssociatedWithAddressReference()
@@ -84,18 +57,17 @@ class HouseholdApiControllerTest extends WebTestCase
$nbReference = $em->createQueryBuilder()->select('count(ar)')->from(AddressReference::class, 'ar')
->getQuery()->getSingleScalarResult();
$reference = $em->createQueryBuilder()->select('ar')->from(AddressReference::class, 'ar')
->setFirstResult(\random_int(0, $nbReference))
->setFirstResult(random_int(0, $nbReference))
->setMaxResults(1)
->getQuery()->getSingleResult();
$p = new Person();
$p->setFirstname('test')->setLastName('test lastname')
->setGender(Person::BOTH_GENDER)
->setCenter($centerA)
;
->setCenter($centerA);
$em->persist($p);
$h = new Household();
$h->addMember($m = (new HouseholdMember())->setPerson($p));
$h->addAddress(Address::createFromAddressReference($reference)->setValidFrom(new \DateTime('today')));
$h->addAddress(Address::createFromAddressReference($reference)->setValidFrom(new DateTime('today')));
$em->persist($m);
$em->persist($h);
@@ -104,49 +76,12 @@ class HouseholdApiControllerTest extends WebTestCase
$this->toDelete = $this->toDelete + [
[HouseholdMember::class, $m->getId()],
[User::class, $p->getId()],
[Household::class, $h->getId()]
[Household::class, $h->getId()],
];
yield [$reference->getId(), $h->getId()];
}
protected function tearDown()
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
foreach ($this->toDelete as list($class, $id)) {
$obj = $em->getRepository($class)->find($id);
$em->remove($obj);
}
$em->flush();
}
public function generatePersonId()
{
self::bootKernel();
$qb = self::$container->get(EntityManagerInterface::class)
->createQueryBuilder();
$period = $qb
->select('ap')
->from(AccompanyingPeriod::class, 'ap')
->where(
$qb->expr()->gte('SIZE(ap.participations)', 2)
)
->getQuery()
->setMaxResults(1)
->getSingleResult()
;
$person = $period->getParticipations()
->first()->getPerson();
yield [ $person->getId() ];
}
public function generateHouseholdId()
{
self::bootKernel();
@@ -165,13 +100,91 @@ class HouseholdApiControllerTest extends WebTestCase
->setParameter('center_name', 'Center A')
->setMaxResults(100)
->getQuery()
->getResult()
;
->getResult();
\shuffle($householdIds);
shuffle($householdIds);
yield [ \array_pop($householdIds)['id'] ];
yield [ \array_pop($householdIds)['id'] ];
yield [ \array_pop($householdIds)['id'] ];
yield [array_pop($householdIds)['id']];
yield [array_pop($householdIds)['id']];
yield [array_pop($householdIds)['id']];
}
public function generatePersonId()
{
self::bootKernel();
$qb = self::$container->get(EntityManagerInterface::class)
->createQueryBuilder();
$period = $qb
->select('ap')
->from(AccompanyingPeriod::class, 'ap')
->where(
$qb->expr()->gte('SIZE(ap.participations)', 2)
)
->getQuery()
->setMaxResults(1)
->getSingleResult();
$person = $period->getParticipations()
->first()->getPerson();
yield [$person->getId()];
}
/**
* @dataProvider generateHouseholdAssociatedWithAddressReference
*/
public function testFindHouseholdByAddressReference(int $addressReferenceId, int $expectedHouseholdId)
{
$client = $this->getClientAuthenticated();
$client->request(
Request::METHOD_GET,
"/api/1.0/person/household/by-address-reference/{$addressReferenceId}.json"
);
$this->assertResponseIsSuccessful();
$data = json_decode($client->getResponse()->getContent(), true);
$this->assertArrayHasKey('count', $data);
$this->assertArrayHasKey('results', $data);
$householdIds = array_map(function ($r) {
return $r['id'];
}, $data['results']);
$this->assertContains($expectedHouseholdId, $householdIds);
}
/**
* @dataProvider generateHouseholdId
*/
public function testSuggestAddressByHousehold(int $householdId)
{
$client = $this->getClientAuthenticated();
$client->request(
Request::METHOD_GET,
"/api/1.0/person/address/suggest/by-household/{$householdId}.json"
);
$this->assertResponseIsSuccessful();
}
/**
* @dataProvider generatePersonId
*/
public function testSuggestByAccompanyingPeriodParticipation(int $personId)
{
$client = $this->getClientAuthenticated();
$client->request(
Request::METHOD_GET,
"/api/1.0/person/household/suggest/by-person/{$personId}/through-accompanying-period-participation.json"
);
$this->assertResponseIsSuccessful();
}
}

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 Chill\PersonBundle\Tests\Controller;
use Chill\PersonBundle\Entity\Household\Household;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\Test\PrepareClientTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Chill\PersonBundle\Entity\Household\Household;
use DateInterval;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
use function array_pop;
use function shuffle;
/**
* @internal
* @coversNothing
*/
class HouseholdControllerTest extends WebTestCase
{
use PrepareClientTrait;
@@ -20,50 +35,35 @@ class HouseholdControllerTest extends WebTestCase
$this->client = $this->getClientAuthenticated();
}
/**
* @dataProvider generateValidHouseholdIds
*/
public function testSummary($householdId)
public function generateValidHouseholdIds()
{
$this->client->request(
Request::METHOD_GET,
"/fr/person/household/{$householdId}/summary"
);
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$this->assertResponseIsSuccessful();
}
/**
* @dataProvider generateValidHouseholdIds
*/
public function testEditMetadata($householdId)
{
$crawler = $this->client->request(
Request::METHOD_GET,
"/fr/person/household/{$householdId}/summary",
[
'edit' => true
]
);
$this->assertResponseIsSuccessful();
$form = $crawler->filter('#form_household_comment_confirm')
->form();
$form['household[commentMembers][comment]'] = "This is a text **generated** by automatic tests";
$form['household[waitingForBirth]']->tick();
$form['household[waitingForBirthDate]'] = (new \DateTime('today'))
->add(new \DateInterval('P1M'))->format('Y-m-d');
$this->client->submit($form);
$this->assertResponseRedirects("/fr/person/household/{$householdId}/summary");
$ids = $em->createQuery(
'SELECT DISTINCT h.id FROM ' . Household::class . ' h ' .
'JOIN h.members m ' .
'JOIN m.person p ' .
'JOIN p.center c ' .
'WHERE c.name = :center'
)
->setParameter('center', 'Center A')
->setMaxResults(100)
->getScalarResult();
shuffle($ids);
yield [array_pop($ids)['id']];
yield [array_pop($ids)['id']];
yield [array_pop($ids)['id']];
}
/**
* @dataProvider generateValidHouseholdIds
*
* @param mixed $householdId
*/
public function testAddresses($householdId)
{
@@ -73,11 +73,12 @@ class HouseholdControllerTest extends WebTestCase
);
$this->assertResponseIsSuccessful();
}
/**
* @dataProvider generateValidHouseholdIds
*
* @param mixed $householdId
*/
public function testAddressMove($householdId)
{
@@ -91,26 +92,48 @@ class HouseholdControllerTest extends WebTestCase
// ici, il faudrait tester la requête POST
}
public function generateValidHouseholdIds()
/**
* @dataProvider generateValidHouseholdIds
*
* @param mixed $householdId
*/
public function testEditMetadata($householdId)
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$crawler = $this->client->request(
Request::METHOD_GET,
"/fr/person/household/{$householdId}/summary",
[
'edit' => true,
]
);
$ids = $em->createQuery("SELECT DISTINCT h.id FROM ".Household::class." h ".
"JOIN h.members m ".
"JOIN m.person p ".
"JOIN p.center c ".
"WHERE c.name = :center"
)
->setParameter('center', "Center A")
->setMaxResults(100)
->getScalarResult()
;
$this->assertResponseIsSuccessful();
\shuffle($ids);
$form = $crawler->filter('#form_household_comment_confirm')
->form();
yield [ \array_pop($ids)['id'] ];
yield [ \array_pop($ids)['id'] ];
yield [ \array_pop($ids)['id'] ];
$form['household[commentMembers][comment]'] = 'This is a text **generated** by automatic tests';
$form['household[waitingForBirth]']->tick();
$form['household[waitingForBirthDate]'] = (new DateTime('today'))
->add(new DateInterval('P1M'))->format('Y-m-d');
$this->client->submit($form);
$this->assertResponseRedirects("/fr/person/household/{$householdId}/summary");
}
/**
* @dataProvider generateValidHouseholdIds
*
* @param mixed $householdId
*/
public function testSummary($householdId)
{
$this->client->request(
Request::METHOD_GET,
"/fr/person/household/{$householdId}/summary"
);
$this->assertResponseIsSuccessful();
}
}

View File

@@ -1,184 +1,114 @@
<?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\ChillPersonBundle\Tests\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\Test\PrepareClientTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Household\HouseholdMember;
use Chill\PersonBundle\Entity\Household\Position;
use Chill\PersonBundle\Entity\Person;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\ORM\EntityManagerInterface;
use Iterator;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use function array_pop;
use function json_decode;
use function json_encode;
use function random_int;
use function shuffle;
/**
* @internal
* @coversNothing
*/
class HouseholdMemberControllerTest extends WebTestCase
{
use PrepareClientTrait;
/**
* @dataProvider provideValidDataMove
*/
public function testMoveMember($personId, $householdId, $positionId, \DateTimeInterface $date)
public function provideValidDataEditMember(): Iterator
{
$client = $this->getClientAuthenticated();
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$client->request(
Request::METHOD_POST,
'/api/1.0/person/household/members/move.json',
[], // parameters
[], // files
[], // server
\json_encode(
[
'concerned' =>
[
[
'person' =>
[
'type' => 'person',
'id' => $personId
],
'start_date' =>
[
'datetime' => $date->format(\DateTimeInterface::RFC3339)
],
'position' =>
[
'type' => 'household_position',
'id' => $positionId
],
'holder' => false,
'comment' => "Introduced by automated test",
],
],
'destination' =>
[
'type' => 'household',
'id' => $householdId
]
],
true)
);
$membershipIds = $em->createQuery('SELECT m.id FROM ' . HouseholdMember::class . ' m ' .
'JOIN m.person p ' .
'JOIN p.center c ' .
'WHERE c.name = :center AND m.endDate IS NULL')
->setParameter('center', 'Center A')
->getScalarResult();
$this->assertEquals(Response::HTTP_OK,
$client->getResponse()->getStatusCode()
);
shuffle($membershipIds);
yield [array_pop($membershipIds)['id']];
}
/**
* @dataProvider provideValidDataMove
*/
public function testMoveMemberToNewHousehold($personId, $householdId, $positionId, \DateTimeInterface $date)
public function provideValidDataMove(): Iterator
{
$client = $this->getClientAuthenticated();
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$yesterday = new DateTimeImmutable('yesterday');
$client->request(
Request::METHOD_POST,
'/api/1.0/person/household/members/move.json',
[], // parameters
[], // files
[], // server
\json_encode(
[
'concerned' =>
[
[
'person' =>
[
'type' => 'person',
'id' => $personId
],
'start_date' =>
[
'datetime' => $date->format(\DateTimeInterface::RFC3339)
],
'position' =>
[
'type' => 'household_position',
'id' => $positionId
],
'holder' => false,
'comment' => "Introduced by automated test",
],
],
'destination' =>
[
'type' => 'household',
]
],
true)
);
$personIds = $em->createQuery(
'SELECT p.id FROM ' . Person::class . ' p ' .
'JOIN p.center c ' .
'WHERE ' .
'c.name = :center '
)
->setParameter('center', 'Center A')
->setMaxResults(100)
->getScalarResult();
$this->assertEquals(Response::HTTP_OK,
$client->getResponse()->getStatusCode()
);
shuffle($personIds);
$data = \json_decode($client->getResponse()->getContent(), true);
$household = new Household();
$em->persist($household);
$em->flush();
$this->assertIsArray($data);
$this->assertArrayHasKey('members', $data);
$this->assertIsArray($data['members']);
$this->assertEquals(1, count($data['members']),
"assert new household count one member");
$this->assertArrayHasKey('person', $data['members'][0]);
$this->assertArrayHasKey('id', $data['members'][0]['person']);
$this->assertEquals($personId, $data['members'][0]['person']['id']);
}
$positions = $em->createQuery('SELECT pos.id FROM ' . Position::class . ' pos ' .
'WHERE pos.shareHouseHold = TRUE')
->getResult();
/**
* @dataProvider provideValidDataMove
*/
public function testLeaveWithoutHousehold($personId, $householdId, $positionId, \DateTimeInterface $date)
{
$client = $this->getClientAuthenticated();
$i = 0;
$client->request(
Request::METHOD_POST,
'/api/1.0/person/household/members/move.json',
[], // parameters
[], // files
[], // server
\json_encode(
[
'concerned' =>
[
[
'person' =>
[
'type' => 'person',
'id' => $personId
],
'start_date' =>
[
'datetime' => $date->format(\DateTimeInterface::RFC3339)
],
'position' =>
[
'type' => 'household_position',
'id' => $positionId
],
'holder' => false,
'comment' => "Introduced by automated test",
],
],
'destination' => null
],
true)
);
do {
$id = array_pop($personIds)['id'];
$person = self::$container->get(EntityManagerInterface::class)
->getRepository(Person::class)
->find($id);
$this->assertEquals(Response::HTTP_OK,
$client->getResponse()->getStatusCode()
);
$participation = $person->getCurrentHouseholdParticipationShareHousehold();
$data = \json_decode($client->getResponse()->getContent(), true);
if (null == $participation
|| (
null === $participation->getEndDate()
&& $participation->getStartDate() <= $yesterday
)) {
++$i;
$this->assertEquals(null, $data);
yield [
$id,
$household->getId(),
$positions[random_int(0, count($positions) - 1)]['id'],
new DateTimeImmutable('tomorrow'),
];
}
} while (1 >= $i);
}
/**
* @dataProvider provideValidDataEditMember
*
* @param mixed $memberId
*/
public function testEditMember($memberId)
{
@@ -199,75 +129,170 @@ class HouseholdMemberControllerTest extends WebTestCase
$this->assertEquals(302, $client->getResponse()->getStatusCode());
}
public function provideValidDataMove(): \Iterator
/**
* @dataProvider provideValidDataMove
*
* @param mixed $personId
* @param mixed $householdId
* @param mixed $positionId
*/
public function testLeaveWithoutHousehold($personId, $householdId, $positionId, DateTimeInterface $date)
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$yesterday = new \DateTimeImmutable('yesterday');
$client = $this->getClientAuthenticated();
$personIds = $em->createQuery("SELECT p.id FROM ".Person::class." p ".
"JOIN p.center c ".
"WHERE ".
"c.name = :center "
$client->request(
Request::METHOD_POST,
'/api/1.0/person/household/members/move.json',
[], // parameters
[], // files
[], // server
json_encode(
[
'concerned' => [
[
'person' => [
'type' => 'person',
'id' => $personId,
],
'start_date' => [
'datetime' => $date->format(DateTimeInterface::RFC3339),
],
'position' => [
'type' => 'household_position',
'id' => $positionId,
],
'holder' => false,
'comment' => 'Introduced by automated test',
],
],
'destination' => null,
],
true
)
->setParameter('center', "Center A")
->setMaxResults(100)
->getScalarResult()
;
);
\shuffle($personIds);
$this->assertEquals(
Response::HTTP_OK,
$client->getResponse()->getStatusCode()
);
$household = new Household();
$em->persist($household);
$em->flush();
$data = json_decode($client->getResponse()->getContent(), true);
$positions = $em->createQuery("SELECT pos.id FROM ".Position::class." pos ".
"WHERE pos.shareHouseHold = TRUE")
->getResult()
;
$i = 0;
do {
$id = \array_pop($personIds)['id'];
$person = self::$container->get(EntityManagerInterface::class)
->getRepository(Person::Class)
->find($id);
$participation = $person->getCurrentHouseholdParticipationShareHousehold();
if (NULL == $participation ||
(
NULL === $participation->getEndDate()
&& $participation->getStartDate() <= $yesterday
)) {
$i++;
yield [
$id,
$household->getId(),
$positions[\random_int(0, count($positions) - 1)]['id'],
new \DateTimeImmutable('tomorrow')
];
}
} while ($i <= 1);
$this->assertEquals(null, $data);
}
public function provideValidDataEditMember(): \Iterator
/**
* @dataProvider provideValidDataMove
*
* @param mixed $personId
* @param mixed $householdId
* @param mixed $positionId
*/
public function testMoveMember($personId, $householdId, $positionId, DateTimeInterface $date)
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$client = $this->getClientAuthenticated();
$membershipIds = $em->createQuery("SELECT m.id FROM ".HouseholdMember::class." m ".
"JOIN m.person p ".
"JOIN p.center c ".
"WHERE c.name = :center AND m.endDate IS NULL")
->setParameter('center', 'Center A')
->getScalarResult()
;
$client->request(
Request::METHOD_POST,
'/api/1.0/person/household/members/move.json',
[], // parameters
[], // files
[], // server
json_encode(
[
'concerned' => [
[
'person' => [
'type' => 'person',
'id' => $personId,
],
'start_date' => [
'datetime' => $date->format(DateTimeInterface::RFC3339),
],
'position' => [
'type' => 'household_position',
'id' => $positionId,
],
'holder' => false,
'comment' => 'Introduced by automated test',
],
],
'destination' => [
'type' => 'household',
'id' => $householdId,
],
],
true
)
);
\shuffle($membershipIds);
$this->assertEquals(
Response::HTTP_OK,
$client->getResponse()->getStatusCode()
);
}
yield [ \array_pop($membershipIds)['id'] ];
/**
* @dataProvider provideValidDataMove
*
* @param mixed $personId
* @param mixed $householdId
* @param mixed $positionId
*/
public function testMoveMemberToNewHousehold($personId, $householdId, $positionId, DateTimeInterface $date)
{
$client = $this->getClientAuthenticated();
$client->request(
Request::METHOD_POST,
'/api/1.0/person/household/members/move.json',
[], // parameters
[], // files
[], // server
json_encode(
[
'concerned' => [
[
'person' => [
'type' => 'person',
'id' => $personId,
],
'start_date' => [
'datetime' => $date->format(DateTimeInterface::RFC3339),
],
'position' => [
'type' => 'household_position',
'id' => $positionId,
],
'holder' => false,
'comment' => 'Introduced by automated test',
],
],
'destination' => [
'type' => 'household',
],
],
true
)
);
$this->assertEquals(
Response::HTTP_OK,
$client->getResponse()->getStatusCode()
);
$data = json_decode($client->getResponse()->getContent(), true);
$this->assertIsArray($data);
$this->assertArrayHasKey('members', $data);
$this->assertIsArray($data['members']);
$this->assertEquals(
1,
count($data['members']),
'assert new household count one member'
);
$this->assertArrayHasKey('person', $data['members'][0]);
$this->assertArrayHasKey('id', $data['members'][0]['person']);
$this->assertEquals($personId, $data['members'][0]['person']['id']);
}
}

View File

@@ -1,159 +1,150 @@
<?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\PersonBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Chill\PersonBundle\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class PersonAddressControllerTest extends WebTestCase
{
/** @var \Doctrine\ORM\EntityManagerInterface The entity manager */
protected $em;
/** @var Person The person on which the test is executed */
protected static $person;
/**
*
* @var \Chill\MainBundle\Entity\PostalCode
*/
protected $postalCode;
/**
*
* @var \Symfony\Component\BrowserKit\Client
*/
protected $client;
/**
* @var \Doctrine\ORM\EntityManagerInterface The entity manager
*/
protected $em;
/**
* @var Person The person on which the test is executed
*/
protected static $person;
/**
* @var \Chill\MainBundle\Entity\PostalCode
*/
protected $postalCode;
public static function setUpBeforeClass()
{
static::bootKernel();
$em = static::$kernel->getContainer()
->get('doctrine.orm.entity_manager');
$center = $em->getRepository('ChillMainBundle:Center')
->findOneBy(array('name' => 'Center A'));
->findOneBy(['name' => 'Center A']);
self::$person = (new Person())
->setLastName("Tested person")
->setFirstName("Test")
->setLastName('Tested person')
->setFirstName('Test')
->setCenter($center)
->setGender(Person::MALE_GENDER);
$em->persist(self::$person);
$em->flush();
}
/**
* Prepare client and create a random person
* Prepare client and create a random person.
*/
public function setUp()
{
static::bootKernel();
$this->em = static::$kernel->getContainer()
->get('doctrine.orm.entity_manager');
$this->postalCode = $this->em->getRepository('ChillMainBundle:PostalCode')
->findOneBy(array('code' => 1000));
$this->client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
));
->findOneBy(['code' => 1000]);
$this->client = static::createClient([], [
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
]);
}
public static function tearDownAfter()
{
$this->refreshPerson();
$this->em->remove(self::$person);
$this->em->flush();
}
/**
* Reload the person from the db
*/
protected function refreshPerson()
{
self::$person = $this->em->getRepository('ChillPersonBundle:Person')
->find(self::$person->getId());
}
public function testEmptyList()
{
$crawler = $this->client->request('GET', '/fr/person/'.
self::$person->getId().'/address/list');
$this->assertTrue($this->client->getResponse()->isSuccessful());
$this->assertEquals(1, $crawler->filter('td:contains("Pas d\'adresse renseignée")')
->count(),
"assert that a message say 'no address given'");
}
/**
* @depends testEmptyList
*/
public function testCreateAddress()
{
$crawler = $this->client->request('GET', '/fr/person/'.
self::$person->getId().'/address/new');
$crawler = $this->client->request('GET', '/fr/person/' .
self::$person->getId() . '/address/new');
$this->assertTrue($this->client->getResponse()->isSuccessful());
// get the form and populate the most obvious fields (postcode will come later)
$form = $crawler->filter('.bt-create')->form(array(
$form = $crawler->filter('.bt-create')->form([
'address[streetAddress1]' => 'Rue de la Paix, 50',
'address[streetAddress2]' => $this->postalCode->getId(),
'address[validFrom]' => '15-01-2016'
));
// select a random postal code
'address[streetAddress2]' => $this->postalCode->getId(),
'address[validFrom]' => '15-01-2016',
]);
// select a random postal code
$values = $form['address[postCode]']->availableOptionValues();
$form['address[postCode]']->setValue($values[array_rand($values)]);
$this->client->submit($form);
$crawler = $this->client->followRedirect();
$this->assertRegexp('|/fr/person/[0-9]{1,}/address/list|',
$this->client->getHistory()->current()->getUri(),
"assert that the current page is on |/fr/person/[0-9]{1,}/address/list|");
$this->assertEquals(1, $crawler
->filter('div.flash_message.success')
->count(),
"Asserting that the response page contains a success flash message");
$this->assertEquals(1, $crawler
->filter('td:contains("Rue de la Paix, 50")')
->count(),
"Asserting that the page contains the new address");
$this->assertRegexp(
'|/fr/person/[0-9]{1,}/address/list|',
$this->client->getHistory()->current()->getUri(),
'assert that the current page is on |/fr/person/[0-9]{1,}/address/list|'
);
$this->assertEquals(
1,
$crawler
->filter('div.flash_message.success')
->count(),
'Asserting that the response page contains a success flash message'
);
$this->assertEquals(
1,
$crawler
->filter('td:contains("Rue de la Paix, 50")')
->count(),
'Asserting that the page contains the new address'
);
}
public function testEmptyList()
{
$crawler = $this->client->request('GET', '/fr/person/' .
self::$person->getId() . '/address/list');
$this->assertTrue($this->client->getResponse()->isSuccessful());
$this->assertEquals(
1,
$crawler->filter('td:contains("Pas d\'adresse renseignée")')
->count(),
"assert that a message say 'no address given'"
);
}
/**
* @depends testCreateAddress
*/
@@ -161,34 +152,48 @@ class PersonAddressControllerTest extends WebTestCase
{
$this->refreshPerson();
$address = self::$person->getLastAddress();
$crawler = $this->client->request('GET', '/fr/person/'.self::$person->getId()
.'/address/'.$address->getId().'/edit');
$crawler = $this->client->request('GET', '/fr/person/' . self::$person->getId()
. '/address/' . $address->getId() . '/edit');
$this->assertTrue($this->client->getResponse()->isSuccessful());
$form = $crawler->filter('.bt-save')->form(array(
$form = $crawler->filter('.bt-save')->form([
'address[streetAddress1]' => 'Rue du Trou Normand, 15',
'address[validFrom]' => '15-01-2015'
));
'address[validFrom]' => '15-01-2015',
]);
$this->client->submit($form);
$crawler = $this->client->followRedirect();
$this->assertRegexp('|/fr/person/[0-9]{1,}/address/list|',
$this->client->getHistory()->current()->getUri(),
"assert that the current page is on |/fr/person/[0-9]{1,}/address/list|");
$this->assertGreaterThan(0, $crawler
->filter('div.flash_message.success')
->count(),
"Asserting that the response page contains a success flash message");
$this->assertEquals(1, $crawler
->filter('td:contains("Rue du Trou Normand")')
->count(),
"Asserting that the page contains the new address");
$this->assertRegexp(
'|/fr/person/[0-9]{1,}/address/list|',
$this->client->getHistory()->current()->getUri(),
'assert that the current page is on |/fr/person/[0-9]{1,}/address/list|'
);
$this->assertGreaterThan(
0,
$crawler
->filter('div.flash_message.success')
->count(),
'Asserting that the response page contains a success flash message'
);
$this->assertEquals(
1,
$crawler
->filter('td:contains("Rue du Trou Normand")')
->count(),
'Asserting that the page contains the new address'
);
}
/**
* Reload the person from the db.
*/
protected function refreshPerson()
{
self::$person = $this->em->getRepository('ChillPersonBundle:Person')
->find(self::$person->getId());
}
}

View File

@@ -1,52 +1,76 @@
<?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\PersonBundle\Tests\Controller;
use Chill\MainBundle\Test\PrepareClientTrait;
use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Iterator;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
use function array_pop;
use function json_decode;
use function shuffle;
/**
* @internal
* @coversNothing
*/
class PersonApiControllerTest extends WebTestCase
{
use PrepareClientTrait;
/**
* @dataProvider dataGetPersonFromCenterB
*/
public function testPersonGetUnauthorized($personId): void
public function dataGetPersonFromCenterA(): Iterator
{
$client = $this->getClientAuthenticated();
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$personIds = $em->createQuery('SELECT p.id FROM ' . Person::class . ' p ' .
'JOIN p.center c ' .
'WHERE c.name = :center')
->setParameter('center', 'Center A')
->setMaxResults(100)
->getScalarResult();
$client->request(Request::METHOD_GET, "/api/1.0/person/person/{$personId}.json");
$response = $client->getResponse();
shuffle($personIds);
$this->assertEquals(403, $response->getStatusCode());
}
/**
* @dataProvider dataGetPersonFromCenterA
*/
public function testPersonGet($personId): void
{
$client = $this->getClientAuthenticated();
$client->request(Request::METHOD_GET, "/api/1.0/person/person/{$personId}.json");
$response = $client->getResponse();
$this->assertResponseIsSuccessful();
$data = \json_decode($client->getResponse()->getContent(), true);
$this->assertArrayHasKey('type', $data);
$this->assertArrayHasKey('id', $data);
$this->assertEquals('person', $data['type']);
$this->assertEquals($personId, $data['id']);
yield array_pop($personIds);
yield array_pop($personIds);
yield array_pop($personIds);
yield array_pop($personIds);
}
public function dataGetPersonFromCenterB(): Iterator
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$personIds = $em->createQuery('SELECT p.id FROM ' . Person::class . ' p ' .
'JOIN p.center c ' .
'WHERE c.name = :center')
->setParameter('center', 'Center B')
->setMaxResults(100)
->getScalarResult();
shuffle($personIds);
yield array_pop($personIds);
yield array_pop($personIds);
}
/**
* @dataProvider dataGetPersonFromCenterA
*
* @param mixed $personId
*/
public function testPersonAddressSuggestion($personId): void
{
@@ -59,6 +83,8 @@ class PersonApiControllerTest extends WebTestCase
/**
* @dataProvider dataGetPersonFromCenterB
*
* @param mixed $personId
*/
public function testPersonAddressSuggestionUnauthorized($personId): void
{
@@ -70,41 +96,40 @@ class PersonApiControllerTest extends WebTestCase
$this->assertEquals(403, $response->getStatusCode());
}
public function dataGetPersonFromCenterA(): \Iterator
/**
* @dataProvider dataGetPersonFromCenterA
*
* @param mixed $personId
*/
public function testPersonGet($personId): void
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$personIds= $em->createQuery("SELECT p.id FROM ".Person::class." p ".
"JOIN p.center c ".
"WHERE c.name = :center")
->setParameter('center', 'Center A')
->setMaxResults(100)
->getScalarResult()
;
$client = $this->getClientAuthenticated();
\shuffle($personIds);
$client->request(Request::METHOD_GET, "/api/1.0/person/person/{$personId}.json");
$response = $client->getResponse();
yield \array_pop($personIds);
yield \array_pop($personIds);
yield \array_pop($personIds);
yield \array_pop($personIds);
}
$this->assertResponseIsSuccessful();
public function dataGetPersonFromCenterB(): \Iterator
$data = json_decode($client->getResponse()->getContent(), true);
$this->assertArrayHasKey('type', $data);
$this->assertArrayHasKey('id', $data);
$this->assertEquals('person', $data['type']);
$this->assertEquals($personId, $data['id']);
}
/**
* @dataProvider dataGetPersonFromCenterB
*
* @param mixed $personId
*/
public function testPersonGetUnauthorized($personId): void
{
self::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$personIds= $em->createQuery("SELECT p.id FROM ".Person::class." p ".
"JOIN p.center c ".
"WHERE c.name = :center")
->setParameter('center', 'Center B')
->setMaxResults(100)
->getScalarResult()
;
$client = $this->getClientAuthenticated();
\shuffle($personIds);
$client->request(Request::METHOD_GET, "/api/1.0/person/person/{$personId}.json");
$response = $client->getResponse();
yield \array_pop($personIds);
yield \array_pop($personIds);
}
$this->assertEquals(403, $response->getStatusCode());
}
}

View File

@@ -1,49 +1,67 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>, <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\PersonBundle\Tests\Controller;
use Chill\MainBundle\Test\PrepareClientTrait;
use DateTime;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DomCrawler\Form;
use Chill\MainBundle\Test\PrepareClientTrait;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
/**
* Test creation and deletion for persons
* Test creation and deletion for persons.
*
* @internal
* @coversNothing
*/
class PersonControllerCreateTest extends WebTestCase
{
use PrepareClientTrait;
public const BIRTHDATE_INPUT = 'chill_personbundle_person_creation[birthdate]';
public const CENTER_INPUT = 'chill_personbundle_person_creation[center]';
public const CREATEDATE_INPUT = 'chill_personbundle_person_creation[creation_date]';
public const FIRSTNAME_INPUT = 'chill_personbundle_person_creation[firstName]';
public const GENDER_INPUT = 'chill_personbundle_person_creation[gender]';
public const LASTNAME_INPUT = 'chill_personbundle_person_creation[lastName]';
public const LONG_TEXT = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosq. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosq.';
private KernelBrowser $client;
const FIRSTNAME_INPUT = 'chill_personbundle_person_creation[firstName]';
const LASTNAME_INPUT = "chill_personbundle_person_creation[lastName]";
const GENDER_INPUT = "chill_personbundle_person_creation[gender]";
const BIRTHDATE_INPUT = "chill_personbundle_person_creation[birthdate]";
const CREATEDATE_INPUT = "chill_personbundle_person_creation[creation_date]";
const CENTER_INPUT = "chill_personbundle_person_creation[center]";
public static function tearDownAfterClass()
{
static::bootKernel();
$em = static::$kernel->getContainer()->get('doctrine.orm.entity_manager');
const LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosq. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosq.";
//remove two people created during test
$jesus = $em->getRepository('ChillPersonBundle:Person')
->findOneBy(['firstName' => 'God']);
if (null !== $jesus) {
$em->remove($jesus);
}
$jesus2 = $em->getRepository('ChillPersonBundle:Person')
->findOneBy(['firstName' => 'roger']);
if (null !== $jesus2) {
$em->remove($jesus2);
}
$em->flush();
}
public function setUp(): void
{
@@ -51,147 +69,84 @@ class PersonControllerCreateTest extends WebTestCase
}
/**
*
* @param Form $creationForm
*/
private function fillAValidCreationForm(
Form &$creationForm,
string $firstname = 'God',
string $lastname = 'Jesus'
) {
$creationForm->get(self::FIRSTNAME_INPUT)->setValue($firstname.'_'.uniqid());
$creationForm->get(self::LASTNAME_INPUT)->setValue($lastname.'_'.uniqid());
$creationForm->get(self::GENDER_INPUT)->select("man");
$date = new \DateTime('1947-02-01');
$creationForm->get(self::BIRTHDATE_INPUT)->setValue($date->format('Y-m-d'));
return $creationForm;
}
/**
* Test the "add a person" page : test that required elements are present
* Test the "add a person" page : test that required elements are present.
*
* see https://redmine.champs-libres.coop/projects/chillperson/wiki/Test_plan_for_page_%22add_a_person%22
*/
public function testAddAPersonPage()
{
$client = $this->client;
$crawler = $client->request('GET', '/fr/person/new');
$this->assertTrue($client->getResponse()->isSuccessful(),
"The page is accessible at the URL /{_locale}/person/new");
$form = $crawler->selectButton("Ajouter la personne")->form();
$this->assertTrue(
$client->getResponse()->isSuccessful(),
'The page is accessible at the URL /{_locale}/person/new'
);
$form = $crawler->selectButton('Ajouter la personne')->form();
$this->assertInstanceOf('Symfony\Component\DomCrawler\Form', $form,
'The page contains a butto ');
$this->assertTrue($form->has(self::FIRSTNAME_INPUT),
'The page contains a "firstname" input');
$this->assertTrue($form->has(self::LASTNAME_INPUT),
'The page contains a "lastname" input');
$this->assertTrue($form->has(self::GENDER_INPUT),
'The page contains a "gender" input');
$this->assertTrue($form->has(self::BIRTHDATE_INPUT),
'The page has a "date of birth" input');
$this->assertInstanceOf(
'Symfony\Component\DomCrawler\Form',
$form,
'The page contains a butto '
);
$this->assertTrue(
$form->has(self::FIRSTNAME_INPUT),
'The page contains a "firstname" input'
);
$this->assertTrue(
$form->has(self::LASTNAME_INPUT),
'The page contains a "lastname" input'
);
$this->assertTrue(
$form->has(self::GENDER_INPUT),
'The page contains a "gender" input'
);
$this->assertTrue(
$form->has(self::BIRTHDATE_INPUT),
'The page has a "date of birth" input'
);
$genderType = $form->get(self::GENDER_INPUT);
$this->assertEquals('radio', $genderType->getType(),
'The gender input has radio buttons');
$this->assertEquals(3, count($genderType->availableOptionValues()),
'The gender input has three options: man, women and undefined');
$this->assertTrue(in_array('man', $genderType->availableOptionValues()),
'gender has "homme" option');
$this->assertTrue(in_array('woman', $genderType->availableOptionValues()),
'gender has "femme" option');
$this->assertEquals(
'radio',
$genderType->getType(),
'The gender input has radio buttons'
);
$this->assertEquals(
3,
count($genderType->availableOptionValues()),
'The gender input has three options: man, women and undefined'
);
$this->assertTrue(
in_array('man', $genderType->availableOptionValues()),
'gender has "homme" option'
);
$this->assertTrue(
in_array('woman', $genderType->availableOptionValues()),
'gender has "femme" option'
);
$this->assertFalse($genderType->hasValue(), 'The gender input is not checked');
return $form;
}
/**
* Test the creation of a valid person.
*
* @param Form $form
* @return string The id of the created person
*/
public function testValidForm()
{
$client = $this->client;
$crawler = $client->request('GET', '/fr/person/new');
$form = $crawler->selectButton("Ajouter la personne")->form();
$this->fillAValidCreationForm($form);
$client = $this->client;
$client->submit($form);
$this->assertTrue($client->getResponse()->isRedirect(),
"a valid form redirect to url /{_locale}/person/{personId}/general/edit");
$client->followRedirect();
// visualize regexp here : http://jex.im/regulex/#!embed=false&flags=&re=%2Ffr%2Fperson%2F[1-9][0-9]*%2Fgeneral%2Fedit%24
$this->assertRegExp('|/fr/person/[1-9][0-9]*/general/edit$|',
$client->getHistory()->current()->getUri(),
"a valid form redirect to url /{_locale}/person/{personId}/general/edit");
$regexPersonId = null;
preg_match("/person\/([1-9][0-9]*)\/general\/edit$/",
$client->getHistory()->current()->getUri(), $regexPersonId);
return $regexPersonId[1];
}
/**
* Test if, for a given person if its person view page (at the url
* fr/person/$personID/general) is accessible
* fr/person/$personID/general) is accessible.
*
* @param string|int $personId The is of the person
* @param int|string $personId The is of the person
* @depends testValidForm
*/
public function testPersonViewAccessible($personId)
{
$client = $this->client;
$client->request('GET', '/fr/person/'.$personId.'/general');
$this->assertTrue($client->getResponse()->isSuccessful(),
"The person view page is accessible at the URL"
. "/{_locale}/person/{personID}/general");
}
/**
* test adding a person with a user with multi center
* is valid
*/
public function testValidFormWithMultiCenterUser()
{
$client = $this->getClientAuthenticated('multi_center');
$crawler = $client->request('GET', '/fr/person/new');
$this->assertTrue($client->getResponse()->isSuccessful(),
"The page is accessible at the URL /{_locale}/person/new");
$form = $crawler->selectButton("Ajouter la personne")->form();
// create a very long name to avoid collision
$this->fillAValidCreationForm($form, 'Carmela Girdana Assuntamente Castalle', 'rabbit');
$this->assertTrue($form->has(self::CENTER_INPUT),
'The page contains a "center" input');
$centerInput = $form->get(self::CENTER_INPUT);
/*
$availableValues = $centerInput->availableOptionValues();
$lastCenterInputValue = end($availableValues);
$centerInput->setValue($lastCenterInputValue);
*/
$client->submit($form);
$this->assertTrue($client->getResponse()->isRedirect(),
"a valid form redirect to url /{_locale}/person/{personId}/general/edit");
$client->followRedirect();
$this->assertRegExp('|/fr/person/[1-9][0-9]*/general/edit$|',
$client->getHistory()->current()->getUri(),
"a valid form redirect to url /{_locale}/person/{personId}/general/edit");
$client->request('GET', '/fr/person/' . $personId . '/general');
$this->assertTrue(
$client->getResponse()->isSuccessful(),
'The person view page is accessible at the URL'
. '/{_locale}/person/{personID}/general'
);
}
public function testReviewExistingDetectionInversedLastNameWithFirstName()
@@ -203,39 +158,121 @@ class PersonControllerCreateTest extends WebTestCase
//test the page is loaded before continuing
$this->assertTrue($client->getResponse()->isSuccessful());
$form = $crawler->selectButton("Ajouter la personne")->form();
$form = $crawler->selectButton('Ajouter la personne')->form();
$form = $this->fillAValidCreationForm($form, 'Charline', 'dd');
$client->submit($form);
$this->assertContains('DEPARDIEU', $client->getCrawler()->text(),
"check that the page has detected the lastname of a person existing in database");
$this->assertContains(
'DEPARDIEU',
$client->getCrawler()->text(),
'check that the page has detected the lastname of a person existing in database'
);
//inversion
$form = $crawler->selectButton("Ajouter la personne")->form();
$form = $crawler->selectButton('Ajouter la personne')->form();
$form = $this->fillAValidCreationForm($form, 'dd', 'Charline');
$client->submit($form);
$this->assertContains('DEPARDIEU', $client->getCrawler()->text(),
"check that the page has detected the lastname of a person existing in database");
$this->assertContains(
'DEPARDIEU',
$client->getCrawler()->text(),
'check that the page has detected the lastname of a person existing in database'
);
}
public static function tearDownAfterClass()
/**
* Test the creation of a valid person.
*
* @return string The id of the created person
*/
public function testValidForm()
{
static::bootKernel();
$em = static::$kernel->getContainer()->get('doctrine.orm.entity_manager');
$client = $this->client;
$crawler = $client->request('GET', '/fr/person/new');
//remove two people created during test
$jesus = $em->getRepository('ChillPersonBundle:Person')
->findOneBy(array('firstName' => 'God'));
if ($jesus !== NULL) {
$em->remove($jesus);
}
$form = $crawler->selectButton('Ajouter la personne')->form();
$this->fillAValidCreationForm($form);
$client = $this->client;
$client->submit($form);
$jesus2 = $em->getRepository('ChillPersonBundle:Person')
->findOneBy(array('firstName' => 'roger'));
if ($jesus2 !== NULL) {
$em->remove($jesus2);
}
$em->flush();
$this->assertTrue(
$client->getResponse()->isRedirect(),
'a valid form redirect to url /{_locale}/person/{personId}/general/edit'
);
$client->followRedirect();
// visualize regexp here : http://jex.im/regulex/#!embed=false&flags=&re=%2Ffr%2Fperson%2F[1-9][0-9]*%2Fgeneral%2Fedit%24
$this->assertRegExp(
'|/fr/person/[1-9][0-9]*/general/edit$|',
$client->getHistory()->current()->getUri(),
'a valid form redirect to url /{_locale}/person/{personId}/general/edit'
);
$regexPersonId = null;
preg_match(
'/person\\/([1-9][0-9]*)\\/general\\/edit$/',
$client->getHistory()->current()->getUri(),
$regexPersonId
);
return $regexPersonId[1];
}
/**
* test adding a person with a user with multi center
* is valid.
*/
public function testValidFormWithMultiCenterUser()
{
$client = $this->getClientAuthenticated('multi_center');
$crawler = $client->request('GET', '/fr/person/new');
$this->assertTrue(
$client->getResponse()->isSuccessful(),
'The page is accessible at the URL /{_locale}/person/new'
);
$form = $crawler->selectButton('Ajouter la personne')->form();
// create a very long name to avoid collision
$this->fillAValidCreationForm($form, 'Carmela Girdana Assuntamente Castalle', 'rabbit');
$this->assertTrue(
$form->has(self::CENTER_INPUT),
'The page contains a "center" input'
);
$centerInput = $form->get(self::CENTER_INPUT);
/*
$availableValues = $centerInput->availableOptionValues();
$lastCenterInputValue = end($availableValues);
$centerInput->setValue($lastCenterInputValue);
*/
$client->submit($form);
$this->assertTrue(
$client->getResponse()->isRedirect(),
'a valid form redirect to url /{_locale}/person/{personId}/general/edit'
);
$client->followRedirect();
$this->assertRegExp(
'|/fr/person/[1-9][0-9]*/general/edit$|',
$client->getHistory()->current()->getUri(),
'a valid form redirect to url /{_locale}/person/{personId}/general/edit'
);
}
private function fillAValidCreationForm(
Form &$creationForm,
string $firstname = 'God',
string $lastname = 'Jesus'
) {
$creationForm->get(self::FIRSTNAME_INPUT)->setValue($firstname . '_' . uniqid());
$creationForm->get(self::LASTNAME_INPUT)->setValue($lastname . '_' . uniqid());
$creationForm->get(self::GENDER_INPUT)->select('man');
$date = new DateTime('1947-02-01');
$creationForm->get(self::BIRTHDATE_INPUT)->setValue($date->format('Y-m-d'));
return $creationForm;
}
}

View File

@@ -1,54 +1,53 @@
<?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>
/**
* 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\PersonBundle\Tests\Controller;
use Chill\PersonBundle\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Chill\MainBundle\Test\PrepareClientTrait;
use Chill\PersonBundle\Entity\Person;
use Closure;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Test the edition of persons
* Test the edition of persons.
*
* As I am logged in as "center a_social"
*
* @internal
* @coversNothing
*/
class PersonControllerUpdateTest extends WebTestCase
{
use PrepareClientTrait;
/** @var \Doctrine\ORM\EntityManagerInterface The entity manager */
private $em;
/** @var Person The person on which the test is executed */
private $person;
/** @var string The url using for editing the person's information */
/**
* @var string The url using for editing the person's information
*/
private $editUrl;
/** @var string The url using for seeing the person's information */
/**
* @var \Doctrine\ORM\EntityManagerInterface The entity manager
*/
private $em;
/**
* @var Person The person on which the test is executed
*/
private $person;
/**
* @var string The url using for seeing the person's information
*/
private $viewUrl;
/**
* Prepare client and create a random person
* Prepare client and create a random person.
*/
public function setUp()
{
@@ -58,235 +57,23 @@ class PersonControllerUpdateTest extends WebTestCase
->get('doctrine.orm.entity_manager');
$center = $this->em->getRepository('ChillMainBundle:Center')
->findOneBy(array('name' => 'Center A'));
->findOneBy(['name' => 'Center A']);
$this->person = (new Person())
->setLastName("My Beloved")
->setFirstName("Jesus")
->setLastName('My Beloved')
->setFirstName('Jesus')
->setCenter($center)
->setGender(Person::MALE_GENDER);
$this->em->persist($this->person);
$this->em->flush();
$this->editUrl = '/fr/person/'.$this->person->getId().'/general/edit';
$this->viewUrl = '/fr/person/'.$this->person->getId().'/general';
$this->editUrl = '/fr/person/' . $this->person->getId() . '/general/edit';
$this->viewUrl = '/fr/person/' . $this->person->getId() . '/general';
$this->client = $this->getClientAuthenticated();
}
/**
* Reload the person from the db
*/
protected function refreshPerson()
{
$this->person = $this->em->getRepository('ChillPersonBundle:Person')
->find($this->person->getId());
}
/**
* Test the edit page are accessible
*/
public function testEditPageIsSuccessful()
{
$this->client->request('GET', $this->editUrl);
$this->assertTrue($this->client->getResponse()->isSuccessful(),
"The person edit form is accessible");
}
/**
* Test the configurable fields are present
*
* @group configurable_fields
*/
public function testHiddenFielsArePresent()
{
$crawler = $this->client->request('GET', $this->editUrl);
$configurables = array('placeOfBirth', 'phonenumber', 'email',
'countryOfBirth', 'nationality', 'spokenLanguages', 'maritalStatus');
$form = $crawler->selectButton('Enregistrer')->form(); //;
foreach($configurables as $key) {
$this->assertTrue($form->has('chill_personbundle_person['.$key.']'));
}
}
/**
* Test if the edit page of a given person is not accessible for a user
* of another center of the person
*/
public function testEditPageDeniedForUnauthorized_OutsideCenter()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center b_social',
'PHP_AUTH_PW' => 'password',
));
$client->request('GET', $this->editUrl);
$this->assertEquals(403, $client->getResponse()->getStatusCode(),
"The edit page of a person of a center A must not be accessible for user of center B");
}
/**
* Test the edit page of a given person are not accessible for an
* administrative user
*/
public function testEditPageDeniedForUnauthorized_InsideCenter()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center a_administrative',
'PHP_AUTH_PW' => 'password',
));
$client->request('GET', $this->editUrl);
$this->assertEquals(403, $client->getResponse()->getStatusCode());
}
/**
* Test the edition of a field
*
* Given I fill the field with $value
* And I submit the form
* Then I am redirected to the 'general' page
* And the person is updated in the db
*
* @dataProvider validTextFieldsProvider
* @param string $field
* @param string $value
* @param \Closure $callback
*/
public function testEditTextField($field, $value, \Closure $callback)
{
$crawler = $this->client->request('GET', $this->editUrl);
$form = $crawler->selectButton('Enregistrer')
->form();
//transform countries into value if needed
switch ($field) {
case 'nationality':
case 'countryOfBirth':
if (FALSE === empty($value)) {
$country = $this->em->getRepository('ChillMainBundle:Country')
->findOneByCountryCode($value);
$transformedValue = $country->getId();
} else {
$transformedValue = '';
}
break;
default:
$transformedValue = $value;
}
$form->get('chill_personbundle_person['.$field. ']')
->setValue($transformedValue);
$this->client->submit($form);
$this->refreshPerson();
$this->assertTrue($this->client->getResponse()->isRedirect($this->viewUrl),
'the page is redirected to general view');
$this->assertEquals($value, $callback($this->person),
'the value '.$field.' is updated in db');
$crawler = $this->client->followRedirect();
$this->assertGreaterThan(0, $crawler->filter('.alert-success')->count(),
'a element .success is shown');
if($field == 'birthdate' or $field == 'memo' or $field == 'countryOfBirth' or $field == 'nationality'
or $field == 'gender') {
// we do not perform test on the web page contents.
} else {
$this->assertGreaterThan(0, $crawler->filter('html:contains("'.$value.'")')->count());
}
}
public function testEditLanguages()
{
$crawler = $this->client->request('GET', $this->editUrl);
$selectedLanguages = array('en', 'an', 'bbj');
$form = $crawler->selectButton('Enregistrer')
->form();
$form->get('chill_personbundle_person[spokenLanguages]')
->setValue($selectedLanguages);
$this->client->submit($form);
$this->refreshPerson();
$this->assertTrue($this->client->getResponse()->isRedirect($this->viewUrl),
'the page is redirected to /general view');
//retrieve languages codes present in person
foreach($this->person->getSpokenLanguages() as $lang){
$languagesCodesPresents[] = $lang->getId();
}
$this->assertEquals(asort($selectedLanguages), asort($languagesCodesPresents),
'the person speaks the expected languages');
}
/**
* Test tbe detection of invalid data during the update procedure
*
* @dataProvider providesInvalidFieldsValues
* @param string $field
* @param string $value
*/
public function testInvalidFields($field, $value)
{
$crawler = $this->client->request('GET', $this->editUrl);
$form = $crawler->selectButton('Enregistrer')
->form();
$form->get('chill_personbundle_person['.$field.']')
->setValue($value);
$crawler = $this->client->submit($form);
$this->assertFalse($this->client->getResponse()->isRedirect(),
'the page is not redirected to /general');
$this->assertGreaterThan(0, $crawler->filter('.alert-danger')->count(),
'a element .error is shown');
}
/**
* provide valid values to test, with field name and
* a function to find the value back from person entity
*
* @return mixed[]
*/
public function validTextFieldsProvider()
{
return array(
['firstName', 'random Value', function(Person $person) { return $person->getFirstName(); } ],
['lastName' , 'random Value', function(Person $person) { return $person->getLastName(); } ],
// reminder: this value is capitalized
['placeOfBirth', 'A PLACE', function(Person $person) { return $person->getPlaceOfBirth(); }],
['birthdate', '1980-12-15', function(Person $person) { return $person->getBirthdate()->format('Y-m-d'); }],
['phonenumber', '+32123456789', function(Person $person) { return $person->getPhonenumber(); }],
['memo', 'jfkdlmq jkfldmsq jkmfdsq', function(Person $person) { return $person->getMemo(); }],
['countryOfBirth', 'BE', function(Person $person) { return $person->getCountryOfBirth()->getCountryCode(); }],
['nationality', 'FR', function(Person $person) { return $person->getNationality()->getCountryCode(); }],
['placeOfBirth', '', function(Person $person) { return $person->getPlaceOfBirth(); }],
['birthdate', '', function(Person $person) { return $person->getBirthdate(); }],
['phonenumber', '', function(Person $person) { return $person->getPhonenumber(); }],
['memo', '', function(Person $person) { return $person->getMemo(); }],
['countryOfBirth', NULL, function(Person $person) { return $person->getCountryOfBirth(); }],
['nationality', NULL, function(Person $person) { return $person->getNationality(); }],
['gender', Person::FEMALE_GENDER, function(Person $person) { return $person->getGender(); }],
);
}
public function providesInvalidFieldsValues()
{
return array(
['firstName', $this->getVeryLongText()],
['lastName', $this->getVeryLongText()],
['firstName', ''],
['lastName', ''],
['birthdate', 'false date']
);
}
public function tearDown()
{
$this->refreshPerson();
@@ -294,10 +81,247 @@ class PersonControllerUpdateTest extends WebTestCase
$this->em->flush();
}
public function providesInvalidFieldsValues()
{
return [
['firstName', $this->getVeryLongText()],
['lastName', $this->getVeryLongText()],
['firstName', ''],
['lastName', ''],
['birthdate', 'false date'],
];
}
public function testEditLanguages()
{
$crawler = $this->client->request('GET', $this->editUrl);
$selectedLanguages = ['en', 'an', 'bbj'];
$form = $crawler->selectButton('Enregistrer')
->form();
$form->get('chill_personbundle_person[spokenLanguages]')
->setValue($selectedLanguages);
$this->client->submit($form);
$this->refreshPerson();
$this->assertTrue(
$this->client->getResponse()->isRedirect($this->viewUrl),
'the page is redirected to /general view'
);
//retrieve languages codes present in person
foreach ($this->person->getSpokenLanguages() as $lang) {
$languagesCodesPresents[] = $lang->getId();
}
$this->assertEquals(
asort($selectedLanguages),
asort($languagesCodesPresents),
'the person speaks the expected languages'
);
}
/**
* Test the edit page of a given person are not accessible for an
* administrative user.
*/
public function testEditPageDeniedForUnauthorizedInsideCenter()
{
$client = static::createClient([], [
'PHP_AUTH_USER' => 'center a_administrative',
'PHP_AUTH_PW' => 'password',
]);
$client->request('GET', $this->editUrl);
$this->assertEquals(403, $client->getResponse()->getStatusCode());
}
/**
* Test if the edit page of a given person is not accessible for a user
* of another center of the person.
*/
public function testEditPageDeniedForUnauthorizedOutsideCenter()
{
$client = static::createClient([], [
'PHP_AUTH_USER' => 'center b_social',
'PHP_AUTH_PW' => 'password',
]);
$client->request('GET', $this->editUrl);
$this->assertEquals(
403,
$client->getResponse()->getStatusCode(),
'The edit page of a person of a center A must not be accessible for user of center B'
);
}
/**
* Test the edit page are accessible.
*/
public function testEditPageIsSuccessful()
{
$this->client->request('GET', $this->editUrl);
$this->assertTrue(
$this->client->getResponse()->isSuccessful(),
'The person edit form is accessible'
);
}
/**
* Test the edition of a field.
*
* Given I fill the field with $value
* And I submit the form
* Then I am redirected to the 'general' page
* And the person is updated in the db
*
* @dataProvider validTextFieldsProvider
*
* @param string $field
* @param string $value
*/
public function testEditTextField($field, $value, Closure $callback)
{
$crawler = $this->client->request('GET', $this->editUrl);
$form = $crawler->selectButton('Enregistrer')
->form();
//transform countries into value if needed
switch ($field) {
case 'nationality':
case 'countryOfBirth':
if (false === empty($value)) {
$country = $this->em->getRepository('ChillMainBundle:Country')
->findOneByCountryCode($value);
$transformedValue = $country->getId();
} else {
$transformedValue = '';
}
break;
default:
$transformedValue = $value;
}
$form->get('chill_personbundle_person[' . $field . ']')
->setValue($transformedValue);
$this->client->submit($form);
$this->refreshPerson();
$this->assertTrue(
$this->client->getResponse()->isRedirect($this->viewUrl),
'the page is redirected to general view'
);
$this->assertEquals(
$value,
$callback($this->person),
'the value ' . $field . ' is updated in db'
);
$crawler = $this->client->followRedirect();
$this->assertGreaterThan(
0,
$crawler->filter('.alert-success')->count(),
'a element .success is shown'
);
if ('birthdate' == $field or 'memo' == $field or 'countryOfBirth' == $field or 'nationality' == $field
or 'gender' == $field) {
// we do not perform test on the web page contents.
} else {
$this->assertGreaterThan(0, $crawler->filter('html:contains("' . $value . '")')->count());
}
}
/**
* Test the configurable fields are present.
*
* @group configurable_fields
*/
public function testHiddenFielsArePresent()
{
$crawler = $this->client->request('GET', $this->editUrl);
$configurables = ['placeOfBirth', 'phonenumber', 'email',
'countryOfBirth', 'nationality', 'spokenLanguages', 'maritalStatus', ];
$form = $crawler->selectButton('Enregistrer')->form(); //;
foreach ($configurables as $key) {
$this->assertTrue($form->has('chill_personbundle_person[' . $key . ']'));
}
}
/**
* Test tbe detection of invalid data during the update procedure.
*
* @dataProvider providesInvalidFieldsValues
*
* @param string $field
* @param string $value
*/
public function testInvalidFields($field, $value)
{
$crawler = $this->client->request('GET', $this->editUrl);
$form = $crawler->selectButton('Enregistrer')
->form();
$form->get('chill_personbundle_person[' . $field . ']')
->setValue($value);
$crawler = $this->client->submit($form);
$this->assertFalse(
$this->client->getResponse()->isRedirect(),
'the page is not redirected to /general'
);
$this->assertGreaterThan(
0,
$crawler->filter('.alert-danger')->count(),
'a element .error is shown'
);
}
/**
* provide valid values to test, with field name and
* a function to find the value back from person entity.
*
* @return mixed[]
*/
public function validTextFieldsProvider()
{
return [
['firstName', 'random Value', function (Person $person) { return $person->getFirstName(); }],
['lastName', 'random Value', function (Person $person) { return $person->getLastName(); }],
// reminder: this value is capitalized
['placeOfBirth', 'A PLACE', function (Person $person) { return $person->getPlaceOfBirth(); }],
['birthdate', '1980-12-15', function (Person $person) { return $person->getBirthdate()->format('Y-m-d'); }],
['phonenumber', '+32123456789', function (Person $person) { return $person->getPhonenumber(); }],
['memo', 'jfkdlmq jkfldmsq jkmfdsq', function (Person $person) { return $person->getMemo(); }],
['countryOfBirth', 'BE', function (Person $person) { return $person->getCountryOfBirth()->getCountryCode(); }],
['nationality', 'FR', function (Person $person) { return $person->getNationality()->getCountryCode(); }],
['placeOfBirth', '', function (Person $person) { return $person->getPlaceOfBirth(); }],
['birthdate', '', function (Person $person) { return $person->getBirthdate(); }],
['phonenumber', '', function (Person $person) { return $person->getPhonenumber(); }],
['memo', '', function (Person $person) { return $person->getMemo(); }],
['countryOfBirth', null, function (Person $person) { return $person->getCountryOfBirth(); }],
['nationality', null, function (Person $person) { return $person->getNationality(); }],
['gender', Person::FEMALE_GENDER, function (Person $person) { return $person->getGender(); }],
];
}
/**
* Reload the person from the db.
*/
protected function refreshPerson()
{
$this->person = $this->em->getRepository('ChillPersonBundle:Person')
->find($this->person->getId());
}
private function getVeryLongText()
{
return <<<EOT
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse molestie at enim id auctor. Vivamus malesuada elit ipsum, ac mollis ex facilisis sit amet. Phasellus accumsan, quam ut aliquet accumsan, augue ligula consequat erat, condimentum iaculis orci magna egestas eros. In vel blandit sapien. Duis ut dui vitae tortor iaculis malesuada vitae vitae lorem. Morbi efficitur dolor orci, a rhoncus urna blandit quis. Aenean at placerat dui, ut tincidunt nulla. In ultricies tempus ligula ac rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce urna nibh, placerat vel auctor sed, maximus quis magna. Vivamus quam ante, consectetur vel feugiat quis, aliquet id ante. Integer gravida erat dignissim ante commodo mollis. Donec imperdiet mauris elit, nec blandit dolor feugiat ut. Proin iaculis enim ut tortor pretium commodo. Etiam aliquet hendrerit dolor sed fringilla. Vestibulum facilisis nibh tincidunt dui egestas, vitae congue mi imperdiet. Duis vulputate ultricies lectus id cursus. Fusce bibendum sem dignissim, bibendum purus quis, mollis ex. Cras ac est justo. Duis congue mattis ipsum, vitae sagittis justo dictum sit amet. Duis aliquam pharetra sem, non laoreet ante laoreet ac. Mauris ornare mi tempus rutrum consequat.
EOT;
return <<<'EOT'
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse molestie at enim id auctor. Vivamus malesuada elit ipsum, ac mollis ex facilisis sit amet. Phasellus accumsan, quam ut aliquet accumsan, augue ligula consequat erat, condimentum iaculis orci magna egestas eros. In vel blandit sapien. Duis ut dui vitae tortor iaculis malesuada vitae vitae lorem. Morbi efficitur dolor orci, a rhoncus urna blandit quis. Aenean at placerat dui, ut tincidunt nulla. In ultricies tempus ligula ac rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce urna nibh, placerat vel auctor sed, maximus quis magna. Vivamus quam ante, consectetur vel feugiat quis, aliquet id ante. Integer gravida erat dignissim ante commodo mollis. Donec imperdiet mauris elit, nec blandit dolor feugiat ut. Proin iaculis enim ut tortor pretium commodo. Etiam aliquet hendrerit dolor sed fringilla. Vestibulum facilisis nibh tincidunt dui egestas, vitae congue mi imperdiet. Duis vulputate ultricies lectus id cursus. Fusce bibendum sem dignissim, bibendum purus quis, mollis ex. Cras ac est justo. Duis congue mattis ipsum, vitae sagittis justo dictum sit amet. Duis aliquam pharetra sem, non laoreet ante laoreet ac. Mauris ornare mi tempus rutrum consequat.
EOT;
}
}

View File

@@ -1,21 +1,10 @@
<?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\PersonBundle\Tests\Controller;
@@ -23,189 +12,211 @@ namespace Chill\PersonBundle\Tests\Controller;
//ini_set('memory_limit', '-1');
use Chill\PersonBundle\Entity\Person;
use Closure;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Test the edition of persons
*
* Test the edition of persons.
*
* As I am logged in as "center a_social"
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class PersonControllerUpdateWithHiddenFieldsTest extends WebTestCase
{
/** @var \Doctrine\ORM\EntityManagerInterface The entity manager */
private $em;
/** @var Person The person on which the test is executed */
private $person;
/** @var string The url using for editing the person's information */
/**
* @var string The url using for editing the person's information
*/
private $editUrl;
/** @var string The url using for seeing the person's information */
private $viewUrl;
/**
* Prepare client and create a random person
* @var \Doctrine\ORM\EntityManagerInterface The entity manager
*/
private $em;
/**
* @var Person The person on which the test is executed
*/
private $person;
/**
* @var string The url using for seeing the person's information
*/
private $viewUrl;
/**
* Prepare client and create a random person.
*/
public function setUp()
{
static::bootKernel(array('environment' => 'test_with_hidden_fields'));
static::bootKernel(['environment' => 'test_with_hidden_fields']);
$this->em = static::$kernel->getContainer()
->get('doctrine.orm.entity_manager');
$center = $this->em->getRepository('ChillMainBundle:Center')
->findOneBy(array('name' => 'Center A'));
->findOneBy(['name' => 'Center A']);
$this->person = (new Person())
->setLastName("My Beloved")
->setFirstName("Jesus")
->setLastName('My Beloved')
->setFirstName('Jesus')
->setCenter($center)
->setGender(Person::MALE_GENDER);
$this->em->persist($this->person);
$this->em->flush();
$this->editUrl = '/en/person/'.$this->person->getId().'/general/edit';
$this->viewUrl = '/en/person/'.$this->person->getId().'/general';
$this->editUrl = '/en/person/' . $this->person->getId() . '/general/edit';
$this->viewUrl = '/en/person/' . $this->person->getId() . '/general';
$this->client = static::createClient(
array(
'environment' => 'test_with_hidden_fields'
),
array(
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
)
);
}
/**
* Reload the person from the db
*/
protected function refreshPerson()
{
$this->person = $this->em->getRepository('ChillPersonBundle:Person')
->find($this->person->getId());
}
/**
* Test the edit page are accessible
*/
public function testEditPageIsSuccessful()
{
$this->client->request('GET', $this->editUrl);
$this->assertTrue($this->client->getResponse()->isSuccessful(),
"The person edit form is accessible");
}
/**
* Test the configurable fields are absent
*
* @group configurable_fields
*/
public function testHiddenFielsAreAbsent()
{
$crawler = $this->client->request('GET', $this->editUrl);
$configurables = array('placeOfBirth', 'phonenumber', 'email',
'countryOfBirth', 'nationality', 'spokenLanguages', 'maritalStatus');
$form = $crawler->selectButton('Submit')->form(); //;
foreach($configurables as $key) {
$this->assertFalse($form->has('chill_personbundle_person['.$key.']'));
}
}
/**
* Test the edition of a field
*
* Given I fill the field with $value
* And I submit the form
* Then I am redirected to the 'general' page
* And the person is updated in the db
*
* @dataProvider validTextFieldsProvider
* @param string $field
* @param string $value
* @param \Closure $callback
*/
public function testEditTextField($field, $value, \Closure $callback)
{
$crawler = $this->client->request('GET', $this->editUrl);
$form = $crawler->selectButton('Submit')
->form();
//transform countries into value if needed
switch ($field) {
case 'nationality':
case 'countryOfBirth':
if ($value !== NULL) {
$country = $this->em->getRepository('ChillMainBundle:Country')
->findOneByCountryCode($value);
$transformedValue = $country->getId();
} else {
$transformedValue = NULL;
}
break;
default:
$transformedValue = $value;
}
$form->get('chill_personbundle_person['.$field. ']')
->setValue($transformedValue);
$this->client->submit($form);
$this->refreshPerson();
$this->assertTrue($this->client->getResponse()->isRedirect($this->viewUrl),
'the page is redirected to general view');
$this->assertEquals($value, $callback($this->person),
'the value '.$field.' is updated in db');
$crawler = $this->client->followRedirect();
$this->assertGreaterThan(0, $crawler->filter('.success')->count(),
'a element .success is shown');
if($field == 'birthdate' or $field == 'memo' or $field == 'countryOfBirth' or $field == 'nationality'
or $field == 'gender') {
// we do not perform test on the web page contents.
} else {
$this->assertGreaterThan(0, $crawler->filter('html:contains("'.$value.'")')->count());
}
}
/**
* provide valid values to test, with field name and
* a function to find the value back from person entity
*
* @return mixed[]
*/
public function validTextFieldsProvider()
{
return array(
['firstName', 'random Value', function(Person $person) { return $person->getFirstName(); } ],
['lastName' , 'random Value', function(Person $person) { return $person->getLastName(); } ],
['birthdate', '15-12-1980', function(Person $person) { return $person->getBirthdate()->format('d-m-Y'); }],
['memo', 'jfkdlmq jkfldmsq jkmfdsq', function(Person $person) { return $person->getMemo(); }],
['birthdate', '', function(Person $person) { return $person->getBirthdate(); }],
['gender', Person::FEMALE_GENDER, function(Person $person) { return $person->getGender(); }],
[
'environment' => 'test_with_hidden_fields',
],
[
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
]
);
}
public function tearDown()
{
$this->refreshPerson();
$this->em->remove($this->person);
$this->em->flush();
}
/**
* Test the edit page are accessible.
*/
public function testEditPageIsSuccessful()
{
$this->client->request('GET', $this->editUrl);
$this->assertTrue(
$this->client->getResponse()->isSuccessful(),
'The person edit form is accessible'
);
}
/**
* Test the edition of a field.
*
* Given I fill the field with $value
* And I submit the form
* Then I am redirected to the 'general' page
* And the person is updated in the db
*
* @dataProvider validTextFieldsProvider
*
* @param string $field
* @param string $value
*/
public function testEditTextField($field, $value, Closure $callback)
{
$crawler = $this->client->request('GET', $this->editUrl);
$form = $crawler->selectButton('Submit')
->form();
//transform countries into value if needed
switch ($field) {
case 'nationality':
case 'countryOfBirth':
if (null !== $value) {
$country = $this->em->getRepository('ChillMainBundle:Country')
->findOneByCountryCode($value);
$transformedValue = $country->getId();
} else {
$transformedValue = null;
}
break;
default:
$transformedValue = $value;
}
$form->get('chill_personbundle_person[' . $field . ']')
->setValue($transformedValue);
$this->client->submit($form);
$this->refreshPerson();
$this->assertTrue(
$this->client->getResponse()->isRedirect($this->viewUrl),
'the page is redirected to general view'
);
$this->assertEquals(
$value,
$callback($this->person),
'the value ' . $field . ' is updated in db'
);
$crawler = $this->client->followRedirect();
$this->assertGreaterThan(
0,
$crawler->filter('.success')->count(),
'a element .success is shown'
);
if ('birthdate' == $field or 'memo' == $field or 'countryOfBirth' == $field or 'nationality' == $field
or 'gender' == $field) {
// we do not perform test on the web page contents.
} else {
$this->assertGreaterThan(0, $crawler->filter('html:contains("' . $value . '")')->count());
}
}
/**
* Test the configurable fields are absent.
*
* @group configurable_fields
*/
public function testHiddenFielsAreAbsent()
{
$crawler = $this->client->request('GET', $this->editUrl);
$configurables = ['placeOfBirth', 'phonenumber', 'email',
'countryOfBirth', 'nationality', 'spokenLanguages', 'maritalStatus', ];
$form = $crawler->selectButton('Submit')->form(); //;
foreach ($configurables as $key) {
$this->assertFalse($form->has('chill_personbundle_person[' . $key . ']'));
}
}
/**
* provide valid values to test, with field name and
* a function to find the value back from person entity.
*
* @return mixed[]
*/
public function validTextFieldsProvider()
{
return [
['firstName', 'random Value', function (Person $person) { return $person->getFirstName(); }],
['lastName', 'random Value', function (Person $person) { return $person->getLastName(); }],
['birthdate', '15-12-1980', function (Person $person) { return $person->getBirthdate()->format('d-m-Y'); }],
['memo', 'jfkdlmq jkfldmsq jkmfdsq', function (Person $person) { return $person->getMemo(); }],
['birthdate', '', function (Person $person) { return $person->getBirthdate(); }],
['gender', Person::FEMALE_GENDER, function (Person $person) { return $person->getGender(); }],
];
}
/**
* Reload the person from the db.
*/
protected function refreshPerson()
{
$this->person = $this->em->getRepository('ChillPersonBundle:Person')
->find($this->person->getId());
}
private function getVeryLongText()
{
return <<<EOT
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse molestie at enim id auctor. Vivamus malesuada elit ipsum, ac mollis ex facilisis sit amet. Phasellus accumsan, quam ut aliquet accumsan, augue ligula consequat erat, condimentum iaculis orci magna egestas eros. In vel blandit sapien. Duis ut dui vitae tortor iaculis malesuada vitae vitae lorem. Morbi efficitur dolor orci, a rhoncus urna blandit quis. Aenean at placerat dui, ut tincidunt nulla. In ultricies tempus ligula ac rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce urna nibh, placerat vel auctor sed, maximus quis magna. Vivamus quam ante, consectetur vel feugiat quis, aliquet id ante. Integer gravida erat dignissim ante commodo mollis. Donec imperdiet mauris elit, nec blandit dolor feugiat ut. Proin iaculis enim ut tortor pretium commodo. Etiam aliquet hendrerit dolor sed fringilla. Vestibulum facilisis nibh tincidunt dui egestas, vitae congue mi imperdiet. Duis vulputate ultricies lectus id cursus. Fusce bibendum sem dignissim, bibendum purus quis, mollis ex. Cras ac est justo. Duis congue mattis ipsum, vitae sagittis justo dictum sit amet. Duis aliquam pharetra sem, non laoreet ante laoreet ac. Mauris ornare mi tempus rutrum consequat.
EOT;
return <<<'EOT'
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse molestie at enim id auctor. Vivamus malesuada elit ipsum, ac mollis ex facilisis sit amet. Phasellus accumsan, quam ut aliquet accumsan, augue ligula consequat erat, condimentum iaculis orci magna egestas eros. In vel blandit sapien. Duis ut dui vitae tortor iaculis malesuada vitae vitae lorem. Morbi efficitur dolor orci, a rhoncus urna blandit quis. Aenean at placerat dui, ut tincidunt nulla. In ultricies tempus ligula ac rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce urna nibh, placerat vel auctor sed, maximus quis magna. Vivamus quam ante, consectetur vel feugiat quis, aliquet id ante. Integer gravida erat dignissim ante commodo mollis. Donec imperdiet mauris elit, nec blandit dolor feugiat ut. Proin iaculis enim ut tortor pretium commodo. Etiam aliquet hendrerit dolor sed fringilla. Vestibulum facilisis nibh tincidunt dui egestas, vitae congue mi imperdiet. Duis vulputate ultricies lectus id cursus. Fusce bibendum sem dignissim, bibendum purus quis, mollis ex. Cras ac est justo. Duis congue mattis ipsum, vitae sagittis justo dictum sit amet. Duis aliquam pharetra sem, non laoreet ante laoreet ac. Mauris ornare mi tempus rutrum consequat.
EOT;
}
}

View File

@@ -1,40 +1,36 @@
<?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\PersonBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Chill\PersonBundle\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Marc Ducobu <marc.ducobu@champs-libres.coop>
* @internal
* @coversNothing
*/
class PersonControllerViewTest extends WebTestCase
{
/** @var \Doctrine\ORM\EntityManagerInterface The entity manager */
/**
* @var \Doctrine\ORM\EntityManagerInterface The entity manager
*/
private $em;
/** @var Person A person used on which to run the test */
/**
* @var Person A person used on which to run the test
*/
private $person;
/** @var String The url to view the person details */
/**
* @var string The url to view the person details
*/
private $viewUrl;
public function setUp()
@@ -45,31 +41,38 @@ class PersonControllerViewTest extends WebTestCase
->get('doctrine.orm.entity_manager');
$center = $this->em->getRepository('ChillMainBundle:Center')
->findOneBy(array('name' => 'Center A'));
->findOneBy(['name' => 'Center A']);
$this->person = (new Person())
->setLastName("Tested Person")
->setFirstName("Réginald")
->setLastName('Tested Person')
->setFirstName('Réginald')
->setCenter($center)
->setGender(Person::MALE_GENDER);
$this->em->persist($this->person);
$this->em->flush();
$this->viewUrl = '/en/person/'.$this->person->getId().'/general';
$this->viewUrl = '/en/person/' . $this->person->getId() . '/general';
}
public function tearDown()
{
$this->refreshPerson();
$this->em->remove($this->person);
$this->em->flush();
}
/**
* Test if the view page is accessible
* Test if the view page is accessible.
*
* @group configurable_fields
*/
public function testViewPerson()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
));
$client = static::createClient([], [
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
]);
$crawler = $client->request('GET', $this->viewUrl);
$response = $client->getResponse();
@@ -86,34 +89,29 @@ class PersonControllerViewTest extends WebTestCase
/**
* Test if the view page of a given person is not accessible for a user
* of another center of the person
* of another center of the person.
*/
public function testViewPersonAccessDeniedForUnauthorized()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center b_social',
'PHP_AUTH_PW' => 'password',
));
$client = static::createClient([], [
'PHP_AUTH_USER' => 'center b_social',
'PHP_AUTH_PW' => 'password',
]);
$client->request('GET', $this->viewUrl);
$this->assertEquals(403, $client->getResponse()->getStatusCode(),
"The view page of a person of a center A must not be accessible for user of center B");
$this->assertEquals(
403,
$client->getResponse()->getStatusCode(),
'The view page of a person of a center A must not be accessible for user of center B'
);
}
/**
* Reload the person from the db
* Reload the person from the db.
*/
protected function refreshPerson()
{
$this->person = $this->em->getRepository('ChillPersonBundle:Person')
->find($this->person->getId());
}
public function tearDown()
{
$this->refreshPerson();
$this->em->remove($this->person);
$this->em->flush();
}
}

View File

@@ -1,80 +1,87 @@
<?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\PersonBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Chill\PersonBundle\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
* @coversNothing
*/
class PersonControllerViewTestWithHiddenFields extends WebTestCase
{
/** @var \Doctrine\ORM\EntityManagerInterface The entity manager */
/**
* @var \Doctrine\ORM\EntityManagerInterface The entity manager
*/
private $em;
/** @var Person A person used on which to run the test */
/**
* @var Person A person used on which to run the test
*/
private $person;
/** @var String The url to view the person details */
/**
* @var string The url to view the person details
*/
private $viewUrl;
public function setUp()
{
static::bootKernel(array('environment' => 'test_with_hidden_fields'));
static::bootKernel(['environment' => 'test_with_hidden_fields']);
$this->em = static::$kernel->getContainer()
->get('doctrine.orm.entity_manager');
$center = $this->em->getRepository('ChillMainBundle:Center')
->findOneBy(array('name' => 'Center A'));
->findOneBy(['name' => 'Center A']);
$this->person = (new Person())
->setLastName("Tested Person")
->setFirstName("Réginald")
->setLastName('Tested Person')
->setFirstName('Réginald')
->setCenter($center)
->setGender(Person::MALE_GENDER);
$this->em->persist($this->person);
$this->em->flush();
$this->viewUrl = '/en/person/'.$this->person->getId().'/general';
$this->viewUrl = '/en/person/' . $this->person->getId() . '/general';
}
public function tearDown()
{
$this->refreshPerson();
$this->em->remove($this->person);
$this->em->flush();
}
/**
* Test if the view page is accessible
*
* Test if the view page is accessible.
*
* @group configurable_fields
*/
public function testViewPerson()
{
$this->markTestSkipped("This configuration does not allow multiple environnements");
$this->markTestSkipped('This configuration does not allow multiple environnements');
$client = static::createClient(
array('environment' => 'test_with_hidden_fields'),
array(
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr'
)
);
['environment' => 'test_with_hidden_fields'],
[
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr',
]
);
$crawler = $client->request('GET', $this->viewUrl);
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());
$this->assertGreaterThan(0, $crawler->filter('html:contains("Tested Person")')->count());
@@ -84,21 +91,13 @@ class PersonControllerViewTestWithHiddenFields extends WebTestCase
$this->assertNotContains('Langues parlées', $crawler->text());
$this->assertNotContains(/* Etat */ 'civil', $crawler->text());
}
/**
* Reload the person from the db
* Reload the person from the db.
*/
protected function refreshPerson()
protected function refreshPerson()
{
$this->person = $this->em->getRepository('ChillPersonBundle:Person')
->find($this->person->getId());
}
public function tearDown()
{
$this->refreshPerson();
$this->em->remove($this->person);
$this->em->flush();
}
}

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\PersonBundle\Tests\Controller;
use Chill\PersonBundle\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
* @coversNothing
*/
class PersonDuplicateControllerViewTest extends WebTestCase
{
public function setUp()
@@ -15,18 +26,18 @@ class PersonDuplicateControllerViewTest extends WebTestCase
->get('doctrine.orm.entity_manager');
$center = $this->em->getRepository('ChillMainBundle:Center')
->findOneBy(array('name' => 'Center A'));
->findOneBy(['name' => 'Center A']);
$this->person = (new Person())
->setLastName("Tested Persan")
->setFirstName("Réginal")
->setLastName('Tested Persan')
->setFirstName('Réginal')
->setCenter($center)
->setGender(Person::MALE_GENDER);
$this->em->persist($this->person);
$this->person2 = (new Person())
->setLastName("Tested Person")
->setFirstName("Réginald")
->setLastName('Tested Person')
->setFirstName('Réginald')
->setCenter($center)
->setGender(Person::MALE_GENDER);
$this->em->persist($this->person2);
@@ -36,12 +47,12 @@ class PersonDuplicateControllerViewTest extends WebTestCase
public function testViewDuplicatePerson()
{
$client = static::createClient(array(), array(
$client = static::createClient([], [
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
));
'PHP_AUTH_PW' => 'password',
]);
$crawler = $client->request('GET', '/en/person/'.$this->person->getId().'/duplicate/view');
$crawler = $client->request('GET', '/en/person/' . $this->person->getId() . '/duplicate/view');
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());
@@ -49,15 +60,15 @@ class PersonDuplicateControllerViewTest extends WebTestCase
$this->assertGreaterThan(0, $crawler->filter('html:contains("Réginal")')->count());
$this->assertGreaterThan(0, $crawler->filter('html:contains("Réginald")')->count());
$crawler = $client->request('GET', '/en/person/'.$this->person->getId().'/duplicate/'.$this->person2->getId().'/confirm');
$crawler = $client->request('GET', '/en/person/' . $this->person->getId() . '/duplicate/' . $this->person2->getId() . '/confirm');
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());
$this->assertGreaterThan(0, $crawler->filter('html:contains("Old person")')->count());
$this->assertGreaterThan(0, $crawler->filter('html:contains("New person")')->count());
$crawler = $client->request('POST', '/en/person/'.$this->person->getId().'/duplicate/'.$this->person2->getId().'/confirm', [
'chill_personbundle_person_confirm_duplicate[confirm]' => 1
$crawler = $client->request('POST', '/en/person/' . $this->person->getId() . '/duplicate/' . $this->person2->getId() . '/confirm', [
'chill_personbundle_person_confirm_duplicate[confirm]' => 1,
]);
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());

View File

@@ -1,17 +1,31 @@
<?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\PersonBundle\Tests\Controller;
use Chill\MainBundle\Test\PrepareClientTrait;
use Chill\PersonBundle\DataFixtures\Helper\PersonRandomHelper;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Relationships\Relation;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Component\HttpFoundation\Request;
use Chill\PersonBundle\Repository\PersonRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
use function array_rand;
use function json_encode;
use function random_int;
/**
* @internal
* @coversNothing
*/
class RelationshipApiControllerTest extends WebTestCase
{
use PrepareClientTrait;
@@ -19,8 +33,9 @@ class RelationshipApiControllerTest extends WebTestCase
private KernelBrowser $client;
/**
* A cache for all relations
* @var array|null|Relation[]
* A cache for all relations.
*
* @var array|Relation[]|null
*/
private ?array $relations = null;
@@ -30,80 +45,6 @@ class RelationshipApiControllerTest extends WebTestCase
$this->client = $this->getClientAuthenticated();
}
/**
* @dataProvider personProvider
*/
public function testGetRelationshipByPerson($personId)
{
$this->client->request(Request::METHOD_GET, sprintf('/api/1.0/relations/relationship/by-person/%d.json', $personId));
$response = $this->client->getResponse();
$this->assertEquals(200, $response->getStatusCode(), 'Test to see that API response returns a status code 200');
}
/**
* @dataProvider relationProvider
*/
public function testPostRelationship($fromPersonId, $toPersonId, $relationId, $isReverse): void
{
$this->client->request(Request::METHOD_POST,
'/api/1.0/relations/relationship.json',
[],
[],
[],
\json_encode([
'type' => 'relationship',
'fromPerson' => ['id' => $fromPersonId, 'type' => 'person'],
'toPerson' => ['id' => $toPersonId, 'type' => 'person'],
'relation' => ['id' => $relationId, 'type' => 'relation'],
'reverse' => $isReverse
]));
$response = $this->client->getResponse();
$this->assertEquals(200, $response->getStatusCode());
}
public function relationProvider(): array
{
static::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$countPersons = $em->createQueryBuilder()
->select('count(p)')
->from(Person::class, 'p')
->join('p.center', 'c')
->where('c.name LIKE :name')
->setParameter('name', 'Center A')
->getQuery()
->getSingleScalarResult()
;
$persons = $em->createQueryBuilder()
->select('p')
->from(Person::class, 'p')
->join('p.center', 'c')
->where('c.name LIKE :name')
->setParameter('name', 'Center A')
->getQuery()
->setMaxResults(2)
->setFirstResult(\random_int(0, $countPersons - 1))
->getResult()
;
return [
[$persons[0]->getId(), $persons[1]->getId(), $this->getRandomRelation($em)->getId(), true],
];
}
private function getRandomRelation(EntityManagerInterface $em): Relation
{
if (null === $this->relations) {
$this->relations = $em->getRepository(Relation::class)
->findAll();
}
return $this->relations[\array_rand($this->relations)];
}
public function personProvider(): array
{
static::bootKernel();
@@ -115,8 +56,7 @@ class RelationshipApiControllerTest extends WebTestCase
->where('c.name LIKE :name')
->setParameter('name', 'Center A')
->getQuery()
->getSingleScalarResult()
;
->getSingleScalarResult();
$person = $em->createQueryBuilder()
->select('p')
->from(Person::class, 'p')
@@ -125,12 +65,91 @@ class RelationshipApiControllerTest extends WebTestCase
->setParameter('name', 'Center A')
->getQuery()
->setMaxResults(1)
->setFirstResult(\random_int(0, $countPersons - 1))
->getSingleResult()
;
->setFirstResult(random_int(0, $countPersons - 1))
->getSingleResult();
return [
[$person->getId()],
];
}
public function relationProvider(): array
{
static::bootKernel();
$em = self::$container->get(EntityManagerInterface::class);
$countPersons = $em->createQueryBuilder()
->select('count(p)')
->from(Person::class, 'p')
->join('p.center', 'c')
->where('c.name LIKE :name')
->setParameter('name', 'Center A')
->getQuery()
->getSingleScalarResult();
$persons = $em->createQueryBuilder()
->select('p')
->from(Person::class, 'p')
->join('p.center', 'c')
->where('c.name LIKE :name')
->setParameter('name', 'Center A')
->getQuery()
->setMaxResults(2)
->setFirstResult(random_int(0, $countPersons - 1))
->getResult();
return [
[$persons[0]->getId(), $persons[1]->getId(), $this->getRandomRelation($em)->getId(), true],
];
}
/**
* @dataProvider personProvider
*
* @param mixed $personId
*/
public function testGetRelationshipByPerson($personId)
{
$this->client->request(Request::METHOD_GET, sprintf('/api/1.0/relations/relationship/by-person/%d.json', $personId));
$response = $this->client->getResponse();
$this->assertEquals(200, $response->getStatusCode(), 'Test to see that API response returns a status code 200');
}
/**
* @dataProvider relationProvider
*
* @param mixed $fromPersonId
* @param mixed $toPersonId
* @param mixed $relationId
* @param mixed $isReverse
*/
public function testPostRelationship($fromPersonId, $toPersonId, $relationId, $isReverse): void
{
$this->client->request(
Request::METHOD_POST,
'/api/1.0/relations/relationship.json',
[],
[],
[],
json_encode([
'type' => 'relationship',
'fromPerson' => ['id' => $fromPersonId, 'type' => 'person'],
'toPerson' => ['id' => $toPersonId, 'type' => 'person'],
'relation' => ['id' => $relationId, 'type' => 'relation'],
'reverse' => $isReverse,
])
);
$response = $this->client->getResponse();
$this->assertEquals(200, $response->getStatusCode());
}
private function getRandomRelation(EntityManagerInterface $em): Relation
{
if (null === $this->relations) {
$this->relations = $em->getRepository(Relation::class)
->findAll();
}
return $this->relations[array_rand($this->relations)];
}
}

View File

@@ -1,11 +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\PersonBundle\Tests\Controller;
use Chill\MainBundle\Test\PrepareClientTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\Test\PrepareClientTrait;
use function array_pop;
use function json_decode;
/**
* @internal
* @coversNothing
*/
class SocialIssueApiControllerTest extends WebTestCase
{
use PrepareClientTrait;
@@ -17,21 +30,6 @@ class SocialIssueApiControllerTest extends WebTestCase
self::bootKernel();
}
public function testList(): array
{
$client = $this->getClientAuthenticated();
$client->request(Request::METHOD_GET, '/api/1.0/person/social-work/social-issue.json');
$this->assertEquals(200, $client->getResponse()->getStatusCode());
$data = \json_decode($client->getResponse()->getContent(), true);
$this->assertGreaterThan(0, $data['count']);
$this->assertGreaterThan(0, count($data['results']));
return $data;
}
/**
* @depends testList
*/
@@ -39,17 +37,31 @@ class SocialIssueApiControllerTest extends WebTestCase
{
$socialIssues = $data['results'];
shuffle($socialIssues);
$socialIssue = \array_pop($socialIssues);
$socialIssue = array_pop($socialIssues);
$client = $this->getClientAuthenticated();
$client->request(Request::METHOD_GET, sprintf('/api/1.0/person/social-work/social-issue/%d.json', $socialIssue['id']));
$this->assertEquals(200, $client->getResponse()->getStatusCode());
$data = \json_decode($client->getResponse()->getContent(), true);
$data = json_decode($client->getResponse()->getContent(), true);
$this->assertArrayHasKey('id', $data);
$this->assertArrayHasKey('type', $data);
}
public function testList(): array
{
$client = $this->getClientAuthenticated();
$client->request(Request::METHOD_GET, '/api/1.0/person/social-work/social-issue.json');
$this->assertEquals(200, $client->getResponse()->getStatusCode());
$data = json_decode($client->getResponse()->getContent(), true);
$this->assertGreaterThan(0, $data['count']);
$this->assertGreaterThan(0, count($data['results']));
return $data;
}
}