Tutorial: Writing a Unit Test for WordPress

Standard

WordPress Unit Testing is an expanding field in the WP world. Currently, there is a big push to add more tests, and you can get in on the action!

If you need help getting started with Unit Testing, check out my previous post about why to get into WordPress Unit Testing. It includes a short section about how to get rolling.

The Basics

The way the test works is relatively simple: a developer makes changes to a WordPress file, then runs the tests to make sure nothing breaks because of their changes. It notifies the dev if he/she needs to change something in their code.

Think of tests as a way to prove that a function still works properly. It tests for the expected output, so sometimes writing a test isn’t very satisfying because, in theory, your test will cause no reaction because everything is working fine.

Important

Unit tests are written to ensure WordPress returns the expected output. To be clear, they are not written to specifically test one’s code, meaning you don’t usually write a test for the sole purpose of testing your new code. To put it another way, Unit Tests exist to prove WordPress works, and if you run your code against all of the WP Unit Tests, you can see if your edits affect the output that WP creates, you can see if it breaks WP’s basic functionality.

A Basic Unit Test

Unit Tests are written then submitted to WordPress Trac to be included in the repository of Unit Tests. They can be very basic or very complicated, but they always seem to do obvious things; they make sure input is processed into the expected output.

I think this can best be explained through example. The following Unit Text will almost work. For the sake of clarity, I’ve left out some of the class information, but check it out as an example to get an idea of how a test is written.

/**
 * Test to see if get_post works.
 *
 * Compares a post ID ($org_post_id) with post ID 
 * taken out of get_post ($new_post_id).
 * If they don't match, get_post() doesn't work, and it will 
 * return an error.
 */
function test_get_post() {
    //Create new post using method provided by WP
    $org_post_id = $this->factory->post->create();
 
    //get post object using the new post's ID
    $post_obj = get_post( $org_post_id );

    //Get the post ID as given to us by get_post
    $new_post_id = $post_obj->ID;

    //Use pre-defined method to test if the two ID's match
    $this->assertEquals( $org_post_id, $new_post_id );
        
}

The purpose of this test is to see if the mechanism of get_post() is broken by whatever changes you submit with your new code. This test should work fine, as long as get_post() works. If it fails, then you know you’ve done somthing to mess up get_post().

A Full-Featured Example

This is a Unit Test I’m working on for the upcoming save_post{$post_type} action hook. The hook is all ready, and this test that I have written just needs to be tested. So, it may have some errors, but it will give you the general idea of how a test works. Check out the comments in the Gist for information on how it works. To fully understand it you’ll need to have a good grasp on Object Oriented Programming (OOP).

If the font size bothers you as much as it does me, you can view the gist here.

<?php
/**
* This has been tested using the diff for save_post_{$post_type}
* https://core.trac.wordpress.org/changeset/25050
*
* @todo Try different post type names
* @todo Create two posts and try to update them both at the same time
*/
class Save_Post_Post_Type {
/**
* Loads our control data into the test post.
*
* First, we'll save the post using wp_update_post and without save_post_{$post_type}
* We'll use this as a control to compare our $result against later.
* We can't just compare the raw post input with the save_post_{$post_type} because saving
* the post strips slashes, validates, etc.
*
* @param int $test_post_id ID of the post we are testing with.
* @return string $control_result content of post saved with wp_update_post
*/
function control_test( $test_post_id ) {
$control_post = array();
$control_post['ID'] = $test_post_id;
$control_post['post_type'] = 'book';
$control_post['post_content'] = "Initial Data.";
$control_post_id = wp_update_post( $control_post );
/**
* when we save it, it returns a post ID,
* so we'll need to get our content back out of the control post.
*/
$control_post = get_post( $control_post_id);
$control_result = $control_post->post_content;
return $control_result;
}
/**
* Test to see if save_post_{$post_type} hooks into the saving action correctly.
*
* @param int $test_post_id ID of the post we are testing with.
* @param string $input Input from provider() method.
* @return string $test_result Content of post(s) updated with save_post_{$post_type}
*/
function test_save_post_post_type( $test_post_id, $input ) {
//Run the hook that should exist, and attempt to change the data.
add_action( 'save_post_book', $this->modify_content( $test_post_id, $input ) );
//Get post content by id
$result_post = get_post( $test_post_id );
$test_result = $result_post->post_content;
return $test_result;
}
/**
* Save our post with new post_content, on 'save_post_book'
*
* @param int $test_post_id ID of the post we are testing with.
* @param string $input Input from provider() method.
* @return void
*/
function modify_content( $test_post_id, $input ) {
/**
* Attempt to overwrite 'the auto-generated post_content' with $input
* This will be done on 'save_post_book' in test_save_post_type()
*/
$test_post_new_content = array();
$test_post_new_content ['ID'] = $test_post_id;
$test_post_new_content['post_content'] = $input;
wp_update_post( $test_post_new_content );
}
}
/**
* Set Up Test
*/
class Tests_Save_Post_Post_Type extends WP_UnitTestCase {
/**
* Establish testing variables
*
* This information will be passed as the parameter ($input) into our test method in this class.
* Note that we use @dataProvider to let test_save_post_post_type know we're using this method
* Note also that it returns a multidimentional array (an array within an array).
* These values will be passed one at a time into our testing function
*
* @return array Array of input content to test "save_post_{$post_type}"
*/
public function provider() {
return array(
array( '023983775900' ),
array( '(*&@#)*)&*#@*~_)*?(#' ),
array( 'http://wordpress.org&#39; ),
array( 'It\'s a trap!' ),
array( 'These aren\'t the droids you are looking for.' ),
array( 'I find you lack of faith disturbing.' ),
array( 'Ready are you? What know you of ready?' ),
);
}
/**
* Tests to ensure save_post_{$post_type} hooks into save_post correctly.
*
* If these $input and $result don't match, the test will throw an error.
* They should match, displaying that the input matches the output ($result),
* when saved by "save_post_{post_type}".
*
* This function must begin with "test".
*
* @param string $input Input from provider()
* @return bool Pass/Fail test Results
*
* The following line is required to let the test know what method is sending the $input
* @dataProvider provider
*/
public function test_run_test( $input ) {
$test = new Save_Post_Post_Type;
//Create Post using extended class WP_UnitTestCase
$test_post_id = $this->factory->post->create();
$control_result = $test->control_test( $test_post_id );
/**
* Run the test. Send the input, return the result.
*
* This method changes the content of our post into a Star Wars quote.
* If it does not change, it will thow an error. Remember, our original content was,
* "Initial Data."
*/
$test_result = $test->test_save_post_post_type( $test_post_id, $input );
/**
* Compare $control_result content with $test_result content.
*
* Since we attempted to modify the content of the "Book" post, this method "assertFlase"
* checks to see that these two statements do not match.
* There are many other methods you can use here:
* http://phpunit.de/manual/current/en/appendixes.assertions.html
*/
$this->assertNotEquals( $control_result, $test_result);
}
}

A Note

Weston Ruter added a comment greatly simplifying this process, which would be the best way to run this test. One of its greatest benfits is that it is extremely compact, although a bit advanced for a less-experienced developer, which may be you. I’ve decided to leave “the long way” to run this test here in this post so you can view more of the features and techniques of Unit Testing.

More

I hope you were able to learn something from viewing the actual code from a Unit Test. I’ve found that always helps me much more than reading long explanations. However, if you have any questions, I’m glad to answer them. Unit Tests are a real need in WordPress, and I’d love to help the community by assisting future Test authors.

Why you need to get into WordPress Unit Testing

Standard

What is Unit Testing?

A non-technical definition of Unit Testing, is “a way to make sure your code won’t break stuff.” In the WordPress world, it means using a provided library of tests to check if your code will return errors. Basically, it’s a program that you put your code files into, and when you run it, you will be notified if there are problems.

It’s important to know that WordPress Unit Testing is typically done with PHPUnit. You’ll see that name thrown around here and there when researching this topic.

Why Automated Testing?

Holy crap, WHY NOT?

In the past, I wasted a lot of time clicking back and forth between posts and settings pages to ensure that my new plugin or theme wouldn’t throw any errors in a WordPress install. Now, you can just type a few commands and your code will be analyzed quickly and thoroughly. Automated Unit Testing lets you quickly check your code in many, many different contexts and scenarios.

Unit Testing has proven invaluable to me in my attempts to write patches for WordPress Core. One time I ran some code I thought would work, and it broke WordPress in 9 other places. Luckily I was able to test it before I submitted it for review, right?

Unit Testing can also reveal unexpected output. Recently, automated testing revealed to me something I didn’t expect to see: when typical date formats were passed into a function, it executed perfectly, but when just one other date format was sent through, it spit out data I hadn’t accounted for. I’m not sure I would have caught that error on my own. It would have required running my code by hand many times and many ways.

Typically, testing looks like this:

  1. Edit code.
  2. Switch to browser.
  3. Input data (e.g., create a new post/comment, ativate a plugin, change admin settings, etc).
  4. Cross fingers.
  5. Check 80,987,096 places for error messages.
  6. Hope you didn’t miss anything.
  7. Repeat 9,464,643,943 times, just to be sure.
  8. Spend the rest of your day answering support questions about errors caused by your last Plugin.

The automated testing process looks more like this:

  1. Edit code.
  2. Switch to terminal.
  3. Start unit testing ($ phpunit).
  4. Make a glass of ice tea.
  5. Wait for Test Results.
  6. ???
  7. Profit.

How to Test your WordPress App, Theme, Plugin, or Patch

Tom McFarlin wrote a great series on this topic, so I won’t waste time and space trying to explain it all over again (and probably in an inferior way). Check his article out on WPTuts+: The Beginner’s Guide to Unit Testing: What Is Unit Testing? Specifically, check out the section titled “Preparing the Environment.” It will help get you started.

Other Resources

Conclusion

Unit testing is very important. It is way faster and way more thorough than you are. It is powerful and will save you a lot of headaches and embarassment when your code goes live. You need to get into Unit Testing.

Your Turn

So, what has been your experience with Unit Testing? What tips do you have for those getting started? Share your thoughts in the comments!

If you’re ready to get to the meat and potatoes, check out the next post, “Tutorial: Writing a Unit Test for WordPress.”

the_title() vs the_title_attribute()

Standard

You might be doing the_title() wrong.

If you have much experience with WordPress, you’ll be familiar with the_title(). This template tag is simply used to generate the title of whatever page or post you’re working with at the current point in The Loop.

Basic Usage of the_title()

    //Inside the Loop

    //Common usage
    <h2><?php the_title() ?></h2>

    //or better yet...
    <?php the_title( '<h2>', '</h2>' ) ?>

Another Common Use of the_title()

Usually a post’s title is wrapped in a link (usually rendered by the template tag the_permalink), and it makes sense to use the post title as the link’s title attribute. So, this is what’s commonly done to generate the link’s title attribute:

    //Inside the Loop

    //Common Post Title Linkage 
    <h2><a href="<?php the_permalink(); ?>" title="<?php the_title() ?>" ><?php the_title() ?></a></h2>

    //Just for clarity, this will output the following markup
    <h2><a href="http://mywebsite.com/my-post" title="My Post">My Post</a></h2>

The Problem

The HTML Spec restricts the characters that can be used in HTML attributes (title="" is an example of an attribute). For instance, ampersands (&) are not allowed to be used in attribute values, so you can’t do something like this:

<h2><a href="#" title="Dog & Pony Show">Dog & Pony Show</a></h2>

(It’s important to note that only the first ampersand in this statement is a problem. The second one is just part of the text as far as the browser’s concerned.)

So what can you do if your post title has one of the illegal characters (less than, greater than, ampersand, double quote and single quote) in it?

The Solution

Savvy WordPress devs know to use esc_attr() when outputting a string into a HTML attribute, which is what we just did above: We output the string “Dog & Pony Show” as the value of the attribute ‘title’. esc_attr() converts illegal characters into their HTML Entities, meaning “&” would be encoded to &amp;, then rendered as the correct character by the browser.

This is where the_title_attribute() comes in.

the_title_attribute() basically does two things with your post title: it runs the title string through PHP’s stripslashes() (a common security procedure), then it gets sent through esc_attr() to encode illegal characters. The effective line in WordPress Core literally looks like this:

// From wp-includes/post-template.php
$title = esc_attr(strip_tags($title));

In the end, your post title is all cleaned up and rendered as valid HTML.

Proper Usage

<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute() ?>" ><?php the_title() ?></a></h2>

//Which will render
<h2><a href="http://my-website.com/dog-pony-show" title="Dog $amp; Pony Show" >Dog & Pony Show</a></h2>

Conclusion

the_title_attribute() is a little-known tool in the developer’s toolbox, but it sure is handy. Be sure to include it in your next Plugin/Theme files.

What other little-known helper functions do you know? Share them in the comments!

The First Step To Coding Like A Pro: Formatting

Standard

At its core, good formatting is more than putting a spit shine on your plugin or theme. Its something that is done from the moment you crack open that first blank text document and begin writing. Formatting is the practice of careful, conscious coding.

I interviewed for an awesome job last week. They were interested in me and wanted to see a code sample of my work. I didn’t have much that was ready for review (because I’ve been working in Front End Development for the last year), so I wrote a Plugin from scratch. I went 96 hours with only a couple of naps, working my hardest to crank out coding perfection. I threw in everything that I could think of: AJAX, OOP, Validation/Sanitization, Actions & Filters, the Settings API, even localization. When I was done, I proudly submitted it for review.

What was the reviewer’s response back to me? “Your code is sloppy.” In fact three-fourths of his comments related to tabs and spacing.

Why did he care so much about such small details? Once I took the time to think about it, the answer became obvious.

Why Formatting Matters

1. It makes your code better.

If your code is written to the correct standard, it has been written and reviewed with attention to detail. It takes several passes to get any file up to standard, and in the course of formatting, you’d be surprised how many bugs you can find. Reviewing your code means refining your code. To put it another way, I can’t imagine you’ll ever see beautiful code that throws lots of errors or breaks things.

Furthermore, organizing functions in a logical way helps you see new ways to write your program. It can show you places where you are repeating yourself, revealing good sections to turn into classes/methods. Don’t forget the DRY principle of programming: Don’t Repeat Yourself.

Good formatting includes commenting your code. It makes your work easy to navigate, allowing others to troubleshoot errors, as well as reminding you of whatever the heck you were doing during the late night coding binge when you wrote it. Well documented code is much easier to extend as well.

2. It makes you look better.

It requires a lot of discipline to write clean code, and it is quickly assumed that the author of organized, well-planned code is a person with an eye for detail. Adherence to coding standards demonstrates that you are well-versed in the language/platform you’re working with. Most of all, it shows that you care; if you’re going to put in the time to do excellent work, chances are you’ll do excellent work for a client or employer.

Principles of WordPress Formatting

So, what goes into good formatting? If we need to adhere to the standards, what are they?

First of all, go take a look at the WordPress Coding Standards Doc. There are four sections, one for PHP, HTML, CSS, and JavaScript. Take the time to review each document. Here are some highlights from the docs:

PHP Highlights

  • Indent your code, and use Tabs instead of Spaces
  • Include commas after the last items in arrays
  • No shorthand PHP tags
  • Read up on the section “Space Usage
  • Commenting/Documenting code. There’s a lot here about the PHPdoc format of commenting, the industry standard.

HTML in a Nutshell

CSS Notes

  • Each Selector should be on its own line
  • Use lowercase, hyphenated selectors (not camelCase or underscored)
  • Always end in semicolons (C’mon, folks, is it necessary to say this?)
  • Order Properties alphabetically

JavaScript Formatting

  • “Always put spaces on both sides of the opening and closing parenthesis of if, else if, for, forin, do, while, and switch blocks.”
  • Name functions and variables using camelCase, not underscores.
  • Use the var keyword as much as possible to keep variables out of the global scope
  • Never end an Object with a comma
  • jQuery and that pesky $

Best Practices

Some of these rules will be natural for you based on your background, but for those which aren’t, keep a list of important formatting points handy. Practice these standards in everything you write, no matter how seemingly insignificant, and they’ll become part of your personal style of coding.

Unless you’re still using NotePad, your IDE (text editor) should have some good tools to help you format your code correctly. Turn on syntax highlighting based on the language you’re using, and set your preferences to eliminate trailing spaces on save.

One of the best ways to clean up your code is to have it reviewed by others. Find some other WordPress geeks and review each other’s code. Be teachable. The process will be humbling, but it will grow you as a developer.

Conclusion

In the end, I got the job! When all was said and done, the reviewer was able to see past my amateur-ish-ness and see potential in my work. Good leaders acknowledge that this is a learning process for us all (In fact, in writing this post I’ve noticed a few things I need to go back and fix in my own code).

So what questions do you have about WordPress formatting? Do you have a horror story about ugly code? Leave a note in the comments!

How to Enqueue Scripts in WordPress

Standard

The right way to include javascripts in your theme isn’t by putting links like this in the <head> of your header.php:

<script type="text/javascript" src="yourscript.js"></script>

The right way to do it is to enqueue the scripts in your functions.php file like so:

function load_my_scripts() {

//don't use (deregister) WP's jQuery version
wp_deregister_script( 'jquery' );

//Use jQuery from Google Code
wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js');
wp_enqueue_script('jquery');

//Include one of my custom javascript files
wp_register_script('myscript', get_bloginfo('template_url').'/js/myscript.js', array('jquery'), '1.0', true );
wp_enqueue_script('myscript');

}
add_action('wp_enqueue_scripts', 'load_my_scripts');

When applied this way, your scripts will load in wp_footer() at the bottom of your pages, allowing the page to load before the scripts do.

For more detail, check out what the Codex has to say. Also, WP.TutsPlus has a related article, but the final code is a little wonky.