Symfony 4: Тестовая БД для JWT и Behat

Я использую платформу API 2.1 с Symfony 4, и я использую LexikJWTAuthenticationBundle для аутентификации и Behat для тестирования.

Я не могу все правильно настроить. Вот моя конфигурация:

Feature: Books feature

@createSchema @dropSchema
Scenario: Adding a new book
  When I add "Content-Type" header equal to "application/json"
  And I add "Accept" header equal to "application/json"
  And I send a "POST" request to "/api/books" with body:
  """
 {
    "title": "King",
    "author": "T. M. Frazier",
    "enabled": true
 }
 """
 Then the response status code should be 201
 And the response should be in JSON
 And the header "Content-Type" should be equal to "application/json"
 And the JSON nodes should contain:
    | title                   | King              |
    | author                  | T. M. Frazier     |
 And the JSON node "enabled" should be true

Вот мой контекст функции:

<?php

use Behat\Behat\Context\Context;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use App\Entity\User;
use Behatch\Context\RestContext;
use Behat\Behat\Context\SnippetAcceptingContext;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\Tools\SchemaTool;


/**
 * This context class contains the definitions of the steps used by the demo 
 * feature file. Learn how to get started with Behat and BDD on Behat's website.
 * 
 * @see http://behat.org/en/latest/quick_start.html
 */
class FeatureContext implements Context, SnippetAcceptingContext
{
    /**
     * @var KernelInterface
     */
    private $kernel;

    private $manager;

    private $jwtManager;

    private $schemaTool;

    private $response;

    private $classes;

    private $restContext;

    public function __construct(KernelInterface $kernel,$manager,$jwtManager)
    {
        $this->kernel = $kernel;
        $this->manager = $manager->getManager();
        $this->jwtManager = $jwtManager;
        $this->schemaTool = new SchemaTool($this->manager);
        $this->classes = $this->manager->getMetadataFactory()->getAllMetadata();
    }

    /**
     * @When a demo scenario sends a request to :path
     */
    public function aDemoScenarioSendsARequestTo(string $path)
    {
        $this->response = $this->kernel->handle(Request::create($path, 'GET'));
    }

    /**
     * @Then the response should be received
     */
    public function theResponseShouldBeReceived()
    {
        if ($this->response === null) {
            throw new \RuntimeException('No response received');
        }
    }

    /**
     * @BeforeScenario @createSchema
     */
    public function createDatabase()
    {
        $this->schemaTool->createSchema($this->classes);
    }

    /**
     * @AfterScenario @dropSchema
     */
    public function dropDatabase()
    {
        $this->schemaTool->dropSchema($this->classes);
    }

    /**
     * @BeforeScenario
     * @login
     *
     * @see https://symfony.com/doc/current/security/entity_provider.html#creating-your-first-user
     */
    public function login(BeforeScenarioScope $scope)
    {
        $user = new User();
        $user->setUsername('admin');
        $user->setPassword('ATestPassword');
        $user->setEmail('[email protected]');

        $this->manager->persist($user);
        $this->manager->flush();

        $token = $this->jwtManager->create($user);

        $this->restContext = $scope->getEnvironment()->getContext(RestContext::class);
        $this->restContext->iAddHeaderEqualTo('Authorization', "Bearer $token");
    }

    /**
     * @AfterScenario
     * @logout
     */
    public function logout() {
        $this->restContext->iAddHeaderEqualTo('Authorization', '');
    }
}

Теперь при выполнении vendor/bin/behat он просто читает файл .env (среда разработки) и пытается добавить администратора в мою базу данных разработки.

1) Как мне убедиться, что тестовая база данных создана, а dev db не используется для тестирования? Я пробовал создать .env.test с другой конфигурацией, но это не сработало.

2) даже без аннотации @login над сценарием он достигает метода login из FeatureContext. Так оно и должно быть?

3) Я нигде не могу найти подходящую документацию о том, как это настроить. Документы по платформе API, похоже, тоже не очень полезны. Ссылка: https://api-platform.com/docs/core/jwt/#jwt-authentication Они говорят о createDB и dropDB, но их нигде даже не существует. Я взял его с другого сайта. Это правильный способ сделать это?


person apfz    schedule 01.04.2018    source источник


Ответы (1)


У меня нет ответа на 1) и 3), но на 2)

    /**
     * @BeforeScenario
     * @login
     */

должен быть в одной строке, например:

    /**
     * @BeforeScenario @login
     */
person user10695352    schedule 23.11.2018
comment
Это сделало мой день! Спасибо! - person Alexandre Tranchant; 12.08.2019