pandora-una/pandora-testes

此包的最新版本(v1.7)没有可用的许可证信息。

Pandora数据库,包含抽象类和辅助类

v1.7 2018-11-14 16:42 UTC

This package is auto-updated.

Last update: 2024-09-20 03:02:51 UTC


README

此仓库包含用于在Zend Framework 2和Doctrine 2应用程序中使用Behat、MinkExtension和WebApiExtension轻松创建验收测试的工具。

  • 用于创建Docrine fixtures的简单接口。
  • 创建数据库中实体的步骤。
  • 等待Ajax请求的步骤。
  • 测试执行期间保持测试数据库的清洁。
  • 在测试执行期间将Apache2环境更改为test的shell脚本
  • 包含Selenium2的二进制文件

安装

推荐的安装方法是使用composer

    {
        "require-dev": {
            "behat/behat": "3.0.*",
            "pandora-una/pandora-testes": "dev-master"
        },
    }

二进制文件

Behat 已经有一个用于运行测试的二进制文件,但是Zend Framework 2不支持简单地将测试环境与开发环境分开。因此,需要创建一个脚本以简化测试执行并避免错误。只需以下命令即可运行测试

$ vendor/bin/pandora-behat

脚本接受与behat二进制文件相同的选项,以下命令列出选项

$ vendor/bin/pandora-behat --help

如果测试需要Selenium2在后台运行,以下命令用于初始化它

$ java -jar vendor/bin/selenium-server-standalone-2.53.0.jar

可选配置

以下是一个更完整的配置示例

'pandora-testes' => array(
    'fixtures_namespace' => 'Application\Fixture',
    'entities_namespace' => 'Application\Entity',
    'clean-after-suite' => false,
    'fixtures' => array(
        'base' => array('usuarioWeb'),
        'Usuario' => array(
            'identifier' => 'id',
            'entity_name' => 'SASLoginExterno\Entity\Usuario'
        )
    )
)

上面的字段具有以下效果

  • fixtures_namespace: fixtures的命名空间,如果省略,默认为Application\Fixture
  • entities_namespace: 实体的默认命名空间,如果省略,默认为Application\Entity。需要注意的是,可以在fixtures选项中为每个实体指定命名空间。
  • fixtures
    • 实体名称:
      • identifier: 识别实体的字段,如果省略,默认为id
      • entity_name: 实体的完整名称,如果省略,默认为entities_namespace中定义的命名空间与实体简单名称的组合。
    • base: 列出在运行测试时始终加载的实体。

Doctrine Fixtures

此仓库的一个重要功能是简化通过 fixtures 如此类创建测试数据库中实体的方式。

namespace Application\Fixture;

use PandoraTestes\Fixture\AbstractFixture;

class Usuario extends AbstractFixture
{

    protected $params = array(
        'email' => 'usuario@email.com',
        'senha' => 'e8d95a51f3af4a3b134bf6bb680a213a'
    );

}
参数

如前例所示,fixture 应定义其基本属性。具有简单值的属性,即不引用其他实体的属性,应在 params 属性中提供。此字段应包含一个哈希,其中键表示属性名称,值表示属性值。

对于我们的用户fixture示例,数组键的设计是为了“匹配”Doctrine的访问方法,即创建实体时,库将执行以下命令以创建用户

$entityUsuario->setEmail('usuario@email.com');
$entityUsuario->setSenha('e8d95a51f3af4a3b134bf6bb680a213a');

因此,键必须是实体的字段,并且必须存在访问方法。

有时一个属性的值不仅仅是数字或字符串那么简单,可能需要进行一些处理才能生成值(时间值是这个类别中最常见的)。为此,需要定义一个如下所示的回调函数。

class Usuario extends AbstractFixture
{

    protected $params = array(
        'email' => 'usuario@email.com',
        'senha' => array('callback' => 'md5', 'value' => '123456'),
    );

}

因此,fixture的工厂将调用在callback键中定义的函数,并使用在value键中定义的参数。回调函数接受与原生函数"call_user_func"在其第一个参数中接受的一切。

