Zombie Pitfalls: Part II

I ran into a problem with connection refused (111) by zombie. And I was told by @havvg to do the following. This is adapted from @havvg gist. You can find his blog here too.

    zombie:
      auto_server: false

and

var net = require('net');
var sys = require('sys');
var zombie = require('zombie');
var browser = null;
var pointers = [];
var buffer = "";
 
net.createServer(function (stream) {
  stream.setEncoding('utf8');
  stream.allowHalfOpen = true;
 
  stream.on('data', function (data) {
    buffer += data;
  });
 
  stream.on('end', function () {
    if (browser == null) {
      browser = new zombie.Browser({ debug: true });
 
      // Clean up old pointers
      pointers = [];
    }
 
    eval(buffer);
    buffer = "";
  });
}).listen(8124, '127.0.0.1');
 
console.log('Zombie.js server running at 127.0.0.1:8124');

This works.

Another problem was that zombie was interacting with modernizr library:

"TypeError: Cannot set property cssText of [object Object] which has only a gettern    at Object.a (/js/libs/modernizr-1.7.min.js:2:2493)n    at Object.flexbox (/js/libs/modernizr-1.7.min.js:2:2595)n    at Object.<anonymous> (/js/libs/modernizr-1.7.min.js:2:7228)n    at Object.<anonymous> (/js/libs/modernizr-1.7.min.js:2:8964)n    in http://h.local/app_test.php/login"

I took away the library and of course it solved the problem.

Symfony2 Zombie Behat Pitfalls

While setting up node and zombie for my first time in ubuntu I ran into problems while installing node. I resolved my problems removing via apt-get node and then installing via git and checking out the stable version which is told us in the webpage for node. The instructions for compiling and for removing also were found here. After that I was able to finish this behat guide which is a good guide teaching some more stuff on doctrine for the steps and also some nice trick with the environment variable for environment dependable database selection.

// configuration
dbname:   %database_name%_%kernel.environment%
// cli sets the environment to test
... -e=test

And this other trick removing entity entries:

$this->getEntityManager()->remove($eachEntity);

Symfony2 TDD with Phabric: Series 3

On our previous blog post on phabric series 2 we saw how we could already set up a Symfony2 project that can capitalize on the advantages provided by phabric within a Symfony2 behat environment.

This time we are going to see a bit about how to work with Phabric. Working a bit more with the settings of Phabric we realize that it supports a lot of things but it does not support read of previously inserted values. At least currently it does not support that now, hopefully it will soon. Phabric’s work is to insert some data and work with it. This is call mapping of data in Phabric. Phabric maps data to a Phabric space where information is tracked. The main object is called Phabric bus from which all operations are performed and all Phabric entities are derived. Notice that Phabric entities are not Symfony2 entities. They have different roles although for configuration it sounds like they correlate one to one sometimes. For all we have said, if we consider existing data mapping in Phabric we realize read is not implemented in the adapter. There was a proposal to subclass the adapter, however we have not gone into it yet.

Persisting Relational Data
While persisting relational data, the important concept is that usually we always persist one main entity/table from which all other tables are but child tables that are related to the main parent table. In Phabric it is always best to think in terms of the main parent table while configuring things. This is important because as long as we get right the configuration for this main table, all the other configuration will follow without problems.
For instance let’s take a look at the main configuration for a main entity `class` and a derived entity `student`. We usually have an entity class with a related column for that table giving the name of the class. However there are some instances where there will be no class name to be set depending on the specifications. In that case we set the `nameCol` to `NULL`. The related entity is `student` and for that we require a transformation to get the `id` of the related object on the derived table (notice the STUDENTLOOKUP closure defined later).

'class' =>
    array (
        'tableName' => 'class',
        'primaryKey' => 'id',
        'nameCol' => NULL,
        'nameTransformations' =>
            array (
                'Class Start' => 'class_start',
                'Student' => 'student_id',
            ),
        'dataTransformations' =>
            array (
                'student_id' => 'STUDENTLOOKUP',
            ),
        ),

After we are done with the main configuration we can proceed to fill the other configuration for student entity which is much simpler. On the Gherkin side, the scenario would provide the `student` table first and then the main table for `class`. It is important to have both of these tables and in that order because of the Phabric mapping.

  Background:
    ...
    And The following student exists
    | Student Name | Student Grade |
    | John Smith   | F             |
    And The following class exists
    | Student     | Class Start |
    | John Smith  | Summer 2011 |
    ...
 
  @insulated @passing
  Scenario: Do something else
    Then ...

You can see above that the Student column on the parent table below needs to be mapped to student_id, then searched with that name, now turned into an id, across the child table and its value returned. This thing happens whenever there is such a relationship between tables. This operation must be achieved with a data transformation closure as follows:

$this->phabric->addDataTransformation(
    'STUDENTLOOKUP', function($studentName, $bus) {
        $ent = $bus->getEntity('student');
        $id = $ent->getNamedItemId($studentName);
        return $id;
    }
);

We have used a behat background block since this sets up the scenario background common for our set of scenarios for that feature. And finally don’t forget to use the insert operation within the step definition on the Feature Context for the entity we have inserted above:

$this->phabric->insertFromTable('class', $table);

I would like to thank my friend Marco Pivetta for his patient guidance and brainstorming.

If this has helped you, please consider donating.

Symfony2 TDD with Phabric: Series 2

Continuing with our series. We have seen in the last episode of this series, namely here, that we wish we could have a simpler configuration for getting phabric into our BDD flow within Symfony2 development.

This time we will go ahead and setup Phabric in a “standalone” fashion. And will try to reuse a lot of what symfony2 has already done for us and that we don’t need to setup again and again.
First we start setting phabric repository into our dependency file deps. We insert the following and we don’t need to get its dependencies of phabric since these are gotten already by symfony2 for us on the autoload.php file and also together with the bundles already registered on the AppKernel.php.

// deps
[Phabric]
    git=https://github.com/benwaine/Phabric.git
    target=/Phabric
 
// autoload
'Phabric'          => __DIR__.'/../vendor/Phabric/lib/',

We are now interested in reproducing the long setup given on the readme.md of the phabric repo but using the symfony2 advantages. For that we would like for now hard code our entities definition since this is going to be done ultimately done by @everzet on the BehatBundle. What @everzet will do is to add the phabric specific configuration parameters so they can read from config_test.yml which is symfony configuration file for tests. The inclusion of these parameters will allow us to call $parameters = $kernel->getParameters(); from within the FeatureContext class so we can pass in turn these to the Phabric bus class. He [@everzet] can of course choose to even better inject the Phabric bus class to the container so that it automatically fetches our database parameters and so all the setup could be done on the config_test.yml under the main behat keyword. Of course options should be set for different database names so that we can have a database for testing and database for other purposes or for different test scenarios. For now we have just chosen to hard-code our parameters at the level of entity definitions.
So after doing in the constructor for the FeatureContext a:

var_export($parameters['Phabric']['entities']);
die();

We get the format we need to follow to hard-code the $parameters_temp:

$parameters_temp =
array (
  'event' => 
  array (
    'tableName' => 'event',
    'primaryKey' => 'id',
    'nameCol' => 'name',
    'nameTransformations' => 
    array (
      'Date' => 'datetime',
      'Desc' => 'description',
    ),
    'dataTransformations' => 
    array (
      'datetime' => 'UKTOMYSQLDATE',
    ),
  ),
  'session' => 
  array (
    'tableName' => 'session',
    'primaryKey' => 'id',
    'nameCol' => 'session_code',
    'nameTransformations' => 
    array (
      'Session Code' => 'session_code',
    ),
  ),
  'attendee' => 
  array (
    'tableName' => 'attendee',
    'primaryKey' => 'id',
    'nameCol' => 'name',
  ),
  'vote' => 
  array (
    'tableName' => 'vote',
    'primaryKey' => 'id',
    'nameCol' => NULL,
    'nameTransformations' => 
    array (
      'Attendee' => 'attendee_id',
      'Session Code' => 'session_id',
    ),
    'dataTransformations' => 
    array (
      'attendee_id' => 'ATTENDEELOOKUP',
      'session_id' => 'SESSIONLOOKUP',
      'vote' => 'UPDOWNTOINT',
    ),
  ),
);

