code prettify

Showing posts with label api. Show all posts
Showing posts with label api. Show all posts

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, 26 October 2014

Assessing HTML5 audio Playback Capabilities using canPlayType method

Assessing <audio> Playback Capabilities

We can test if a particular format of audio can be played by the browser by using the "canPlayType" method of the audio object.

Basically, "canPlayType" method takes an audio format and returns a string that suggests / represents how confident the browser feels that it can play that type of audio.

Below are 3 results from "canPlayType" method:
- "" (Empty string -> cannot play)
- maybe (might be able to)
- probably (browser is reasonably confident that it can play)

Some caution is required when trying to select media in this way, because browsers differ in their way of assessing their ability to play a format.

The different ways in which support is assessed means that the canPlayType method should be used very carefully. A better alternative to it is to provide audio files in more than one format as <source> options.

Example Code:

<audio id="media" controls preload="metadata">
    Audio cannot be played
</audio>
<table id="info" border="1">
    <tr><th>Property</th><th>Value</th></tr>
</table>
<script>
    var mediaElem = document.getElementById("media");
    var tableElem = document.getElementById("info");

    // List of audio files which can be provided for playing
    var mediaFiles = ["sample.ogg", "sample.wav", "sample.mp3"];
    var mediaTypes = ["audio/ogg", "audio/wav", "audio/mp3"];

    // Loop through the audio type list
    // and determine the type which can be played by the browser
    // and set the "src" to it
    for (var i = 0; i < mediaTypes.length; i++) {
        var playable = mediaElem.canPlayType(mediaTypes[i]);

        // if "playable" is empty, then browser can not play the
        // audio format
        if (!playable) {
            playable = "no";
        }

        tableElem.innerHTML += "<tr><td>" + mediaTypes[i] 
            + "</td><td>" + playable + "</td></tr>";

        if (playable == "probably") {
            mediaElem.src = mediaFiles[i];
        }
    }
</script>

In the above example, we are looping through all the audio formats and displaying the info in a table related to whether the browser can play the audio or not. While doing so we are also setting the "src" attribute to audio file which can be played by the browser.

Tuesday, 14 October 2014

How to play a series of audio files using HTML5 audio element?

By default the HTML5 <audio> tag allows us to play any one audio file at a time. How do we go about playing a series of audio files that are related but are present separately, lets say something like intro.mp3, part1.mp3, part2.mp3, conclusion.mp3 (something part of our presentation) ?

Well, this can be done with a little bit of coding using the following apis from <audio> element:
- "src" property
- "load" and "play" methods
- "ended" event

Logic:
It goes something like this. We play our first audio file, and then wait or listen for the "ended" event and as soon as it is fired, we change the "src" attribute of <audio> element to our next audio file and call the "load" method to load the file and then call "play" event to play the next audio. This continues for other audio files until we complete all the audio files and then again start from beginning if required.

Code:

<!-- audio element to play our audio files -->
<!-- Notice there is no "src" attribute defined -->
<audio controls id="audio"></audio>


<script>
    var position = 0; // Store position of audio currently playing
    var audioList;    // Store array list of audios to be played
    var audio;        // Store reference to the <audio> element

    window.onload = function () {
        // List of audio files to be played
        audioList = [
            "intro.mp3",
            "part1.mp3",
            "part2.mp3",
            "conclusion.mp3"
        ];

        // Reference to the <audio> element
        audio = document.getElementById("audio");

        // Attach listener to the "ended" event
        audio.addEventListener("ended", nextAudio, false);


        // Play the first audio file when the page loads first time
        playAudio();

    };

    // Handler function to be called when "ended" event is 
    // called on <audio> element that is when the audio files
    // reaches its end
    function nextAudio() {
        // Increase the position to indicate playing next audio file
        position++;

        // If we have reached the end of the list, then start
        // playing from first audio again
        if (position >= audioList.length) {
            position = 0;
        }

        // Play the next audio
        playAudio();
    }

    // Plays the currently positioned audio file
    function playAudio() {
        // Set the "src" of the current audio file, load and play it
        audio.src = audioList[position];
        audio.load();
        audio.play();
    }
</script>

Monday, 13 October 2014

How do you know you have reached the end of an HTML5 audio?

It is very useful to know when an audio file has reached its end in the browser to indicate it visually.

To do so, we can attach an "ended" event on the HTML5 audio element, which happens when the audio reaches the end and stops playing. Using javascript, we can listen to this event and take necessary action.

Example:

<audio id="sample_audio" src="sample.mp3"></audio>

<script>
    var audio_elem = document.getElementById("sample_audio");

    audio_elem.addEventListener("ended", function() {
        alert("The audio file has finished playing");
    });
</script>