code prettify

Tuesday, 12 April 2016

Developing a To-Do application using TDD approach using QUnit as the testing framework

I recently tried my hands at TDD to develop a basic ToDo app using QUnit as the testing framework.

Here is the link to the application demo.

I have written both unit and integration / functional tests while developing this app. The source code can be checked here.

To run and see the results of tests, refer below links:

Unit test results
Integration / Functional test results

Hope this helps in learning :)

Monday, 11 April 2016

Video Tutorial on Network Throttling tool provided by Google Chrome Developer tools


Network Throttling tool provided by Google Chrome Developer tools

In this video we will be seeing how this tool helps us to test your application at different network speeds, thus giving us info and insight as to how users having different speeds of internet use our application and the challenges they face and how the performance can be improved and how the application can be made more usable in such cases.




Friday, 8 April 2016

Interesting article on importance of coding and testing

A very interesting article on testing and coding illustrating many simple tips, important points:

- why one should test and code
- what one should test
- how and what kind of testing one can provide
- what one should not test
- how important testing is
- and others

If you are new to testing, it is a good place to start. Overall as the title of the article says "Why and how testing can make you happier", so it is time to be happy :D

Interesting read it makes. Hope you enjoy it too as I have :)

http://mikbe.com/code/testing/dx/2016/03/11/why-and-how-testing-can-make-you-happier.html

Thursday, 31 March 2016

Lorem ipsum content for html

If you want some dummy html content for test purpose like form, paragraph or list content then you can use content from http://html-ipsum.com/

Sunday, 27 March 2016

Testing APIs in CodeIgniter 2.x using phpunit and Guzzle Http client

Sometimes we have apis implemented in our application and there are different levels at which these can be tested.

1. Unit tested at model level to check the logic is working fine
2. Tested at API call level to ascertain whether all the apis as expected are working and are returning data as expected.


Today, we will be learning how to test APIs in CodeIgniter 2.x version using phpunit and Guzzle Http client.

Basically Guzzle Http client is a client used to make http client requests.

Ref: https://github.com/guzzle/guzzle

"Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services."

We will basically be creating an API for a blog so as to get blog posts and add blog post. When testing APIs, we are basically testing the output format, expected fields in the output and their data type and value if needed.

Sample code can be found at git repository here: https://github.com/satejkumar/CodeIgniter_API_Testing

We are using composer to install the dependencies: phpunit and Guzzle http client.

So download the latest CodeIgniter 2.x version and create a composer.json file with the following content:

{
    "require": {
        "guzzlehttp/guzzle": "^6.1",
        "phpunit/phpunit": "*",
        "phpunit/php-invoker": "*",
        "phpunit/dbunit": "*"
    }
}

and then install the dependencies using the below command:

$ composer install

Then we create our test file inside application/tests/ folder called PostsTest.php

All the dependencies are included by the autoload file.

require('../../vendor/autoload.php');

Before doing each test case, we setup the Guzzle Http client and set the base uri of the API request as below inside setUp() function which is called before each test function call.

protected function setUp()
{
        $this->client = new GuzzleHttp\Client([
            'base_uri' => 'http://localhost/'
        ]);
}

One function is to test get post API request, so we are making a get request to url http://localhost/posts/index/1 to get the first post and are expecting a json content and the json content should have some fields and should have an id value of 1.

public function testGet_ValidInput_PostObject()
{
        $response = $this->client->get('posts/index/1');
        $this->assertEquals(200, $response->getStatusCode());

        $data = json_decode($response->getBody(), true);

        $this->assertArrayHasKey('id', $data);
        $this->assertArrayHasKey('title', $data);
        $this->assertArrayHasKey('content', $data);
        $this->assertArrayHasKey('author_id', $data);
        $this->assertArrayHasKey('emails_sent', $data);
        $this->assertArrayHasKey('created_at', $data);
        $this->assertArrayHasKey('updated_at', $data);
        $this->assertEquals(1, $data['id']);
}

So we are using assertArrayHasKey() function to check if a particular field is present in the data set and assertEquals() to check for value.

Another function is to test POST request to create a new blog post.

public function testPost_NewBlog_Post()
{
        $response = $this->client->post('posts/index', [
            'form_params' => [
                'title' => 'My Random Post',
                'content' => 'Content',
                'author_id' => 1
            ]
        ]);

        $this->assertEquals(200, $response->getStatusCode());
        $data = json_decode($response->getBody(), true);
        $this->assertGreaterThanOrEqual(1, $data['id']);
}

In the above function we are creating a post request to the url http://localhost/posts/index with post parameters and are then expecting a 200 status code output and a json content with a field "id" which should have an integer value greater than or equal to 1.

Now that we are done with the tests, we can run them from the project root directory using below command:

$ ./vendor/bin/phpunit application/tests/

Basically phpunit and Guzzle Http client help us in making requests and verify responses thus enabling us to test APIs.

Ref: https://ole.michelsen.dk/blog/testing-your-api-with-phpunit.html
Excerpt: "Remember it's just as important to test failing/edge cases as testing when things go well. Also you should run these tests against an isolated testing environment if they modify your data."

Sunday, 14 February 2016

