Skip to content

Commit

Permalink
feat: init Library
Browse files Browse the repository at this point in the history
  • Loading branch information
IiiigorGG committed Aug 11, 2021
0 parents commit 249377f
Show file tree
Hide file tree
Showing 9 changed files with 413 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/vendor/
/composer.lock
/build/
/.phpunit.result.cache
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Ihor Roik

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Messenger Behat Context

### Install
```shell script
composer require macpaw/messenger-behat-context
```
62 changes: 62 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"name": "macpaw/messenger-behat-context",
"type": "library",
"description": "Behat Context for testing messenger component",
"keywords": [
"MacPaw",
"symfony",
"behat",
"BDD",
"Context",
"Messenger"
],
"authors": [
{
"name": "IiiigorGG",
"email": "[email protected]",
"homepage": "https://macpaw.com/",
"role": "Software Engineer"
},
{
"name": "Yozhef Hisem",
"email": "[email protected]",
"homepage": "https://macpaw.com/",
"role": "Software Engineer"
}
],
"license": "MIT",
"require": {
"php": "^7.4 || ^8.0",
"ext-json": "*",
"symfony/messenger": "^4.4 || ^5.0",
"behat/behat": "^3.0",
"symfony/serializer": "^5.0"
},
"require-dev": {
"phpstan/phpstan": "0.12.*",
"phpunit/phpunit": "9.3.*",
"squizlabs/php_codesniffer": "3.5.*"
},
"autoload": {
"psr-4": {
"MessengerBehatContext\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"MessengerBehatContext\\Tests\\": "tests"
}
},
"scripts": {
"phpstan": "./vendor/bin/phpstan analyse -l max",
"code-style": "./vendor/bin/phpcs",
"code-style-fix": "./vendor/bin/phpcbf",
"phpunit": "./vendor/bin/phpunit",
"dev-checks": [
"composer validate",
"@phpstan",
"@code-style",
"@phpunit"
]
}
}
38 changes: 38 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?xml version="1.0"?>
<ruleset name="Platform-Mail-Service-Api">
<description>The coding standard of Platform-Mail-Service-Api package</description>
<arg value="p" />

<config name="ignore_warnings_on_exit" value="1" />
<config name="ignore_errors_on_exit" value="1" />

<arg name="colors" />
<arg value="s" />

<!-- Use the PSR12 Standard-->
<rule ref="PSR12" />

<rule ref="Generic.PHP.ForbiddenFunctions">
<properties>
<property name="forbiddenFunctions" type="array" value="eval=>NULL,dd=>NULL,die=>NULL,var_dump=>NULL,dump=>NULL,sizeof=>count,delete=>unset,print=>echo,echo=>NULL,print_r=>NULL,create_function=>NULL"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.FunctionSpacing">
<properties>
<property name="spacing" value="1" />
<property name="spacingBeforeFirst" value="0" />
<property name="spacingAfterLast" value="0" />
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.SuperfluousWhitespace">
<properties>
<property name="ignoreBlankLines" value="false" />
</properties>
</rule>

<rule ref="Squiz.PHP.LowercasePHPFunctions"/>
<rule ref="Generic.PHP.RequireStrictTypes"/>
<rule ref="Squiz.Arrays.ArrayBracketSpacing"/>

<file>src/</file>
</ruleset>
8 changes: 8 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
parameters:
excludes_analyse:
paths:
- src
level: 8
treatPhpDocTypesAsCertain: false
ignoreErrors:
- '#Parameter \#1 \$value of function count expects array|Countable, iterable<Symfony\\Component\\Messenger\\Envelope> given.*#'
28 changes: 28 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Symfony Behat Context Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<logging>
<log type="junit" target="build/report.junit.xml"/>
<log type="coverage-html" target="build/coverage"/>
<log type="coverage-text" target="build/coverage.txt"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
199 changes: 199 additions & 0 deletions src/Context/MessengerContext.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
<?php

declare(strict_types=1);

namespace MessengerBehatContext\Context;

use MessengerBehatContext\Context\Traits\ArraySimilarTrait;
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use Exception;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Messenger\Transport\InMemoryTransport;
use Symfony\Component\Serializer\Serializer;

