Stivlo'st in Asia

Programming and Travel

Unit testing is useful to test individual parts of the program, to check if they respect the specifications. Actually as any type of testing, can only point out bugs, but can’t prove that the program is correct.

Despite that, they are very useful during development, as TDD (Test Driven Development) suggests, it can be a good idea to write the test before the actual code. It clears up the specification of the method and may point out that we have to refine the specification a little before start coding, for instance about handling of special cases. When our code pass all the test the job is done, or at least done for that method.

PHP doesn’t have the awesome tools that come with Java, but in this respect there is a simpler implementation of Unit Testing that is still quite useful, called PHPUnit.

Installation

PHPUnit Manual describes installation in details, but actually on Ubuntu installation is much simpler. It’s enough to install package phpunit and the framework will be installed in /usr/share/php/PHPUnit.

Writing a test

Writing a test is as simple as defining a class, that by convention we call as the class we want to test with Test suffix. For example if we need to test a class named Customer, our unit test class will be called CustomerTest.

require_once "Customer.php";
require_once "PHPUnit/Framework.php"; //since /usr/share/php is in the path

class CustomerTest extends PHPUnit_Framework_Test {

    private $customer;    

    //anything that should be set up before running the tests
    public static function setUpBeforeClass() {
        $this->customer = new Customer();
    }

    //a test method for myMethod()
    public function testMyMethod() {
        $result = $this->customer->myMethod();
        $this->assertEquals(43, $result);
    }

}

Running the tests

To run the test from the command line, is enough to type:

phpunit CustomerTest.php

This is the basics to start using tests, but there is much more information in the online manual.

It’s useful to be able to set field content programmatically, for example I’d want to show the results of an Ajax call. Since I am learning Ext Js, I had a hard time to find how to do it, and I found two ways to do it.

First here is the code for the simplest form, with just one text input.

Ext.onReady(function () {
    new Ext.FormPanel({
        id: 'myForm',
        renderTo: 'myFormDiv',
        frame: true,
        title: 'This is the form title',
        width: 590,
        height: 80,
	items: [ {
            xtype: 'textfield',
            width: 470,
            fieldLabel: 'myField',
            name: 'myField',
            id: 'myFieldId'
        } ]
    });
});

And here is how it looks:

We just need one line of Javascript:

Ext.getCmp('myForm').getForm().findField('myField').setValue('Virtues of programmers: laziness, impatience and hubris');

You can run the code by copying this line in firebug console and pressing the Run button, or you can press the Run button below.

The above code sets the field searching it by field name. A simpler way to set the text input is using its id. Normally I would put both id and name and they would be the same, but to be more clear on which one I am using, I choose ‘myField’ for the name and ‘myFieldId’ for the id.

If you know the field id, it’s simpler to set the value. To try it, copy it in firebug, or press the Run button below.

Ext.getCmp('myFieldId').setValue('Simplicity is prerequisite for reliability');

Basic ExtJs cheat sheet

No comments

I learnt the basic of Ext JS in the book “Ext JS in action” – Jesus Garcia – Manning” and then proceeded to read “Ext JS 3.0 Cookbook” – Jorge Ramon – Packt Publishing.

I wrote a kind of cheatsheet to remember the basic functions. For more details you can buy the books or look in the API docs.

DOM

Ext.onReady(function () { }); //callback to execute when the DOM is ready
var myDiv = Ext.get('divId'); //retrieve a Ext.Element
var combo = Ext.getCmp('colorsCombo'); //retrieve a Ext.Component
Ext.getBody(); //return the body of the document as an Ext.Element
Ext.getDom(id) ; //return the DOM node as HTMLElement

//Dom Query to return an Array of Ext.Element, includes selector/XPath processing
var nodes = Ext.query('div'); //Ext.query('.msg'); for all elements with msg class
Ext.each(nodes, function (item, index, allItems) {
   document.write(index + '<br/>');
});

JSON and URL encoding

Ext.USE_NATIVE_JSON = true;
JSON Encoding: var objectJson  = Ext.encode(myObject);
JSON Decoding: var myObject = Ext.decode(objectJson);

var encodedUrl = Ext.urlEncode(selectedColors); //URL Encoding
var decodedUrl = Ext.urlDecode(encodedUrl); //URL Decode

Reflection

Ext.type(myObject); //Determine object type: array, object, number
Ext.isArray(myObject);  Ext.isNumber(myObject); Ext.isString(myObject);

Array functions

var position = myArray.indexOf('Duck');  //find an object in an array
//0 is the first element, -1 is not found
myArray.remove('Dog'); //remove an object from an array

