Переглянути джерело

Agregado de test generico para webservice

gabriel 7 роки тому
батько
коміт
0e900db50a
1 змінених файлів з 348 додано та 0 видалено
  1. 348 0
      tests/WebTestCaseBase.php

+ 348 - 0
tests/WebTestCaseBase.php

@@ -0,0 +1,348 @@
+<?php
+
+namespace WebserviceBundle\tests;
+
+use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
+use Symfony\Component\BrowserKit\Cookie;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
+use Symfony\Bundle\FrameworkBundle\Client;
+
+use Doctrine\Common\Collections\ArrayCollection;
+use ReflectionClass;
+
+class WebTestCaseBase extends WebTestCase
+{
+    /**
+     * @var Client Cliente web.
+     */
+    private $client;
+    /**
+     * @var bool Me dice si estamos en  el  modulo base.
+     */
+    protected $isModuleBase;
+    /**
+     * @var int Contiene el id de usuario a simular
+     */
+    protected $idUser;
+
+    /**
+     * Funcion que crea un nuevo cliente para realizar consultas. Para cada consulta web necesito crear un nuevo cliente.
+     * @param bool $new Me dice si tengo que crear un nuevo cliente.
+     * @return Client Retorna el cliente.
+     */
+    protected function getClient($new = false)
+    {
+        if (!$this->client || $new) {
+            //  por defecto es environment=test y debug = true
+            $this->client = static::createClient();
+        }
+        return $this->client;
+    }
+
+    /**
+     * Funcion que busca un servicio dentro del container.
+     * @param mixed $service Contiene el nombre del servicio.
+     * @return mixed Retorna el servicio.
+     */
+    protected function get($service)
+    {
+        return $this->getClient()->getContainer()->get($service);
+    }
+
+    /**
+     * @return mixed Retorna el manager de doctrine.
+     */
+    protected function getDoctrineManager()
+    {
+        return $this->get('doctrine')->getManager();
+    }
+
+    /**
+     * @return bool Retorna TRUE si estoy en el modulo base.
+     */
+    public function isModuleBase()
+    {
+        if ($this->isModuleBase == null) {
+            $em = $this->getDoctrineManager();
+            if ($em == null) {
+                $this->isModuleBase = false;
+            } else {
+                $this->isModuleBase = array_key_exists('BaseTenancyBundle', $this->getClient()->getContainer()->getParameter('kernel.bundles'));
+            }
+        }
+        return $this->isModuleBase;
+    }
+
+    /**
+     * Se creo este metodo para crear objeto desde un string para no tener conflictos en otros modulos.
+     * @param string $repository Contiene el objeto del repositorio.
+     * @return mixed Crea una instancia de una objeto.
+     */
+    public function getObject($repository)
+    {
+        $obj = $this->getDoctrineManager()->getMetadataFactory()->getMetadataFor($repository)->getName();
+        $rc = new ReflectionClass($obj);
+        return $rc->newInstance();
+    }
+
+    /**
+     * Funcion que crea el servicio de tenencias. Por defecto crea la tenencia base.
+     * @param int $current Contiene la tenencia actual.
+     * @param array $tenancies Contiene las tenencias. Ej. array(array('id'=>1,'name'=>'base'))
+     */
+    protected function fakeTenancyService($current = 1, $tenancies = array())
+    {
+        $service_tenancy = $this->get('base_tenancy.tenancy_service');
+        if (count($tenancies) == 0) {
+            $tenancies [] = array('id' => 1, 'name' => 'Tenencia Base');
+        }
+        if ($this->isModuleBase()) {
+            // tengo que cargar las tenencias que no existan en la base de datos.
+            $em = $this->getDoctrineManager();
+            $user = $em->getRepository("BaseUserBundle:User")->findOneBy(array('id' => $this->idUser));
+            if (!$user) {
+                // el usuario no existe, entonces lo creo
+                $user = $this->getObject("BaseUserBundle:User");
+                $user->setUsername("adminpruebas");
+                $user->setPassword("adminpass");
+                $user->setEnabled(true);
+                $user->setEmail("pepe@pepe.com");
+                $em->persist($user);
+                $em->flush();
+            }
+            $arrayTenancies = new ArrayCollection();
+            foreach ($tenancies as $tenancyData) {
+                $tenancy = $em->getRepository("BaseTenancyBundle:Tenancy")->findOneBy(array('id' => $tenancyData['id']));
+                if (!$tenancy) {
+                    // la tenencia no existe, entonces la creo
+                    $tenancy = $this->getObject("BaseTenancyBundle:Tenancy");
+                    $tenancy->setId($tenancyData['id']);
+                    $tenancy->setName($tenancyData['name']);
+                    $tenancy->setEnabled(true);
+                    $em->persist($tenancy);
+                    $em->flush();
+                }
+                $ten_user = $em->createQueryBuilder()
+                    ->select('t')
+                    ->from('BaseTenancyBundle:Tenancy', 't')
+                    ->join('t.users', 'ut',
+                        \Doctrine\ORM\Query\Expr\Join::WITH,
+                        $em->getExpressionBuilder()->eq('ut.id', $this->idUser))
+                    ->where($em->getExpressionBuilder()->eq('t.id', $tenancyData['id']))
+                    ->getQuery()
+                    ->execute();
+                if (!$ten_user) {
+                    $arrayTenancies[] = $tenancy;
+                }
+            }
+            // actualizo las tenencias asociadas al usuario
+            $user->setTenancies($arrayTenancies);
+            $em->flush();
+        }
+        $service_tenancy->setTenancy($current);
+    }
+
+    /**
+     * Se crean los datos para hacer el fake al oauth
+     * @param int $idUser Contiene el id de usuario a simular.
+     * @throws \ErrorException Lanza una excepcion durante las distintas validaciones.
+     */
+    protected function FakeLogin($idUser = 1)
+    {
+        $this->idUser = $idUser;
+        // obtengo la session
+        $session = $this->get('session');
+        if ($session != null) {
+            // busco el usuario logueado
+            $em = $this->getDoctrineManager();
+            if ($em != null) {
+                // FOS\UserBundle\Model\UserManager
+                // FOS\UserBundle\Doctrine\UserManager
+                $userManager = $this->get('fos_user.user_manager');
+                if ($userManager != null) {
+                    try {
+                        $user = $userManager->findUserBy(array('id' => $this->idUser));
+                    } catch (\Throwable $t) {
+                        $user = null;
+                    }
+                    if (!$user) {
+                        // el usuario no existe por lo tanto lo creo. Deberia ver el tema de las tenencias
+                        // no tengo la oportunidad de probarlo
+                        $user = $userManager->createUser();
+                        $cargo = false;
+                        try {
+                            $em = $this->getDoctrineManager();
+                            $userDB = $em->getRepository("BaseUserBundle:User")->findOneBy(array('id' => $this->idUser));
+                            if ($userDB) {
+                                $cargo = true;
+                                $user->setEmail($userDB->email);
+                                $user->Id = $idUser;
+                                $user->setUsername($userDB->username);
+                                $user->setPlainPassword($userDB->plainPassword);
+                                $user->setEnabled(true);
+                                $user->setRoles($userDB->getRoles());
+                                // este comando ademas se setear los datos, los persiste en la base de datos.
+                                $userManager->updateUser($user);
+                            }
+                        } catch (\Throwable $t) {
+                        }
+                        if (!$cargo) {
+                            // no se cargo el usuario por algun error. Lo hago manual.
+                            $user->setEmail("pepe@pepe.com");
+                            $user->Id = $idUser;
+                            $user->setUsername('admin');
+                            $user->setPlainPassword('adminpass');
+                            $user->setEnabled(true);
+                            $user->setRoles(array("ROLE_USER"));
+                            $userManager->updateCanonicalFields($user);
+                            $userManager->updatePassword($user);
+                        }
+                    }
+                    // contiene el nombre de firewall a utilizar
+                    $firewall = 'main';
+                    // busco el token en el security
+                    $tokenStorage = $this->get('security.token_storage');
+                    if ($tokenStorage != null) {
+                        $token = null;
+                        if (!$tokenStorage->getToken()) {
+                            // no tengo el token, entonces lo creo
+                            $token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_SUPER_ADMIN'));
+                        } else {
+                            // utilizo el token que yo esta creado
+                            $token = $tokenStorage->getToken();
+                        }
+                        // seteo en la session el firewall que voy a utilizar y el token
+                        $session->set('_security_' . $firewall, serialize($token));
+                        $session->save();
+                        // creo una cookie con los datos de la session.
+                        $cookie = new Cookie($session->getName(), $session->getId());
+                        $this->getClient()->getCookieJar()->set($cookie);
+                        // seteo el token en el security.token_storage
+                        $tokenStorage->setToken($token);
+                    } else {
+                        throw new \ErrorException("Error al obtener el token storage.");
+                    }
+                } else {
+                    throw new \ErrorException("Error al obtener el fos user manager.");
+                }
+            } else {
+                throw new \ErrorException("Error al obtener doctrine.");
+            }
+        } else {
+            throw new \ErrorException("Error al obtener la session.");
+        }
+    }
+
+    /**
+     * Crea las tenencias.
+     * @param int $quantity Contiene la cantidad de tenencias a crear por defecto.
+     * @return array Retorna una matriz con las tenencias a crear.
+     * @throws \Exception Lanza un excepcion en caso de no poder crear las tenencias.
+     */
+    protected function generateTenancies($quantity = 0)
+    {
+        if ($quantity <= 0) {
+            throw new \Exception("No se pasaron los argumentos de forma correcta.");
+        } else {
+            $resp = array();
+            for ($i = 0; $i < $quantity; $i++) {
+                if ($i == 1) {
+                    $resp[$i] = array('id' => $i, 'name' => 'Tenencia Base');
+                } else {
+                    $resp[$i] = array('id' => $i, 'name' => 'Tenencia ' . $i);
+                }
+            }
+            return $resp;
+        }
+    }
+
+    /**
+     * Cambia los datos para realizar una modificacion
+     * @param array $original Contiene los datos originales.
+     * @param array $newData Contiene los nuevos datos a setear.
+     * @return array|string Retorna el array con los datos o el valor de la key pasada como parametro.
+     * @throws \Exception Lanza un excepcion en caso de no encontrar la key.
+     */
+    protected function obtainDataChange($original, $newData)
+    {
+        foreach ($newData as $k => $v) {
+            $original[$k] = $v;
+        }
+        return $original;
+    }
+
+    /**
+     * Genera el filtro de busqueda filters
+     * @param array $data Contiene los datos a buscar de la forma clave -> valor.
+     * @param bool $qbcriteria Me dice si utiliza qb-criteria.
+     * @return string Retorna el string generado.
+     */
+    protected function generateFilters($data, $qbcriteria = true)
+    {
+        $resp = '?';
+        if ($qbcriteria) {
+            $resp .= 'filters[qb-criteria]';
+        }
+        if ($data != null && count($data) > 0) {
+            foreach ($data as $k => $v) {
+                $resp .= '&filters[' . $k . ']=' . $v;
+            }
+        }
+        return $resp;
+    }
+
+    /**
+     * Funcion que busca el valor de una propiedad dentro del response.
+     * @param Response $response Contiene el response.
+     * @param string $property Contiene el nombre de la propiedad.
+     * @param string $object Contiene el nombre del objeto del cual voy a obtener la propiedad.
+     * @return null|mixed Retorna el valor de la propiedad.
+     */
+    protected function getProperty(Response $response, $property, $object = null)
+    {
+        $resp = json_decode($response->getContent(), true);
+        if (count($resp) > 0) {
+            if ($object != null) {
+                // busco el objecto
+                foreach ($resp as $k => $v) {
+                    if ($k == $object) {
+                        $resp = $v;
+                        break;
+                    }
+                }
+            }
+            foreach ($resp as $v) {
+                try {
+                    if (isset($v[$property])) {
+                        return $v[$property];
+                    }
+                } catch (\Throwable $t) {
+                }
+            }
+            return null;
+        } else {
+            if (isset($resp[$property])) {
+                return $resp[$property];
+            } else {
+                return null;
+            }
+        }
+    }
+
+    /**
+     * Funcion que inicializa por defecto las variables.
+     * Crea el client para el request.
+     * Hace el fake del login.
+     * Crea 1 tenencia por defecto (TENENCIA BASE = 1).
+     */
+    protected function initDefault()
+    {
+        // creo un nuevo cliente para consultar. Lo tengo que crear para cada consulta.
+        $this->getClient(true);
+        // hago fake del login
+        $this->FakeLogin();
+        // creo el servicio de tenencias
+        $this->fakeTenancyService();
+    }
+}