Posts Tagged ‘Unit’


So, I read this article a couple days ago: . As a result I started pulling my hair out. I decided that is too much work. Perhaps CakePHP 1.3 fixed some of the issues mentioned in that document, but no one has really documented anything. In any case, it took a few days of experimentation, but I got a nice template going. I see a ton of people interested in testing now a days, one thing to remember when you are starting out is that we are only testing controllers, and as such should only test what THIS controller is doing. Controllers in this sense only transfer data from one place to another, add a little bit of data, and really function as ¬†glue between models, views, components, utility classes etc. SOOO you should not be testing auth methods or if data is saved (thats what the tests for those classes are for. Furthermore, don’t test cake internal functions.

A couple more notes before the code…
– You need to set your debug level to 3
– This was a test straight from a CakeTestCase I started working on
– I tried a few ways to get access to auth/session data. This seemed to be the easiest way to do this. Simply login to your site with the user level that you’d like to test (or stay logged out). I tried to manually set the session data. I think cake doesn’t like that, and kills your session as a result.

* @author parris
class LrapackagesControllerTest extends CakeTestCase{
    * These should go somewhere more global
    private function genRandomString() {
        $length = 10;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $string = '';
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, strlen($characters)-1)];
        return $string;

    private function genRandomDouble() {
        $randomnumber = rand(0,5);
        return $randomnumber;

    function startCase(){
        echo "<h1>Starting LrapackagesController Test Case</h1>";
        $this->path = APP_PATH.'/lrabuilder/lrapackages/';
        $this->testPackage = array(

    function endCase(){
        echo "<h1>Ending LrapackagesController Test Case</h1>";

    function startTest($method){
        echo '<h3>Starting method '.$method.'</h3>';

    function endTest($method){
        echo '<hr/>';

    function testAdd(){
		$result = $this->testAction($this->path.'add',array('data'=>$this->testPackage,'method'=>'post','return'=>'vars'));
		if($_SESSION['Auth']['User']['role_id']==1 || $_SESSION['Auth']['User']['role_id']==2)

    function tAddLoggedInUser($data){
        //I would assertWithinMargin, but since the data needs to be identical, I don't need that.
        //1000 is selected arbitrarily, but I dont care about real accuracy here.
        $this->assertWithinMargin(strtotime($data['created']),strtotime(date('Y-m-d H:i:s')),1000);

    function tAddPublicUser(){
    	//echo($result); the only bad thing about this method is that you need to decide what the return var is before you
    	//have the session info... however, assuming you have properly setup your acl you shouldn't even need this test...
        //let the acl tests confirm that logged out users dont have access to logged in areas!!

    function testIndex(){
        $result = $this->testAction($this->path.'index');
        //debug($result); this results in an overwhelming amount of data, be selective of the output!!


Go forth and unit test :)!

Some useful docs:


I have been making tests using Selenium IDE + Selenium RC + Python and trying to get Selenium Grid working as well. I will try to outline what I did in order get a pretty awesome test going. First download selenium IDE (firefox plugin to record your actions), Selenium RC and your choice of Language (I choose python). You can get Selenium here. Also you will need Java and the JDK or SDK whatever they call it.

Start by opening the Selenium IDE in Firefox and then record your test by hitting the record button and navigating around your website. Once you are done turn off the record button. Then play your test back to make sure its doing what you want. Click Options->Format and select the language your want to use. You can integrate this with JUnit or TestNG, but I will make another post about that. I want to try to get this to work with pyunit.

Once you are done, make sure to save your test. Open up the folder you extracted your Selenium RC folder and navigate to selenium-server-1.0.1 and make a bat file in there with the following line.

java -jar selenium-server.jar

Make sure to type this in rather than copy paste, or else it wont work. Now when you click on the bat file it should just start your Selenium RC server and show you a command prompt. If you close this command prompt the server will stop. Now in back in Selenium IDE copy all the code it generated and paste it either in an IDE or text file so you can launch it. Note that if the Selenium RC Server is not running then it will not work and you will get some exceptions thrown at you. One thing I did was tidy everything up, and automate my scripting to batch test a bunch of searches.

So I read an XML file generated by Excel and parsed the data accordingly. Here is part of my source:

from selenium import selenium
import unittest, re, time
from datetime import date, datetime
from xml.dom import minidom

class getParamTest(unittest.TestCase):
   testXML = '../xml/test.xml'
   baseURL = ""
   basePage = "/somePage.htm"
   machine = "localhost"
   port = 4444
   #you can add or remove browsers here
   browsers = ["*iexplore","*firefox"]

   def testMain(self):
      courses = self.getAllCourses()
      for browser in self.browsers:
         for course in courses:

   def getParamTest(self, course_name, browser):
      #select local port for the Selenium RC, select the browser, pick the starting URL and start Selenium
      self.selenium = selenium(self.machine, self.port, browser, self.baseURL)
      sel = self.selenium
      #open the first page
      #paste your code here
      #you should always try catch your tests or else you may get some nasty breaks
      #end Selenium before trying another test!

   #All windows should probably be closed here. Firefox closes them all
   #Other browsers such as Internet Explorer do not! This will close all
   #Windows selenium knows about
   def closeAllWindows(self,sel):
      names = sel.get_all_window_names()
      while len(names)>0:
      the_window = "name="+names.pop()
      except Exception, (e):

   #gets a list of all courses as specified by the given XML file
   def getAllCourses(self):
      courses = []
      xmldoc = minidom.parse(self.testXML)
      table = xmldoc.getElementsByTagName("Data")
      counter = 0
      #in an excel XML file everything is stored in dom element data
      #the only relevent info for me was in the third column.
      for item in table:
         if counter == 3:
         counter = 0
      return courses

if __name__ == "__main__":

So I didn’t give you all my test code because it is kind of sensitive. Anyways you should have your own code for that already just paste it where I told you to in the code. One thing to note is then while you use firefox your windows will close automatically once Selenium is stopped at the end of the test; however, IE won’t do that so I found a way to make that happen. You could also use this technique to select nameless windows or popups.

I didn’t have an issue targeting elements on a page; however, if you do consider giving them names in the DOM. If you can’t do that there are usually ways around it. You can use Names, IDs, and maybe even the text present. My main issue was window popups didn’t have names so I grabbed all windows and popped them off of my stack (the last one in is always the last window opened. Another issue is pages not opening to fast. Usually if you insert “time.sleep(5)” or some equivalent waiting thing everything should workout. You should first always try to use “sel.wait_for_page_to_load(“30000″)” where 30000 is in milliseconds; whereas, the 5 in time.sleep is in seconds. Finally, the main method is the one with the word “test” in the front. This method is selected from the unittest class in Selenium as the main method.

Enjoy :-D! Updates coming soon for running tests in parallel and JUnit/PYUnit!