Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Unit tests & additions to russian documentation

  • Loading branch information...
commit 90f157f77af990b77fe426bfc42f929bafa238c0 1 parent b223cf2
Semyon authored
79 Controller/ForTestingController.php
View
@@ -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 DependencyInjection/Configuration.php
View
@@ -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()
@@ -35,9 +38,6 @@ public function getConfigTreeBuilder()
->scalarNode('namespace')
->defaultValue('Actions')
->end()
- ->scalarNode('error_template')
- ->defaultValue('ExtDirectBundle::extjs_errors.html.twig')
- ->end()
->end()
->end();
47 Entity/Test.php
View
@@ -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 Form/Type/TestType.php
View
@@ -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 Resources/doc/index.rus.md
View
@@ -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  Response/Error.php
View
@@ -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);
}
12 Router/Call.php
View
@@ -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']))
20 Router/CallForm.php
View
@@ -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;
}
35 Tests/Api/ApiTest.php
View
@@ -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.
*/
40 Tests/ControllerTest.php
View
@@ -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);
+ }
+
+}
263 Tests/GeneralTest.php
View
@@ -0,0 +1,263 @@
+<?php
+namespace Ext\DirectBundle\Tests;
+
+use Ext\DirectBundle\Tests\ControllerTest;
+use Ext\DirectBundle\Tests\Router;
+
+/**
+ * Testing basic function.
+ *
+ * @author Semyon Velichko <semyon@velichko.net>
+ */
+class GeneralTest extends ControllerTest
+{
+ // generic array response
+ public function testGeneralArrayResponse()
+ {
+ $postRawArray = array('action' => 'ExtDirect_ForTesting',
+ 'method' => 'testArrayResponse',
+ 'data' => array(array('page' => rand(1,10), 'start' => rand(10,20), 'limit' => rand(100,9999))),
+ 'type' => 'rpc',
+ 'tid' => rand(1, 10));
+ $postRawData = json_encode($postRawArray);
+
+ $client = static::createClient();
+ $crawler = $client->request('POST',
+ $this->get('router')->generate('ExtDirectBundle_route'),
+ array(),
+ array(),
+ array(),
+ $postRawData);
+
+
+ $jsonResult = $client->getResponse()->getContent();
+ $arrayResult = json_decode($jsonResult, true);
+ $this->assertInternalType('array', $arrayResult);
+ $this->assertArrayHasKey(0, $arrayResult);
+ $arrayResult = array_shift($arrayResult);
+
+ $this->assertArrayHasKey('result', $arrayResult);
+
+ $this->assertArrayHasKey('page', $arrayResult['result']);
+ $this->assertEquals($postRawArray['data'][0]['page'], $arrayResult['result']['page']);
+
+ $this->assertArrayHasKey('start', $arrayResult['result']);
+ $this->assertEquals($postRawArray['data'][0]['start'], $arrayResult['result']['start']);
+
+ $this->assertArrayHasKey('limit', $arrayResult['result']);
+ $this->assertEquals($postRawArray['data'][0]['limit'], $arrayResult['result']['limit']);
+ }
+
+ // Ext\DirectBundle\Response\Response;
+ public function testGeneralObjectResponse()
+ {
+ $postRawArray = array('action' => 'ExtDirect_ForTesting',
+ 'method' => 'testObjectResponse',
+ 'data' => array(array('page' => rand(1,10), 'start' => rand(10,20), 'limit' => rand(100,9999))),
+ 'type' => 'rpc',
+ 'tid' => rand(1, 10));
+ $postRawData = json_encode($postRawArray);
+
+ $client = static::createClient();
+ $crawler = $client->request('POST',
+ $this->get('router')->generate('ExtDirectBundle_route'),
+ array(),
+ array(),
+ array(),
+ $postRawData);
+
+
+ $jsonResult = $client->getResponse()->getContent();
+ $arrayResult = json_decode($jsonResult, true);
+ $this->assertInternalType('array', $arrayResult);
+ $this->assertArrayHasKey(0, $arrayResult);
+ $arrayResult = array_shift($arrayResult);
+
+ $this->assertArrayHasKey('result', $arrayResult);
+
+ $this->assertArrayHasKey('page', $arrayResult['result']);
+ $this->assertEquals($postRawArray['data'][0]['page'], $arrayResult['result']['page']);
+
+ $this->assertArrayHasKey('start', $arrayResult['result']);
+ $this->assertEquals($postRawArray['data'][0]['start'], $arrayResult['result']['start']);
+
+ $this->assertArrayHasKey('limit', $arrayResult['result']);
+ $this->assertEquals($postRawArray['data'][0]['limit'], $arrayResult['result']['limit']);
+ }
+
+ // Ext\DirectBundle\Response\Response;
+ public function testObjectResponseWithConfiguredReader()
+ {
+ $postRawArray = array('action' => 'ExtDirect_ForTesting',
+ 'method' => 'testResponseWithConfiguredReader',
+ 'data' => array(array('page' => rand(1,10), 'start' => rand(10,20), 'limit' => rand(100,9999))),
+ 'type' => 'rpc',
+ 'tid' => rand(1, 10));
+ $postRawData = json_encode($postRawArray);
+
+ $client = static::createClient();
+ $crawler = $client->request('POST',
+ $this->get('router')->generate('ExtDirectBundle_route'),
+ array(),
+ array(),
+ array(),
+ $postRawData);
+
+
+ $jsonResult = $client->getResponse()->getContent();
+ $arrayResult = json_decode($jsonResult, true);
+ $this->assertInternalType('array', $arrayResult);
+ $this->assertArrayHasKey(0, $arrayResult);
+ $arrayResult = array_shift($arrayResult);
+
+ $this->assertArrayHasKey('result', $arrayResult);
+ $this->assertArrayHasKey('root', $arrayResult['result']);
+
+ $this->assertArrayHasKey('page', $arrayResult['result']['root']);
+ $this->assertEquals($postRawArray['data'][0]['page'], $arrayResult['result']['root']['page']);
+
+ $this->assertArrayHasKey('start', $arrayResult['result']['root']);
+ $this->assertEquals($postRawArray['data'][0]['start'], $arrayResult['result']['root']['start']);
+
+ $this->assertArrayHasKey('limit', $arrayResult['result']['root']);
+ $this->assertEquals($postRawArray['data'][0]['limit'], $arrayResult['result']['root']['limit']);
+
+ $this->assertArrayHasKey('successProperty', $arrayResult['result']);
+ $this->assertEquals(true, $arrayResult['result']['successProperty']);
+
+ $this->assertArrayHasKey('totalProperty', $arrayResult['result']);
+ $this->assertEquals(100, $arrayResult['result']['totalProperty']);
+ }
+
+ // Ext\DirectBundle\Response\Response;
+ public function testFormHandlerResponse()
+ {
+ $postArray = array('extAction' => 'ExtDirect_ForTesting',
+ 'extMethod' => 'testFormHandlerResponse',
+ 'extType' => 'rpc',
+ 'extTID' => rand(1, 10),
+ 'extUpload' => false,
+
+ 'id' => rand(1,99),
+ 'name' => 'Joker',
+ 'count' => rand(100,200));
+
+ $client = static::createClient();
+ $crawler = $client->request('POST', $this->get('router')->generate('ExtDirectBundle_route'), $postArray);
+ $jsonResult = $client->getResponse()->getContent();
+ $arrayResult = json_decode($jsonResult, true);
+
+ $this->assertInternalType('array', $arrayResult);
+ $this->assertArrayHasKey(0, $arrayResult);
+ $arrayResult = array_shift($arrayResult);
+
+ $this->assertArrayHasKey('result', $arrayResult);
+ $this->assertArrayHasKey('data', $arrayResult['result']);
+
+ $this->assertArrayHasKey('success', $arrayResult['result']);
+ $this->assertEquals(true, $arrayResult['result']['success']);
+
+ foreach(array('id', 'name', 'count') as $key) {
+ $this->assertArrayHasKey($key, $arrayResult['result']['data']);
+ $this->assertEquals($postArray[$key], $arrayResult['result']['data'][$key]);
+ }
+
+ }
+
+ // Ext\DirectBundle\Response\Response;
+ // Ext\DirectBundle\Response\FormError;
+ public function testFormValidationResponse()
+ {
+ $postArray = array('extAction' => 'ExtDirect_ForTesting',
+ 'extMethod' => 'testFormValidationResponse',
+ 'extType' => 'rpc',
+ 'extTID' => rand(1, 10),
+ 'extUpload' => false,
+
+ 'id' => rand(1,99),
+ 'name' => 'Joker',
+ 'count' => rand(1, 99));
+
+ $client = static::createClient();
+ $crawler = $client->request('POST', $this->get('router')->generate('ExtDirectBundle_route'), $postArray);
+ $jsonResult = $client->getResponse()->getContent();
+ $arrayResult = json_decode($jsonResult, true);
+
+ $this->assertInternalType('array', $arrayResult);
+ $this->assertArrayHasKey(0, $arrayResult);
+ $arrayResult = array_shift($arrayResult);
+
+ $this->assertArrayHasKey('result', $arrayResult);
+ $this->assertArrayHasKey('success', $arrayResult['result']);
+ $this->assertEquals(true, $arrayResult['result']['success']);
+
+ // catch errors from form
+ $postArray['name'] = '';
+ $postArray['count'] = -100;
+
+ $crawler = $client->request('POST', $this->get('router')->generate('ExtDirectBundle_route'), $postArray);
+ $jsonResult = $client->getResponse()->getContent();
+ $arrayResult = json_decode($jsonResult, true);
+
+ $this->assertInternalType('array', $arrayResult);
+ $this->assertArrayHasKey(0, $arrayResult);
+ $arrayResult = array_shift($arrayResult);
+
+ $this->assertArrayHasKey('result', $arrayResult);
+ $this->assertArrayHasKey('success', $arrayResult['result']);
+ $this->assertEquals(false, $arrayResult['result']['success']);
+
+ $this->assertArrayHasKey('msg', $arrayResult['result']);
+ $this->assertRegExp('/This value should not be blank/', $arrayResult['result']['msg']);
+ $this->assertRegExp('/This value should be 0 or more/', $arrayResult['result']['msg']);
+ }
+
+ // Ext\DirectBundle\Response\Response;
+ // Ext\DirectBundle\Response\Validator;
+ public function testFormEntityValidationResponse()
+ {
+ $postArray = array('extAction' => 'ExtDirect_ForTesting',
+ 'extMethod' => 'testFormEntityValidationResponse',
+ 'extType' => 'rpc',
+ 'extTID' => rand(1, 10),
+ 'extUpload' => false,
+
+ 'id' => rand(1,99),
+ 'name' => 'Joker',
+ 'count' => rand(1, 99));
+
+ $client = static::createClient();
+ $crawler = $client->request('POST', $this->get('router')->generate('ExtDirectBundle_route'), $postArray);
+ $jsonResult = $client->getResponse()->getContent();
+ $arrayResult = json_decode($jsonResult, true);
+
+ $this->assertInternalType('array', $arrayResult);
+ $this->assertArrayHasKey(0, $arrayResult);
+ $arrayResult = array_shift($arrayResult);
+
+ $this->assertArrayHasKey('result', $arrayResult);
+ $this->assertArrayHasKey('success', $arrayResult['result']);
+ $this->assertEquals(true, $arrayResult['result']['success']);
+
+ // catch errors from form
+ $postArray['name'] = '';
+ $postArray['count'] = -100;
+
+ $crawler = $client->request('POST', $this->get('router')->generate('ExtDirectBundle_route'), $postArray);
+ $jsonResult = $client->getResponse()->getContent();
+ $arrayResult = json_decode($jsonResult, true);
+
+ $this->assertInternalType('array', $arrayResult);
+ $this->assertArrayHasKey(0, $arrayResult);
+ $arrayResult = array_shift($arrayResult);
+
+ $this->assertArrayHasKey('result', $arrayResult);
+ $this->assertArrayHasKey('success', $arrayResult['result']);
+ $this->assertEquals(false, $arrayResult['result']['success']);
+
+ $this->assertArrayHasKey('msg', $arrayResult['result']);
+ $this->assertRegExp('/This value should not be blank/', $arrayResult['result']['msg']);
+ $this->assertRegExp('/This value should be 0 or more/', $arrayResult['result']['msg']);
+ }
+}
+
Please sign in to comment.
Something went wrong with that request. Please try again.