Встроенный сервер Yii2 начинается с index.php

Я пытаюсь выполнить приемочный тест кода в соответствии с https://github.com/yiisoft/yii2-app-basic/blob/master/README.md#testing

Я не могу понять, почему yii serve начинается с entryScript index.php, а я ожидаю index-test.php. Это приводит к YII_DEBUG = false и, как следствие, невозможности сохранения электронной почты в файл.

Вот мой codeception.yml

actor: Tester
paths:
    tests: tests
    log: tests/_output
    data: tests/_data
    helpers: tests/_support
coverage:
    enabled: true
    remote: false
    c3_url: 'http://localhost:8080/index-test.php'
    include:
      - commands/*
      - components/*
      - controllers/*
      - models/*
      - modules/*
settings:
    bootstrap: _bootstrap.php
    memory_limit: 1024M
    colors: true
modules:
    config:
        Yii2:
            configFile: 'config/test.php'
            entryScript: index-test.php
            cleanup: false

Вот мой accept.yml:

actor: AcceptanceTester
extensions:
    enabled:
        - Codeception\Extension\RunProcess:
            - ./tests/bin/yii serve
            - wait 2
modules:
    enabled:
    - WebDriver:
        url: 'http://localhost:8080/'
        window_size: 1920x1080
        browser: chrome
        capabilities:
            chromeOptions:
                args: ["--no-sandbox", "--headless", "--disable-gpu"]
                binary: "/usr/bin/google-chrome-stable"
            unexpectedAlertBehaviour: 'accept'

    - Yii2:
        part: [orm, email]
        entryScript: index-test.php

Я добавил c3.php в свой index-test.php. Это единственное отличие от оригинального файла.


person Dekar    schedule 07.06.2018    source источник


Ответы (2)


Вы не указали index-test.php для модуля Webdriver. Попробуй это:

 - WebDriver:
     url: 'http://localhost:8080/index-test.php'
     window_size: 1920x1080
person sunomad    schedule 07.06.2018
comment
В этом случае тесты не выполняются с пустой страницей в _output. - person Dekar; 08.06.2018
comment
Вот вывод для wget:wget http://localhost:8080/index-test.php --2018-06-08 16:17:27-- http://localhost:8080/index-test.php Resolving localhost (localhost)... ::1, 127.0.0.1 Connecting to localhost (localhost)|::1|:8080... connected. HTTP request sent, awaiting response... 301 Moved Permanently Location: // [following] http://: Invalid host name. - person Dekar; 08.06.2018
comment
Вам нужно будет выяснить, почему он перенаправляется, и исправить это в первую очередь. Лично я всегда устанавливаю виртуальные хосты, чтобы запускать сайт, например, на mywebapp.loc и mywebapp.test , где второй будет запускаться из index-test.php - person sunomad; 11.06.2018
comment
Спасибо за ваш ответ. Если я правильно понимаю, yii serve запускает встроенный сервер Php на локальном хосте: 8080, поэтому между ним и конфигурацией vhost или nginx нет никакой связи. Я поймал, что localhost:8080/index.php сделал то же самое перенаправление 301. Последние две строки больше пересекаются - это ни к чему не перенаправляет: Местоположение: // [следующий] - person Dekar; 13.06.2018
comment
А что, если вы не используете yii serve с Codeception, а просто настроите vhost? - person sunomad; 15.06.2018
comment
В этом случае мы не можем получать электронные письма - person Dekar; 23.07.2018

У меня была аналогичная проблема. Возможно, это не идеальное решение, но у меня на локальной машине оно работает нормально:

В accept.yml:

extensions:
    enabled:
        - Codeception\Extension\RunProcess:
            - php ./tests/bin/yii serve -r=web/index-test.php
            - wait 2

В web/index-test.php:

<?php

// NOTE: Make sure this file is not accessible when deployed to production
if (!in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1'])) {
   die('You are not allowed to access this file.');
}

chdir(__DIR__);

// ignore query params
$file = preg_replace('/\\?.*$/', '', $_SERVER["REQUEST_URI"]);
$filePath = realpath(ltrim($file, '/'));

if ($filePath && is_file($filePath)) {
    // 1. check that file is not outside of this directory for security
    // 2. check for circular reference to router
    // 3. don't serve dotfiles
    if (strpos($filePath, __DIR__ . DIRECTORY_SEPARATOR) === 0 &&
        $filePath != __DIR__ . DIRECTORY_SEPARATOR . 'index-test.php' &&
        substr(basename($filePath), 0, 1) != '.'
    ) {
        if (strtolower(substr($filePath, -4)) == '.php') {
            // php file; serve through interpreter
            include $filePath;
        } else {
            // asset file; serve from filesystem
            return false;
        }
    } else {
        // disallowed file
        header("HTTP/1.1 404 Not Found");
        echo "404 Not Found";
    }
} else {
    defined('YII_DEBUG') or define('YII_DEBUG', true);
    defined('YII_ENV') or define('YII_ENV', 'test');
    
    require(__DIR__ . '/../vendor/autoload.php');
    require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

    $config = require(__DIR__ . '/../config/test.php');

    (new yii\web\Application($config))->run();
}

Ссылки:

yii2/framework/console/controllers/ServeController.php< /а>

PHP: встроенный веб-сервер — вручную

Встроенный сервер PHP и мод .htaccess переписывает

person Yaroslav Kabaliuk    schedule 12.04.2021