Skip to content

Commit

Permalink
Split the context in two to not depend on the sonata user bundle (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
goetas authored Oct 26, 2021
1 parent 66d112c commit b75ae4a
Show file tree
Hide file tree
Showing 9 changed files with 443 additions and 197 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
composer.lock
vendor
.php_cs.cache
.phpunit.result.cache
46 changes: 46 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Changelog

[![Build Status](https://travis-ci.org/OskarStark/SonataAdminBehatContext.svg?branch=master)](https://travis-ci.org/OskarStark/SonataAdminBehatContext)

## Upgrading from 1.x to 2.0

- The `friends-of-behat/symfony-extension` is used instead of `behat/symfony2-extension` (that is not maintained anymore)
- The context `SonataAdminContext` has been split into two separate contexts.

- `SonataAdminContext` contains step definitions for `sonata-project/admin-bundle`.
- `SonataAdminUserBundleContext` contains step definitions for `sonata-project/user-bundle`.

Before:
```yaml
# behat.yml.dist
default:
suites:
default:
contexts:
- OStark\Context\SonataAdminContext:
userManager: '@sonata.user.user_manager'
tokenStorage: '@security.token_storage'
session: '@session'
```
After:
```yaml
# behat.yml.dist
default:
suites:
default:
contexts:
- OStark\Context\SonataAdminContext:
# needed only if you are using sonata-project/user-bundle
- OStark\Context\SonataAdminUserBundleContext:

# config/services_test.yaml
services:
OStark\Context\SonataAdminUserBundleContext:
arguments:
- '@sonata.user.user_manager'
- '@security.token_storage'
- '@session'
- '@service_container'

```
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ default:
default:
contexts:
- OStark\Context\SonataAdminContext:
# this can be disabled if you do not use the SonataAdminUserBundle
- OStark\Context\SonataAdminUserBundleContext:
userManager: '@sonata.user.user_manager'
tokenStorage: '@security.token_storage'
session: '@session'
Expand Down
9 changes: 6 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
"php": ">=7.1",
"behat/behat": "^3.0",
"behat/mink-extension": "^2.3",
"behat/symfony2-extension": "^2.1",
"sonata-project/user-bundle": "^4.0"
"friends-of-behat/symfony-extension": "^2.1"
},
"require-dev": {
"behat/mink-goutte-driver": "^1.1",
"behat/mink-selenium2-driver": "^1.3",
"guzzlehttp/guzzle": "^6.3",
"phpunit/phpunit": "^6.0",
"phpunit/phpunit": "^7.0|^8.5.21",
"sonata-project/user-bundle": "^4.0",
"symfony/browser-kit": "^4.3"
},
"config": {
Expand All @@ -43,5 +43,8 @@
"psr-4": {
"Tests\\OStark\\": "tests/"
}
},
"suggest": {
"sonata-project/user-bundle": "Allows User & Authentication scenarios"
}
}
6 changes: 5 additions & 1 deletion phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,9 @@
<directory>tests</directory>
</testsuite>
</testsuites>

<filter>
<whitelist>
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
185 changes: 1 addition & 184 deletions src/Context/SonataAdminContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,72 +13,22 @@

use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Gherkin\Node\TableNode;
use Behat\Mink\Driver\BrowserKitDriver;
use Behat\Mink\Driver\Selenium2Driver;
use Behat\Mink\Element\NodeElement;
use Behat\Mink\Exception\ElementNotFoundException;
use Behat\Mink\Exception\ExpectationException;
use Behat\Mink\Exception\UnsupportedDriverActionException;
use Behat\MinkExtension\Context\MinkContext;
use Behat\MinkExtension\Context\RawMinkContext;
use Behat\Symfony2Extension\Context\KernelAwareContext;
use Sonata\UserBundle\Model\UserManagerInterface;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserInterface;

/**
* Defines features for the SonataAdmin context.
*/
final class SonataAdminContext extends RawMinkContext implements KernelAwareContext
final class SonataAdminContext extends RawMinkContext
{
const DEFAULT_USERNAME = '[email protected]';

/**
* @var UserInterface
*/
private $user;

/**
* @var UserManagerInterface
*/
protected $userManager;

/**
* @var TokenStorageInterface
*/
protected $tokenStorage;

/**
* @var Session
*/
protected $session;

/**
* @var KernelInterface
*/
protected $kernel;

/**
* @var MinkContext
*/
private $minkContext;

public function __construct(UserManagerInterface $userManager, TokenStorageInterface $tokenStorage, Session $session)
{
$this->userManager = $userManager;
$this->tokenStorage = $tokenStorage;
$this->session = $session;
}

public function setKernel(KernelInterface $kernel)
{
$this->kernel = $kernel;
}

/**
* @BeforeScenario
*/
Expand Down Expand Up @@ -323,86 +273,6 @@ public function iCloseFlashMessage()
$xButton->click();
}

/**
* @When /^(?:|I )delete last created user$/
*
* @codeCoverageIgnore Selenium2Driver needed
*/
public function deleteLastCreatedUser()
{
$user = $this->userManager->findBy([], ['createdAt' => 'DESC'], 1);
$this->userManager->deleteUser(current($user));
}

/**
* @Given /^I am an authenticated User$/
*
* @throws ExpectationException
* @throws UnsupportedDriverActionException
*
* @codeCoverageIgnore Selenium2Driver needed
*/
public function iAmAnAuthenticatedUser()
{
$user = $this->userManager->createUser();

$user->setEmail(self::DEFAULT_USERNAME);
$user->setUsername(self::DEFAULT_USERNAME);
$user->setPlainPassword('foobar');

$this->userManager->updateUser($user);

$this->user = $user;

$this->createUserSession($user);
}

/**
* @Given /^I have role "([^"]*)"$/
*
* @param string $role
*
* @throws ExpectationException
* @throws UnsupportedDriverActionException
*
* @codeCoverageIgnore Selenium2Driver needed
*/
public function iHaveRole($role)
{
$user = $this->getCurrentUser();

$user->setRoles([$role]);
$this->userManager->updateUser($user);

$this->user = $user;

$this->createUserSession($user);
}

/**
* @Given /^I am authenticated as User "([^"]*)"$/
*
* @param string $username
*
* @throws ExpectationException
* @throws UnsupportedDriverActionException
*
* @codeCoverageIgnore Selenium2Driver needed
*/
public function iAmAuthenticatedAsUser($username)
{
$driver = $this->getSession()->getDriver();

$user = $this->userManager->findOneBy(['username' => $username]);
if (null === $user) {
throw new ExpectationException(sprintf('User with username "%s" does not exist', $username), $driver);
}

$this->user = $user;

$this->createUserSession($user);
}

/**
* @When /^(?:|I )logout User$/
*
Expand Down Expand Up @@ -648,54 +518,6 @@ public function theFieldShouldNotBeEmtpy($field)
$this->assertSession()->fieldValueNotEquals($field, '');
}

/**
* @throws UnsupportedDriverActionException
*
* @codeCoverageIgnore Selenium2Driver needed
*/
private function createUserSession(UserInterface $user)
{
$providerKey = $this->kernel->getContainer()->getParameter('fos_user.firewall_name');

$token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
$this->tokenStorage->setToken($token);

$authenticated = $this->tokenStorage->getToken()->isAuthenticated();
if (!$authenticated) {
throw new \RuntimeException('Not authenticated!');
}

$this->session->set('_security_'.$providerKey, serialize($token));
$this->session->save();

$driver = $this->getSession()->getDriver();
if ($driver instanceof BrowserKitDriver) {
$client = $driver->getClient();
$cookie = new Cookie($this->session->getName(), $this->session->getId());
$client->getCookieJar()->set($cookie);
} elseif ($driver instanceof Selenium2Driver) {
$this->visitPath('/'); // this step is needed, otherwise the user is not logged in the first time!
} else {
throw new UnsupportedDriverActionException('The Driver is not supported!', $driver);
}

$this->getSession()->setCookie($this->session->getName(), $this->session->getId());
}

private function getCurrentUser(): UserInterface
{
if (null != $this->user) {
return $this->user;
}

$user = $this->userManager->findOneBy(['username' => self::DEFAULT_USERNAME]);
if (null === $user) {
throw new ExpectationException(sprintf('User with username "%s" does not exist', self::DEFAULT_USERNAME), $this->getSession()->getDriver());
}

return $user;
}

/**
* Returns fixed step argument (with \\" replaced back to ").
*
Expand Down Expand Up @@ -773,9 +595,4 @@ private function notFindElement(string $locator, string $type): void
throw new ExpectationException(sprintf('%s found, but should not!', $type), $this->getSession()->getDriver());
}
}

public static function getAcceptedSnippetType()
{
return 'regex';
}
}
Loading

0 comments on commit b75ae4a

Please sign in to comment.