Skip to content
Snippets Groups Projects
  • Laurent's avatar
    Merge branch 'hotline-master' · 387d9fa7
    Laurent authored
    # Conflicts:
    #	library/Class/MoteurRecherche.php
    #	library/Class/WebService/Vignette.php
    #	tests/application/modules/opac/controllers/RechercheControllerTest.php
    #	tests/library/Class/NoticeTest.php
    387d9fa7
AbstractControllerTestCase.php 9.94 KiB
<?php
/**
 * Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
 *
 * BOKEH 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.
 *
 * There are special exceptions to the terms and conditions of the AGPL as it
 * is applied to this software (see README file).
 *
 * BOKEH 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 BOKEH; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
 */
abstract class AbstractControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase {
  use Storm_Test_THelpers;
  protected
    $_registry_sql,
    $_storm_default_to_volatile = false;

  //permet d'authentifier sur la partie admin avant test
  public $bootstrap = 'bootstrap_frontcontroller.php';

  protected function _initProfilHook($profil) {}


  protected function _initMockProfil() {
    $this->fixture('Class_Profil',
                   ['id' => 1,
                    'libelle' => 'portail']);

    $profil = $this->fixture('Class_Profil',
                             ['id' => 2,
                              'libelle' => 'PHP Unit',
                              'titre_site' => 'PHP Unit',
                              'cfg_site'  => ["largeur_site" => 1000,
                                              "nb_divisions" => 3,
                                              "menu_haut_on" => 0,
                                              "barre_nav_on" => 1,
                                              "accessibilite_on" => 0,
                                              "largeur_division1" => 250,
                                              "marge_division1" => 10,
                                              "largeur_division2" => 600,
                                              "marge_division2" => 10,
                                              "largeur_division3" => 150,
                                              "marge_division3" => 10,
                                              "ref_description" => '',
                                              "division_three_always_visible" => false,
                                              "ref_tags" => ''],
                              'skin' => 'original',
                              'ref_tags' => '',
                              'mail_site' => 'nanook@afi-sa.net',
                              'browser' => 'opac',
                              'cfg_modules' => []])->beCurrentProfil();



    $this->_initProfilHook($profil); //so subclasses can put custom values
  }


  protected function _loginHook($account) {}

  protected function _login() {
    $account = new stdClass();
    $account->username     = 'AutoTest' . time();
    $account->password     = md5( 'password' );
    $account->ID_USER      = 666;
    $account->ROLE_LEVEL   = ZendAfi_Acl_AdminControllerRoles::ADMIN_PORTAIL;
    $account->ROLE         = "admin_portail";
    $account->ID_SITE      = 1;
    $account->confirmed    = true;
    $account->enabled      = true;

    Class_Bib::getLoader()
      ->newInstanceWithId(1)
      ->setLibelle('Tombouctou');

    $this->_loginHook($account);

    $user = Class_Users::getLoader()
      ->newInstanceWithId(666)
      ->setLogin($account->username)
      ->setRoleLevel($account->ROLE_LEVEL)
      ->setIdSite($account->ID_SITE);

    ZendAfi_Auth::getInstance()->getStorage()->write($account);
  }


  public function setUp() {
    Storm_Model_Abstract::unsetLoaders();
    if($this->_storm_default_to_volatile)
      Storm_Model_Loader::defaultToVolatile();

    $this->_registry_sql = Zend_Registry::get('sql');
    if (!is_object($this->_registry_sql))
      $this->fail('SQL in registry should be an object');
    Class_ScriptLoader::resetInstance();

    $this->_initMockProfil();

    parent::setUp();

    Zend_Registry::get('locale')->setLocale('fr');
    Zend_Registry::get('translate')->setLocale('fr');

    $this->_login();

    $session = new Zend_Session_Namespace('FlashMessenger');
    $session->unsetAll();

    $admin_var_loader = Class_AdminVar::getLoader();
    $admin_var_loader
      ->newInstanceWithId('WORKFLOW')
      ->setValeur(0);

    $admin_var_loader
      ->newInstanceWithId('TEXT_REPLACEMENTS')
      ->setValeur('');

    Class_TextReplacements::reset();

    $admin_var_loader
      ->newInstanceWithId('LANGUES')
      ->setValeur(null);

    $admin_var_loader
      ->newInstanceWithId('CACHE_ACTIF')
      ->setValeur(0);

    $admin_var_loader
      ->newInstanceWithId('BIBNUM')
      ->setValeur(1);

    $admin_var_loader
      ->newInstanceWithId('OAI_SERVER')
      ->setValeur(1);

    $admin_var_loader
      ->newInstanceWithId('PACK_MOBILE')
      ->setValeur(1);

    $admin_var_loader
      ->newInstanceWithId('CNIL_CONSENT_ENABLE')
      ->setValeur(false);

    Class_AdminVar::newInstanceWithId('JS_STAT', ['valeur' => '']);
    ZendAfi_Controller_Action_Helper_TrackEvent::setDefaultWebAnalyticsClient(null);
    Storm_Cache::setDefaultZendCache(null);
    Class_WebService_AllServices::setHttpClient(null);
    Class_SessionFormationInscription::beVolatile();
  }


