Ransford Okpoti's Blog

13 August, 2016

A Regular Expression (RegEx) To Match Integers and Doubles

Filed under: Java, JavaScript, Programming — ranskills @ 6:05 am

These regular expressions matches both the positive and negative variations of the data types specified below

  • integers – e.g., 1, 89, 81223, -7, etc.
  • floating point numbers (doubles or floats) – e.g., .0, 59.3, 300.12, -.87


The adopted approach was to avoid nested expressions which is not needed if it is only the number that is of interest and not its components like the decimal part and the fractional part.


var numberRegex = /(\-?\d*\.?\d+)/;

// Testing
var testNumber = "-45.8974";



String numberRegex = "(\\-?\\d*\\.?\\d+)";


Coming soon.



The site below allows the building and testing of regular expressions online, it is really nice with some colour coded tags and parenthesis colour matching to make a really complicated regular expression bearable to spot errors.



31 July, 2016

Forcing Maven To Use The Local .m2 Repository

Filed under: Java — ranskills @ 6:54 am

If each Maven run on a project results in always downloading dependency jars even though they have already been downloaded and stored in your local .m2 repository which is by default located at USER_HOME/.m2 e.g., on my Windows 10 machine, mine is C:\Users\ransk\.m2, then you only have to instruct Maven to operate in an offline mode.

One way to do is to locate the main Maven install directory, this is referred to as the MAVEN_HOME, which contains the settings.xml file in the conf directory, e.g. E:\tools\apache-maven-3.3.9\conf\settings.xml.

The offline settings is off by default and it only has to be turned on by ensuring you have the entry below in the settings.xml file.


With this in place, Apache Maven will check to see if required dependencies are available locally before contacting any remote repositories.

19 March, 2015

Import An Oracle Dump File

Filed under: Database — Tags: — ranskills @ 7:40 pm

These are the steps I normally follow when restoring Oracle dump files for the purposes of my work.

I prefer to logically keep the restored entities logically and physically separate through the use of tablespace and associated datafile(s) respectively.


Create and assign the user to the earlier defined tablespace.


If I want the created user to log in to the database, the statement below is executed.


And now to the import part,

Oracle Dump Log File With Highlighted User

IMP system/[password here] IGNORE=Y FROMUSER={...} TOUSER=xxx FILE=&quot;path to the .dmp file&quot;

8 February, 2015

This is not an ACL project Problem, My Solution

Filed under: ACL Analytics — ranskills @ 9:36 am

I was greeted by the unpleasant message “This is not an ACL project” from a dialog box after I tried opening an ACL Analytics 11 project and had selected Working from the earlier dialog box that welcomed me when I opened the project.

ACL Analytics This is not an ACL project

This is a message I haven’t seen before, but I just suspected the ACL project file was somehow corrupted. I quickly searched for solutions online, but not a single search contained my search terms “This is not an ACL project”, even using the almighty Google. Then it dawned on me that it is a problem that hardly happens or people just forget about it and move on.

This is what I tried and worked for me.

  1. I opened ACL Analytics, created a new project in the same location and with the same name as the corrupted project file and confirmed the old file should be replaced.
  2. I opened the log file, by double-clicking on it from the Overview tab or by simply clicking on the Log tab, and selected the entire project history log entries by checking the box beside the Project History root node of the log entries. Right click to copy the scripts from the logs.
  3. I added a script file, through File > New > Script…, you may rename the file Recover from its default name of New_Script, but this is entirely optional. Next, I pasted the log entries into the script file.
  4. Finally, I run the script, answered yes for the old files to be replaced on disk.

This worked for me for a couple of reasons highlighted below.

  1. I had the entire log entries for the project since I had not deleted any entries throughout the inception of the project.
  2. The source data, such as Excel files, I had imported were still at the same locations where I had earlier imported them. As you can obviously imagine, if you did import some files on removable drives and those are not plugged in with the same drive letter assigned by the operating system when following this approach, then you will not have a smooth process as I did.

