Skip to content

Instantly share code, notes, and snippets.

@Alex-D
Created August 10, 2017 16:23
Show Gist options
  • Save Alex-D/809f903c4a11e0bfb1b2ae304a8804c9 to your computer and use it in GitHub Desktop.
Save Alex-D/809f903c4a11e0bfb1b2ae304a8804c9 to your computer and use it in GitHub Desktop.
<?php
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use GuzzleHttp\Psr7\Request;
use Imbo\BehatApiExtension\Context\ApiContext;
use Symfony\Component\Process\Process;
/**
* Defines application features from the specific context.
*/
class FeatureContext extends ApiContext
{
use \Behat\Symfony2Extension\Context\KernelDictionary;
const COPY_MAX_ATTEMPTS = 3;
/** @var array $jwts */
private $jwts = [];
/**
* Prints last response body.
*
* @Then print response
*/
public function printResponse()
{
$request = $this->request;
$response = $this->response;
echo sprintf(
"%s %s => %d:\n%s",
$request->getMethod(),
(string)$request->getUri(),
$response->getStatusCode(),
(string)$response->getBody()
);
}
/**
* Reset the current request
*
* @Given I prepare a new request
*/
public function givenIPrepareNewRequest()
{
$this->request = new Request('GET', $this->client->getConfig('base_uri'));
}
/**
* Convert TableNode to PyStringNode for JSON data
*
* @param string $path
* @param string $method
* @param TableNode $table
* @When I request :path using HTTP :method with JSON data:
*/
public function whenIRequestPathWithJsonData(string $path, string $method, TableNode $table)
{
$rows = [];
foreach ($table as $row) {
$rows[$row['name']] = $row['value'];
}
$body = new PyStringNode([json_encode($rows)], 0);
parent::whenIRequestPathWithJsonBody($path, $method, $body);
}
/**
* Assert that the response body do not matches some content using a regular expression
*
* @param PyStringNode $pattern The regular expression pattern to use for the match
* @Then the response body should not matches:
*/
public function theResponseBodyShouldNotMatches(PyStringNode $pattern)
{
$patternParts = explode('/', (string)$pattern);
array_shift($patternParts);
$modifiers = array_pop($patternParts);
$negatedPattern = "/^(?:(?!" . implode('/', $patternParts) . ").)*$/" . $modifiers;
try {
parent::thenTheResponseBodyMatches(new PyStringNode([$negatedPattern], 0));
} catch (InvalidArgumentException $e) {
throw new InvalidArgumentException(str_replace('does not ', '', $e->getMessage()));
}
}
/**
* Add JWT to header to be authenticated
*
* @param PyStringNode $data JWT data
* @Given I am authenticated with:
*/
public function givenIamAuthenticatedWith(PyStringNode $data)
{
$key = md5(serialize($data));
if (!array_key_exists($key, $this->jwts)) {
$this->jwts[$key] = $this->getContainer()->get('lexik_jwt_authentication.jwt_encoder')
->encode(\GuzzleHttp\json_decode((string)$data, true));
}
$this->request = $this->request->withHeader(
'Authorization',
'Bearer ' . $this->jwts[$key]
);
}
/**
* @BeforeSuite
*/
public static function createBackup()
{
self::copy("app/behat.db.cache", "app/behat.db.cache.bak");
}
/**
* @BeforeScenario
*/
public static function cleanDB()
{
self::copy("app/behat.db.cache.bak", "app/behat.db.cache");
exec('php bin/console redis:flushdb --no-interaction --env=test');
}
/**
* @AfterSuite
*/
public static function removeDatabaseAndBackup()
{
unlink("app/behat.db.cache");
unlink("app/behat.db.cache.bak");
}
protected static function copy(string $source, string $destination): bool
{
$attempts = 0;
do {
$isCopied = @copy($source, $destination);
if ($isCopied) {
return true;
} else {
$attempts += 1;
sleep(1);
}
} while (!$isCopied && $attempts < self::COPY_MAX_ATTEMPTS);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment