Skip to content

Commit

Permalink
Merge pull request #36 from gdubost/v3
Browse files Browse the repository at this point in the history
Passage du rabbitmq context en v3
  • Loading branch information
Kumatetsu authored Nov 6, 2018
2 parents a9d137a + 7e33b40 commit e6709ab
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 33 deletions.
4 changes: 1 addition & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
}
],
"require": {
"php": "^7.1.3"
},
"require-dev": {
"php": "^7.1.3",
"behat/behat": "^3.4",
"guzzlehttp/guzzle": "~6.1",
"etna/php-rsa": "~0.2.0",
Expand Down
71 changes: 71 additions & 0 deletions src/HttpApiMockContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public function __construct($host = 'localhost', $port = 8080)
public static function clearProxyExpectations()
{
self::$phiremock->clearExpectations();
self::$phiremock->reset();
}

/**
Expand Down Expand Up @@ -76,6 +77,50 @@ public function queLeProxyEffectueUneRequeteSurUneUrlQuiMatchEtRenvoieLeStatusHT
self::$phiremock->createExpectation($expectation);
}

/**
* @Then que le proxy effectue une requête :method sur ":route" et renvoie le status HTTP :status avec l'image contenue dans ":image"
*/
public function queLeProxyEffectueUneRequeteSurEtRenvoieStatusHTTPAvecLImageContenueDans($method, $route, $status, $image)
{
if (!file_exists($this->results_path . "/" . $image)) {
throw new \Exception("Image not found");
}

$response = \Mcustiel\Phiremock\Client\Utils\Respond::withStatusCode(intval($status))
->andHeader('Content-Type', 'image/jpg')
->andBinaryBody(file_get_contents($this->results_path . "/" . $image));

$method_name = strtolower($method) . 'Request';

// On set l'url et la méthode attendue par le mock
$expectation = Phiremock::on(
\Mcustiel\Phiremock\Client\Utils\A::{$method_name}()->andUrl(\Mcustiel\Phiremock\Client\Utils\Is::equalTo($route))
)->then($response);

// L'expectation attend la requête, la réponse est envoyée par le serveur phiremock
self::$phiremock->createExpectation($expectation);
}

/**
* @Then /^que le proxy "([^"]*)" effectue une requête (GET|POST|PUT|DELETE|OPTIONS) sur "((?:[a-zA-Z0-9,:!\/\.\?\&\=\+_%-]*)|"(?:[^"]+)")" avec comme corps "([^"]*)" et renvoie le status HTTP (\d+)(?: avec le résultat contenu dans "([^"]*\.json)")?$/
*/
public function queLeProxyEffectueUneRequeteSurAvecLeCorpsEtRenvoieLeStatusHTTP($proxy_name, $method, $url, $req_body, $status_code, $body = null)
{
$response = self::prepareMockResponse($status_code, $body);

$method_name = strtolower($method) . 'Request';

// On set l'url et la méthode attendue par le mock
$expectation = Phiremock::on(
\Mcustiel\Phiremock\Client\Utils\A::{$method_name}()
->andUrl(\Mcustiel\Phiremock\Client\Utils\Is::equalTo($url))
->andBody(\Mcustiel\Phiremock\Client\Utils\Is::equalTo($req_body))
)->then($response);

// L'expectation attend la requête, la réponse est envoyée par le serveur phiremock
self::$phiremock->createExpectation($expectation);
}

private function prepareMockResponse($status_code, $body)
{
$response = \Mcustiel\Phiremock\Client\Utils\Respond::withStatusCode(intval($status_code))->andHeader('Content-Type', 'application/json');
Expand All @@ -92,4 +137,30 @@ private function prepareMockResponse($status_code, $body)

return $response;
}

/**
* @Then le serveur de mock devrait avoir traité toutes les requêtes contenues dans ":scenario_file"
*/
public function leServeurDeMockDevraitAvoirTraiteToutesLesRequetesContenuesDans($scenario_file)
{
$requests = [];
$methods = ['get', 'post', 'put', 'delete'];

// Oui, on ne peut tout récupérer d'un coup..
foreach ($methods as $method) {
$function_name = "{$method}Request";
$requests = array_merge($requests, self::$phiremock->listExecutions(
\Mcustiel\Phiremock\Client\Utils\A::{$function_name}()
));
}

$body = file_get_contents($this->results_path . $scenario_file);
if (!$body) {
throw new \Exception("File not found : {$this->results_path}${body}");
}
$body = json_decode($body);

$this->check($body, $requests, "result", $errors);
$this->handleErrors($requests, $errors);
}
}
65 changes: 35 additions & 30 deletions src/RabbitContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,15 @@ class RabbitContext extends BaseContext
public static $vhosts = ["/test-behat"];
private $response;

