Skip to content
This repository has been archived by the owner on Aug 3, 2023. It is now read-only.

Commit

Permalink
Browse files Browse the repository at this point in the history
Unit tests & additions to russian documentation
  • Loading branch information
ghua committed Jul 21, 2012
1 parent b223cf2 commit 90f157f
Show file tree
Hide file tree
Showing 11 changed files with 531 additions and 48 deletions.
79 changes: 79 additions & 0 deletions Controller/ForTestingController.php
@@ -0,0 +1,79 @@
<?php

namespace Ext\DirectBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Ext\DirectBundle\Response\Response;
use Ext\DirectBundle\Response\FormError;
use Ext\DirectBundle\Response\ValidatorError;
use Ext\DirectBundle\Entity\Test;
use Ext\DirectBundle\Form\Type\TestType;

class ForTestingController extends Controller
{

public function testArrayResponseAction($_data)
{
return $_data;
}

public function testObjectResponseAction($_data)
{
return $this->get('ext_direct')->createResponse(new Response(), $_data);
}

public function testResponseWithConfiguredReaderAction($_data)
{
return $this->get('ext_direct')
->createResponse(new Response(), $_data)
->setSuccess(true)
->setTotal(100);
}

public function testFormHandlerResponseAction($_data)
{
return $this->get('ext_direct')
->createResponse(new Response(), $_data)
->setSuccess(true);
}

public function testFormValidationResponseAction($_data)
{
$Entity = new Test();

$form = $this->createForm(new TestType(), $Entity);
$_data = array_intersect_key($_data, $form->getChildren());
$form->bind($_data);

if($form->isValid())
{
return $this->get('ext_direct')
->createResponse(new Response())
->setSuccess(true);
} else {
return $this->get('ext_direct')
->createResponse(new FormError(), $form);
}
}

public function testFormEntityValidationResponseAction($_data)
{
$Entity = new Test();

$form = $this->createForm(new TestType(), $Entity);
$_data = array_intersect_key($_data, $form->getChildren());
$form->bind($_data);

$errors = $this->get('validator')->validate($Entity);

if(count($errors) === 0)
{
return $this->get('ext_direct')
->createResponse(new Response())
->setSuccess(true);
} else {
return $this->get('ext_direct')
->createResponse(new ValidatorError(), $errors);
}
}

}
6 changes: 3 additions & 3 deletions DependencyInjection/Configuration.php
Expand Up @@ -26,6 +26,9 @@ public function getConfigTreeBuilder()
// more information on that topic.

$rootNode->children()
->scalarNode('error_template')
->defaultValue('ExtDirectBundle::extjs_errors.html.twig')
->end()
->arrayNode('basic')
->addDefaultsIfNotSet()
->children()
Expand All @@ -35,9 +38,6 @@ public function getConfigTreeBuilder()
->scalarNode('namespace')
->defaultValue('Actions')
->end()
->scalarNode('error_template')
->defaultValue('ExtDirectBundle::extjs_errors.html.twig')
->end()
->end()
->end();

Expand Down
47 changes: 47 additions & 0 deletions Entity/Test.php
@@ -0,0 +1,47 @@
<?php

namespace Ext\DirectBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Test
{
private $id;

/**
* @Assert\NotBlank()
*/
private $name;

/**
* @Assert\NotBlank()
* @Assert\Min(0)
* @Assert\Max(100)
*/
private $count;

public function getId()
{
return $this->id;
}

public function setName($name)
{
$this->name = $name;
}

public function getName()
{
return $this->name;
}

public function setCount($count)
{
$this->count = $count;
}

public function getCount()
{
return $this->count;
}
}
29 changes: 29 additions & 0 deletions Form/Type/TestType.php
@@ -0,0 +1,29 @@
<?php

namespace Ext\DirectBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class TestType extends AbstractType
{

public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('name');
$builder->add('count');
}

public function getName()
{
return 'TestType';
}

public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Ext\DirectBundle\Entity\Test',
'csrf_protection' => false
);
}
}
46 changes: 46 additions & 0 deletions Resources/doc/index.rus.md
Expand Up @@ -460,3 +460,49 @@ _Дополнительную информацию по событиям луч
}

В данном примере специально ошибки извлекаются из сервиса validator, формат ответа будет аналогичен ответу из предыдущего раздела.

Разработка
---------

#### Тестирование ####
Для тестирования добавьте в config_test.yml:

ext_direct:
router:
rules:
testArrayResponse:
defaults: { _controller: ExtDirectBundle:ForTesting:testArrayResponse, params: true }
testObjectResponse:
defaults: { _controller: ExtDirectBundle:ForTesting:testObjectResponse, params: true }
testResponseWithConfiguredReader:
defaults: { _controller: ExtDirectBundle:ForTesting:testResponseWithConfiguredReader, params: true }
reader: { root: root, successProperty: successProperty, totalProperty: totalProperty }
testFormHandlerResponse:
defaults: { _controller: ExtDirectBundle:ForTesting:testFormHandlerResponse, params: true, form: true }
reader: { root: data }
testFormValidationResponse:
defaults: { _controller: ExtDirectBundle:ForTesting:testFormValidationResponse, params: true, form: true }

