Thursday, October 31, 2013

Headless Selenium Server and PHPUnit on Ubuntu - Easy!

About this article

There is nothing new in this article, but I’ve made information from the Internent about this problem more concise. Generally, I’ve collected all required tips into a short solution.
With this guide you will install Xvfb to hide browsers and lunch the selenium server within its hidden virtual display.
I’m providing you a script that allows you to manage Xvfb and Selenium together. The script already can configure Xvfb the way allows you to make screenshots.
And you’ll be able to learn here the small and clear example of the PHPUnit test using the selenium server.

I have a remark for beginners: don’t be confused when I talk about the selenium server side and the web server side. I assume that your hosts with a browser and a web server are different machines. But everything should work fine when they are launched on the same machine.


Instillation

One have to install the following things on the selenium server side:
apt-get install Xvfb xfonts-base xfonts-75dpi xfonts-100dpi xfonts-cyrillic

It is required to install the following packages on the web server side:
apt-get install php-pear
sudo pear channel-discover pear.phpunit.de
sudo pear install phpunit/PHPUnit
sudo pear install phpunit/PHPUnit_Selenium

Download this package:
https://code.google.com/p/selenium/downloads/detail?name=selenium-server-2.35.0.zip&can=1&q=
Extract it to get the fallowing path existing on the selenium server side:
/usr/local/lib/selenium-2.35.0/selenium-server-standalone-2.35.0.jar
You can download a newer version of the selenium, but in this case you should consider this point further.

Let's get required configuration on the selenium side. Download this file:
selenium
And put it to the /etc/init.d directory. You’ll get the /etc/init.d/selenium script. Make root its owner and make it executable.

Download this file:
selenium.conf
And put it to the /etc/selenium directory. You’ll get /etc/selenium/selenium.conf. Make root its owner.
The last file contains configuration and has the following content:
# This is the display that will be used by Xvfb
XVFB_DISPLAY=":99"
# Specify your own path to the selenium server
SELENIUM_PATH="/usr/local/lib/selenium-2.35.0/selenium-server-standalone-2.35.0.jar"
# Specify your own path to a Firefox profile
FIREFOX_TPL="/home/igor/.mozilla/firefox/r2p6pyfi.default"
# Port you want the server to listen to
SELENIUM_PORT=4443

Create the following directory:
sudo mkdir /var/log/selenium
Now you can run and shutdown selenium service:
sudo service selenium start
sudo service selenium stop
sudo service selenium restart


PHPUnit test with Selenium

Remember: the selenium server should be started :)
You should replace {PUBLIC_HTML} with the path to the document root of your web server further.
Let’s create the file we are going to test:
{PUBLIC_HTML}/testable.php
<p><?php echo "Hi" ?></p>

Now we can create the PHPUnit config:
{PUBLIC_HTML}/phpunit.xml
<phpunit backupGlobals="true"
         backupStaticAttributes="false"
 
         cacheTokens="false"
         colors="false"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         forceCoversAnnotation="false"
         mapTestClassNameToCoveredClassName="false"
         printerClass="PHPUnit_TextUI_ResultPrinter"

         processIsolation="false"
         stopOnError="false"
         stopOnFailure="false"
         stopOnIncomplete="false"
         stopOnSkipped="false"
         testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"

         timeoutForSmallTests="1"
         timeoutForMediumTests="10"
         timeoutForLargeTests="60"
         strict="false"
         verbose="true">
    <testsuites>
        <testsuite name="All Tests">
             <!-- This is a relative path to the folder with tests: -->
            <directory suffix="Test.php">test</directory>
        </testsuite>
    </testsuites>
</phpunit>

Let’s follow to the main part of this article. This is the test itself:
{PUBLIC_HTML}/test/MyTest.php
<?php

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class MyTest extends PHPUnit_Extensions_Selenium2TestCase
{

    
    protected function setUp()
    {
        // Specify your browser here.
        $this->setBrowser('firefox');
        // Specify the url of your web server.
        $this->setBrowserUrl('http://testapache2.php-clean.flt0/');
        // Specify the hostname or the ip address of your selenium server.
        $this->setHost('phyrotab.flt0');
        $this->setPort(4443);
    }
 
    public function testTitle()
    {
        $this->url('http://testapache2.php-clean.flt0/testable.php');
        $element = $this->byTag('p');
        $this->assertEquals('Hi', $element->text());
        // {PUBLIC_HTML}/var directory should be 
        // created and has write permissions.
        // You will be able to find a screenshot after the test there:
        $fp = fopen('var/2.png','wb'); 
        fwrite($fp,$this->currentScreenshot());
        fclose($fp);
        $this->stop();
    }    
    
}
Finally, we can run it:
Open the folder {PUBLIC_HTML} and type:
phpunit

That’s it!


Troubleshooting

You will be able to find log files into /var/log/selenium directory. Usually there are plenty of information about what happens there.


Useful links

1 comment:

  1. Я благодарю г-на Педро за помощь в приобретении ипотечной ссуды VA. Было здорово получить ссуду в размере 900 000 долларов США от этого кредитора. Меня зовут Красимир Тодор, я бельгиец. Я получил ссуду от этого авторитетного кредитора 20 ноября 2019 года, и я хочу быстро использовать это средство, чтобы сообщить всем здесь, что вы можете получить любой ссуду у этой надежной кредитной компании. Найти ссудодателя VA непросто, и он должен быть рекомендован Департаментом по делам ветеранов. Г-н Педро предоставит вам ссуды под низкие проценты в размере 2% и очень быстро. Получите кредиты по электронной почте: pedroloanss@gmail.com /
    Текст в WhatsApp: +18632310632

    ReplyDelete