  public function tearDown() {
    if($this->_storm_default_to_volatile)
      Storm_Model_Loader::defaultToDb();

    Storm_Model_Abstract::unsetLoaders();
    Zend_Registry::set('sql', $this->_registry_sql);
    Class_Codification::resetInstance();
    Class_MoteurRecherche::resetInstance();
    Class_WebService_Abstract::resetHttpClient();
    Class_WebService_AllServices::setHttpClient(null);
    Class_I18n::reset();
    ZendAfi_Form_Element_Captcha::reset();
  }


  protected function _generateLoaderFor($model, $methods) {
    $loader = $this->getMock('Mock'.$model, $methods);
    Storm_Model_Abstract::setLoaderFor($model, $loader);
    return $loader;
  }


  public function postDispatch($url, $data) {
    $this->getRequest()
      ->setMethod('POST')
      ->setPost($data);

    return $this->dispatch($url, true);
  }

  /**
   * Retourne la valeur du header Location
   * @return String
   */
  function getResponseLocation() {
    $headers = $this->_response->getHeaders();
    foreach ($headers as $header)
      if ($header['name'] = 'Location')
        return $header['value'];
    return null;
  }



  public function dispatch($url = null, $throw_exceptions = false) {
    // redirector should not exit
    $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
    $redirector->setExit(false);
    // json helper should not exit
    $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
    $json->suppressExit = true;

    $request    = $this->getRequest();
    if (null !== $url) {
      $request->setRequestUri($url);
    }
    $request->setPathInfo(null);

    $this->frontController
      ->setRequest($request)
      ->setResponse($this->getResponse())
      ->throwExceptions($throw_exceptions)
      ->returnResponse(false);
    $this->frontController->dispatch();
  }


  public function assertHTML5($content=null) {
    if ($content == null)
      $content = $this->_response->getBody();

    $httpClient = (new Zend_Http_Client('http://sandbox.pergame.net/html-validator/'))
      ->setMethod(Zend_Http_Client::POST)
      ->setEncType(Zend_Http_Client::ENC_FORMDATA)
      ->setParameterPost('content', $content);
    $response = $httpClient->request()->getBody();

    $content_lines = explode("\n", $content);
    $content_with_lines = "HTML:\n";
    foreach($content_lines as $i => $line) {
      $content_with_lines .= sprintf("%4s %s\n", $i + 1, $line);
    }

    $this->assertContains('No errors found', $response, $content_with_lines);
  }


  public function assertFlashMessengerEquals($value, $message = '') {
    $session = new Zend_Session_Namespace('FlashMessenger');
    $messages = $session->__get('default');
    $this->assertEquals($messages, $value, $message);
  }


  protected function _getFlashMessengerMessages() {
    $session = new Zend_Session_Namespace('FlashMessenger');
    $messages = $session->__get('default');
    return $messages ? $messages : [];
  }


  public function assertFlashMessengerContains($value, $message = '') {
    $this->assertContains($value,
                          $this->_getFlashMessengerMessages(),
                          $message);
  }


  public function assertFlashMessengerContentContains($value, $message = '') {
    $messages = $this->_getFlashMessengerMessages();
    $messages = array_filter($messages,
                             function($data)
                             {
                               return is_array($data)
                                 && isset($data[ZendAfi_Controller_Action_Helper_FlashMessenger::NOTIFICATION]);
                             });
    foreach($messages as $message){
      if (false!==strpos($message[ZendAfi_Controller_Action_Helper_FlashMessenger::NOTIFICATION]['message'],
                         $value))
        return;
    }

    $this->fail("Flash messenger does not contains: \n".$value."\nbut:\n".implode('. ', $messages)."\n".$message);
  }


  public function assertFlashMessengerContainsPopup($url) {
    $searched = [ZendAfi_Controller_Action_Helper_FlashMessenger::POPUP => ['url' => $url]];
    $messages = $this->_getFlashMessengerMessages();
    foreach($messages as $message_value) {
      if ($message_value == $searched)
        return true;
    }

    $this->fail("Flash messenger does not contains popup with url: ".$url);
  }


  public function assertNotFlashMessengerPopup() {
    $messages = $this->_getFlashMessengerMessages();
    foreach($messages as $message_value) {
      if (isset($message_value[ZendAfi_Controller_Action_Helper_FlashMessenger::POPUP]))
        $this->fail("Flash messenger contains a popup");
    }
  }
}

?>