testFormEntityValidationResponse:
defaults: { _controller: ExtDirectBundle:ForTesting:testFormEntityValidationResponse, params: true, form: true }

Также в конфигурации phpunit.xml нужно добавить:

<directory>../vendor/bundles/Ext/DirectBundle/Tests</directory>

Результат запуска тестов должен быть примерно следующим:

$ phpunit -v
PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from symfony2sandbox/app/phpunit.xml

.......

Time: 1 second, Memory: 46.75Mb

OK (7 tests, 78 assertions)
2 changes: 1 addition & 1 deletion Response/Error.php
Expand Up @@ -18,7 +18,7 @@ public function formatResponse(array $data)
$msg = $this->factory
->getContainer()
->get('ext_direct.controller')
->render($this->config['basic']['error_template'], array('errors' => $data))
->render($this->config['error_template'], array('errors' => $data))
->getContent();
return array($config['reader']['successProperty'] => $this->success, 'msg' => $msg);
}
Expand Down
12 changes: 8 additions & 4 deletions Router/Call.php
Expand Up @@ -140,10 +140,14 @@ public function getResponse($result)
*/
public function initialize($call)
{
$this->action = $call['action'];
$this->method = $call['method'];
$this->type = $call['type'];
$this->tid = $call['tid'];
foreach(array('action', 'method', 'type', 'tid') as $key)
{
if(!isset($call[$key]))
throw new \Ext\DirectBundle\Exception\InvalidJsonException(sprintf('%s key does not exist', $key));

$this->$key = $call[$key];
}

$this->data = array();

if(is_array($call['data']) && !empty($call['data']))
Expand Down
20 changes: 13 additions & 7 deletions Router/CallForm.php
Expand Up @@ -15,13 +15,19 @@ class CallForm extends Call
*/
public function initialize($call)
{

$this->action = $call['extAction']; unset($call['extAction']);
$this->method = $call['extMethod']; unset($call['extMethod']);
$this->type = $call['extType']; unset($call['extType']);
$this->tid = $call['extTID']; unset($call['extTID']);
$this->upload = $call['extUpload']; unset($call['extUpload']);

foreach(array('action' => 'extAction',
'method' => 'extMethod',
'type' => 'extType',
'tid' => 'extTID',
'upload' => 'extUpload') as $key => $value)
{
if(!isset($call[$value]))
throw new \Ext\DirectBundle\Exception\InvalidJsonException(sprintf('%s key does not exist', $value));

$this->$key = $call[$value];
unset($call[$value]);
}

foreach ($call as $key => $value) {
$this->data[$key] = $value;
}
Expand Down
35 changes: 2 additions & 33 deletions Tests/Api/ApiTest.php
@@ -1,47 +1,16 @@
<?php
namespace Ext\DirectBundle\Tests\Api;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Ext\DirectBundle\Tests\ControllerTest;
use Ext\DirectBundle\Api\Api;

require_once __DIR__.'../../../../../../../app/AppKernel.php';

/**
* Test class of ExtDirect Api.
*
* @author Otavio Fernandes <otavio@neton.com.br>
*/
class ApiTest extends WebTestCase
class ApiTest extends ControllerTest
{

protected static $kernel;
protected static $container;
/**
* @var \Doctrine\ORM\EntityManager
*/
private $em;

public function __construct() {
self::$kernel = new \AppKernel('test', true);
self::$kernel->boot();
self::$container = self::$kernel->getContainer();
$this->em = self::$container ->get('doctrine.orm.entity_manager');
}

/**
* Enter description here ...
* @return \Doctrine\ORM\EntityManager
*/
protected function getEntityManager ()
{
return $this->em;
}

public function get($serviceId)
{
return self::$container->get($serviceId);
}

/**
* Test Api->__toString() method.
*/
Expand Down
40 changes: 40 additions & 0 deletions Tests/ControllerTest.php
@@ -0,0 +1,40 @@
<?php
namespace Ext\DirectBundle\Tests;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Ext\DirectBundle\Api\Api;

require_once __DIR__.'../../../../../../app/AppKernel.php';

class ControllerTest extends WebTestCase
{

protected static $kernel;
protected static $container;
/**
* @var \Doctrine\ORM\EntityManager
*/
private $em;

public function __construct() {
self::$kernel = new \AppKernel('test', true);
self::$kernel->boot();
self::$container = self::$kernel->getContainer();
$this->em = self::$container ->get('doctrine.orm.entity_manager');
}

/**
* Enter description here ...
* @return \Doctrine\ORM\EntityManager
*/
protected function getEntityManager ()
{
return $this->em;
}

public function get($serviceId)
{
return self::$container->get($serviceId);
}

}

0 comments on commit 90f157f

Please sign in to comment.