What is the difference in setBrowserUrl() and url() in Selenium 2 web driver for phpunit? - selenium

In many examples, I have seen calls made to both webdriver->setBrowserURL(url) and webdriver->url(url). Why would I want to use one instead of the other. One such example shows using both in the same manner (taken from the phpunit manual):
<?php
class WebTest extends PHPUnit_Extensions_Selenium2TestCase
{
protected function setUp()
{
$this->setBrowser('firefox');
$this->setBrowserUrl('http://www.example.com/');
}
public function testTitle()
{
$this->url('http://www.example.com/');
$this->assertEquals('Example WWW Page', $this->title());
}
}
?>
Why would setBrowserUrl() be called once in setup -- and then url() be called with the identical url in the test case itself?
In other examples, I've seen url() called with just a path for the url. What is the proper usage here? I can find almost no documentation on the use of url().

setBrowserUrl() sets a base url, allowing you to use relative paths in your tests.
The example from the phpunit manual is kind of confusing - I believe setBrowserUrl() is being used during setup simply because it'll throw an error without it:
public function start()
{
if ($this->browserUrl == NULL) {
throw new PHPUnit_Framework_Exception(
'setBrowserUrl() needs to be called before start().'
);
}
$this->url will use this base if a relative path is given.

Related

How to write a PHPUnit test for a SOAP server?

UPD. Sorry, guys.
I have an application that acts as a SOAP server, how do I write a PHPUnit test to test it?
SOAP extension is reading data from PHP input stream. You just provide your own data there and create some integration/unit tests for your API.
Take a look at the signature of SoapServer::handle() method. It takes as an argument a string which is a request itself. This parameter is optional and if you don't pass anything in, PHP will just read the data itself. But you can simply override it.
I used streams to do it. First you wrap the SoapServer with your own class like this:
class MyServer
{
/** \SoapServer */
private $soapServer;
public function __construct(\SoapServer $soapServer)
{
$this->soapServer = $soapServer;
}
public function handle(Psr\Http\Message\StreamInterface $inputStream): void
{
$this->soapServer->handle($inputStream->getContent());
}
}
Now you are ready to mock the request.
In your test you can do:
class MyTest extends TestCase
{
public function testMyRequest(): void
{
$mySoapServer = $this->createMySoapServer();
$request = $this->createRequest();
$mySoapServer->handle($request);
}
private function createRequest(): StreamInterface
{
$requestString = '<soap:Envelope></soap:Envelope>';
$fh = fopen('php://temp', 'rw');
fwrite($fh, $requestString);
fseek($fh, SEEK_SET);
return new Psr\Http\Message\StreamInterface\Stream($fh);
}
private function createMySoapServer(): MyServer
{
return new MyServer(new \SoapServer());
}
}
One thing to keep in mind - this test will generate output. You may want to test this output or ignore it. Depends on your use case.
Another side note. What you are asking for has really nothing to do with PHPUnit. It just a matter of designing your SOAP server correctly.
If you are wondering how to set up the stream when you have a live request, this is really simple:
$server->handle(new Psr\Http\Message\StreamInterface\Stream(fopen('php://input', 'r+')));

How to create unit test for the function "beforeControllerAction" extended from yii framework

I need some idea, to create unit test for the action 'beforeControllerAction', which is extended from yii framework.
beforeControllerAction is parent method from any 'mycontroller' app controller, coming from framework core. You don't need to test specific core framework code (is already tested). You need to test your own code.
One way to test your controller is to extend/inherit your own 'mycontroller' controller first and build a test for it. Taken from this excellent article:
Create your unit test class under the protected/tests/unit
folder and name it the same as your class name you want to test,
adding a Test word after it.
In my case, I will create a file named ApiControllerTest.php that
contains all tests for ApiController.php class.
<?php
// You can use Yii import or PHP require_once to refer your original file
Yii::import('application.controllers.ApiController');
class ApiControllerTest extends ApiController
{
}
Open your ApiControllerTest.php unit test class in step #1
above and make it something similar like this (based on your
requirement and structure):
class ApiControllerTest extends CTestCase
{
public function setUp()
{
$this->api = new ApiController(rand());
}
public function tearDown()
{
unset($this->api);
}
}
Let’s try to test one single method in my ApiController.php, that is
formatResponseHeader. This is what it is doing.
public function formatResponseHeader($code)
{
if (!array_key_exists($code, $this->response_code))
{
$code = '400';
}
return 'HTTP/1.1 ' . $code . ' ' . $this->response_code[$code];
}
Now, to test this method, I’ll open ApiControllerTest.php and add this
code below after setUp() and before tearDown() methods:
public function testFormatResponseHeader()
{
$this->assertEquals('HTTP/1.1 400 Bad Request',$this->api->formatResponseHeader('400'));
$this->assertEquals('HTTP/1.1 200 OK',$this->api->formatResponseHeader('200'));
$this->assertEquals('HTTP/1.1 400 Bad Request',$this->api->formatResponseHeader('500'));
$this->assertNotEquals('HTTP/1.1 304 Not Modified',$this->api->formatResponseHeader('204'));
}
Save the change in ApiControllerTest.php and then try to run this in
protected/tests directory:
phpunit .

Understanding cakephp3 error handling

I want to create a maintenance Page for my cake website by checking a Database Table for a maintenance flag using a sub-function of my AppController "initilize()" method. If the flag is set, i throw my custom MaintenanceException(Currently containing nothing special):
class MaintenanceException extends Exception{
}
To handle it, I implemented a custom App Exception Renderer:
class AppExceptionRenderer extends ExceptionRenderer {
public function maintenance($error)
{
return "MAINTENANCE";
}
}
I am able to see this maintenance Text on my website if I set my DB flag to true, but I could not find any information in cake's error handling documentation (http://book.cakephp.org/3.0/en/development/errors.html) on how I can actually tell the Exception renderer to render view "maintenance" with Template "infopage".
Can I even us that function using the ExceptionRenderer without a custom error controller? And If not, how should a proper ErrorController implementation look like? I already tried this:
class AppExceptionRenderer extends ExceptionRenderer {
protected function _getController(){
return new ErrorController();
}
public function maintenance($error)
{
return $this->_getController()->maintenanceAction();
}
}
together with:
class ErrorController extends Controller {
public function __construct($request = null, $response = null) {
parent::__construct($request, $response);
if (count(Router::extensions()) &&
!isset($this->RequestHandler)
) {
$this->loadComponent('RequestHandler');
}
$eventManager = $this->eventManager();
if (isset($this->Auth)) {
$eventManager->detach($this->Auth);
}
if (isset($this->Security)) {
$eventManager->detach($this->Security);
}
$this->viewPath = 'Error';
}
public function maintenanceAction(){
return $this->render('maintenance','infopage');
}
}
But this only throws NullPointerExceptions and a fatal error. I am really dissapointed by the cake manual as well, because the code examples there are nowhere close to give me an impression of how anything could be done and what functionality I actually have.
Because I had some more time today, I spent an hour digging into the cake Source and found a solution that works well for me (and is propably the way it should be done, altough the cake documentation does not really give a hint):
Step 1: Override the _template(...)-Method of the ExceptionRenderer in your own class. In my case, I copied the Method of the parent and added the following Code at the beginning of the method:
$isMaintenanceException = $exception instanceof MaintenanceException;
if($isMaintenanceException){
$template = 'maintenance';
return $this->template = $template;
}
This tells our Renderer, that the error Template called "maintentance"(which should be located in Folder: /Error) is the Error Page content it should render.
Step 2: The only thing we have to do now (And its is kinda hacky in my opinion, but proposed by the cake documentation in this exact way) is to set the layout param in our template to the name of the base layout we want to render with. So just add the following code on top of your error template:
$this->layout = "infopage";
The error controller I created is actually not even needed with this approach, and I still don't know how the cake error controller actually works. maybe I will dig into this if I have more time, but for the moment.

Geb page url method from ConfigSlurper

I am trying to store the urls I need in a config file that gets pulled using ConfigSlurper. I think this may not work but not sure. Thoughts?
You are probably looking for functionality provided by baseUrl configuration. When using to MyPage the url which is used by the browser is determined by combining basUrl configuration and the url property of your page class.
If you wanted a slightly cleaner method of doing this, you could implement a base page such as the one below - inner class for brevity and to avoid calling protected methods directly - (we have apps on 26 different subdomains!):
package page.admin
import geb.Configuration
import geb.Page
class AdminPage extends Page {
class WrappedConfig extends Configuration {
WrappedConfig(ConfigObject rawConfig) {
super(rawConfig)
}
String getAdminBaseUrl() {
return readValue('adminUrl', '<invalid-url>')
}
}
String getPageUrl() {
WrappedConfig config = new WrappedConfig(browser.config.rawConfig)
return config.adminBaseUrl + this.class.url
}
}
Your config might look something like this:
baseUrl = 'http://base-app.example.net'
adminUrl = 'http://admin-app.example.com'
This way, you can still use normal geb syntax:
given:
to PageWhichExtendsAdminPage, 'your-path', key1: 'value1
to generate the url http://admin-app.example.com/your-path/?key1=value1
I run geb on different locales so I encountered the same issue. I usually load the different urls out of a config file with locale.getCountry() as parameter for the environment.
In the running class I replace the baseUrl with the loaded entry with the ConfigSlurper. The advantage is that I can handle multiple locales and localhost environments. Testing locally vs testing the staging environment.
I have one main spock file containing the whole regression testing and a inheriting spock class for every country. The inheriting spock files doesn't contain much except the country/language encoding in the class name.
The config file:
environment{
CA{
url="ca.somewhere.com"
validZipCode=...
...
}
...
}
The main class:
class MainRegression extends GebReportingSpec{
#Shared Locale locale
def setupSpec(){
...
locale = ParameterReader.getLocale(this.class.name)
...
}
def "testing the website"(){
when: "entering the main url"
go URLService.getBaseUrl(locale)
...
}
The inheriting class:
#Stepwise
class CaEnRegressionSpec{} // Canada with english language
A good way to handle the at-verification with different languages / locales:
http://ldaley.com/post/1013531080/painless-page-identification-with-geb-grails

How to access methods from a class based wordpress plugin?

I have a plugin which registers a post type, taxonomy and handles some business logic.
I went ahead and made my perfectly working plugin OO based and now it only works some of the time.
Its set-up like the following:
class Fruit {
public function __construct() {
add_action('init', array(&$this, 'init'));
}
public function init() {
$this->the_apple();
}
public function the_apple() {
return print $apple = 'my apple';
}
}
$fruit = new Fruit();
Then in taxonomy.php, withing the loop the following works:
$fruit->the_apple();
But once I use get_template_part with loop.php, this no longer works
$fruit->the_apple();
I get the following notice:
Notice: Undefined variable the_apple();
My fix was to use:
global $fruit;
and now it works all the time, just fyi about globals they get a bad rep. and there's namespacing issues, along with dumping everything into globals vs. using a registry.
In production i would never use the name $fruit, instead i would call it,
global $skylar_fruit;