Unit testing plugins: The 5 W's and an H

  • 2,263 views
Uploaded on

WordCamp Chicago 2013 presentation

WordCamp Chicago 2013 presentation

More in: Technology , Business
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,263
On Slideshare
0
From Embeds
0
Number of Embeds
5

Actions

Shares
Downloads
0
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • Welcome to Plugin Unit Testing, The 5W’s and one H.Since I know many of you will feel the urge to tweet during this talk I encourage you to do so. In fact I’ve taken the liberty of suggesting a hashtag for this presentation. Feel free to use it.
  • So let’s start with the first W, Who.
  • I won’t bore you with the details of my life story but as far as my involvement with WordPress;How many of you had a blog on blogger?I began blogging in 2004 with a blogger blog and eventually wanted to have my own domain and more control. So in late 2007 / early 2008 I moved to self hosting and began using WordPress 2.3. My progression to WP developer mirrored that I think of most people at the time, I simply wanted to make changes to my theme and add features. Beginning there I transitioned that knowledge into building themes as a freelancer. I found out rather quickly that I hated trying to create designs, which was fortunate because I sucked at it. What I did love though was working on themes that allowed me to create unique functionality, or at least functionality that I hadn’t done before. That lead me into breaking down pieces of functionality into plugins and my eventual desire to do nothing but plugin development when it comes to WordPress. I eventually moved from freelancing to working for agencies and presently I work for The Nerdery as a PHP developer with a WordPress primary.
  • The second W, What?
  • So what are we going to talk about today. My hope, is that after you leave here today you’ll realize that unit testing can improve your plugin development, allow for easier upgrades when WordPress comes out with a new version, and overall just write better code.In order to make all the magic work we do have a few pre-requisites. Obviously since were unit testing we’ll need PHP Unit. The WordPress test suite so we can do our WordPress integration, and some extra files within our plugin that allows it to integrate with the test suite.The way you setup your testing environment is entirely up to you. One thing to keep in mind about the WordPress test suite, is that tests are written to work with trunk. This does not mean you have to use trunk when doing plugin testing, just be aware that if you attempt to run the WordPress core unit tests on an install other than trunk, you will often see failed tests. This is due to trunk having testable functions that may not be present in the stable public version. Since your plugin will be meant for use on the version you choose, this won’t be a problem as you won’t be using functions that aren’t available to you.The install and setup of the testing environment can be accomplished in two ways. Automated, and manually. If you are a WP-CLI user testing can be setup via command line that will both download the WordPress Test Suite and create a plugin template for your use.
  • Moving onto the 3rd W, Where?
  • So let’s dig in: Here is the make wordpress page that will help guide you in the setup of the core test suite. I’m not going to make you watch me setup the environment since it would take a while to download everything and configure but we can go through the commands for future reference.
  • First we need to checkout the latest version of the test suite via svn and install it into a directory. In this case I’ve chosen “wp-tests”. You can name the directory whatever you’d like, this is just what I use.
  • You don’t want to forget this next step. When the test suite is run it will expect a database to be setup with a specific set of data for comparison. You don’t want to wipe out what your doing so give the test suite it’s own database.This represents a departure from what would be considered normal PHP Unit Testing. Although a database can be used, a popular methodology uses mock objects to represent database data and run tests against it.For our WP test suite though, we’ll stick with what WordPress does and use the mysql database.
  • The plugin testing skeleton is provided by the fine folks who gave us the wordpress command line utility. This github repo contains a copy of the output files generated by the command line tool for those times when you choose to go the manual setup route which were following here. This skeleton gives you everything you need to get yourself up and running. It includes the prerequisite bootstrap files, tests folder and gives us a nice structure. So let’s cover the config setup.
  • TestsconfigBootstrap setup
  • I personally don’t use WP-CLI in my workflow as it doesn’t fit our structure at work, but I’ve lifted the code from their website here.The first command will add the WordPress test suite and setup the configuration.Next you create a database for the test suite to use.
  • The 4th W is When.When should we do unit testing of our plugins?
  • How about Always?
  • Ehh, maybe.So I’m going to have plenty of people in this room who will probably disagree with me on this point. And all of them will more than likely have valid arguments. But to be honest I’m more of a pragmatist when it comes to this and not so much of a purist. Do I think you should be doing it everytime, yes. Do I think it’s practical? No.Although I hope you can take some knowledge from this talk and incorporate it into your daily workflow, we all know that isn’t necessarily feasible. There are plenty of factors to consider, if your dealing with clients there is the budget issue vs. the complexity issue. The more complicated the functionality, the more likely you should be writing unit tests. The time it costs you on the front end writing the tests, will save you on the backend when you’d normally be troubleshooting bugs.If your writing the plugin for use in the WordPress repository, then you 100% should be writing tests for your code, there is no reason not to. In fact it would be nice if tests were required for submission to the repository so we wouldn’t run into the problem of plugins breaking, or uncertainty as to whether a wordpress version is supported.If your writing the plugin for a side project, or as a premium plugin, then yes 100% of the time, write tests.
  • Code coverage comes into play as well. 100% coverage may not be needed depending on complexity, but I’m of the mindset that if you can, then you should.
  • And the last W, why?Why do we write unit tests
  • Easier bug fixingSo how are you currently testing your code if your not using unit tests?Do you have a testing script written out with steps to follow so all your features are covered?What’s that process look like, load the site in a browser, view the functionality in different scenarios and data sets?How long does that take?These are “almost” all questions you can eliminate via unit testing. With proper code coverage you can pinpoint the exact function call causing the problem and get it resolved quicker and retested much quicker than doing it the manual way. It only takes a few seconds to run a test, it might take you a half hour to step through a manual testing scenario.I’d suggest that whenever a new version of WordPress reaches the release candidate phase that you load it up and run your tests. Continue this with each itteration and when it’s launched as stable you’ll be confident in knowing that none of your users will have issues.
  • Cleaner Code
  • Maybe.I added the maybe to this one, because your bad coding habits are going to be your bad coding habits. There are plenty of benefits to thinking about your tests before you write any code at all. You can take a TDD or Test Driven Development approach and in fact write all of your tests before writing a single piece of actionable plugin code. Deciding whether to do this is personal choice. It’s perfectly fine to write the plugin and then go back and write tests as well. Whatever fits your mind set, is what you should do. One of the things that unit testing does bring into the forefront though is dependency injection. Making sure your functions are written as silos, where everything the function needs is passed into it. WordPress can make this difficult though. There are times you need to rely on globals, or perhaps your calling a WordPress function within your function that is going to give you some data. There are always going to be gotchas to think about.
  • Architecture is something I think most coders struggle with. It seems that no matter how much planning you put into it, there always seems to be something that could be done better. I myself will sometimes fall into the trap where I believe I’ve got a good game plan in my head so I just jump right in and start coding. When this happens I always spend more time refactoring, or maybe missing a minor detail of the project scope where I then have to go back in and add it. If you go in with the mind set that you need to have your code test ready, you will find that you start considering things a bit more carefully.
  • That brings us to the How,To use a real world example we’re going to work with a plugin that I wrote while working for a former employer about a year and a half, two years ago. We kept needing to have about us pages with employee bios listed and my go to solution was to use WordPress users and add images. Unfortunately the content people wanted greater flexibility and didn’t want to have to mess with using WordPress roles. So I came up with a simple plugin called Employees On Parade. That company has since closed it’s doors and I was given rights to take any code I’d written for my own use. I’ve been meaning to rewrite the plugin and put it in the repository but hadn’t gotten around to it. So here’s my opportunity.
  • So what are the things we need to do, to make this plugin meet our goals.There is other functionality as well but for our purposes we’ll try to get through these before time runs out.