关联

当一个fixture引用另一个实体时,可以引用另一个fixture。假设存在一个这样的fixture

class TipoUsuario extends AbstractFixture
{
    protected $params = array(
        'descricao' => 'OPERADOR',
    );
}

要创建关联,需要实例化一个新的fixture字段,如以下示例所示

class Usuario extends AbstractFixture
{
    protected $params = array(
        'email' => 'usuario@email.com',
        'senha' => 'e8d95a51f3af4a3b134bf6bb680a213a'
    );

    protected $associations = array(
        'tipo' => 'tipoUsuario'
    );
}

数组的键引用了doctrine实体字段的键(在这个例子中,将调用setTipo()方法)和值引用了fixture类名,但首字母小写。因此,“tipoUsuario”是类名为“Application/Fixture/TipoUsuario”的fixture的名称。显然,可以创建无数关联。

方面

在测试中,你可能需要不同版本的同一实体,或者同一实体的不同实例,这可以通过方面来实现。

要创建一个方面,需要再实例化一个新的fixture字段,即traits字段。假设你想要一个用于测试的“第二个”用户,fixture将是这样的

class Usuario extends AbstractFixture
{

    protected $params = array(
        'email' => 'usuario@email.com',
        'senha' => 'e8d95a51f3af4a3b134bf6bb680a213a'
    );

    protected $associations = array(
        'tipo' => 'tipoUsuario'
    );

    protected $traits = array(
        'segundo' => array(
            'email'=>'segundo.usuario@email.com'
        )
    );

}

trait属性的数组键引用了方面的名称。建议使用形容词作为名称,因为这将使接受性测试中两个实例之间的差异更加清晰。重要的是要注意,"第二个用户"和我们的原始用户之间的唯一区别是电子邮件,其他所有字段都使用相同的值。

方面也可以有与基本fixture不同的关联。例如,以下是这样类型的fixture类型Usuario

class TipoUsuario extends AbstractFixture
{
    protected $params = array(
        'descricao' => 'OPERADOR',
    );

    protected $traits = array(
        'admin' => array(
            'descricao'=>'ADMINISTRADOR'
        )
    );
}

因此,一个具有不同密码的管理员用户的方面如下所示

class Usuario extends AbstractFixture
{

    protected $params = array(
        'email' => 'usuario@email.com',
        'senha' => 'e8d95a51f3af4a3b134bf6bb680a213a'
    );

    protected $associations = array(
        'tipo' => 'tipoUsuario'
    );

    protected $traits = array(
        'segundo' => array(
            'email'=>'segundo.usuario@email.com'
        ),
        'administrador' => array(
            'senha' => '21232f297a57a5a743894a0e4a801fc3',
            '_associations' => array(
                'tipo' => 'admin tipoUsuario'
            )
        )
    );
}

重要的是要注意,方面在fixture名称之前。这是因为接受性测试是用英文编写的。此外,尽管不常见,但在葡萄牙语中也是正确的。

如果你想让管理员用户也有一个不同的电子邮件地址,不需要更改fixture,因为可以连接方面。"第二个管理员用户"fixture创建了一个具有以下参数的用户(格式为json)

{
    "email": "segundo.usuario@email.com",
    "senha": "21232f297a57a5a743894a0e4a801fc3",
    "tipo": {
        "descricao": "ADMINISTRADOR"
    }
}

有时我们需要对原始fixture进行更简单的修改,或者对大量实体进行同一字段的修改。为了简化,trait可以这样编写:<字段名>:<字段值>。例如,假设在测试中需要创建四个具有不同电子邮件地址的用户,而不是声明四个仅更改电子邮件的trait,fixture "usuario"、"email:usuario2@email.com usuario"、"email:usuario3@email.com usuario"、"email:usuario4@email.com usuario"已经解决了问题。

测试步骤

此存储库包含一个Behat上下文,其中包含自定义步骤。

Behat配置

为了使用库步骤,需要声明pandora上下文,以及Mink,如果您想使用与Ajax请求相关的步骤。以下是一个示例配置

