Я учусь писать плагин для Wordpress и пытаюсь протестировать его, используя Codeception / WP-Browser .Я хочу написать приемочные тесты , чтобы проверить поведение плагина при его активации.Приемочный тест запускается с Selenium Webriver / ChromeDriver
Тем не менее, есть поведение, которое я не знаю, как тестировать.Тест «счастливого пути» выделен зеленым, а случаи сбоев - красным, потому что плагин успешно активирован.
Как сделать так, чтобы тесты на отказ стали зелеными?
Что должно произойти
Если пользователь активирует плагин, класс проверит
- версия PHP на сервере
- версия Wordpress
и если они не совместимы с плагином, он покажет страницу ошибки пользователю звоните wp_die .
Что происходит сейчас
Тест счастливого пути проходит успешно, но не случаи сбоя .
Проблема в том, что, поскольку в приемочных тестах у меня нет доступа к коду на стороне сервера, я не знаю, как я мог бы изменить поведение плагина во время активации, чтобы протестировать егов случае неудачи .
Этот учебный проект структурирован следующим образом:
testwidget
|
+-----tests
| +---acceptance
| +----activationCest.php
+-----src
| +---activation
| +----activation.php
+-------widget-plugin.php
Это мой код:
. / widget-plugin.php
<?php
/**
* Plugin Name: testwidget
* Description: a test of developing a Post of the Day widget
* Author: Rafael
* Text Domain: testwidget
*/
namespace Testwidget;
require __DIR__ . '\vendor\autoload.php';
// to avoid exposing information if the plugin is called directly
if (function_exists('add_action') === false) {
echo 'I am a plugin. I cannot be called directly';
exit();
}
register_activation_hook(
__FILE__,
function () {
$wpVersion = get_bloginfo('version');
$act = new Activation(PHP_VERSION, $wpVersion);
$act->checkEnvironment();
}
);
Я думаю, что проблема здесь: я не знаю как изменить из тестового файла поведение функции, register_activation_hook будет звонить .
Второй параметр register_activation_hook
- это функция без параметров, согласно официальной документации.
В этой функции я передаю некоторые параметры конструктору Activation, чтобы сделать его модульно-тестируемым(нет проблем в модульных тестах).
Это тестовый файл:
. / tests / accept / активацииCest.php
<?php
class activationCest
{
public function _before(AcceptanceTester $I)
{
// to reset the state of the plugin after each test
try {
$I->loginAsAdmin();
$I->amOnPluginsPage();
$I->seePluginDeactivated('testwidget');
} catch(\Exception $e) {
$I->deactivatePlugin('testwidget');
}
}
public function _after(AcceptanceTester $I)
{
}
// tests
public function activationCaseFailPHP(AcceptanceTester $I)
{
$I->wantTo('see an error message if the PHP version
is not compatible with the plugin');
$I->loginAsAdmin();
$I->amOnPluginsPage();
$I->activatePlugin('testwidget');
$I->see(
'<h2>Your PHP version is outdated</h2>
<p>Testwidget requires a PHP version equal or superior to 7.0.</p>
<p>Contact your hosting provider to update PHP</p>'
);
}
public function activationCaseFailWP(AcceptanceTester $I)
{
$I->wantTo('see an error message if the Wordpress version
is not compatible with the plugin');
$I->loginAsAdmin();
$I->amOnPluginsPage();
$I->activatePlugin('testwidget');
$I->see(
'<h2>Your Wordpress version is outdated</h2>
<p>Testwidget requires a PHP version equal or superior to 5.0.</p>
<p>Contact your hosting provider to update Wordpress</p>'
);
}
public function activationCaseFailPHPAndWP(AcceptanceTester $I)
{
$I->wantTo('see an error message if the PHP and Wordpress
versions are not compatible with the plugin');
$I->loginAsAdmin();
$I->amOnPluginsPage();
$I->activatePlugin('testwidget');
$I->see(
'<h2>Your PHP and Wordpress versions are outdated</h2>
<p>Testwidget requires
<ul>
<li>a PHP version equal or superior to 7.0 and</li>
<li>a Wordpress version equal or superior to 5.0.</li>
</ul>
<p>Contact your hosting provider to update PHP and Wordpress</p>'
);
}
public function activationCaseSuccess(AcceptanceTester $I)
{
$I->wantTo('see a success message if the PHP and Wordpress versions
are compatible with the plugin');
// setup
$I->loginAsAdmin();
Хотя это может быть ненужным, я включаю здесь код класса Activation просто для того, чтобы быть тщательным:
. / Src / Activation / Activation.php
<?php
namespace Testwidget;
/**
* checks the environment of the plugin allows it to be
* activated correctly. If that is not the case, it will
* show an error message
*
*/
class Activation
{
private $phpVersion;
private $wpVersion;
private const PHP_LOWEST_VERSION = '7.0';
private const WP_LOWEST_VERSION = '5.0';
public function __construct($phpVersion, $wpVersion)
{
$this->phpVersion = $phpVersion;
$this->wpVersion = $wpVersion;
}
/**
* predicate that returns true if the PHP version
* running on the server is superior to the minimal
* version the plugin requires; otherwise, false
*
* @return boolean
*
* @see https://www.php.net/manual/en/function.version-compare.php
*/
private function comparePhpVersions()
{
return version_compare($this->phpVersion, self::PHP_LOWEST_VERSION, '>=');
}
/**
* predicate that returns true if the Wordpress version
* running on the server is superior to the minimal
* version the plugin requires; otherwise, false
*
* @return boolean
*
* @see https://www.php.net/manual/en/function.version-compare.php
*/
private function compareWpVersions()
{
return version_compare($this->wpVersion, self::WP_LOWEST_VERSION, '>=');
}
/**
* If the PHP and Wordpress versions aren't compatible with the plugin,
* the method shows an error message.
*/
public function checkEnvironment()
{
// Array with cases and conditions to evaluate the environment
$conditions = [
'phpAndWp' => function () {
return $this->comparePhpVersions() === false &&
$this->compareWpVersions() === false;
},
'php' => function () {
return $this->comparePhpVersions() === false;
},
'wp' => function () {
return $this->compareWpVersions() === false;
}
];
// array with cases and error messages
$errors = [
'phpAndWp' => '<h2>Your PHP and Wordpress versions are outdated</h2>
<p>Testwidget requires
<ul>
<li>a PHP version equal or superior to 7.0 and</li>
<li>a Wordpress version equal or superior to 5.0.</li>
</ul>
<p>Contact your hosting provider to update PHP and Wordpress</p>',
'php' => '<h2>Your PHP version is outdated</h2>
<p>Testwidget requires a PHP version equal or superior to 7.0.</p>
<p>Contact your hosting provider to update PHP</p>',
'wp' => '<h2>Your Wordpress version is outdated</h2>
<p>Testwidget requires a PHP version equal or superior to 5.0.</p>
<p>Contact your hosting provider to update Wordpress</p>'
];
foreach(array_keys($conditions) as $case) {
if ($conditions[$case]()) {
wp_die($errors[$case]);
exit();
}
}
}
}
Только что пройденный тест является успешным .Тесты случаев сбоя отмечены красным, потому что плагин успешно активирован.
Я не понимаю, как провести приемочные испытания поведения моего класса в случае неудачи.
Как бы вы решили эту проблему?Вы бы изменили структуру файла, чтобы сделать код более легко тестируемым?