Transcript

  • 1. Plugin Unit Testing The 5 W’s and one H
  • 2. Tweet? #omgunittestingforwordpressismindbogglingeas yandwhenigethomeiwillincorporateitintomyexist ingworkflow
  • 3. WHO? Tom Jenkins @techguytom tdjenkins techguytom
  • 4. WHAT? Unit Testing a plugin? • PHP Unit https://github.com/sebastianbergmann/phpunit/ • WordPress Test Suite https://unit-tests.svn.wordpress.org/trunk • Base Plugin Setup https://github.com/wp-cli/sample-plugin or WP-CLI http://wp-cli.org/
  • 5. WHERE? Test Suite Requirements: http://make.wordpress.org/core/handbook/automated-testing/
  • 6. WHERE? Test Suite Requirements: http://make.wordpress.org/core/handbook/automated-testing/ From a directory of your choice: 1) svn co https://unit-tests.svn.wordpress.org/trunk wp-tests
  • 7. WHERE? Test Suite Requirements: http://make.wordpress.org/core/handbook/automated-testing/ From a directory of your choice: 1) svn co https://unit-tests.svn.wordpress.org/trunk wp-tests 2) Create a new MYSQL database
  • 8. WHERE? Test Suite Requirements: http://make.wordpress.org/core/handbook/automated-testing/ From a directory of your choice: 1) svn co https://unit-tests.svn.wordpress.org/trunk wp-tests 2) Create a new MYSQL database 3) Add the plugin testing skeletonhttps://github.com/wp- cli/sample-plugin
  • 9. WHERE? WP-CLI # Initialize the testing library wp core init-tests ~/svn/wp-tests --dbname=wp_test --dbuser=root -- dbpass=asd mysql -u'root' -p'asd' -e 'CREATE DATABASE IF NOT EXISTS wp_test' # Generate the plugin files wp scaffold plugin sample-plugin # Run the tests cd wp-content/plugins/sample-plugin WP_TESTS_DIR=~/svn/wp-tests phpunit
  • 10. WHEN? Always?!?
  • 11. WHEN? Always?!? Ehh, maybe
  • 12. WHEN? Code Coverage Do we need 100%?
  • 13. WHY? • Easier bug fixing
  • 14. WHY? • Easier bug fixing • Cleaner code
  • 15. WHY? • Easier bug fixing • Cleaner code, maybe?
  • 16. WHY? • Easier bug fixing • Cleaner code, maybe? • Better Architecture
  • 17. HOW? Employees On Parade • Custom Post Type (Employee) • Custom Taxonomy (Departments) • Custom Meta Fields (Title, Email, Phone, Bio) • Shortcode (For displaying employees) • Template Tag (For displaying employees)