Good luck recovering your ACL Analytics project.

18 March, 2012

Creating Dynamic Log Files In Zend Framework (ZF)

Filed under: PHP — Tags: , — ranskills @ 11:58 am

The motivation for wanting to do something like this could be any of the following:

  • You want to have separate logs depending on the context (i.e. application, testing, development, etc) in which the application is being run and you do not want to inherit a context and override some values in another context in the configuration file.
  • If your application builds huge log files and, as a result, you want to partition the logs into, say, daily, weekly, monthly, yearly, etc. logs

Below is a typical configuration in the application.ini file.

; Loggers
resources.log.stream.writerName             = "Stream"
resources.log.stream.writerParams.stream    = APPLICATION_PATH "/../data/logs/application.log"
resources.log.stream.writerParams.mode      = "a"
resources.log.stream.filterName             = "Priority"
resources.log.stream.filterParams.priority  = 4

The problem can easily be overcome by adding the highlighted lines to the configuration file, these settings will be used in the bootstrap file to create the log files.

; Loggers
resources.log.stream.writerName             = "Stream"
resources.log.stream.writerParams.stream    = APPLICATION_PATH "/../data/logs/application"
resources.log.stream.writerParams.mode      = "a"
resources.log.stream.filterName             = "Priority"
resources.log.stream.filterParams.priority  = 4

log.path               = APPLICATION_PATH "/../data/logs"
log.partitionStrategy  = "context"
log.partitionFrequency = "weekly"

New Entries Explained

Specifies the location/directory where the files would be created. NOTE: Linux users have to make sure the appropriate read/write permissions are set.
Defaults to context which denotes that log files will be prefixed with the context, or application environment, as is know in ZF, (e.g., production, development, testing , etc.) in which the application is being run.
Specifies when new log files get created and take on any of the following values: daily, weekly, monthly and yearly.