/**
* @BeforeSuite
*/
public static function loadEnv()
{
if (file_exists('./app/env/' . getenv('APPLICATION_ENV') . '.php')) {
require_once './app/env/' . getenv('APPLICATION_ENV') . '.php';
}
}

private static function getRabbitMqClient()
{
$rmq_url = getenv("RABBITMQ_URL");
$config = parse_url($rmq_url);
$base_uri = "{$config['scheme']}://{$config['host']}:15672";
$base_uri = "http://localhost:15672";

return new Client(
[
"base_uri" => $base_uri,
"headers" => ["Content-Type" => "application/json"],
"auth" => [$config["user"], $config["pass"]]
"auth" => ["guest", "guest"]
]
);
}
Expand Down Expand Up @@ -73,6 +61,7 @@ public static function deleteVhosts()
}
}


/**
* @Given /le producer "([^"]*)" devrait avoir publié un message dans la queue "([^"]*)"$/
*/
Expand Down Expand Up @@ -114,8 +103,9 @@ public function leProducerDevraitAvoirPublieUnMessageDansLaQueueEnJSON($producer

private function fetchMessage($producer, $queue)
{
$channel = self::$silex_app["rabbit.producer"][$producer]->getChannel();
$channel = $this->getContainer()->get("old_sound_rabbit_mq.{$producer}_producer")->getChannel();
$message = $channel->basic_get($queue, true);
$channel->close();

if (null === $message) {
throw new \Exception("Queue {$queue} is empty");
Expand All @@ -133,37 +123,35 @@ public function leProducerPublieUnJobAvecLeCorpsContenuDans($producer, $body)
throw new \Exception("File not found : {$this->requests_path}${body}");
}

$body = json_decode(file_get_contents($this->requests_path . $body));
if (false === isset(self::$silex_app['rabbit.producer'][$producer])) {
throw new \Exception("Producer {$producer} not found");
}
$body = json_decode(file_get_contents($this->requests_path . $body));
$producer = $this->getContainer()->get("old_sound_rabbit_mq.{$producer}_producer");

$routing_key = self::$silex_app['rabbit.producers'][$producer]['queue_options']['routing_keys'][0];
self::$silex_app['rabbit.producer'][$producer]->publish(json_encode($body), $routing_key);
$producer->publish(json_encode($body));
$producer->getChannel()->close();
}

/**
* @Given /je traite (\d+) jobs avec le consumer "([^"]*)"/
*/
public function jeTraiteJobsAvecLeConsumer($nb_jobs, $consumer)
{
if (false === isset(self::$silex_app['rabbit.consumer'][$consumer])) {
throw new \Exception("Consumer {$consumer} not found");
}
$consumer = $this->getContainer()->get("old_sound_rabbit_mq.{$consumer}_consumer");

self::$silex_app['rabbit.consumer'][$consumer]->consume($nb_jobs);
$consumer->consume($nb_jobs);
$consumer->getChannel()->close();
}

/**
* @Then /^il doit y avoir un message dans la file "([^"]*)"$/
*/
public function ilDoitYAvoirUnMessageDansLaFile($queue = null)
{
$app = self::$silex_app;
$channel = $app["rabbit.connection"]['default']->channel();
$channel = $this->getContainer()->get("old_sound_rabbit_mq.connection.default")->channel();

$response_msg = $channel->basic_get($queue);
$response_msg = $channel->basic_get($queue, true, null);
$parsed_response = json_decode($response_msg->body);
$channel->close();

if (empty($parsed_response)) {
throw new \Exception("{$parsed_response}");
}
Expand All @@ -181,14 +169,31 @@ public function ilDoitYAvoirUnMessageDansLaFileAvecLeCorpsContenuDans($queue = n
$body = file_get_contents($this->results_path . $body);
$parsed_wanted = json_decode($body);

$app = self::$silex_app;
$channel = $app["rabbit.connection"]['default']->channel();
$channel = $this->getContainer()->get("old_sound_rabbit_mq.connection.default")->channel();

$response_msg = $channel->basic_get($queue);
$parsed_response = json_decode($response_msg->body);
$channel->close();

$this->response[$queue] = $parsed_response;

$this->check($parsed_wanted, $parsed_response, "result", $errors);
$this->handleErrors($parsed_response, $errors);
}

/**
* @Then la queue ":queue_name" devrait être vide
*/
public function laQueueDevraitEtreVide($queue_name)
{
$channel = $this->getContainer()->get("old_sound_rabbit_mq.connection.default")->channel();

list($queue, $message_count, $consumer_count) = $channel->queue_declare($queue_name, true);

$channel->close();

if (0 !== $message_count) {
throw new \Exception("Expecting {$queue_name} to be empty, but found {$message_count} job(s)");
}
}
}

0 comments on commit e6709ab

Please sign in to comment.