Skip to content

Instantly share code, notes, and snippets.

@pix-art
Last active October 12, 2015 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pix-art/01ce4f80e965ff3e414b to your computer and use it in GitHub Desktop.
Save pix-art/01ce4f80e965ff3e414b to your computer and use it in GitHub Desktop.
Custom faker context with extra logging on failure
<?php
namespace FrontendBundle\Features\Context;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Behat\Gherkin\Node\TableNode;
use Behat\Symfony2Extension\Context\KernelAwareContext;
use Behat\Symfony2Extension\Context\KernelDictionary;
use Faker\Factory as FakerFactory;
class FakerContext implements KernelAwareContext
{
use KernelDictionary;
const GENERATE_TEST_DATA_REGEX = '~\[([$a-zA-Z0-9]+)=([a-zA-Z]+)(\(([,\'" 0-9a-zA-Z:-]+)\))?\]~';
const GET_TEST_DATA_REGEX = '~\[([$a-zA-Z0-9]+)\]~';
protected $_generatedTestData;
protected $_faker;
/**
* @BeforeScenario
*/
public function setUp($event)
{
$this->_generatedTestData = array();
}
/**
* @AfterScenario
* If tests fail we want to log the current faker context so we can debug the issue
*/
public function after(AfterScenarioScope $scope)
{
$result = $scope->getTestResult();
if (!$result->isPassed() && !empty($this->_generatedTestData)) {
$logger = $this->getContainer()->get('logger');
$steps = $scope->getScenario()->getSteps();
foreach ($steps as $step) {
$logger->addCritical($step->getKeywordType().' '.$step->getText());
}
$logger->addCritical(http_build_query($this->_generatedTestData));
}
}
/**
* @Transform /^([^"]*)$/
*/
public function transformTestData($arg)
{
if ($arg instanceof TableNode) {
return $this->transformTable($arg);
} else {
return $this->transformValue($arg);
}
}
/**
* @param $fakerProperty
* @param array $fakerParameters
* @return mixed
*/
public function generateTestData($fakerProperty, $fakerParameters = array())
{
$fakerProperty = (string) $fakerProperty;
if ($fakerProperty == 'email') {
return $this->generateEmail();
}
if ($fakerParameters) {
if (!is_array($fakerParameters)) {
throw new \InvalidArgumentException(
"generateTestData function only supports arrays for second parameter"
);
}
$result = call_user_func_array(array($this->getFaker(), $fakerProperty), $fakerParameters);
if (is_a($result, 'DateTime')) {
$result = $result->format('Y-m-d H:i:s');
}
return $result;
} else {
return $this->getFaker()->$fakerProperty;
}
}
public function generateEmail()
{
return strtolower($this->getFaker()->firstName) . '.' . strtolower($this->getFaker()->lastName) . '@testing.com';
}
/**
* @param TableNode $table
* @return TableNode
*/
public function transformTable(TableNode $table)
{
$rows = array();
foreach ($table->getRows() as $row) {
foreach ($row as $key => $value) {
$row[$key] = $this->transformValue($value);
}
$rows[] = $row;
}
$tableNode = new TableNode();
$tableNode->setRows($rows);
return $tableNode;
}
/**
* @param $string
* @return mixed
*/
public function transformValue($string)
{
if (preg_match(self::GENERATE_TEST_DATA_REGEX, $string, $matches)) {
$key = $matches[1];
$fakerProperty = $matches[2];
if (isset($matches[4])) {
$fakerParameters = array_map("trim", explode(',', str_replace(array('"', "'"), "", $matches[4])));
} else {
$fakerParameters = array();
}
$testData = $this->generateTestData($fakerProperty, $fakerParameters);
$this->setTestData($key,$testData);
return $testData;
} else if (preg_match(self::GET_TEST_DATA_REGEX, $string, $matches)) {
$position = $matches[1];
$testData = $this->getTestData($position);
return $testData;
}
return $string;
}
/**
* @param $key
* @param $value
*/
protected function setTestData($key, $value)
{
$this->_generatedTestData[$key] = $value;
}
/**
* @param $position
* @return mixed
*/
protected function getTestData($position)
{
return $this->_generatedTestData[$position];
}
/**
* @return \Faker\Generator
*/
protected function getFaker()
{
if (!$this->_faker) {
$this->_faker = FakerFactory::create('nl_BE');
}
return $this->_faker;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment