Categories
GNU/Linux Free Software & Open Source Programming & Web Development

Easy PHP code test development with SimpleTest unit testing framework

Simpletest, Unit Testing for PHP

Testing is a task every developer has to do eventually on any programming project. You can do it manually after writing all your code to see if it works as you intended, or better yet, before writing your code, using test driven development techniques that will save you time and frustrations down the road. One of those techniques is called Unit Testing.

Ideally, unit testing takes place before writing any code. Its a way to plan out how your functions, classes and objects will behave. The basic idea is that you plan the outcomes of each part of your program, then you write those parts to provide that outcome. So think of it as a black box that you will give some input and expect some output. This way you know how objects will be organized, what methods to write in each class, what needs to be their input and how are they going to output the results. Having all your code in tests will help you add new features, change or refactor parts of your code faster without the fear of breaking something else in your software. If you changed something and all your tests still pass, you’re good to go, if not, you can easily track down where the error is and what got affected.

PHP is famous for having spaghetti code and being too flexible that you can mess things out pretty fast, specially when you’re not an experienced programmer, or you have a team of developers with different programming styles and experience working on several components of the same project.

Although there are several unit testing frameworks for PHP, I’ll talk about SimpleTest since its very light, easy to install and easy to learn. Also, if you’re a Drupal developer, its the testing framework of choice.

Setup

To install it, go to the Simpletest download page and get the latest version. Extract the files to your PHP path, or use require_once() calls to the autorun file:

Usage

Here’s an example of a class’ tests (testfile.php):

getList(5);

/* test result is an array */
$this->assertTrue(is_array($result));

/* test correct number of output elements */
$this->assertEqual(count($result), 5);

/* make a different call with different parameter */
$result = $obj->getList();

/* confirm that output is always an array, even with 0 elements */
$this->assertTrue(is_array($result));
}
}

Now you have a basic skeleton of you methods and their behaviors, now you can go ahead and write the real code (myclass.php).

Run it

Once we’ve written the class, we can test out its methods by running our tests script. You can do that by using the command line, or by viewing the php script in a browser window.

Personally, I prefer to use the command line for convenience and faster testing without needing even to setup any web server. Running it will look like this:

$ php testfile.php
testfile.php
OK
Test cases run: 1/1, Passes: 3, Failures: 0, Exceptions: 0

Do more

This is a very small and simple test, but you can also test out the interface of your project. SimpleTest has a browser class that can perform some events like simulating browser visits, doing clicks on your interface’s links and checking the HTML structure of the web server responses.

Check out the full documentation, which is very easily laid out as a big tutorial, and start testing all your code!

Categories
GNU/Linux Free Software & Open Source Programming & Web Development

command line tools for web developers

Computer Data Output

Many people are typically afraid of the terminal. Yes, it might look scary for some, retro for others, but for the practical busy programmer, the terminal is the best tool you can have.

Lately for my day job, I’ve been required to work with lots of static web pages, as I’ve mentioned on several of my previous posts. So for my daily tasks, I’ve been using a lot of command line tools on the terminal that make my work a lot faster.

Here are some of the tools that I’ve been using and how I’ve used them:

  • find

    Helps me list and filter certain types of files for processing. For example find . -name *.html This will give me a list of all files with .html extension under the current directory and subdirectories.

  • sed

    GNU sed is very handy to do all kinds of text manipulation without having to write a whole script about it. For example one common task would be search and replace a text or regular expression pattern on a file. Example: sed -e "s/My Search/My replace/g" myfile.html

  • xargs

    This is a ‘piping’ command, it will take the output of one tool and place it as arguments for the subsequent tool in the line. Example: find . -name *.temp -print0 | xargs sed -n -e "s/Hello/Goodbye/g" This will find all .temp files, then on each of them will search the word “Hello” and will replace it with the word “Goodbye”.

  • tidy

    When you have a bunch of legacy HTML code or “messy” (X)HTML documents you must parse, a good idea is to first clean up the code before working with it. Tidy is a command line tool that will help you with the task of cleaning, reformatting and indenting any messy (X)HTML document. It even does a good job cleaning MS Word generated HTML files!

  • GNU make

    This is an “old school” tool, for the ones that grew up with web development and away from C/C++ development. Make is used to automate certain tasks and in a given order, checking for dependancies. In the web development process, I use make to automate repetitive tasks, such as deploying files to the testing server, making a tag in my version control system and publishing the site on the production server, cleaning up temporary files, and so on. So I write a Makefile with these tasks, and every time I have to upload my code to the testing server I only execute something like make upload and it will do the task. For example, cleaning up all temporary files on my project would involve me doing: find . -name *.temp | xargs rm -rf. I can create a Makefile with the following:

    clean:
    find . -name *.temp | xargs rm -rf

    then every time I need to cleanup my codebase, I simply run make clean Hope you get the idea 😉

  • git

    My preferred version control system for the past 4 years has been Git. Its a distributed version control system that is very simple and very practical to use because its extremely fast and doesn’t get in your way while programming. It has lots of features and tools for the everyday tasks and its a very good practice to version control *all* your projects, even if you’re the only developer of them. Since its distributed, you don’t need to setup a server for it and you can replicate your repository on any media and with as many copies you like. Version controlling your projects will save you from troubles like accidentally deleting files, or, using local code branches, you can easily experiment new features without affecting your main “stable” version of your code. There’s a lot to say about version controlling and Git and I guess I haven’t written about it before (strange since its a big topic for me), so I guess I’ll put more of these details for another post. Just take my advice, use git and version control all your projects. You’ll thank me later.

  • rsync

    Rsync is a great tool to synchronize files and directories from one location to another. This can be on the same machine or on different (remote) machines. The typicall use of rsync is for automated backups. You can use it as so, or you can also use it to mirror your website on another folder or machine. I use it to deploy my files on the testing and/or production servers. This way I don’t have to be worried about forgetting to upload a file, the whole project can be synchronized with one single command on multiple machines. You can configure rsync to connect through ssh (more on this below) to move your files around in a secure, encrypted file transfer.

  • ssh & scp

    You definately don’t want your files to be going through the network in plain sight. I know, some might say: “who cares?” but really, its better to be paranoid and careful about your data. You never know. So the best way to transport your files from one machine to another is through a secure encrypted channel. This is what SSH does for you. With ssh you can connect securely to your server’s command line to execute command there, or you can securely copy files from one machine to another using scp.

There might be several other tools that I use daily but these are the ones more present in my mind as I’ve been using them a constantly.

What command line tools do you use for your web development tasks? Do you have other ideas on which the tools listed here can be used? Send me your comments, this might get interesting and useful for all of us.

Categories
GNU/Linux Free Software & Open Source Interesting random stuff Programming & Web Development

Random links from my bookmarks

I’d like to share my bookmarks from time to time. I think sometimes random browsing can be very fruitful and sometimes even productive.

This week on my delicious bookmaks, I’d like to share:

I hope you find these links interesting or usefull as they’ve been for me.

Categories
GNU/Linux Free Software & Open Source Programming & Web Development

PHP 5 OOP implementation quirks

PHP 5 is supposed to be fully object oriented. Yes, it has classes and inheritance and all those things an OOP language is supposed to have. But, is it implemented like most OOP languages?

First of all, I come from a C/C++ background, so there’s where I got all my OOP lessons. Then I started to learn Python and Ruby, and well, finally lots of little OOP details I couldn’t understand were clear. Ruby has a beautiful OOP implementation, sometimes it can get confusing having everything as an object and the object and class themselves are objects. But once you pass that, everything is cystal clear.

Constructors

What bothers me about PHP 5’s OOP implementation is first of all, constructors. If I declare a Parent class, with a constructor, then a Child class that inherits from Parent, and this Child class has its constructor, when I instantiate an object of the Child class, only the Child class constructor is called.

class Parent
{
  __construct()
   {
      echo "hello from parent ";
   }
}
class Child extends Parent
{
 __construct()
   {
      echo "hello from child ";
   }
}
dummy = new Child();

This will display only

hello from child

Where in other languages, such as C++, Python or Ruby (don’t know about Java, but I expect the same) the output would be:

hello from parent hello from child

So in order to have this constructor cascading effect, in PHP 5 I have to explicitly call the parent constructor on my child’s constructor like this:

class Child extends Parent
{
 __construct()
   {
      echo "hello from child ";
      parent::__construct();
   }
}

Which is not very nice.

Accessor methods

Another aspect that I dislike is the class attribute accessor methods. I call them accessors like in Ruby, but they are commonly called setter and getter methods. So in order to control and filter my input/output for my object, I usually do so with this methods.

If I declare a User class with some methods, I expect the setter and getter methods to filter my I/O everytime I want to access the class’ attributes.

class User
{
   public $name;
   public $email;
   public $password;
 //set and get functions
  public function __get($variable)
    {
      return $this->$variable;
    }
  public function __set($var, $value)
    {
      trim($value);
      if($var != "password")
        {
          $this->$var = $value;
        }
      else
        {
          $this->password = hash('md5',$value);
        }
    }
}

This is supposed to encrypt the password everytime I set something on my password object attribute. What is wrong with this? That it doesn’t work! The get and set functions only work when you have NO attributes or undefined attributes in the class. So in order for this getter and setter methods to really filter I/O to the instantiated objects is to not declare the attributes, and this methods will generate them, like the PHP people say, “magically”. Maybe its a nice flexibility feature to have attributes generated on-the-fly, but it doesn’t help on object consistency.

PHP 5 is a nice tool, but as a language I think there’s still work to do on the OOP implementation.