String functions

var newString = String.escape(myString);
var newString = beforeTrim.trim();
var newString = String.format('You have {0} messages', msgCount);
var newString = Ext.util.Format.uppercase(myString);
//Other functions with one argument:  Ext.util.Format.lowercase(),
//Ext.util.Format.capitalize(),  Ext.util.Format.stripScripts(),
//Ext.util.Format.nl2br(), Ext.util.Format.usMoney()
var newString = Ext.util.Format.ellipsis(myString, 20);
var newString = Ext.util.Format.substr(myString, 0, 5);
var newString = Ext.util.Format.leftPad('23', 4, '0');

Value checking

Ext.num(myObject, 0); //provide a default value it's not a number
var allowZeroLen = false; //this is the default and you can omit
Ext.value(myObject, 'default', allowZeroLen); //provide a default value for the string
var constrained = number1.constrain(25, 50); //force it in the range

Dates

var now = new Date();
var formatted = now.format('Y-m-d');
var aDate = Date.parseDate('2010-12-09', 'Y-m-d');
var inRange = now.between(lowDate, highDate);

I copied the following text from S3tools-general mailing list and I’m posting it here because is an excellent explanation on how to enable S3 logs.

there are two sorts of access logs – one is the log of the S3 storage itself (generated per-bucket) and one is usage log for CloudFront, obviously only available if you deliver content from S3 over CloudFront, i.e. when you use S3 as a storage for web content as oppose to, say, for backup purposes.

The former (S3 logs) are enabled with:
s3cmd accesslog –access-logging-target-prefix=s3://your-log-bucket/target-bucket/s3/ s3://target-bucket
That will enable access logging for ‘s3://target-bucket’ and store the logs to ‘s3://your-log-bucket/target-bucket/s3/’ (obviously you should create s3://your-log-bucket first).

Similarly for CloudFront logging can be enabled with:
s3cmd cfmodify –access-logging-target-prefix=s3://your-log-bucket/target-bucket/cf/ cf://THEDISTID

At the end of the month simply download all the logs from s3://your-log-bucket/ and process to get whatever reports you need.

It is recommended to store the S3 logs in a separate bucket, not in the one being monitored. Otherwise writing the logfiles into the same bucket generates access requests and is logged too, which creates kind of a loop.

Hope that helps

Michal

JavaScript can be fun

No comments

Really. I’ve always hated JavaScript, struggling with it and cursing it. Now I’m changing my mind. It’s the most ubiquitous programming language. Every computer who has a web browser has JavaScript and is very compatible among different implementations. The bigger problems come from the DOM, but are nowadays nicely hidden by JavaScript libraries. One of the biggest frustrations working with JavaScript comes from working with it without understanding it. Since the syntax is similar to Java/C++ I’ve also committed the mistake to start working with it without studying it.

JavaScript is an object oriented language that doesn’t have classes but has objects and has prototypes. Prototypes are a way to dynamic link objects. The syntax is weird so it’s better to have a Object.create helper function defined as follows:

if (typeof Object.create !== 'function' ) {
     Object.create = function (o) {
         var F = function () {};
         F.prototype = o;
         return new F() ;
     };
}

This is really powerful, we augmented the basic type Object with a new method create() and as a consequence, now all objects have this new method! We will try this by declaring an object called mork and create a new object called mindy based on it.

var mork = {
    "name": "Mork",
    "greet": function() {
        alert("Hi, I'm "+this.name);
    }
};
var mindy = Object.create(mork);

This is not the same as saying var mork2 = mork, because in this latter case we are simply copying the object reference, so if we change any property of mork2, we are actually changing mork. With Object.create we are actually creating a new object, as the name suggests.

mindy.name="Mindy";
mindy.greet();
mork.greet();

You can run the code by clicking on the Run button, and as expected it will say “Hi, I’m Mork” and “Hi, I’m Mindy”.

Now the fun part: if we delete mindy.name, mork anchestor property will be visible again:

delete mindy.name;
mindy.greet();

To run mindy.greet() after deleting mindy.name use the run button below:

In this case mindy will say: “Hi, I’m Mork” because the original property of the prototype can be seen again. What is even more fun is adding a new property or even method to mork:

mork.mood = "happy";
alert(mindy.mood);

In this example mindy mood will be also happy because it will get it from its prototype, with a very late binding. The property mood will actually be only in mork memory because when I call mindy.mood, the interpreter will have to go to the prototype object to read it.

Powered by WordPress Web Design by SRS Solutions © 2010 Stivlo'st in Asia Design by SRS Solutions