A link I found highlighting principles that guide us in development for an ethical web

I found this very simple yet very clear list of principles that can be kept in mind while developing for the web.

https://ethicalweb.org/

Excerpt from above link:

"As web developers, we are responsible for shaping the experiences of user's online lives. By making choices that are ethical and user-centered, we create a better web for everyone."

Hope it helps and guides us in creating a better web for everyone :)

Saturday, 13 February 2016

Using git pre-commit hook for php and js syntax check

This is a followup from my two previous posts on php and js git pre-commit syntax check where I had mentioned how to check for php and js syntax independently using pre-commit with git.



But what if we wanted to check for both php and js syntax at same time while committing. So, I used the scripts used for both and combined them. Below is the final result.

#!/bin/bash

commit_error=false

ROOT_DIR="$(pwd)/"
LIST=$(git diff-index --cached --name-only --diff-filter=ACMR HEAD)
ERRORS_BUFFER=""
for file in $LIST
do
    EXTENSION=$(echo "$file" | grep ".php$")
    if [ "$EXTENSION" != "" ]; then
        ERRORS=$(php -l "$ROOT_DIR$file" 2>&1 | grep "Parse error")
        if [ "$ERRORS" != "" ]; then
            if [ "$ERRORS_BUFFER" != "" ]; then
                ERRORS_BUFFER="$ERRORS_BUFFER\n$ERRORS"
            else
                ERRORS_BUFFER="$ERRORS"
            fi
            echo "Syntax errors found in file: $file "
        fi

        # Check for xdebug statments
        ERRORS=$(grep -nH xdebug_ "$ROOT_DIR$file" | \
                 sed -e 's/^/Found XDebug Statment : /')
        if [ "$ERRORS" != "" ]; then
            if [ "$ERRORS_BUFFER" != "" ]; then
                ERRORS_BUFFER="$ERRORS_BUFFER\n$ERRORS"
            else
                ERRORS_BUFFER="$ERRORS"
            fi
        fi
    fi
done
if [ "$ERRORS_BUFFER" != "" ]; then
    echo
    echo "Found PHP parse errors: "
    echo -e $ERRORS_BUFFER
    echo
    echo "PHP parse errors found. Fix errors and commit again."
    commit_error=true
else
    echo "No PHP parse errors found. Committed successfully."
fi

files=$(git diff --cached --name-only --diff-filter=ACM | grep "\.js$")
if [ "$files" = "" ]; then
    exit 0
fi

pass=true

JS_ERRORS_BUFFER=""

echo -e "\nValidating JavaScript:\n"

for file in ${files}; do
    result=$(jslint ${file} | grep "${file} is OK")

    if [ "$result" != "" ]; then
        echo -e "\t\033[32mJSLint Passed: ${file}\033[0m"
    else
        JS_ERRORS=$(jslint ${file})
        JS_ERRORS_BUFFER="$JS_ERRORS_BUFFER\n$JS_ERRORS"
        echo -e "\t\033[31mJSLint Failed: ${file}\033[0m"
        pass=false
    fi
done

echo -e "\nJavaScript validation complete\n"

if ! $pass; then
    echo -e "\033[41mCOMMIT FAILED:\033[0m Your commit contains files that should pass JSLint but do not. Please fix the JSLint errors and try again."
    echo -e $JS_ERRORS_BUFFER
    echo
    commit_error=true
else
    echo -e "\033[42mCOMMIT SUCCEEDED\033[0m\n"
fi

if $commit_error; then
    exit 1
fi

Store it in .git/hooks/pre-commit
Give it execute permission: $ chmod +x .git/hooks/pre-commit and it should be good to go :)

Sample output when I try to commit two php files and two js files with syntax errors:

Filenames with code content:

error.php


<?php
$
array = ;

another_error.php

<?php
var_dump(');

error.js

i =

another_error.js

i = k;

$ git commit -m 'Error Commit' error.php another_error.php error.js another_error.js
Output from above error commit:

Syntax errors found in file: another_error.php 
Syntax errors found in file: error.php 

Found PHP parse errors: 
PHP Parse error: syntax error, unexpected ';' in /var/www/html/error.php on line 2
PHP Parse error: syntax error, unexpected '');' (T_ENCAPSED_AND_WHITESPACE) in /var/www/html/another_error.php on line 2

PHP parse errors found. Fix errors and commit again.

Validating JavaScript:

JSLint Failed: error.js
JSLint Failed: another_error.js

JavaScript validation complete

COMMIT FAILED: Your commit contains files that should pass JSLint but do not. Please fix the JSLint errors and try again.

error.js #1 'i' was used before it was defined. i = // Line 1, Pos 1 #2 Unexpected character '(space)'. i = // Line 1, Pos 4 #3 Unexpected '(end)'. i = // Line 1, Pos 3 #4 Stopping. (50% scanned). // Line 1, Pos 3
another_error.js #1 'i' was used before it was defined. i = k; // Line 1, Pos 1 #2 'k' was used before it was defined. i = k; // Line 1, Pos 5

Above script can be further modified to format the output better but is helpful for basic php and js syntax issues and js standard checks in code :)