Next, in the Bootstrap.php, add _initLog()function as show below to dynamically create the log files based on the customized settings we provided in the application.ini.
The function simply alters the file name for the Stream logger by appending a unique string to the selected base file name based on the log.partitionFrequency value.

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

    protected function _initLog() {
        $options = $this->getOption('resources');

        $partitionConfig = $this->getOption('log');
        $logOptions = $options['log'];

        $baseFilename = $logOptions['stream']['writerParams']['stream'];
        if ($partitionConfig['partitionStrategy'] == 'context'){
            $baseFilename = $partitionConfig['path'].'/'.APPLICATION_ENV;

        $logFilename = '';
            case 'daily':
                $logFilename = $baseFilename.'_'.date('Y_m_d');

            case 'weekly':
                $logFilename = $baseFilename.'_'.date('Y_W');

            case 'monthly':
                $logFilename = $baseFilename.'_'.date('Y_m');

            case 'yearly':
                $logFilename = $baseFilename.'_'.date('Y');

                $logFilename = $baseFilename;


        $logOptions['stream']['writerParams']['stream'] = $logFilename;

        $logger = Zend_Log::factory($logOptions);
        Zend_Registry::set('logger', $logger);

        return $logger;

21 February, 2012

Talk: Web Scraping, An Important Technique For Data Extraction

Filed under: Uncategorized — Tags: , — ranskills @ 7:14 pm

After the successful launch of Java 7, late last year, here in Ghana by Coders4Africa where I was the main speaker highlighting on the new language changes in Java, I am pleased to announce that I will be making another presentation on Web Scraping at the upcoming meeting.


Web Scraping, An Important Technique For Data Extraction

Introduces Web Scraping using PHP as a valuable alternative to extract data from other websites in the absence of APIs in Africa. Demonstrating how to fetch related data and producing outputs in standard formats such as json, xml, csv, etc.

Event Details

Coders4Africa In Action in Accra Ghana – March 3rd 2012 at BusyInetnet
Saturday, March 3, 2012 from 3:00 PM to 6:00 PM (GMT)
Accra, Ghana

You can register here.
A tutorial will be posted after the event on this blog.

5 February, 2012

Dropping All Tables In A MySQL Database Using A Stored Procedure

Filed under: MySQL — ranskills @ 1:33 pm

Using an engine like InnoDB, which enforces referential integrity through the use of foreign keys, poses a little problem when deleting a table whose field(s) act as foreign keys in other table(s). Dropping an entire database may seem like a convenient approach to use, but will not be an option to users who do not have database creation privileges on the database server, and for those who would want to preserve other objects in the database like views, functions, stored prodecures, etc.

Deleting interconnected tables in a database can be a little frustrating, but the solution is that simple, suppress foreign key checks, if necessary, and delete the tables of interest.
Implementing a solution in the database through the use of a stored procedure is show below.


CREATE PROCEDURE procDropAllTables()

		DECLARE table_name VARCHAR(255);
		DECLARE end_of_tables INT DEFAULT 0;

			SELECT t.table_name 
			FROM information_schema.tables t 
			WHERE t.table_schema = DATABASE() AND t.table_type='BASE TABLE';

		OPEN cur;

		tables_loop: LOOP
			FETCH cur INTO table_name;

			IF end_of_tables = 1 THEN
				LEAVE tables_loop;
			END IF;

			SET @s = CONCAT('DROP TABLE IF EXISTS ' , table_name);
			PREPARE stmt FROM @s;
			EXECUTE stmt;

		CLOSE cur;

Now, let’s drop all the tables by calling our stored procedure as show below.

CALL procDropAllTables();

The above procedure can be tweaked if table deletion is not desired, but should be rather emptied by changing the highlighted line to

SET @s = CONCAT('DELETE FROM ' , table_name);

This is only one of the approaches that could be used to solve the problem, but they all basically work on the same premise that foreign key checks MUST BE disabled.

4 October, 2011

How To Solve MySQL Character Sets and Collations Mixing Problems

Filed under: MySQL — Tags: , — ranskills @ 11:20 am

Character sets and collations enable MySQL to perform comparisons on strings, so if have two or more columns with different character sets and/or collations are used in a way that performs some comparison of some sort on them (either using =, >, <, , a JOIN ON, etc), MySQL will be a little confused and display the error message:

[Err] 1267 – Illegal mix of collations (latin1_danish_ci,IMPLICIT) and (latin1_swedish_ci,IMPLICIT) for operation ‘=’

Unfortunately, there is no single command at the database level that could convert the character sets and collations of all tables within a database. In fact, the only command which appears to get the job done only changes the default values of the character set and/or collation of a database, and does not affect existing tables, but only has effect on new tables to be created.

ALTER DATABASE {database_name} CHARACTER SET {character_set} COLLATE {collation};

Likely for us, there is just a command/syntax for changing these values at the table level, syntax shown below.

ALTER TABLE {table_name} CONVERT TO CHARACTER SET {character_set} COLLATE {collation};


ALTER TABLE employees CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

This problem can be resolved by ensuring that all the tables and their corresponding columns have the same character set and collation. If multiple databases are employed, then they should all have the same character set and collation.
Using the above commands would be a very boring and painful process if you have, say, anything above 20 tables in your database. You will realize that is no fun at all, so we will develop a stored procedure that will automatically iterate through all the tables in the database and sets the character set and collations to our desired values.

The codes for the stored procedure is show below, I presume you can create this in MySQL (If not, jump to the screencast below to see it).

DROP PROCEDURE IF EXISTS procChangeCharSetandCollationForAllTables $$

CREATE PROCEDURE procChangeCharSetandCollationForAllTables()


		DECLARE table_name VARCHAR(255);
		DECLARE end_of_tables INT DEFAULT 0;
		DECLARE num_tables INT DEFAULT 0;

			SELECT t.table_name 
			FROM information_schema.tables t 
			WHERE t.table_schema = DATABASE() AND t.table_type='BASE TABLE';


		OPEN cur;

		tables_loop: LOOP

			FETCH cur INTO table_name;
			IF end_of_tables = 1 THEN
				LEAVE tables_loop;
			END IF;

			SET num_tables = num_tables + 1;

			SET @s = CONCAT('ALTER TABLE ' , table_name , ' CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_ci');

			PREPARE stmt FROM @s;
			EXECUTE stmt;

		CLOSE cur;
	END $$

Once you have the above stored procedure created in the database, just run it as shown below to have all the tables use the same character set and collation which in this case happens to be
COLLATE = latin1_general_ci

CALL procChangeCharSetandCollationForAllTables();

If you prefer to use a different character set and collation, say utf8 and utf8_general_ci respectively, just change the codes in line 23 to

SET @s = CONCAT('ALTER TABLE ' , table_name , ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci ');


11 July, 2011

How To Create a Gherkin Syntax Highlighter In gedit

Filed under: Uncategorized — Tags: , , , , , — ranskills @ 8:29 am

So, I woke up today and did a little bit of surfing, like I always do, and came across Cucumber, a Behaviour-Driven Development (BDD) framework in Ruby and I bought into the idea as it focuses on the behavioural aspects of the system by allowing you to describe and test the system’s behavior. Well, like a typical PHP junkie, I had to look for alternatives in PHP and luckily my search lead me to Behat, a BDD framework in PHP and inspired by Ruby’s Cucumber. Python’s users of Freshen may also find this informative since it uses the same syntax.

I decided to try out the examples only to realize that Gherkin, the Domain-Specific Language (DSL) used to describe the features to be tested in the features file, had no syntax highlighting in gedit, the official text editor of the GNOME desktop environment.

These are steps required to provide a basic gherkin syntax highlighting.


  1. Locate the directory where all the language files used for source code highlighting are kept, i.e. the language-specs directory.


    1. Type the command below to help us locate the language-specs directory.
    2.  locate gtksourceview | grep 'javascript.lang$' 

      The outcome of the above command is shown below with /usr/share/gtksourceview-2.0/language-specs/ as the directory of interest to us.



      The location is going to be either one of these, provided gedit was installed on drive C:\.

    1. C:\Program Files (x86)\gedit\share\gtksourceview-2.0\language-specs (if on Windows 7)
    2. OR

    3. C:\Program Files\gedit\share\gtksourceview-2.0\language-specs
  2. Create a gherkin.lang file into the language-specs directory with the content below.
  3. <?xml version="1.0" encoding="UTF-8"?>
    <!-- Author: 2011 Ransford Okpoti -->
    <language id="gherkin" _name="Gherkin" version="2.0" _section="Scripts">
                <property name="mimetypes">text/x-feature</property>
                <property name="globs">*.feature</property>
                <style id="keyword" 	_name="Keyword"		map-to="def:keyword"/>
                <style id="feature" 	_name="Feature"		map-to="def:type"/>
                <style id="steps_keywords" 	_name="Steps Keywords"	map-to="def:keyword"/>
                <style id="constructors" 	_name="Constructors"	map-to="def:type"/>
                <style id="variables" 	_name="Variables"	map-to="def:comment"/>
                <style id="comments" 	_name="Comments"	map-to="def:comment"/>
                <context id="gherkin" class="no-spell-check">
                            <!-- Keywords -->
                            <context id="steps_keywords" style-ref="steps_keywords">
                            <context id="comments" style-ref="comments" end-at-line-end="true">
                            <context id="feature" style-ref="feature">
                            <context id="constructors" style-ref="constructors">
                            <context id="variables" style-ref="variables">
                            <context id="arguments" end-at-line-end="true">
                                        <context ref="def:decimal" />
                                        <context ref="def:float" />
                                        <context ref="def:string" />
                                        <context id="table_headings">
  4. We are done, close gedit, if you have it opened, and open a gherkin source file with the extension .feature to see the beauty of our work.
  5. NOTE: On line 3, the _section attribute was set to Scripts indicating that the Gherkin menu item can be located from the program’s menu navigation: View -> Highlight Mode -> Scripts -> Gherkin.

Below is a gherkin source file with no syntax highlighting in gedit.

Gherkin File With No Syntax Highlighting

After the completion of our little procedure, you can see how beautiful our gherkin source file appears in gedit.

Gherkin File With Syntax Highlighting

NOTE: The above procedure can be followed to create syntax highlighting for any source file.
For a thorough explanation of the structure of the xml file, follow the official guide.

24 June, 2011

A Practical Introduction to Client-side JavaScript Unit Testing Using QUnit

Filed under: JavaScript — Tags: , , , — ranskills @ 10:55 am

“Wow, I thought I had that working”, how often do you say that to yourself or hear a colleague ranting and raving about this. Well, things break all the time in the software development cycle and you will need to have a consistent, unobtrusive and quick approach to finding out if critical features of an application is malfunctioning.

Over the past few years, automated application testing (unit testing, etc) has been associated with the traditional server-side programming languages, server-side because am discussing this in the web development context, such as Java, PHP, Python, any of the .NET languages. These languages have enjoyed testing frameworks that have been used on enterprise projects by teams that know and recognize the importance of testing on such large-scale projects where the risks are high. Testing is a vital ingredient in any important project, be it large-scale or not. At least, it gives you the added confidence that the application still performs like it was designed to, and as a developer, it is a requisite skill for you to possess. It also serves as a quality measure and aids in detecting points of failures in the application.

Below are some testing frameworks for some server-side programming languages:




For a more comprehensive list, check Wikipedia’s List of Unit Testing Frameworks.

JavaScript, the most popular scripting language on the internet, has not been left out in all of these, there are quite a number of unit testing frameworks namely:

In this demonstration, I will be using jQuery‘s unit testing framework known as QUnit.
NOTE: Unit Testing is not difficult, you test an actual result against an expected result and that is it, nothing magical or mythical about it. So, do not think it is for the Zoros, the Rambos, the James Bonds of programming? Definitely not!

Show Me Some Code, Please!

Ok, I will be using two different examples to demonstrate how unit testing is done, i hope the examples satisfy a broad range of readers. Before I get started, you need to set up the initial project folder structure by doing the following, if you want to code along:

  1. Download QUnit by clicking on this link.
  2. Uncompressing the saved file should show a similar directory structure below.
  3. QUnit Download Entries

  4. Setup a folder structure like the one below for the purposes of this demonstration.
    1. Create the project folder called js_unit_testing
    2. Inside the folder created above, create a test folder with the name test, this will contain the unit tests we will be writing and the html file(s) to run the tests
    3. From the uncompressed file, copy the qunit folder into the project folder js_unit_testing and the test/index.html file into the test folder created above in step 3.2
    4. Your project folder structure should looking like this.

      Project Directory Initial Structure

      Project Directory Initial Structure

Now, with the project structure out of the way, lets do some real coding.

Example 1

A trivial example meant to demonstrate unit testing of a function that sums up numbers. This is a good place to start since it does not involve any thinking at all, at least i presume we can all do simple summation, like 1 + 3 = 4, 0 + 0 = 0, 60 + 40 + 1 = 101, etc.
In addition, our function should be able to sum up any number of numbers passed to it and throw an exception if any of the arguments is not a number.

  1. Create num.js file in the project folder with the content below.
  2. /**
     * A vararg function that sums up numbers
     * @return {Number}
     * @throws {Error} If any of the arguments is not strictly a number
    function sum() {
        var total = 0,
            num = 0,
            numArgs = arguments.length;
        if (numArgs === 0) { 
            throw new Error('Arguments expected');
        for (var i = 0; i < numArgs; i++) {
            num = arguments[i];
            if (typeof (num) !== 'number') {
                throw new Error('Only numbers are allowed but found ', typeof (num));
            total += num;
        return total;

    Now we have to test the sum function. Note: a good test should not only test for situation that always make the program work, but should be broad enough to test for conditions that could actually let the test result in failures to see how well the code deals with such scenarios. A good test should always lead to the detection of errors in a program so that if can be fixed.

  3. Inside the test folder, create test.js, all tests will go here, with the content below.
  4. test("testSumWithValidArguments", function() {
        equal(sum(0, 0), 0, '0+0 = 0');
        equal(sum(2, 2), 4, '2+2 = 4');
        equal(sum(10, -1), 9, '10 + -1 = 9');
        equal(sum(-10, -1), -11, '-10 + -1 = -11');
        equal(sum(2,1, 5, 6), 14, '2 + 1 + 5 + 6 = 14');
        equal(sum(2.3, 1.5), 3.8, '2.3 + 1.5 = 3.8');
        notEqual(sum(2, 1), 5, '2 + 1 <> 5');
    test("testSumWithNoArguments", function() {
        raises(function(){ sum(); }, 'Exception thrown');
    test("testSumWithWrongDataToResultInException", function() {
        raises(function(){sum(2,'Ghana')}, 'String rejected');
        raises(function(){sum(2,{num:3})}, 'Object rejected');

    Now, lets see the magic at work by opening the index.html in the test folder in the browser. Below is the screenshot of the output.

    Sum Test Successful

    Now to the beauty of this whole process, that is a convenient way to detect defects in the application. Let’s say, a colleague somehow deleted the line that throws an exception when no arguments are passed to the sum() function. On running the test again, the test for that scenario, testSumWithNoArguments, will fail as captured below.

    Sum Test Failure

Example 2

This second demonstration closely models a real world programming scenario.

A government agency has tasked you to develop an application to enable them keep track of all quasi-government institutions/companies. They should be able to add any number of departments to a particular company and also keep track of a company’s employees to enable the prompt notification of those who are due for retirement.
Here are some constraints/features for the system:

  1. A department can only be associated with a company once.
  2. A person who does not meet the minimum age of employment for a company must not be employed.
  3. Employee ids must be automatically generated for those who have not manually been assigned ids.

UML Diagram
The simplified UML Class diagram above depicts some of attributes of the models identified for the scenario in this example and their relationships. The diagram was generated using yUML, an online tool for creating and publishing simple UML diagrams. You can use the DSL codes below to regenerate the UML Class diagrams above on the site.

[note: A simple UML diagram{bg:cornsilk}]

Cool, huh?

Lets get into action.

  1. Create a new folder named app in the main project directory.
  2. Create model.js file in app with the content below. This file contains our three domain objects namely: Company, Department and Employee
  3. /** @namespace All entities in the application are defined here */
    var model = model || {};
     * @class Creates a new Employee instance
    model.Employee = function (data) {
        data = data || {};
         * The first name of the employee
         * @property {String} firstName
        this.firstName = data.firstName || '';
         * The last name or surname of the employee
         * @property {String} lastName
        this.lastName = data.lastName || '';
         * The birth year of the employee
         * @property {Integer} birthYear
        this.birthYear = data.birthYear ||  new Date().getFullYear();
         * The monthly salary of the employee
         * @property {Number} salary
        this.salary = data.salary || 0;
         * @return {Integer} The age of the employee
        this.getAge   = function () {
            return new Date().getFullYear() - this.birthYear;
        /** @return {String} The name of the employee */
        this.getName  = function () {
            return this.firstName + ' ' + this.lastName;
        /** @return {String} A string representation of this object */
        this.toString = function () {
            return this.getName();
     * @class Creates a new Department instance
     * @param {String} name The name of the department
     * @param {Integer} [id=AUTO_GENERATED]
    model.Department = function (name, id) {
    	 * The id of the department which is auto generated when set blank
    	 * @property {Integer} id
        this.id = id || parseInt(Math.random() * 100, 10);
    	 * The name of the department
    	 * @property {String} name
        this.name = name;
        /** The company the department belongs to */
        this.company = null;
        /** List of employees in the department */
        this.employees = [];
         * @param {model.Employee} employee The employee to join the department
        this.addEmployee = function (employee) {
         * @return {Double} Total monthly salary for the department
        this.getTotalMonthlySalary = function () {
            var total = 0;
            this.employees.forEach(function (employee) {
                total += employee.salary;
            return total;
         * @param {Department} obj
         * @return {Boolean} true if the objects are the same, false otherwise
        this.equals = function (obj) {
            return this.id === obj.id;
     * @class Creates a new Company instance
    model.Company = function (data) {
        data = data || {};
        /** The minimum age of employment */
         * @property {String} name The name of the company
        this.name = data.name;
        /** List of departments making up the company */
        this.departments = [];
         * Adds a new department to the company
         * @param {model.Department} department
         * @throws {exception.DepartmentExistException} Department already exist
        this.addDepartment = function (department) {
            this.departments.forEach(function (item) {
                if (department.equals(item)) {
                    throw new exception.DepartmentExistException(department.name);
            department.company = this;
         * @param {model.Employee} employee
         * @param {model.Department} department
         * @throws {exception.EmployeeException} Exception thrown if the person fails any of the required criteria for employment
        this.employ = function (employee, department) {
            if (employee.getAge() < this.MIN_AGE_OF_EMPLOYMENT) {
                throw new exception.EmployeeException('Employee must be at least ' + this.MIN_AGE_OF_EMPLOYMENT + ' years');
         * @return {Double} Total monthly salary for the company
        this.getTotalMonthlySalary = function () {
            var total = 0;
            this.departments.forEach(function (department) {
                total += department.getTotalMonthlySalary();
            return total;
  4. Next, lets throw in some exceptions like you would do on the server-side by creating exception.js file with the content below.
  5. /** @namespace All exceptions thrown in the application are defined here */
    var exception = exception || {};
    /** @class Exception */
    exception.DepartmentExistException = function (value) {
        this.value = value;
        this.name = 'exception.DepartmentExistException';
        this.message = ' department already exist';
        this.toString = function () {
            return this.value + this.message;
    /** @class Exception */
    exception.EmployeeException = function (message) {
        this.name = 'exception.EmployeeException';
        this.message = message;
        this.toString = function () {
            return this.value + this.message;
  6. Finally, lets write some unit tests by adding the codes below to our test.js.
  7. module("model", {
        company: new model.Company({name: 'Coders4Africa'}),
        infoSys: new model.Department('Information System', 1),
        hr: new model.Department('Human Resource'),
        internalAudit: new model.Department('Internal Audit'),
        setup: function () {
            ok(this.company instanceof model.Company, 'Created company is of type model.Company');
    test("Employee", function () {
        var empInstance = new model.Employee({firstName: 'Ransford', lastName: 'Okpoti', birthYear: 1990, salary: 2000});
        ok(empInstance instanceof model.Employee, 'Created employee is an instance of model.Employee class');
        equal(empInstance.getName(), 'Ransford Okpoti', 'getName() function passed');
        ok(empInstance.getAge() >= 0, 'age should never be negative');
    test("Department", function () {
        ok(this.infoSys instanceof model.Department, 'Created object is an instance of model.Department class');
        equal(this.infoSys.getTotalMonthlySalary(), 0, 'Total monthly salary for a new department is 0');
        equal(this.infoSys.company, null, 'Company is null for a newly created department');
        ok(this.infoSys.equals(this.infoSys), 'A department should pass the equals() test on itself');
        ok(!this.infoSys.equals(this.hr), 'Two different departments must not be the same');
        ok(typeof (this.internalAudit.id) === 'number' && this.internalAudit.id > 0, 'Auto-generated id is a positive integer');
    test("Company", function () {
        var that        = this,
            year        = new Date().getFullYear(), // current year
            leger       = new model.Employee({firstName: 'Leger', lastName: 'Djiba', birthYear: year - 30, salary: 930}),
            amadou      = new model.Employee({firstName: 'Amadou', lastName: 'Daffe', birthYear: year - 35, salary: 850}),
            khalil      = new model.Employee({firstName: 'Ibrahima', lastName: 'Ndiaye', birthYear: year - 40, salary: 68}),
            kwame       = new model.Employee({firstName: 'Kwame', lastName: 'Andah', birthYear: year - 30, salary: 51}),
            abderemane  = new model.Employee({firstName: 'Abderemane', lastName: 'Abdou', birthYear: year - 50, salary: 41}),
            ranskills   = new model.Employee({firstName: 'Ransford', lastName: 'Okpoti', birthYear: year - 22, salary: 40}),
            prince      = new model.Employee({firstName: 'Prince', lastName: 'Nyarko', birthYear: year - 42, salary: 33}),
            james       = new model.Employee({firstName: 'James', lastName: 'Gaglo', birthYear: year - 50, salary: 32}),
            rufin       = new model.Employee({firstName: 'Rufin', lastName: 'Slyvestre', birthYear: year - 53, salary: 31}),
            mohammed    = new model.Employee({firstName: 'Mohammed-Sani', lastName: 'Abdulai', birthYear: year - 15, salary: 27});
        equal(this.company.departments.length, 0, 'Departments should be empty for a newly created company');
        equal(this.company.getTotalMonthlySalary(), 0, 'Total monthly salary for a new company is 0');
        this.company.employ(leger, this.infoSys);
        this.company.employ(amadou, this.infoSys);
        this.company.employ(khalil, this.infoSys);
        this.company.employ(kwame, this.hr);
        this.company.employ(abderemane, this.hr);
        this.company.employ(ranskills, this.hr);
        this.company.employ(prince, this.internalAudit);
        this.company.employ(james, this.internalAudit);
        this.company.employ(rufin, this.internalAudit);
        raises(function () { that.company.employ(mohammed, that.internalAudit); }, function (e) { return e.name === 'exception.EmployeeException'; }, 'exception.EmployeeException thrown when employing an unqualified person');
        equal(this.company.departments.length, 3, 'Department list correctly updated');
        raises(function () { that.company.addDepartment(that.infoSys); }, function (e) { return e.name === 'exception.DepartmentExistException'; }, 'exception.DepartmentExistException thrown when adding an existing department');
        equal(this.company.departments.length, 3, 'Department list does not get incremented when adding existing department');
        equal(this.company.getTotalMonthlySalary(), 2076, 'Checking the total monthly salary of the company');
  8. Below is the screenshot after refreshing the test page in the browser.
  9. All Tests Successful

    You can drilldown to find the details of a test by clicking on it. E.g., clicking on the Company test shows the details of all the 8 successful tests that were run.

    Company Test Details

Suggested Activities

The best way to learn is to get involved, so I have intentionally left out some features you could implement and test for, like:

  1. Finding all employees who are qualified to go on a mandatory pension based on a simple age criteria.
  2. Ensure the uniqueness of a department’s id generated by the program when no id is passed to the Department constructor
  3. etc


There is so much more to software testing and what I have demonstrated should give you an idea of how testing is done, I would advise you to find some good books and read. For those who want to take it further and make a career out of it, you can find out more from the organization responsible for certifying software testers the world over, International Software Testing Qualifications Board (ISTQB).


Download all the source codes here. All the codes are JSLint complaint.

Older Posts »

Blog at WordPress.com.