Sunday, September 18, 2011

Pfcongres 2011 wrap up

This Saturday I started early to go to Pfcongres, a small PHP community conference in Utrecht organized by the Dutch PHP user group PHPFreakz and after about two hours driving I arrived about half an hour in time before the conference started, with me kick starting with my keynote "Community Works", a 199 slide deck explaining what the PHP community is and how people can be part of that community.

My keynote was well received by the audience, although some comments were made it needed a more elegant flow of community tips. It even started a discussion whether I should use visuals or not to emphasize my words. I will take these comments into consideration when I'm reviewing these slides.

Although I spend a major part of the conference in the so-called "Hallway tracks" I was able to jump into a couple of great talks that have intrigued me to look into their details. A couple of tracks that really stood out were "SPL Data Structures and their Complexity" by Jurrien Stutterheim, "15 Protips for MySQL users" by Joshua Thijssen and of course the closing keynote "PHP — Status Check" by no one less than co-founder of Zend Mr. Zeev Suraski.

The good
The team of PHPFreakz managed to do the impossible: creating a good balance for Dutch and non-Dutch speakers, offering a good lunch (especially for Dutch standards) with a wide variety of sandwiches and a constant flow of good coffee.

The bad
I have no complaints regarding the organization, the audience or the venue. I just felt bad I had to wake up at 6am just to be there on time.

The ugly
The venue's wifi was a real burden, and I know from experiences that most conference wifi settings are flakey as a rule, but this wifi experience was bad, even considering the flakey ones.

Conclusion
This conference showed the world again that a small community group can amaze everyone by bringing quality speakers into their community offering them high level content at a really reasonable prize. I'd like to express my gratitude to the organization to be part of this event.

Bonus challenge
I keep thinking about what Joshua Thijssen said during his talk about getting certified as a MySQL engineer. As it was on my to-do list for a couple of years, I think I needed the push Joshua had given me to follow up on my commitments and schedule an exam.

Thursday, September 15, 2011

Quality Assurance on PHP projects - PHPUnit lessons learned

This is what I like about the PHP community: people work out similar ideas and share what they've learned in the process. Sometimes people pick up ideas and work them out, sometimes people just continue the conversation.

And I believe Lars Tesmer has done the latter, where he blogs on testing PHPUnit itself and the lessons learned in that process.

Thank you Lars for sharing your lessons.


Saturday, September 03, 2011

Quality Assurance on PHP projects - PHPUnit part 4

     In parts one, two and three we focussed on writing tests for a game of tic-tac-toe, with in parts two and three we optimized our tests so they focus on the functionality of the individual parts Grid and Player, with a collection class Players to handle Player objects.

In this fourth part we should focus on playing the game. Let's go over the steps again:

  • each player chooses a symbol
  • for each turn (max 9 turns)
    • a player places his symbol on the grid
    • if 3 symbols appear in a single row (horizontal, vertical or diagonal)
      • player is a winner
So this is a simple and a straightforward rule we can turn into code. But let's look at the tests we've written in part 1 to see if they're still valid.
    public function testGameCanBePlayed()
    {
        $playerX = $this->_ttt->getPlayers()->seek(0)->current();
        $playerO = $this->_ttt->getPlayers()->seek(1)->current();
        
        $this->assertFalse($this->_ttt->play(0, 0, $playerX));
        $this->assertFalse($this->_ttt->play(0, 1, $playerX));
        $this->assertTrue($this->_ttt->play(0, 2, $playerX));
        
        $this->_ttt->setGrid(new Grid());
        
        $this->assertFalse($this->_ttt->play(0, 0, $playerX));
        $this->assertFalse($this->_ttt->play(1, 0, $playerX));
        $this->assertTrue($this->_ttt->play(2, 0, $playerX));
        
        $this->_ttt->setGrid(new Grid());
        
        $this->assertFalse($this->_ttt->play(0, 0, $playerX));
        $this->assertFalse($this->_ttt->play(1, 1, $playerX));
        $this->assertTrue($this->_ttt->play(2, 2, $playerX));
        
        $this->_ttt->setGrid(new Grid());
        
        $this->assertFalse($this->_ttt->play(0, 2, $playerX));
        $this->assertFalse($this->_ttt->play(1, 1, $playerX));
        $this->assertTrue($this->_ttt->play(2, 0, $playerX));
    }
As you see, we only tested the functionality to see if we can have a winner when 3 identical symbols appear in a single row horizontal, vertical or diagonal. We can make a couple of comments on this test:
  • this test is named wrong as it doesn't test the gameplay functionality
  • this test should be branched out into different tests for each row
  • this test doesn't test turn-by-turn game play
In other words, we need to clean this up and come up with better tests! Let's focus on tearing this test into 3 separate tests, testing just a single direction. Again, we can use a dataProvider method for this.
    public function rowColProvider()
    {
        return array (
            array (array (array (0,0), array (0,1), array (0,2))),
            array (array (array (0,0), array (1,0), array (2,0))),
            array (array (array (0,0), array (1,1), array (2,2))),
            array (array (array (0,2), array (1,1), array (2,0))),
        );
    }
    /**
     * @dataProvider rowColProvider
     */
    public function testGameplayCanDetectWinner($rowCols)
    {
        $player = $this->_ttt->getPlayers()->seek(0)->current();
        $this->assertFalse($this->_ttt->play($rowCols[0][0], $rowCols[0][1], $player));
        $this->assertFalse($this->_ttt->play($rowCols[1][0], $rowCols[1][1], $player));
        $this->assertTrue($this->_ttt->play($rowCols[2][0], $rowCols[2][1], $player));
    }