default:
  extensions:
    Behat\WebApiExtension:
      base_url: 'https:///html/Teste/srv/public/api/'
    Behat\MinkExtension:
      base_url:  'https:///html/Teste/cli/'
      sessions:
        default:
          selenium2: ~
  suites:
    srv:
      paths: [ %paths.base%/features/srv ]
      contexts:
        - Behat\WebApiExtension\Context\WebApiContext
        - FeatureContext
        - PandoraTestes\Context\PandoraSrvContext
    cli:
      paths: [ %paths.base%/features/cli ]
      contexts:
        - Behat\MinkExtension\Context\MinkContext
        - FeatureContext
        - PandoraTestes\Context\PandoraCliContext:
            error_folder: '/home/testes/screenshots'

要使用此存储库的上下文,FeatureContext类必须扩展PandoraContext类,因为需要扩展用于启动应用程序的静态方法initializeZendFramework。以下是一个示例

use PandoraTestes\Context\PandoraContext;

/**
 * Defines application features from the specific context.
 */
class FeatureContext extends PandoraContext
{
    /**
     * @BeforeSuite
     */
    public static function initializeZendFramework()
    {
        try {
            if (self::$zendApp === null) {
                putenv('APPLICATION_ENV=test');
                $path          = __DIR__.'/../../config/application.config.php';
                self::$zendApp = \Zend\Mvc\Application::init(require $path);
            }
        } catch (Zend\ServiceManager\Exception\ServiceNotCreatedException $e) {
            $error_message = "Exception Stack: \n";
            while ($e) {
                $error_message .= $e->getMessage() . ";\n";
                $e = $e->getPrevious();
            }
            throw new \Exception($error_message, 500);
        }
    }
}
创建实体

要使用上一节中描述的fixture,此存储库具有以下测试步骤

 Given exists a "<nome da fixture>"

此步骤创建测试所需的实体,如下例所示。

Scenario: Deslogar no sistema
    Given exists a "tipoUsuario" #cria um tipo de usuário no banco de dados.
    Given exists an "administrador usuario" #cria um usuário com o aspecto administrador no banco de dados.
    And I am logged
    When I go to "/#/page"
    And I press "Sair"
    Then I should be on "/#/login"

请注意,步骤参数的结构与在方面中引用fixture时相同,即首先引用方面(形容词),然后是fixture名称。

修改实体

要更改已加载的固定装置,请使用此paddo

 Given "the <campo>" of "<nome da fixtue>" is "<valor>"

此步骤更改已创建的实体。值作为字符串传递给实体,除了"null"和"false"之外

附加步骤

除了创建实体的步骤之外,这个库还包含其他附加步骤。

API步骤

然后响应应该包含具有此格式的json

  • 接收一个JSON作为参数。
  • 假设响应已经发送并且处于JSON格式。
  • 使用PHPmacher标记比较响应JSON中的每个元素与提供的JSON
  • 示例
Then the response should contain json with this format:
"""
    {
        "id": "@integer@",
        "username": "USUARIO",
        "email": "@string@.matchRegex('/^[^@]+@[a-z0-9]+[.][a-z0-9]+$/')",
        "permissoes": "@array@"
    }
"""

更多信息即将揭晓...

PHPMatcher扩展

计数

检查数组是否包含一定数量的元素。

示例

And the response should contain json with at least these fields:
"""
{
  "_embedded": {
    "turma": [
      {
        "alunos": "@array@.count(3)"
      },
      {
        "alunos": "@array@.count(3)"
      },
      {
        "alunos": "@array@.count(2)"
      }
    ]
  }
}
"""
panToday

检查一个日期是否与测试执行的日期有关。格式与\DateTime::modify方法相同

示例

And the response should contain json with at least these fields:
"""
{
  "_embedded": {
    "turma": [
      {
        "dataInicio": "panToday:'-3 days'"
        "dataFim": "panToday:'+40 hours'"
      }
    ]
  }
}
"""