承接 lchrusciel/api-test-case 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

lchrusciel/api-test-case

Composer 安装命令:

composer require lchrusciel/api-test-case

包简介

Perfect PHPUnit TestCase for JSON/XML API TDD with Symfony.

README 文档

README

Build Scrutinizer Code Quality

ApiTestCase is a PHPUnit TestCase that will make your life as a Symfony API developer much easier. It extends basic Symfony WebTestCase with some cool features.

Thanks to PHP-Matcher you can, according to its readme, "write expected json responses like a gangster". We definitely agree.

It also uses Alice for easy Doctrine fixtures loading.

Features:

  • Clear TDD workflow for API development with Symfony;
  • JSON/XML matching with clear error messages;
  • Fixtures loading with Alice (optional);

Installation

Assuming you already have Composer installed globally:

composer require --dev lchrusciel/api-test-case

And it's done! ApiTestCase is working with the default configuration.

Usage

We provide two base classes for your test cases: JsonApiTestCase and the XmlApiTestCase. Choose one based on the format of the API you want to create.

Json Example

The basic TDD workflow is the following:

  1. Write a test case that sends the request and use assertResponse assertion method to check if response contents are matching your expectations. You need a name for the response file;
  2. Create the file with name that you picked in step 1. and put expected response contents there. It should be put in src/AppBundle/Tests/Responses/Expected/hello_world.json for example.
  3. Make it red.
  4. Make it green.
  5. Refactor.

Let's see a simple example! Write the following test:

namespace AppBundle\Tests\Controller\HelloWorldTest;

use ApiTestCase\JsonApiTestCase;

class HelloWorldTest extends JsonApiTestCase
{
    public function testGetHelloWorldResponse()
    {
        $this->client->request('GET', '/');

        $response = $this->client->getResponse();

        $this->assertResponse($response, 'hello_world');
    }
}

Now define the expected response file:

{
    "message": "Hello ApiTestCase World!"
}

Run your tests:

vendor/bin/phpunit

Your test should fail with some errors, you are probably missing the controller and routing, so go ahead and define them! As soon as you implement your Controller and configure appropriate routing, you can run your tests again:

If the response contents will match our expectations, console will present a simple message:

OK (1 tests, 2 assertions)

Otherwise it will present diff of received messages:

"Hello ApiTestCase World" does not match "Hello ApiTestCase World!".
@@ -1,4 +1,3 @@
 {
-    "message": "Hello ApiTestCase World!"
+    "message": "Hello ApiTestCase World"
 }
-

Firstly, function assertResponse will check the response code (200 is a default response code), then it will check if header of response contains application/json content type. At the end it will check if the response contents matches the expectation. Sometimes you can't predict some values in the response, for example autogenerated date or id from the database. No magic is needed here because PHP-Matcher comes with a helping hand. These are just a few examples of available patterns:

  • @string@
  • @integer@
  • @boolean@
  • @array@

Check for more on PHP-Matcher's documentation.

With these patterns your expected response will look like this:

{
    "message": "@string@"
}

With this in place, any string under key message will match the pattern. More complicated expected response could look like this:

[
    {
        "id": "@integer@",
        "name": "Star-Wars T-shirt",
        "sku": "SWTS",
        "price": 5500,
        "sizes": "@array@",
        "created_at": "@string@.isDateTime()"
    },
    {
        "id": "@integer@",
        "name": "Han Solo Mug",
        "sku": "HSM",
        "price": 500,
        "sizes": "@array@",
        "created_at": "@string@.isDateTime()"
    }
]

And will match the following list of products:

array(
    array(
        'id' => 1,
        'name' => 'Star-Wars T-shirt',
        'sku' => 'SWTS',
        'price' => 5500,
        'sizes' => array('S', 'M', 'L'),
        'created_at' => new \DateTime(),
    ),
    array(
        'id' => 2,
        'name' => 'Han Solo Mug',
        'sku' => 'HSM',
        'price' => 500,
        'sizes' => array('S', 'L'),
        'created_at' => new \DateTime(),
    ),
)

Testing With Database Fixtures

ApiTestCase is integrated with nelmio/alice. Thanks to this nice library you can easily load your fixtures when you need them. You have to define your fixtures and place them in an appropriate directory. Here is some example how to define your fixtures and use case. For more information how to define your fixtures check Alice's documentation.

In order to use Alice with Doctrine, you should enable two additional bundles:

Symfony 4.0+

