Не получается создать тест

Всё про тестирование в Yii 2.0
Закрыто
Аватара пользователя
raidkon
Сообщения: 2
Зарегистрирован: 2018.10.07, 06:47

Не получается создать тест

Сообщение raidkon »

Только начал разбираться в тестах, прошу сильно не пинать.

При попытке вызова vendor\bin\codecept run --debug появляется ошибка: Сайт на найден.

Если дойти дебагером к месту где в базе ищется домен, и сделать ->all() то возвращает [] есть подозрение что не загружаются фикстуры.

Подскажите куда копать?


лог вызова

Код: Выделить всё

Codeception PHP Testing Framework v4.1.6
Powered by PHPUnit 6.5.14 by Sebastian Bergmann and contributors.
Running with seed:



[api\tests]: tests from D:\OSPanel\domains\crm.board\api


Api\tests.api Tests (1) -----------------------------------------------------------------------------------------------------------------------------------------------------------------
Modules: \api\tests\Helper\Api, REST, PhpBrowser, Yii2
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
UserCest: Try to test
Signature: api\tests\api\UserCest:tryToTest
Test: tests\api\UserCest.php:tryToTest
Scenario --
  Destroying application
  Starting application
  [ConnectionWatcher] watching new connections
  [Fixtures] Loading fixtures
  [Fixtures] Done
  [TransactionForcer] watching new connections
 I have fixtures {"user":{"class":"common\\fixtures\\user\\UserFixture","dataFile":"D:\\OSPanel\\domains\\crm.board\\api\\tests/_data\\user\\user.php"},"site":{"class":"common\\fixt...}
  [yii\db\Connection::open] 'Opening DB connection: pgsql:host=localhost;dbname=board_test'
  [ConnectionWatcher] Connection opened!
  [TransactionForcer] Connection opened!
  [TransactionForcer] Transaction started for: pgsql:host=localhost;dbname=board_test
 I am bearer authenticated "www-1"
 I have http header "Cookie","XDEBUG_SESSION=PHPSTORM"
 I send get "/user"
  [Request] GET http://crm.board.api/index-test.php/user
  [Request Headers] {"Authorization":"Bearer www-1","Cookie":"XDEBUG_SESSION=PHPSTORM"}
  [Page] http://crm.board.api/index-test.php/user
  [Response] 400
  [Request Cookies] []
  [Response Headers] {"Date":["Mon, 27 Jul 2020 21:03:57 GMT"],"Server":["Apache"],"Content-Length":["157"],"Connection":["close"],"Content-Type":["application/json; charset=UTF-8"]}
  [Response] {
      "name": "Bad Request",
      "message": "Сайт на найден",
      "code": 0,
      "status": 400,
      "type": "yii\\web\\BadRequestHttpException"
  }
 I see response code is 200
 FAIL 

  [TransactionForcer] Transaction cancelled; all changes reverted.
  [TransactionForcer] no longer watching new connections
  Destroying application
  [ConnectionWatcher] no longer watching new connections
  [ConnectionWatcher] closing all (1) connections
  Suite done, restoring $_SERVER to original
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Time: 996 ms, Memory: 16.00MB

There was 1 failure:

---------
1) UserCest: Try to test
 Test  tests\api\UserCest.php:tryToTest
 Step  See response code is 200
 Fail  Expected HTTP Status Code: 200 (OK). Actual Status Code: 400 (Bad Request)
Failed asserting that 400 matches expected 200.

Scenario Steps:

 5. $I->seeResponseCodeIs(200) at tests\api\UserCest.php:34
 4. $I->sendGET("/user") at tests\api\UserCest.php:33
 3. $I->haveHttpHeader("Cookie","XDEBUG_SESSION=PHPSTORM") at tests\api\UserCest.php:32
 2. $I->amBearerAuthenticated("www-1") at tests\api\UserCest.php:31
 1. $I->haveFixtures({"user":{"class":"common\\fixtures\\user\\UserFixture","dataFile":"D:\\OSPanel\\domains\\crm.board\\api\\tests/_data\\user\\user.php"},"site":{"class":"common\...})
 at tests\api\UserCest.php:22

Artifacts:

Body: {
    "name": "Bad Request",
    "message": "Сайт на найден",
    "code": 0,
    "status": 400,
    "type": "yii\\web\\BadRequestHttpException"
}
Html: D:\OSPanel\domains\crm.board\api\tests/_output\api.tests.api.UserCest.tryToTest.fail.json
Response: D:\OSPanel\domains\crm.board\api\tests/_output\api.tests.api.UserCest.tryToTest.fail.json

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.



Компонент, который определяется настройки для текущего сайта (определяет по домену), он указан в bootstap для автозагрузки.

Код: Выделить всё

class SiteConfig extends Component
{
    protected ?Site $site = null;
    
    public function init(): void
    {
        parent::init();
        
        if (Yii::$app->id === SiteID::API) {
            Yii::$app->on(Application::EVENT_BEFORE_REQUEST, fn() => $this->initCurrentSite());
        }
    }

    private function initCurrentSite()
    {
        $host = parse_url(Yii::$app->request->hostInfo, PHP_URL_HOST);
        if (!$this->site = Site::find()->host($host)->one()) {
            throw new BadRequestHttpException('Сайт на найден');
        }
    }

    /** остальное */
}

Есть тест:

Код: Выделить всё

<?php

namespace api\tests\api;

use api\tests\ApiTest;
use Codeception\Util\HttpCode;
use common\fixtures\system\SiteFixtute;
use common\fixtures\user\UserFixture;

class UserCest
{
    public function _before(ApiTest $I)
    {
        $I->haveFixtures(
            [
                'user' => [
                    'class' => UserFixture::class,
                    'dataFile' => codecept_data_dir() . 'user\user.php',
                ],
                'site' => [
                    'class' => SiteFixtute::class,
                    'dataFile' => codecept_data_dir() . 'system\site.php',
                ],
            ]
        );
    }

    // tests
    public function tryToTest(ApiTest $I)
    {
        $I->amBearerAuthenticated('www-1');
        $I->haveHttpHeader('Cookie', 'XDEBUG_SESSION=PHPSTORM');
        $a = $I->sendGET('/user');
        $I->seeResponseCodeIs(HttpCode::OK);
    }
}
Содержимое 2х фикстуры:

user\user.php:

Код: Выделить всё

<?php

return [
    [
        'id' => '!!!!',
        'username' => 'raidkon',
        'auth_key' => null,
        'password_hash' => '1',
        'password_reset_token' => '2',
        'email' => 'n@raidkon.com',
        'access_token' => 'www-1',
        'status' => 300,
        'created_at' => '2020-01-01 00:00:00.000',
        'updated_at' => '2020-01-01 00:00:00.000',
        'site_id' => 1
    ],
];

system\site.php:

Код: Выделить всё

<?php
return [
    [
        'id' => 1,
        'hostName' => 'crm.board.api',
        'status_id' => 1
    ]
];
Содержимое /codeception.yml

Код: Выделить всё

# global codeception file to run tests from all apps
include:
    - api
paths:
    log: console/runtime/logs
settings:
    colors: true
Содержимое: api/codeception.yml

Код: Выделить всё

namespace: api\tests
actor_suffix: Tester
paths:
  tests: tests
  output: tests/_output
  data: tests/_data
  support: tests/_support
bootstrap: _bootstrap.php
settings:
  colors: true
  memory_limit: 1024M
modules:
  enabled:
    - PhpBrowser:
        url: http://crm.board.api/index-test.php
    - REST:
        depends: PhpBrowser
        url: http://crm.board.api/index-test.php
  config:
    Yii2:
      configFile: 'config/codeception-local.php'

Аватара пользователя
raidkon
Сообщения: 2
Зарегистрирован: 2018.10.07, 06:47

Re: Не получается создать тест

Сообщение raidkon »

чтоб заработало надо поправить файл: api/codeception.yml

Код: Выделить всё

namespace: api\tests
actor_suffix: Tester
paths:
  tests: tests
  output: tests/_output
  data: tests/_data
  support: tests/_support
bootstrap: _bootstrap.php
settings:
  colors: true
  memory_limit: 1024M
modules:
  enabled:
    - Yii2:
    - REST:
        depends: Yii2
        part: Json
  config:
    Yii2:
      configFile: 'config/codeception-local.php'

Закрыто