Now on your FeatureContext.php class:

$this->doctrine = $this->getContainer()->get('doctrine');
$this->db = $this->doctrine->getConnection();
$datasource = new \Phabric\Datasource\Doctrine($this->db, $parameters_temp);
$this->phabric = new Phabric($datasource);
$this->phabric->createEntitiesFromConfig($parameters_temp);

This let us all setup to continue to develop with our behat and phabric setup all under symfony2. Hope you appreciate this blog post and please donate. Thanks!

GitHub Flow vs. Git-Flow for Symfony2: Brain Storming

I have been thinking about the implications that the git flows GitHub Flow and Git-Flow have in terms of TDD development. I have even been thinking in adapting PHPAutotest to integrate with git a little bit better. The automation of tests to make a red green are there already however there should be an easier prompt for “new feature to implement”-type of branch mechanism that can help adopters of each flow. The idea is to boost the work while using git and TDD techniques, especially in Symfony2 :) . Seeking for ideas are you up to it too? Please provide comments below. Thanks!

Symfony2 TDD with Phabric: Series 1

I have read a bit about Phabric. Phabric responds to the need of further controlling data setup on behat scenarios at a high level of abstraction. Basically it is the doctrine:fixtures:load of behat or more properly it is the tdd version of that turning gherkin tables into database data.

The discussion is here for the first issue filed when Phabric saw the light. Once the Behat conditional dependency is included into BehatBundle we would be able to load the Phabric too within our Symfony2 project. Implementing a Symfony2 bundle ourselves would involve that we have to pass by injection a service into the Behat context. That may result in more difficulties at this time.
https://github.com/benwaine/Phabric/issues/1

Thinking in how it could be done, perhaps, first we can unfold this as adding a regular dependency. That is basically modifying the xml file for Behat, however that is sourced by BehatBundle from the Behat behat.xml.
There is another xml file for services that is loaded here.
So I wonder if we could use this to insert that dependency? What other further modifications would need to take place.
It would be great to develop an example for how to make these guys play together within Symfony2.

Until next time for part 2.

Symfony2 Integrated TDD: TestBundle

Introducing TestBundle[1], a Symfony2 bundle that integrates TDD methodology for the main frameworks Behat, PHPSpec, and PHPUnit into one development tool. It is created to foster the BDD methodology into Symfony2 app development.

Instructions to install:

// AppKernel.php
php new Cordova\Bundle\TestBundle\CordovaTestBundle(),
 
// autoload.php
    'Cordova'          => __DIR__.'/../vendor/bundles',
 
// deps
[PHPAutotest]
    git=https://github.com/Programania/PHPAutotest.git
    target=/PHPAutotest
[TestBundle]
    git=https://github.com/cordoval/TestBundle.git
    target=/bundles/Cordova/Bundle/TestBundle
 
// update
bin/vendors update
 
// creates autotest.phar
cd vendor/PHPAutotest
./compile

And here is its usage:

php app/console test:auto vendor/PHPAutotest/demo/Behat/features/minesweeper.feature

What can you do with it?
Well it depends how well one knows the integration of all the frameworks. Basically this bundle currently exploits PHPAutotest[2] and brings it into Symfony2 framework developers to foster new ways of automation and aid in the TDD task. There is a sweepminer’s example you can try and I am working on bringing more information into testing it with a complete integrated flow from start to end.

