Unit Testing with QUnit, Growl, Watchr

Posted on by Steven McConnon

To be sure, the situation with Unit-Testing DOM Javascript is pretty abysmal right now. There is not really a nice neat way to have continuos testing for Jquery/Javascript yet that I know of. I have created a way to do this though and I’m sure other developers will find it absolutely fantastic.

Goal: Have growl automatically alert us when saving a javascript file whether our unit tests passed or not.

Install Grunt

Rather than create a new tutorial on how to do this, go here for a nicely explained way to install it. Once installed go to the place where you created your javascript files in the terminal and type

grunt init:gruntfile

then just follow the bouncing ball and you should have a working gruntfile, no need to change it.

Install Watchr

gem install watchr

Create jsWatchr.rb

Copy and place the code below into a file called jsWatchr.rb.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
watch('(.*).js')  { |m| code_changed(m[0]) }
 
def code_changed(file)
    run "grunt qunit --force"
end
 
def run(cmd)
    result = `#{cmd}`
    growl result rescue nil
end
 
def growl(message)
    puts(message)
    messageSplit = message.split("\n").last(3);
    growlnotify = `which growlnotify`.chomp
 
    title = messageSplit.find { |e| /warnings/ =~ e } ? "FAILURES" : "PASS"
    if title == "FAILURES"
        image = "~/.watchr_images/failed.png"
        info =  messageSplit[0].split
        info = info[1].gsub("[33m", '') + " " + info[2] + " " + info[3]
 
    else
        image = "~/.watchr_images/passed.png"
        info =  messageSplit[0].split
        info = info[1].gsub("[39m", '') + " " + info[2] + " " + info[3] + " " + info[4]
    end
 
    options = "-w -n Watchr --image '#{File.expand_path(image)}' --html '#{title}'  -m '#{info}'"
    system %(#{growlnotify} #{options} &)
end

Test it

Create a blank file in the same directory as your grunt.js & jsWatchr.rb files called myExample.js. Create another file in a sub-directory “test” called myExampleTest.html. After starting watchr by going into the directory containing grunt.js and jsWatchr.rb and typing

watchr jsWatchr.js

and going to myExample.js and re-saving it, you will get a growl notification of whether your tests passed or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!-- test/myExampleTest.html -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
  <script>
  $(document).ready(function(){
 
test("a basic test example", function() {
  ok( true, "this test is fine" );
  var value = "hello";
  equal( value, "hello", "We expect value to be hello" );
});
 
module("Module A");
 
test("first test within module", function() {
  ok( true, "all pass" );
});
 
test("second test within module", function() {
  ok( true, "all pass" );
});
 
module("Module B");
 
test("some other test", function() {
  expect(2);
  equal( true, false, "failing test" );
  equal( true, true, "passing test" );
});
 
  });
  </script>
 
</head>
<body>
  <h1 id="qunit-header">QUnit example</h1>
 <h2 id="qunit-banner"></h2>
 <div id="qunit-testrunner-toolbar"></div>
 <h2 id="qunit-userAgent"></h2>
 <ol id="qunit-tests"></ol>
 <div id="qunit-fixture">test markup, will be hidden</div>
</body>
</html>

Unit Testing with PHPUnit, Growl, Watchr

Posted on by Steven McConnon

There has already been a tutorial on how to do this here and here, but I need to create my own spin on their tutorials.

We all know that Unit Testing is essential for proper software development, and in PHP it’s especially necessary to do unit testing because of the loads of bad code out there. Unit testing should really be more mainstream for PHP developers. If you want to find out why unit testing or continuous integration is important, google it, and when you decide you want to start doing it check out my tutorial on how to set it up. This tutorial is specifically for mac OSX Lion.

1. Download and install PHPUnit.

Make sure you have pear installed before attempting this. An important thing to note is that it is possible to have multiple versions of PHP/Pear on your machine. Personally, I do and the way I needed to install PHPUnit through pear was to use the full path to the specific pear like blah/blah/blah/pear. Sudo may be required.

pear config-set auto_discover 1
pear install pear.phpunit.de/PHPUnit

2. Download and install Watchr.

This was pretty straight forward. Go to the terminal and type this, sudo may be required. After you are done installing watchr, go into your ~/ directory and create a new folder called “.watchr_images” and place your success and fail icons in there. Call them failed.png and passed.png, or name them whatever you want and edit the phpWatchr.rb file to match.

gem install watchr

3. Download and install growlnotify

You will need to update your growl to at least version 1.3.3 first and yes that will cost $1.99 at the app store. Go update that then install growl notify using their installer which can be downloaded here.

4. Create phpWatchr.rb

Place a new file called phpWatchr.rb inside the place where you save your PHP files for each project. Place your test PHP files inside a sub-folder called “test”. Copy and paste the code below into phpWatchr.rb, and remember that I used Sebastian Marek’s code any modified it slightly to my needs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#phpWatchr.rb
watch('(.*).php')  { |m| code_changed(m[0]) }
 
def code_changed(file)
    run "/usr/local/php5-20120203-085139/bin/phpunit --colors ."
end
 
def run(cmd)
    result = `cd test && #{cmd}`
    growl result rescue nil
end
 
def growl(message)
    puts(message)
    messageSplit = message.split("\n").last(3);
    growlnotify = `which growlnotify`.chomp
 
    title = messageSplit.find { |e| /FAILURES/ =~ e } ? "FAILURES" : "PASS"
    if title == "FAILURES"
        image = "~/.watchr_images/failed.png"
        info = /\x1b\[37;41m\x1b\[2K(.*)/.match(messageSplit[1])[1]
    else
        image = "~/.watchr_images/passed.png"
        info = /\x1b\[30;42m\x1b\[2K(.*)/.match(messageSplit[1])[1]
    end
 
    options = "-w -n Watchr --image '#{File.expand_path(image)}' --html '#{title}'  -m '#{info}'"
    system %(#{growlnotify} #{options} &)
end

5. Test it

So now you want to test it. Create 2 php files in your project. On called myExample.php and another in the “test” directory called myExampleTest.php.

1
2
3
4
5
6
7
8
//myExample.php
<?php
class myExample {
	function getBool() {
		return true;	
	}		
}
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// test/myExampleTest.php
<?php
require_once '../myExample.php';
 
class test2 extends PHPUnit_Framework_TestCase
{
    protected $b;
 
    protected function setUp()
    {
        $this->b = new myExample;
    }
 
 
    public function testBalanceIsInitiallyZero() {
        $this->assertEquals(true, $this->b->getBool());        
    }  
 
}
?>

If it works you should get a growl notification that everything worked out OK! Change the test code to make the assertion fail to see what that looks like too.

How to send files via cURL in PHP

Posted on by Steven McConnon

Sometimes it is necessary to forward an uploaded file to an external script such as API usage. It is really quite simple but I will show you how to do it.

Here is the form:

<form method="post" enctype="multipart/form-data">
Description: <input type="text" name="description">
File: <input type="file" name="fileName">
<input type="submit" name="submit">
</form>

Here is the php:

<?php
if($_POST['photoSubmit']) {
 
	$postArgs = Array();
 
	//put each post variable into the array
	foreach ($_POST as $key => $value) {
		$postArgs[$key] = $value;
	}
 
	//put all the file info into the post array
	foreach ($_FILES['file'] as $key => $value) {
		$postArgs[$key] = $value;
	}
 
	//here we attach the file
	$postArgs['file'] = '@'.$_FILES['file']['tmp_name'];
 
	//upload the image
	$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://example.com/backend/adminPhoto.php?do=upload");
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);]
 
	$response = curl_exec($ch);
	curl_close($ch);
}
?>

Self Balancing Robot Tutorial – Part 1

Posted on by Steven McConnon

I was talking with some of my friends at UCF and discovered that there exists an inexpensive microcontroller that can be programmed to do embedded systems called the Arduino. Since embedded systems is the whole reason I’m going to college, a week after hearing about the Arduino, I’ve bought it and a slew of parts to create my very own self balancing robot with hopes to scale it up and create my own segway.

Here is a video to show you what I’m talking about (not mine):

Basically, I’m going to be teaching you all how to build your very own version of this robot as I build it myself.

Here is a list of things I have bought so far. I have done lots of research to keep costs low on this project. This parts lists costs approximately $210.

1. Arduino Uno
2. Pololu MinIMU-9
3. Sabertooth dual 5A motor driver
4. Parallax Motor/Bracket/Wheel Kit
5. 2- 1/4 Inch diameter x 36in threaded rods
5. Spare plywood
6. Wire
7. A battery
8. 24 – 1/4″ Nuts (for threaded rod)
9. 8 – #8 Machine Screw Nuts
10. 8 – #8 Threaded Machine Screws

Why I chose the Arduino:

I chose the Arduino over cheaper, more powerful microcontrollers like the Teensy, Propeller, and the PicAXE because of the huge user base of it. I know that if I run into any problems there will be thousands of other users to help me in the forums. Anyone who knows anything about programming knows that it’s much easier to use something with a large community.

Why I chose the Pololu MinIMU-9:

Basically for this project, all that’s needed for the robot to keep balance is 3-degrees of freedom in an IMU, but this was the cheapest thing I could find. This particular IMU was actually retired which is why I think it was so cheap. It will do the trick.

Why I chose the Sabertooth dual 5A motor driver:

It’s simply the cheapest motor controller that can stand 5A worth of current and spikes up to 10A. My motors have a stall rating of 4.8A so this is perfect.

Why I chose the Parallax Motor/Bracket/Wheel Kit:

Believe me, I have looked at other kits such as this, but items like that are more expensive, slower, have less torque, and are heavier. Granted, I could have found my own motors, wheels, and mounting brackets separately, but that would be very very time consuming to find something comparable. To me, time is money and I can’t spend the time it takes to put some stuff like that together.

Gamification for higher user engagement.

Posted on by Steven McConnon

I was working on a fitness directory application for a personal project a while back. While the web application is no longer live, I gained a lot of experience from it. I built the application and spent a very small amount of money on advertising. One of the main problems of launching a free web application is how to gain the initial users. Although it did not occur to me at the time, I could have enticed the 100 or so initial users to use my site more if I had used game dynamics.

Gamification, or adding game dynamics to a web application is a great way to make your users stay on your site for longer and fill out their profiles more completely. Basically, the premise behind gamification is that if you create a rewards for users who complete tasks on your site, they will use your site more, thus accomplishing the goal of making an application more engaging. Some of the techniques for gamification include, giving points, badges, and awards to users who do things you want. Some of these things could include posting helpful things to other users, filling out their profiles more completely, and adding more friends. Progress bars showing completion of tasks give the users more incentive to finish because they don’t want to see that they have only completed 60% or their profile or whatever. One of the ways that yahoo answers uses gamification is through their point and level system. With each post I make on Yahoo answers, the more points I get, then after a certain number of points I go up a level or receive a badge. The perks of being a level 3 are that I now have the ability to do more things such as give more thumbs ups or make more posts within a given time period.

So a little creative thinking can go a long way and make the difference between making a successful and fun to use web application, and a boring web application that nobody wants to use. Use gamification to improve the user experience and you will see the engagement rate of your users increase.

Arrange Rows in Columns of 2 or 3

Posted on by Steven McConnon

When making a CMS web application, the layout should be dynamic. In the case of arranging hundreds of textboxes neatly, some logic is involved. Here is a snippet of code that creates an array for the number of columns each row has.

For example, if we have a prime number of textboxes, we want things arranged neatly like this:

/*//Here is a sketch of we want to happen:
	//if it's 1
	1 - row of 1
 
	//evenly divisible by 2, and not by 3		
	2 - row of 2
	4 - row of 2
	8 - row of 2
	10- row of 2
	14- row of 2
 
	//evenly divisible by 3 or 6 
	3 - row of 3
	6 - row of 3
	9 - row of 3
	12- row of 3
 
	//if it's prime and then the last row has the remainder
	5 - row of 3 then 2
	7 - row of 3 then 2
	11- row of 3 then 2
	13- row of 3 then 1
	17- row of 3 then 2
	19- row of 3 then 1
	23- row of 3 then 2
	29- row of 3 then 2
	31- row of 3 then 1
	37- row of 3 then 1
*/
 
$map = array();
 
//detects prime numbers
function is_prime($i) {
	if($i % 2 != 1) return false;
	$d = 3;
	$x = sqrt($i);
	while ($i % $d != 0 && $d < $x) $d += 2;
	return (($i % $d == 0 && $i != $d) * 1) == 0 ? true : false;
}
 
 
array_push($map, 1);
//do the array for the suites
for($i=0; $i<($roomBlock->numSuites * $roomBlock->maxPplSuites); $i++) {
	$title = 0;
	echo $i . "  - ";
	//every $roomBlock->maxPplSuites number of times, add a 1 for the title
	if($i%$roomBlock->maxPplSuites == 0) {
		array_push($map, 1);
		$j=0;
		$primeRows = 0;
	}
 
	if($roomBlock->maxPplSuites%2 == 0 && $roomBlock->maxPplSuites%3 != 0 && $j<($roomBlock->maxPplSuites/2))
		array_push($map, 2);
 
	if(($roomBlock->maxPplSuites%3 == 0 || $roomBlock->maxPplSuites%6 == 0) && $j<($roomBlock->maxPplSuites/3))
		array_push($map, 3);
 
	if(is_prime($roomBlock->maxPplSuites) && $j<($roomBlock->maxPplSuites/3) ) {
		//add to number of rows
		$primeRows = $primeRows + 3;
 
		if($roomBlock->maxPplSuites%$primeRows >= 1 && ($roomBlock->maxPplSuites - $primeRows) < 1){
			$val = $roomBlock->maxPplSuites%($primeRows - 3);
			array_push($map, $val);
		} else {
			array_push($map, 3);
		}
 
	}
 
	$j++;
}

How to show errors on ASP.NET website

Posted on by Steven McConnon

I was recently working on an ASP.NET 4.0 application and had some problems when uploading my site on to Godaddy’s servers. Basically I was getting INTERNAL SERVER 500 ERROR. This isn’t very useful for a developer who is trying to fix the error, although it looks better than just showing a bunch of details from a security standpoint. Basically all you have to do is modify the Web.Config file and add this into it:

<system.webServer>
     <validation validateIntegratedModeConfiguration="false" />
     <asp scriptErrorSentToBrowser="true"/>
     <httpErrors errorMode="Detailed"/>
</system.webServer>

and bam, there ya go, error messages for you and the world to see.

How to blink text in all browsers

Posted on by Steven McConnon

I am not saying that <blink></blink>  tags are smart, but sometimes clients want things to blink indefinitely. So here is a snippet of code that will help you on your way.

Javascript:

<script type="text/javascript" language="javascript">
 window.onload=blinkOn;
 
function blinkOn()
{
  document.getElementById("blink").style.color="#CCC"
  setTimeout("blinkOff()",1000)
}
 
function blinkOff()
{
  document.getElementById("blink").style.color=""
  setTimeout("blinkOn()",1000)
}
 
 
 
</script>

HTML:

<div id="blink">Hello World!</div>

How to link includes to full url

Posted on by Steven McConnon

When working on a project for a blog recently I tried linking my includes to something like this:

1
<?php include("http://sitename.com/includes/header.php"); ?>

And it would not work. The proper way to link that would be

1
<?php include($_SERVER['DOCUMENT_ROOT'] . "/includes/header.php"); ?>

The $_SERVER['DOCUMENT_ROOT'] refers to /home1/orlandp9/public_html which is the full document root.

There is actually a way to link to a full external url but it is not safe because a criminal hacker could include files that are malicious and an external include could be configured to steal credit card or other personal information. Another malicious thing that I have seen with a remote include is that the hacker includes a file full of html links to his site effectively creating back links to whoever he wanted. The hacker who was hacking into sites and creating back links to his sites must have been involved in SEO. I do not condone any use of malicious code and you shouldn’t either.

If you are really desperate and are not afraid to get hacked then you can turn on a php configuration in php.ini called allow_url_include or allow_url_fopen.

How to center a div on the page using CSS

Posted on by Steven McConnon

A long time ago when I first started doing web-design I would always run into the problem of how to center a div on the page. Now of course that is a very simple problem for experienced coders but this tutorial is made for the beginners.

Example:

This is an outer div centered in the page.

This nested inner div is centered.

View full entry