定制 cspray/http-client-test-interceptor 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

cspray/http-client-test-interceptor

Composer 安装命令:

composer require cspray/http-client-test-interceptor

包简介

README 文档

README

A framework for testing amphp/http-client v5 using the application interceptor design pattern it introduces. The primary reason for using this library is in your Unit or Integration Tests to test known HTTP interactions. This library provides 2 mechanisms for testing these interactions:

  1. Writing unit tests where every Request should be mocked and no network requests are made.
  2. Writing integration tests where a Request will be sent over the network if there isn't a fixture stored for that Request. The response received from the network request will be stored and subsequent requests will not go over the network.

Whether you're writing unit or integration tests the same underlying mechanisms are used. You can specify fine-grained pieces of the Request that should be matched against or provide your own strategy for matching Requests against a Fixture or Mock.

There are plenty of reasons not to use this library:

  • You aren't using amphp/http-client v5 or greater.
  • You already have a viable, working solution for testing your API interactions.

Installation

composer require amphp/http-client:v5.0.0-beta.3
composer require --dev cspray/http-client-test-interceptor

The amphp/http-client library is still in beta. You may need to adjust your minimum stability until http-client releases a 5.0 version.

Unit Testing Quick Start

Unit testing is meant to test your HttpClient against specific, known HTTP interactions. For example, you may need to test how your code under test responds to different headers, specific error codes, or a precise body structure. These tests can often be hard, or even impossible, to test reliably with integration tests.

Unlike writing integration tests that use fixtures there's no setup steps necessary. The first step is to write your TestCase!

<?php declare(strict_types=1);

namespace Acme\HttpMockingDemo;

use Amp\Http\Client\HttpClientBuilder;use Amp\Http\Client\Request;use Cspray\HttpClientTestInterceptor\HttpMock\MockResponse;use Cspray\HttpClientTestInterceptor\HttpMockAwareTestTrait;use League\Uri\Http;use PHPUnit\Framework\TestCase;

final class ApiUnitTest extends TestCase {

    use HttpMockAwareTestTrait;
    
    public function testGetResource() : void {
        $request = new Request(Http::createFromString('http://example.com'), 'POST');
        $response = MockResponse::fromBody('My expected body');
        $this->httpMock()->whenClientReceivesRequest($request)->willReturnResponse($response);
            
        $client = (new HttpClientBuilder())->intercept($this->getMockingInterceptor())->build();
        
        // We match on the values of the mocked Request ... NOT the identity of the object
        $actual = $client->request(new Request(Http::createFromString('http://example.com')), 'POST');
        
        // If you were to uncomment the below line this test would fail with a RequestNotMocked exception as the methods do not match
        // $client->request(new Request(Http::createFromString('http://example.com')), 'GET');
        
        self::assertSame($response, $actual);
    }

}

Mocking Request Matching

Because mocks require more manual setup the way they get matched uses a looser set of request matching strategies; instead of checking against the entire Request only the method and URI are matched against. If you'd like to make this more strict you can provide a set of Matchers when defining the Request to mock.

<?php declare(strict_types=1);

namespace Acme\HttpMockingDemo;

use Amp\Http\Client\HttpClientBuilder;use Amp\Http\Client\Request;use Cspray\HttpClientTestInterceptor\HttpMock\MockResponse;use Cspray\HttpClientTestInterceptor\HttpMockAwareTestTrait;use Cspray\HttpClientTestInterceptor\Matcher\Matcher;use League\Uri\Http;use PHPUnit\Framework\TestCase;

final class ApiHeadersMatchingUnitTest extends TestCase {

    use HttpMockAwareTestTrait;
    