Contribute
If you have further ideas of how much more this bundle can include you are welcome to post below on the comments. And if you would like to boost development of this bundle then please donations are a strong motivation (see link above).

Praise the Lord Jesus Christ!

References:
[1] TestBundle Repository.
[2] PHPAutotest Tool Repository intro.

New Friend on the TDD Block: PHPAutotest with Behat and et al

So here I will present a snapshot of what it looks like to work with PHPAutotest:

./autotest.php behat demo/Behat/features/minesweeper.feature

Then we shall see:

And the icon on the right corner notifying the current test is passing:

Should we change and save file or press ‘r’ on the terminal we would get a red non passing test:

The little gadget will wait for you to fix this on your next iteration:

credits to its authors at https://github.com/Programania/PHPAutotest.

PHPSpec Autorun-Test Notifier

This article here basically tells us to do:

sudo apt-get install libnotify-bin

This other article pushes us to install also:

sudo apt-get install inotify-tools

Now we would like to modify the basic phpunit monitor script autotest-phpunit in a way that works for phpspec command. Wow after a whole day of work we end up collaborating on a github project and the result was:

https://github.com/Programania/PHPAutotest

Now you can ejoy all the flavors! And you are welcome to participate. We are now working on a bundle version.

Behat + Symfony 2 Secret: How To Subcontext MinkContext

Update: Check comments for solution. Thanks everzet.

Behat is a scenario framework. It means that you can describe scenarios for the interaction between user and the browser and use those as your acceptance criteria. A scenario is basically a telling of what is to happen (then), in which circumstances it is going to happen (given), and what is causing the thing that is going to happen (when).

Put it the other way around, in each scenario, and there can be as many as needed, there is a set of steps to be taken for setting things up (given), for acting things that cause things to happen (when), and for describing things that should happen (then).

Each scenario comprises several steps that are described in a human like language. The specification can then be run without a problem, however, there is no way to make the web application at hand what the words of a step mean unless they are tied to the browser on which the web application is running. The link between browser and human like language steps is called a step definition, step description, or is also called step contextualization. It contextualize the human steps by interpreting the human like language steps and determining the manner in which they are run into code that controls a browser client driver.

Behat allows to have multiple ways of interpreting steps. These ways or manners of interpreting are called contexts. So contexts hold rules for interpretation or also called step definitions. In order to set all the interpretation rules straight Behat allows for organization contextualizing and grouping certain rules for certain contexts and using them when needed.

The use case for multiple contextualization can be seen this way. Imagine an app that reacts differently for different type of users. Say the app behavior is similar to all, but the interaction is different. Some users like to do a lot of clicks on some things a certain way, using links a certain way, reset their password, or contact support through specific channels or even chat a certain way. Even more simple, imagine that a user uses the accessibility features of a site for blind users and the regular user use the regular features of a site for people that can see. These are two different contexts. A step can be for instance: “When I login”. Both user blind and no blind will login eventually. However, the interpretation of the same step will take different routes. One will touch the screen or type whereas perhaps the other will speak up or trigger some actions that end up in the same action, that is log in.

Mink comes with a context of its own premade and home cooked. Moreover Behat allows us to use multiple contexts as subcontexts from a top root FeatureContext file. This post is about showing how to make use of subcontexts and how to instantiate MinkContext as one of those subcontexts we can use.

So in our FeatureContext class we have the following:

class FeatureContext extends BehatContext
{
    public function __construct(array $parameters) {
        $this->useContext('clicking', new ClickingContext($parameters));
        $this->useContext('dropoff', new DropoffContext($parameters));
        $this->useContext('mink', new MyMinkContext());
 
    }

And we create a MyMinkContext class like:

class MyMinkContext extends MinkContext{
 // your step definitions here
}

Notice we are extending our homemade class from MinkContext. And we are using it as subcontext since we aliased it to ‘mink’ above. The usage of how to get to methods/steps defined in the context is shown elsewhere in other posts of this site and on the Behat documentation.

The idea shown here is that the organization for contexts and subcontexts fosters horizonal reusability before we get traits on php5.4. What this means in terms of application development? It means that one can organize contexts and run multiple context-based scenarios, do comparisons for certain usage cases through different patters of usage, etc.

Update: This warning is wrong.
Warning: It is important for reason of updating that you use Behat classes on your use clauses when coding. If you use BehatBundle or other can give you problems. So unless otherwise said, use the Behat classes.

Adapted explanation by everzet:
BehatBundle makes Behat to inject Kernel instead of parameters array into context constructor by default, whereas Behat creates context with array of context parameters.
In addition to this there is more information related to the use of methods for different contexts, especially the methods MinkContexts brings into the table. Therefore there are 3 ways of doing this:

1) add mink-related steps in MinkContext child
2) record newly created MinkContext in your FeatureContext instance variable, so you'll have access to it's methods (like getSession()) later
3) use getMainContext()->getContext('MINK_CONTEXT_ALIAS')->getSession

So here we give example of what we have been talking about implementing a nice aliasing taken from here:

<?php
 
namespace Acme\DemoBundle\Features\Context;
 
use Behat\BehatBundle\Context\BehatContext,
    Behat\Behat\Exception\PendingException;
use Behat\Gherkin\Node\PyStringNode,
    Behat\Gherkin\Node\TableNode;
 
/**
 * Feature context.
 */
class FeatureContext extends BehatContext
{
    /**
     * BehatBundle's main context constructor gets
     * KernelInterface instance as single parameter
     */
    public function __construct($kernel)
    {
        // Instantiate and use BehatBundle's MinkContext with provided $kernel
        $this->useContext('mink', new MyMinkContext($kernel));
    }
 
    /**
     * Get Mink session from MinkContext
     */
    public function getSession($name = null)
    {
        reutrn $this->getSubcontext('mink')->getSession($name);
    }
}

And the MyMinkContextClass here:

<?php
 
namespace Acme\DemoBundle\Features\Context;
 
use Behat\BehatBundle\Context\MinkContext as BaseMinkContext,
    Behat\Behat\Exception\PendingException;
use Behat\Gherkin\Node\PyStringNode,
    Behat\Gherkin\Node\TableNode;
 
/**
 * Mink-enabled context.
 */
class MyMinkContext extends BaseMinkContext
{
}

And here I just dump a very good explanation on all the details seen so far and problems I ran into:

Explanation: https://github.com/Behat/Mink/issues/68#issuecomment-1797567

If you use BehatBundle – use it’s contexts. If you don’t use BehatBundle – use Behat or Mink context as parent. Where’s the confusion???

The main difference between them is that BehatBundle’s contexts gets kernel instance injected into constructor instead of array of parameters. That’s all. BehatBundle provides extensions for both MinkContext and BehatContext which:

Gets kernel instead of array of parameters into __constructor()
Gets services out of service container (bound to kernel) instead of instantiating them by hands
Gets parameters out of service container (bound to kernel) instead of maintaining them by hands
That’s all.

So, if you use BehatBundle – extend Behat\BehatBundle\Context\BehatContext, it’ll give you access to kernel and container in child class. BUT don’t forget to provide kernel instance into it’s constructor.

Behat provides BehatContext with basic functionality
Mink provides MinkContext layer on top of the BehatContext functionality
BehatBundle overrides both BehatContext and MinkContext with kernel, container and services knowledge, so you can talk with your Symfony2 app through them
Also, in counterpart with Behat\BehatBundle\Context\BehatContext, which does nothing except defining some helper methods, Behat\BehatBundle\Context\MinkContext describes step definitions and hooks, needed for Mink. And as you remember – you can’t have 2 same definitions in suite. So, you can extend OR use Behat\*\Context\MinkContext only once!

Hope you have enjoyed this post, if you feel like so please donate. Thanks!