Run a PHPUnit Selenium test case programatically ("within PHP") - php

How can I run a test "within PHP" instead of using the 'phpunit' command? Example:
<?php
require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
class MySeleniumTest extends PHPUnit_Extensions_SeleniumTestCase {
protected function setUp() {
$this->setBrowser("*firefox");
$this->setBrowserUrl("http://example.com/");
}
public function testMyTestCase() {
$this->open("/");
$this->click("//a[#href='/contact/']");
}
}
$test = new MySeleniumTest();
//I want to run the test and get information about the results so I can store them in the database, send an email etc.
?>
Or do I have to write the test to a file, invoke phpunit via system()/exec() and parse the output? :(

Just use the Driver that's included.
require_once 'PHPUnit/Extensions/SeleniumTestCase/Driver.php';
//You may need to load a few other libraries. Try it.
Then you need to set it up like SeleniumTestCase does:
$driver = new PHPUnit_Extensions_SeleniumTestCase_Driver;
$driver->setName($browser['name']);
$driver->setBrowser($browser['browser']);
$driver->setHost($browser['host']);
$driver->setPort($browser['port']);
$driver->setTimeout($browser['timeout']);
$driver->setHttpTimeout($browser['httpTimeout']);
Then just:
$driver->open('/');
$driver->click("//a[#href='/contact/']");

Here's an example from the phpunit docs:
<?php
require_once 'PHPUnit/Framework.php';
require_once 'ArrayTest.php';
require_once 'SimpleTestListener.php';
// Create a test suite that contains the tests
// from the ArrayTest class.
$suite = new PHPUnit_Framework_TestSuite('ArrayTest');
// Create a test result and attach a SimpleTestListener
// object as an observer to it.
$result = new PHPUnit_Framework_TestResult;
$result->addListener(new SimpleTestListener);
// Run the tests.
$suite->run($result);
?>
The code for SimpleTestListener is on the same page.

Related

PHP - Call class function from another class

I am developing an app where I need to log the proccess.
So I was loggin from main.php and now I need to log from another class (class_TestingLog.php)
Next code is how I am trying. Could you tell me what I am doing wrong?
Thank you in advance.
main.php
[...]
#Logging class
include_once("./classes/class_log.php");
$Class_Log = New Class_Log();
#TestingLog Class
include_once("./classes/class_testingLog.php");
$Class_TestingLog = New Class_TestingLog();
[...]
$Class_Log->FreeLog("Test log");
$Class_TestingLog->AnyFuncion();`
[...]
class_log.php
[...]
public function FreeLog($text)
{
// echo $text . "\n"; #mistake
$this->outputText .= text; #correct one
}
[...]
class_testingLog.php
private $Class_Log = '';
[...]
public function __construct()
{
#Requires
require_once("./classes/class_log.php");
$this->Class_Log = New Class_Log();
}
public function AnyFuncion()
{
var_dump($this); #From real file
$this->Class_Log->FreeLog("Test log from another classs");
}
[...]
Browser output
Test log
Browser output expected
Test log
Test log from another classs
===========================================================================
EDIT
I made an error copying FreeLog();
It stores the parameter string value into a private variable instead echo the variable.
You require_once statement inside __construct for Class_TestingLog is invalid and unnecessary. As both files are in the same directory it should be "class_log.php" not "./classes/class_log.php". There is no need for it anyway, as when you include them both in main.php it is loaded already. So try it without the require_once.
EDIT: As discussed in chat do it like this:
in main.php:
$Class_TestingLog = New Class_TestingLog($Class_Log);
in class_testingLog.php:
public function __construct($ClassLog)
{
$this->Class_Log = $ClassLog;
}
This will use the same instance inside the Class_TestingLog class as on the main.php.

PHPT avoid constructor and target functions directly

I have the following class:
class Validator {
public function __construct($file){
$errors = $this->errors($file_array[CSV]['errors']);
}
public function errors_func($errors){
if($errors != 0){
throw new Exception('Error Uploading');
}
}
}
I'm attempting to target the errors_func() function directly through my test script without the need to first invoke the constructor. The PHPT test script can be seen below:
--TEST--
check_mime() function - A basic test to see if check mime works. :)
--FILE--
<?php
require_once('my/path');
$valid = new Validation;
$re = $valid->errors_func('1);
var_dump($re);
?>
--EXPECT--
bool(true)
As you would expect though the test script fails becuase a parameter is expected when the object of the class is created. Is there a way to create an object of the Validation class without needing to pass an argument to the class __constructer?
I've found a solution to this by using ReflectionClass. The new test script would look like this:
--TEST--
check_mime() function - A basic test to see if check mime works. :)
--FILE--
<?php
require_once('my/path');
$valid = new ReflectionClass('Validator');
$valid_direct = $valid->newInstanceWithoutConstructor();
$re = $valid_direct->errors_func('1);
var_dump($re);
?>
--EXPECT--
bool(true)

Integrating Whatsapp API in symfony

I am trying to integrate the WHAnonymous API in my symfony project.
I have included it in my project using composer install and it is now in my vendor folder.
But I am not understanding how to import it into my project!
This is my manager class.
<?php
namespace AppBundle\Managers;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class WhatsAppManager
{
private $test;
/**
* Constructor
*/
public function __construct()
{
$this->test =1;
}
public function sendMessage()
{
$username = ""; // Your number with country code, ie: 34123456789
$nickname = ""; // Your nickname, it will appear in push notifications
$debug = true; // Shows debug log
// Create a instance of WhastPort.
$w = new WhatsProt($username, $nickname, $debug);
var_dump("In send message method");
}
}
?>
I have used
require_once 'whatsprot.class.php';
and
require_once 'Whatsapp\Bundle\Chat-api\src\whatsprot.class.php';
and
use Whatsapp\Bundle\Chat-api\Whatsprot
But it is just not working.
Please tell me the right way to do it!
And is there something i should do when i am using 3rd party vendors in symfony.
I did look into the documentation of the WHanonymous but i found only snippets of code to use it and not the way to import it.
Git repo for WHAnonymous : https://github.com/WHAnonymous
The class doesn't have a namespace, but is correctly loaded by the autoload system created my composer. So you can reference to the class without any include or require directive but simply with a \ as example:
// Create a instance of WhastPort.
$w = new \WhatsProt($username, $nickname, $debug);
Hope this help

ZF2 - Job queue to create a PDF file using SlmQueueBeanstalkd and DOMPDFModule

I'm trying to run a job queue to create a PDF file using SlmQueueBeanstalkd and DOMPDFModule in ZF".
Here's what I'm doing in my controller:
public function reporteAction()
{
$job = new TareaReporte();
$queueManager = $this->serviceLocator->get('SlmQueue\Queue\QueuePluginManager');
$queue = $queueManager->get('myQueue');
$queue->push($job);
...
}
This is the job:
namespace Application\Job;
use SlmQueue\Job\AbstractJob;
use SlmQueue\Queue\QueueAwareInterface;
use SlmQueue\Queue\QueueInterface;
use DOMPDFModule\View\Model\PdfModel;
class TareaReporte extends AbstractJob implements QueueAwareInterface
{
protected $queue;
public function getQueue()
{
return $this->queue;
}
public function setQueue(QueueInterface $queue)
{
$this->queue = $queue;
}
public function execute()
{
$sm = $this->getQueue()->getJobPluginManager()->getServiceLocator();
$empresaTable = $sm->get('Application\Model\EmpresaTable');
$registros = $empresaTable->listadoCompleto();
$model = new PdfModel(array('registros' => $registros));
$model->setOption('paperSize', 'letter');
$model->setOption('paperOrientation', 'portrait');
$model->setTemplate('empresa/reporte-pdf');
$output = $sm->get('viewPdfrenderer')->render($model);
$filename = "/path/to/pdf/file.pdf";
file_put_contents($filename, $output);
}
}
The first time you run it, the file is created and the work is successful, however, if you run a second time, the task is buried and the file is not created.
It seems that stays in an endless cycle when trying to render the model a second time.
I've had a similar issue and it turned out it was because of the way ZendPdf\PdfDocument reuses it's object factory. Are you using ZendPdf\PdfDocument?
You might need to correctly close factory.
class MyDocument extends PdfDocument
{
public function __destruct()
{
$this->_objFactory->close();
}
}
Try to add this or something similar to the PdfDocument class...
update : it seem you are not using PdfDocument, however I suspect this is the issue is the same. Are you able to regenerate a second PDF in a normal http request? It is your job to make sure the environment is equal on each run.
If you are unable to overcome this problem a short-term quick solution would be to set max_runs configuration for SlmQueue to 1. That way the worker is stopped after each job and this reset to a vanilla state...

Register class methods with nusoap

I've a php class and i want to use it with Nusoap. Can I register the class method's that already exists inside the nusoap with the register command?
Sample :
Here we register a function that we defined inside this script. But if we've a class that we maybe develop months ago and we want to use it as a webservice using the WSDL. Is there a way to register the methods of that class so that Nusoap creates a WSDL of it's stucture (methods inside)?
require_once("nuSOAP/lib/nusoap.php");
$server = new soap_server();
$namespace = "http://localhost/nusoapSCRIPT/index.php";
$server->wsdl->schemaTargetNamespace = $namespace;
$server->configureWSDL("SAMPLE");
$server->register('HelloWorld');
function HelloWorld()
{
return "Hello, World!";
}
Well here's how i solve this... maybe someone can try an approach in another way.
[File : index.php]
require_once "nuSOAP/lib/nusoap.php";
require_once "myClass.class.inc.php";
$namespace = "http://localhost/html/nusoap/index.php";
// create a new soap server
$server = new soap_server();
// configure our WSDL
$server->configureWSDL("Class Example");
// set our namespace
$server->wsdl->schemaTargetNamespace = $namespace;
// register the class method and the params of the method
$server->register("myClass.ShowString"
,array('name'=>'xsd:string')
,array('return'=>'xsd:string')
,$namespace,false
,'rpc'
,'encoded'
,'Sample of embedded classes...'
);
//
// Get our posted data if the service is being consumed
// otherwise leave this data blank.
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA'])
? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
// pass our posted data (or nothing) to the soap service
$server->service($POST_DATA);
exit();
and the class code.
[File 'myClass.class.inc.php']
class myClass{
public function __construct(){
}
public function ShowString($mens){
return "\n##Remote Class :".__CLASS__."\n##Remote Method : ".__METHOD__."\n## mSG :{$mens}";
}
}
I also create a soap client in c# and it consumes correctly the soap service.
Hope this help!
You can call the method using getProxy()
$proxy->className__methodname

Categories