Test protected methods of ZF controllers with PHPUnit - zend-framework

I want to test a protected method which is inside a controller:
class AuthenticateController extends Zend_Controller_Action
{
protected function getAuthAdapter(){}
}
My test (following this post) look like this:
public function testGetAuthAdapterShouldReturnZendAuthAdapterDbTable()
{
require_once(APPLICATION_PATH.'/controllers/AuthenticateController.php');
$method = new Zend_Reflection_Method('AuthenticateController',
'getAuthAdapter');
$class = new AuthenticateController();
$result = $method->invoke($class);
// assert result value
$this->assertInstanceOf('Zend_Auth_Adapter_DbTable', $result);
}
When I execute the test, I got this runtime exception
RuntimeException: Fatal error: Call to a member function getModuleName() on a non-object in /Users/padawan_rodrigo/Documents/workspace/ZendFramework-1.11.5/library/Zend/Controller/Action/Helper/ViewRenderer.php on line 226
Call Stack:
0.0030 396924 1. {main}() -:0
0.0755 4593044 2. __phpunit_run_isolated_test() -:207
0.0771 4718524 3. PHPUnit_Framework_TestCase->run() -:22
0.0785 4798460 4. PHPUnit_Framework_TestResult->run() /usr/local/pear/share/pear/PHPUnit/Framework/TestCase.php:576
0.3565 4827948 5. PHPUnit_Framework_TestCase->runBare() /usr/local/pear/share/pear/PHPUnit/Framework/TestResult.php:666
0.6696 10508956 6. PHPUnit_Framework_TestCase->runTest() /usr/local/pear/share/pear/PHPUnit/Framework/TestCase.php:628
0.6697 10509780 7. ReflectionMethod->invokeArgs() /usr/local/pear/share/pear/PHPUnit/Framework/TestCase.php:738
0.6697 10509796 8. AuthenticateControllerTest->testGetAuthAdapterShouldReturnZendAuthAdapterDbTable() /project/code/tests/application/controllers/AuthenticateControllerTest.php:0
0.6794 10753940 9. Zend_Controller_Action->__construct() /project/code/tests/application/controllers/AuthenticateControllerTest.php:172
I also tried to mock the class with same results. Any ideas?
Thanks

You need to pass in a request and response to the controller's constructor.
$class = new AuthenticateController(
new Zend_Controller_Request_HttpTestCase(),
new Zend_Controller_Response_HttpTestCase()
);

Related

SuiteCRM v7.10.29 Custom API v4.1

I am creating a custom API for SuiteCRM. When I attempt to run the new API from {CRM Home}/custom/service/v4_1_custom I receive an 'HTTP ERROR 500'. There are not errors in the error_log file or the SuiteCRM.log file.
I have followed the method in the following two url's
https://fayebsg.com/2013/05/extending-the-sugarcrm-api-updating-dropdowns/
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_10.0/Integration/Web_Services/Legacy_API/Extending_Web_Services/
registry.php
<?php
require_once('service/v4_1/registry.php');
class registry_v4_1_custom extends registry_v4_1
{
protected function registerFunction()
{
parent::registerFunction();
$this->serviceClass->registerFunction('test', array(), array());
}
}
SugarWebServicesImplv4_1_custom.php
<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('service/v4_1/SugarWebServiceImplv4_1.php');
class SugarWebServiceImplv4_1_custom extends SugarWebServiceImplv4_1
{
/**
* #return string
*/
public function test()
{
LoggerManager::getLogger()->warn('SugerWebServiceImplv4_1_custom test()');
return ("Test Worked");
} // test
} // SugarWebServiceImplv4_1_custom
I found the answer to this issue.
In the file {SuiteCRM}/include/entryPoint.php there are many files that are included thru require_once. In this list of require_once files, there were 4 files that were set as require not require_once. These were classes and therefore could not be included a second time. I changed these to require_once and the HTTP Error 500 went away and the custom APIs started working.

Use of undefined constant APPATH - assumed 'APPATH'

I encounter this Error and i can't Fix it, Someone please help me T_T
A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant APPATH - assumed 'APPATH'
Filename: controllers/Pages.php
Line Number: 4
Backtrace:
File: C:\xampp\htdocs\Project\application\controllers\Pages.php
Line: 4
Function: _error_handler
File: C:\xampp\htdocs\Project\index.php
Line: 315
Function: require_once
and this is my Code
<?php
class Pages extends CI_Controller{
public function view($page = 'home'){
if(!file_exists(APPATH.'views/pages'.$page.'php')){
show_404();
}
$data['title'] = ucfirst($page);
$this->load->view('tenplates/Header');
$this->load->view('pages/'.$page, $data);
$this->load->view('tenplates/Footer');
}
}
When you get a message like...
A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant APPATH - assumed 'APPATH'
Filename: controllers/Pages.php
....
It means the constant, in this case APPATH is not defined. So could be a typo?
If you check out the user guide it states that it is actually APPPATH. A good way to remember it is imagining it as APPlication PATH.
3 "P"'s - not two.
So your code would then become...
<?php
class Pages extends CI_Controller{
public function view($page = 'home'){
if(!file_exists(APPPATH.'views/pages'.$page.'php')){
show_404();
}
$data['title'] = ucfirst($page);
$this->load->view('tenplates/Header');
$this->load->view('pages/'.$page, $data);
$this->load->view('tenplates/Footer');
}
}

How to fix error "Cannot dispatch middleware Application\Middleware\IndexMiddleware"?

I've set up a Zend Application as normal, except in my case the difference is that I set it up over an existing legacy web application.
I still want to call my existing legacy application over the ZF3 app. It was suggested I can do so using Middleware. I went over https://docs.zendframework.com/zend-mvc/middleware/ and set up my routing as described there.
However, when I run the application, I am greeted by this:
Cannot dispatch middleware Application\Middleware\IndexMiddleware
#0 zend-mvc\src\MiddlewareListener.php(146):
Zend\Mvc\Exception\InvalidMiddlewareException::fromMiddlewareName('Application\\Mid...')
Here is where the exception happens:
https://github.com/zendframework/zend-mvc/blob/release-3.1.0/src/MiddlewareListener.php#L146
Just to note:
$middlewareToBePiped; //'Application\Middleware\IndexMiddleware'
is_string($middlewareToBePiped); // true
$serviceLocator->has($middlewareToBePiped);//false
$middlewareToBePiped instanceof MiddlewareInterface; //false
is_callable($middlewareToBePiped);//false
My class is:
namespace Application\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Zend\Http\Response;
class IndexMiddleware implements MiddlewareInterface
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
{}
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{}
}
I am thinking that my issue is that my IndexMiddleware class is not being found in ServiceLocator... (line 142 of linked API). How do I get it in there?
I put this into my application.config.php file:
'service_manager' => [
'invokables' => array(
'middleware' => IndexMiddleware::class
)
]
onto the next error it is.. (Last middleware executed did not return a response.)
but looks like it has executed)

send email through cakephp shell Fatal error: Class 'CakeLog' not found

i am trying to send email using cakephp shell. Following is my code:
<?php
error_reporting(0);
class EmailShell extends AppShell {
public $uses = array('Email');
public function show() {
$Email = new CakeEmail();
$Email->from('abc#gmail.com');
$Email->to('xyz#gmail.com');
$Email->subject('Forgot Password');
$Email->send();
}
}
?>
when i run this in shell i get the following error:
Fatal error: Class 'CakeLog' not found in /mnt/public_html/music_directory/web/cakephp/app/Config/bootstrap.php on line 172
where am i getting wrong? how do i solve it?
If you actually use the CakeLog class that early (in your own bootstrap)
you need to assert it is loaded.
You forgot the following statement prior to using the class:
App::uses('CakeLog', 'Log');

Unit Testing with PHPUnit & Doctrine2: Autoloading Failed

I am getting this error
D:\Projects\Tickle\tests>phpunit
PHPUnit 3.5.5 by Sebastian Bergmann.
..........ok1
Fatal error: Doctrine\Common\ClassLoader::loadClass(): Failed opening required 'D:\Projects\Tickle\Application\Models\Ap
plication\Models\User.php' (include_path='D:\Projects\Tickle\application/../library;D:\Projects\Tickle\application;D:\Pr
ojects\Tickle\library;D:\ResourceLibrary\Frameworks\PHPFrameworks;C:\Program Files (x86)\PHP\pear;.;c:\php\includes') in
D:\ResourceLibrary\Frameworks\PHPFrameworks\Doctrine\Common\ClassLoader.php on line 148
Notice its repetition "D:\Projects\Tickle\Application\Models\Application\Models\User.php" of Application\Models. I narrowed it down to 1 function of my unit tests with the help of some echo statements
protected function isAllowed($userId, $taskId, $privilege) {
$user = $this->em->find('Application\Models\User', $userId);
echo 'ok1'; // this gets printed
$task = $this->em->find('Application\Models\Task', $taskId); // this seem to be the cause of the problem
echo 'ok2'; // this doesn't get printed
return $this->acl->isAllowed($user, $task, $privilege);
}
The full class http://pastebin.com/rJungFvP
So I tried looking of something in the Tasks class that uses User ... the only thing that might use the User class are
/**
* #ManyToOne(targetEntity="User", inversedBy="ownedTasks")
*/
protected $owner;
/**
* #ManyToOne(targetEntity="User", inversedBy="assignedTasks")
*/
protected $assigned;
apart from that, I don't see use of any Users. full class http://pastebin.com/wDPXUPSV.
What did I do wrong?
The problem was actually found in the TodoList class ... I had something like
public function setProject(Application\Models\Project $project) {
...
}
when I should be using something like
public function setProject(Project $project) {
$this->project = $project;
}
instead