    public function testGetResource() : void {
        $request = new Request(Http::createFromString('http://example.com'), 'POST');
        $request->setHeader('Authorization', 'some-token');
        $response = MockResponse::fromBody('My expected body');
        $this->httpMock()->whenClientReceivesRequest($request, [Matcher::Uri, Matcher::Method, Matcher::Headers])
            ->willReturnResponse($response);
            
        $client = (new HttpClientBuilder())->intercept($this->getMockingInterceptor())->build();
        
        // We match on the values of the mocked Request ... NOT the identity of the object
        $actualRequest = new Request('http://example.com', 'POST');
        $actualRequest->setHeader('Authorization', 'some-token');
        $actual = $client->request($actualRequest);
        
        // If you were to uncomment the below line this test would fail with a RequestNotMocked exception as the _headers_ do not match
        // $client->request(new Request(Http::createFromString('http://example.com')), 'POST');
        
        self::assertSame($response, $actual);
    }

}

Integration Testing Quick Start

Integration testing is meant when you want to test your HttpClient against real responses from an actual API. When the request is sent over the network the first time a fixture is stored with the response. If a matching request is sent again the response will be generated from the stored fixture and not sent over the network.

Create a Fixture Directory

The first thing needs to be done is to create a directory where HTTP Fixtures will be stored. There's no "right" place to store these files, any writable directory will work. Assuming your tests live in a directory named test, this guide recommends creating a test/http_fixture directory.

mkdir -p test/http_fixture

Mark Tests Making HTTP Requests

Now, in your tests Attribute your TestCase or test method with the path where Fixtures will be stored and used to match requests.

<?php declare(strict_types=1);

// Stored in test/ApiTest.php

namespace Acme\HttpFixtureDemo;

use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\Request;
use Cspray\HttpClientTestInterceptor\Attribute\HttpFixture;
use Cspray\HttpClientTestInterceptor\HttpFixtureAwareTestTrait;
use PHPUnit\Framework\TestCase;

#[HttpFixture(__DIR__ . '/http_fixture')]
final class ApiTest extends TestCase {

    use HttpFixtureAwareTestTrait;

    public function testGetResource() : void {
        $httpClient = (new HttpClientBuilder())
            ->intercept($this->getTestInterceptor())
            ->build();
        
        $response = $httpClient->request(new Request('https://api.example.com'));
        
        self::assertSame(200, $response->getStatus());
    }

}

Integration Request Matching

Out-of-the-box the library will attempt to match every aspect of the Request against a stored Fixture in integration tests. It is possible to have granular control over what parts of the Request are matched against. For example, let's set up our TestInterceptor to only match the Request method and URI instead of everything.

<?php declare(strict_types=1);

// Stored in test/ApiTest.php

namespace Acme\HttpFixtureDemo;

use Amp\Http\Client\HttpClientBuilder;use Amp\Http\Client\Request;use Cspray\HttpClientTestInterceptor\Attribute\HttpFixture;use Cspray\HttpClientTestInterceptor\Attribute\HttpRequestMatchers;use Cspray\HttpClientTestInterceptor\HttpFixtureAwareTestTrait;use Cspray\HttpClientTestInterceptor\Matcher\Matcher;use PHPUnit\Framework\TestCase;

#[HttpFixture(__DIR__ . '/http_fixture')]
#[HttpRequestMatchers(Matcher::Method, Matcher::Uri)]
final class ApiTest extends TestCase {

    use HttpFixtureAwareTestTrait;

    public function testGetResource() : void {
        $httpClient = (new HttpClientBuilder())
            ->intercept($this->getTestInterceptor())
            ->build();
        
        $response = $httpClient->request(new Request('https://api.example.com'));
        
        self::assertSame(200, $response->getStatus());
    }

}

Now the RequestMatchingStrategy utilized will only check the method and URI. You can compose your request matching with whatever pieces of the Request are appropriate. It is also possible to define the #[HttpRequestMatchers] and #[HttpFixture] Attributes on individual test methods. If you provide Attributes on both the Attributes on the test method will override those on the TestCase.

cspray/http-client-test-interceptor 适用场景与选型建议

cspray/http-client-test-interceptor 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 126 次下载、GitHub Stars 达 2, 最近一次更新时间为 2022 年 08 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 cspray/http-client-test-interceptor 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 126
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 18
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: Unknown
  • 更新时间: 2022-08-20