class MessengerContext implements Context
{
use ArraySimilarTrait;

private ContainerInterface $container;
private Serializer $serializer;

public function __construct(
ContainerInterface $container,
Serializer $serializer
) {
$this->container = $container;
$this->serializer = $serializer;
}

/**
* @Then bus :busName should contain message with JSON:
*/
public function busShouldContainMessageWithJson(string $busName, PyStringNode $expectedMessage): void
{
$expectedMessage = $this->decodeExpectedJson($expectedMessage);

$transport = $this->getMessengerTransportByName($busName);
foreach ($transport->get() as $envelope) {
$actualMessage = $this->convertToArray($envelope->getMessage());
if ($this->isArraysSimilar($actualMessage, $expectedMessage)) {
return;
}
}

throw new Exception(
sprintf(
'The transport doesn\'t contain message with JSON: %s',
$this->getPrettyJson($expectedMessage)
)
);
}

/**
* @Then bus :busName should contain message with JSON and variable fields :variableFields:
*/
public function busShouldContainMessageWithJsonAndVariableFields(
string $busName,
string $variableFields,
PyStringNode $expectedMessage
): void {
$variableFields = $variableFields ? array_map('trim', explode(',', $variableFields)) : [];
$expectedMessage = $this->decodeExpectedJson($expectedMessage);

$transport = $this->getMessengerTransportByName($busName);
foreach ($transport->get() as $envelope) {
$actualMessage = $this->convertToArray($envelope->getMessage());
if ($this->isArraysSimilar($actualMessage, $expectedMessage, $variableFields)) {
return;
}
}

throw new Exception(
sprintf(
'The transport doesn\'t contain message with JSON: %s',
$this->getPrettyJson($expectedMessage)
)
);
}

/**
* @Then all bus :busName messages should be JSON:
*/
public function allBusMessagesShouldBeJson(string $busName, PyStringNode $expectedMessageList): void
{
$expectedMessageList = $this->decodeExpectedJson($expectedMessageList);

$transport = $this->getMessengerTransportByName($busName);
$actualMessageList = [];
foreach ($transport->get() as $envelope) {
$actualMessageList[] = $this->convertToArray($envelope->getMessage());
}

if (!$this->isArraysSimilar($actualMessageList, $expectedMessageList)) {
throw new Exception(
sprintf(
'The expected bus messages doesn\'t match actual: %s',
$this->getPrettyJson($actualMessageList)
)
);
}
}

/**
* @Then all bus :busName messages should be JSON with variable fields :variableFields:
*/
public function allBusMessagesShouldBeJsonWithVariableFields(
string $busName,
string $variableFields,
PyStringNode $expectedMessageList
): void {
$variableFields = $variableFields ? array_map('trim', explode(',', $variableFields)) : [];
$expectedMessageList = $this->decodeExpectedJson($expectedMessageList);

$transport = $this->getMessengerTransportByName($busName);
$actualMessageList = [];
foreach ($transport->get() as $envelope) {
$actualMessageList[] = $this->convertToArray($envelope->getMessage());
}

if (!$this->isArraysSimilar($actualMessageList, $expectedMessageList, $variableFields)) {
throw new Exception(
sprintf(
'The expected bus messages doesn\'t match actual: %s',
$this->getPrettyJson($actualMessageList)
)
);
}
}

/**
* @Then there is :expectationMessageCount messages in bus :busName
*/
public function thereIsCountMessagesInBus(int $expectedMessageCount, string $busName): void
{
$transport = $this->getMessengerTransportByName($busName);
$actualMessageCount = count($transport->get());

if ($actualMessageCount !== $expectedMessageCount) {
throw new Exception(
sprintf(
'In transport exist actual count: %s, but expected count: %s',
$actualMessageCount,
$expectedMessageCount
)
);
}
}

/**
* @param array<mixed> $message
* @return string|bool
*/
private function getPrettyJson(array $message)
{
return json_encode($message, JSON_PRETTY_PRINT);
}

/**
* @param mixed $object
* @return array<mixed>
*/
private function convertToArray($object): array
{
return (array) $this->serializer->normalize($object);
}

/**
* @return array<mixed>
*/
private function decodeExpectedJson(PyStringNode $expectedJson): array
{
return json_decode(
trim($expectedJson->getRaw()),
true,
512,
JSON_THROW_ON_ERROR
);
}

private function getMessengerTransportByName(string $busName): InMemoryTransport
{
$fullName = 'messenger.transport.' . $busName;
$hasTransport = $this->container->has($fullName);

if ($hasTransport === false) {
throw new Exception('Transport' . $fullName . ' not found');
}

$transport = $this->container->get($fullName);

if ($transport instanceof InMemoryTransport) {
return $transport;
}

throw new Exception(
'In memory transport' . $fullName . ' not found'
);
}
}
Loading

0 comments on commit 249377f

Please sign in to comment.