Now we know that with each turn, the return value will indicate if we have a winner (TRUE) or not (FALSE). But we still need to see if we can have the same result when playing with two players. As you see with the last line, the third entry gives us a positive result.

But we still don't have a gameplay going! We need to have two players enter the arena and each player playing turn by turn. So how do we approach this? Well, the easiest way for now is to create a test that does just that. The benefit here is we can decide which player is going to win the game.
    public function testGameCanBePlayed()
    {
        $playerX = $this->_ttt->getPlayers()->seek(0)->current();
        $playerO = $this->_ttt->getPlayers()->seek(1)->current();
        $this->assertFalse($this->_ttt->play(0, 0, $playerX));
        $this->assertFalse($this->_ttt->play(0, 1, $playerO));
        $this->assertFalse($this->_ttt->play(1, 1, $playerX));
        $this->assertFalse($this->_ttt->play(2, 2, $playerO));
        $this->assertFalse($this->_ttt->play(1, 0, $playerX));
        $this->assertFalse($this->_ttt->play(2, 0, $playerO));
        $this->assertTrue($this->_ttt->play(1, 2, $playerX));
    }
Visual this result looks like the following grid:
 X | O |   
 X | X | X 
 O |   | O 
But most importantly our tests are still green, giving us that wonderful feeling of achievement.

Let's finish up our tests so we can see no one can play any further after we've got a winner. PHPUnit provides a nice anotation we can use for this: depends. So now we can test that the game is stopped, depending on our test "testGameCanBePlayed".
For this to work, we need to return our game (in this case $this->_ttt). Just add the following line at the bottom of the test class "testGameCanBePlayed".
    public function testGameCanBePlayed()
    {
        $playerX = $this->_ttt->getPlayers()->seek(0)->current();
        $playerO = $this->_ttt->getPlayers()->seek(1)->current();
        $this->assertFalse($this->_ttt->play(0, 0, $playerX));
        $this->assertFalse($this->_ttt->play(0, 1, $playerO));
        $this->assertFalse($this->_ttt->play(1, 1, $playerX));
        $this->assertFalse($this->_ttt->play(2, 2, $playerO));
        $this->assertFalse($this->_ttt->play(1, 0, $playerX));
        $this->assertFalse($this->_ttt->play(2, 0, $playerO));
        $this->assertTrue($this->_ttt->play(1, 2, $playerX));
        return $this->_ttt;
    }
And the next step is simple:
    /**
     * @depends testGameCanBePlayed
     * @expectedException RuntimeException
     */
    public function testGameStopsAfterWinning($game)
    {
        $playerO = $game->getPlayers()->seek(1)->current();
        $game->play(2,1, $playerO);
    }
In order for this test to succeed we need to add a couple of things to our game:
  • a status property that will tell us if there's a winner
  • a setter method to flip the flag once a winner is detected
  • a checking method to verify a winner is not yet detected
  • modify our play method so it throws a RuntimeException when we try to play when a winner exists.
<?php
...

class Tictactoe
{
    ...

    /**
     * Status indicator to say there's a winner or not
     * 
     * @var bool
     */
    protected $_winner = false;

    ...

    /**
     * Sets a flag to indicate this game has a winner
     * 
     * @param bool $flag
     * @return Tictactoe
     */
    public function setWinner($flag = true)
    {
        $this->_winner = $flag;
        return $this;
    }
    /**
     * Checks if the game has a winner
     * 
     * @return bool
     */
    public function hasWinner()
    {
        return $this->_winner;
    }
    /**
     * Plays the game and returns TRUE if a player has become a winner, FALSE
     * if the player is not (yet) a winner.
     * 
     * @param int $row
     * @param int $column
     * @param Player $player
     * @return bool
     * @throws RuntimeException
     */
    public function play($row, $column, Player $player)
    {
        if ($this->hasWinner()) {
            throw new RuntimeException('Game already has a winner');
        }
        $this->getGrid()->setSymbol($row, $column, $player->getSymbol());
        return $this->isWinner($player);
    }
    /**
     * Returns TRUE if a player has become a winner, FALSE if not.
     * 
     * @param Player $player
     * @return bool
     */
    public function isWinner(Player $player)
    {
        if ($this->getGrid()->inRow($player->getSymbol())) {
            $this->setWinner();
            return true;
        }
        if ($this->getGrid()->inColumn($player->getSymbol())) {
            $this->setWinner();
            return true;
        }
        if ($this->getGrid()->inDiagonal($player->getSymbol())) {
            $this->setWinner();
            return true;
        }
        return false;
    }
}
That's it. We covered the main purpose of the game and we did it semi test driven. We can start playing a cute little game of Tictactoe and covered a couple important features of PHPUnit. I also showed that it's not a bad thing if you modify parts of your tests to achieve new or other specifications.

The full game source code can be found on my github account (https://github.com/DragonBe/tictactoe), and as you go over the log, you can follow along with these series as well. When playing with the source code, you might think about testing edge cases: playing 9 rounds and no winner, try to place a symbol off the grid, place twice a symbol on the grid of a single player (cheating), and so on.

Another thing could be that you turn this little game into an online game. What are the things you need to concider in that situation. Are our tests still valid or do we need to modify our architecture and our tests to support that kind of game playing?

Since it's on GitHub, you can fork it and send me a pull request once you have an edge case figured out.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License.