// config/bundles.php
return [
    // ...
    
    Nelmio\Alice\Bridge\Symfony\NelmioAliceBundle::class => ['test' => true],
    Fidry\AliceDataFixtures\Bridge\Symfony\FidryAliceDataFixturesBundle::class => ['test' => true],
];

Now, let's say you have a mapped Doctrine entity called Book in your application:

    class Book 
    {
        private $id;
        private $title;
        private $author;
    
        // ... 
    }

To load fixtures for the test, you need to define a simple YAML file in src/AppBundle/Tests/DataFixtures/ORM/books.yml:

    ApiTestCase\Test\Entity\Book:
        book1:
            title: "Lord of The Rings"
            author: "J. R. R. Tolkien"
        book2:
            title: "Game of Thrones"
            price: "George R. R. Martin"

Finally, to use these fixtures in a test, just call a proper method:

    public function testBooksIndexAction()
    {
        // This method require subpath to locate specific fixture file in your DataFixtures/ORM directory.
        $this->loadFixturesFromFile('books.yml');  
      
        // There is another method that allows you to load fixtures from directory.
        $this->loadFixturesFromDirectory('big_library');
    }

Configuration Reference

To customize your test suite configuration you can add a few more options to phpunit.xml:

<php>
    <server name="KERNEL_CLASS" value="Acme\Kernel" />
    <server name="EXPECTED_RESPONSE_DIR" value="/path/to/expected/responses/" />
    <server name="FIXTURES_DIR" value="/path/to/DataFixtures/ORM/" />
    <server name="OPEN_ERROR_IN_BROWSER" value="true/false" />
    <server name="OPEN_BROWSER_COMMAND" value="open %s" />
    <server name="IS_DOCTRINE_ORM_SUPPORTED" value="true/false" />
    <server name="TMP_DIR" value="/tmp/path/to/temporary/folder/" />
    <server name="ESCAPE_JSON" value="true/false" />
</php>
  • KERNEL_CLASS allows you to specify exactly which class should be used in order to setup the Kernel.
  • ERESPONSE_DIR variable contain paths to folder with expected responses. It is used when API result is compared with existing json file. If this value isn't set, ApiTestCase will try to guess location of responses, looking for the responses in a folder: '../Responses' relatively located to your controller test class.
  • FIXTURES_DIR variable contains a path to folder with your data fixtures. By default if this variable isn't set it will search for ../DataFixtures/ORM/ relatively located to your test class . ApiTestCase throws RunTimeException if folder doesn't exist or there won't be any files to load.
  • OPEN_ERROR_IN_BROWSER is a flag which turns on displaying error in a browser window. The default value is false.
  • OPEN_BROWSER_COMMAND is a command which will be used to open browser with an exception.
  • IS_DOCTRINE_ORM_SUPPORTED is a flag which turns on doctrine support includes handy data fixtures loader and database purger.
  • TMP_DIR variable contains a path to temporary folder, where the log files will be stored.
  • ESCAPE_JSON is a flag which turns on escaping (unicode characters and slashes) of your JSON output before comparing it to expected data. The default value is false. This flag only exists for backwards compatibility with previous versions of ApiTestCase (when turned on) and will be removed in a future version.

Sample Project

In the test/ directory, you can find sample Symfony project with minimal configuration required to use this library.

Testing

In order to run our PHPUnit tests suite, execute following commands:

composer install
test/app/console doctrine:database:create
test/app/console doctrine:schema:create
vendor/bin/phpunit

Bug Tracking and Suggestions

If you have found a bug or have a great idea for improvement, please open an issue on this repository.

Versioning

Releases will be numbered with the format major.minor.patch.

And constructed with the following guidelines.

  • Breaking backwards compatibility bumps the major.
  • New additions without breaking backwards compatibility bumps the minor.
  • Bug fixes and misc changes bump the patch.

For more information on SemVer, please visit semver.org website.

MIT License

License can be found here.

Authors

The library was originally created by:

at Lakion company under https://github.com/Lakion/ApiTestCase repository.

See the list of contributors.

lchrusciel/api-test-case 适用场景与选型建议

lchrusciel/api-test-case 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5.86M 次下载、GitHub Stars 达 411, 最近一次更新时间为 2018 年 11 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「symfony」 「json」 「xml」 「api」 「phpunit」 「TDD」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 lchrusciel/api-test-case 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 lchrusciel/api-test-case 我们能提供哪些服务?
定制开发 / 二次开发

基于 lchrusciel/api-test-case 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 5.86M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 411
  • 点击次数: 20
  • 依赖项目数: 73
  • 推荐数: 0

GitHub 信息

  • Stars: 411
  • Watchers: 10
  • Forks: 40
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-11-09