<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace tests;
|
|
|
|
use app\BusinessException;
|
|
use app\service\WxService;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/**
|
|
* 微信服务测试
|
|
*
|
|
* 不发起真实网络请求:只测 mock 模式与安全阀
|
|
* 真实 code2Session 需要 appid/secret 与联网,属于联调阶段验证
|
|
*/
|
|
final class WxServiceTest extends TestCase
|
|
{
|
|
/**
|
|
* 构造服务
|
|
* createService
|
|
* @param bool $mock 是否 mock 模式
|
|
* @param bool $is_debug 是否调试模式
|
|
* @return WxService
|
|
*/
|
|
private function createService($mock, $is_debug): WxService
|
|
{
|
|
$config = [];
|
|
$config['mock'] = $mock;
|
|
$config['appid'] = '';
|
|
$config['secret'] = '';
|
|
$config['api_base'] = 'https://api.weixin.qq.com';
|
|
$config['timeout'] = 5;
|
|
|
|
return new WxService($config, $is_debug);
|
|
}
|
|
|
|
/** mock 模式下同一 code 必得同一 openid,便于本地重复登录与自动化测试 */
|
|
public function testMockOpenidIsDeterministic(): void
|
|
{
|
|
$wx_service = $this->createService(true, true);
|
|
|
|
$first = $wx_service->code2Session('same-code');
|
|
$second = $wx_service->code2Session('same-code');
|
|
|
|
self::assertSame($first['openid'], $second['openid']);
|
|
}
|
|
|
|
/** 不同 code 必须得到不同 openid,否则所有人会登进同一个账号 */
|
|
public function testDifferentCodeDifferentOpenid(): void
|
|
{
|
|
$wx_service = $this->createService(true, true);
|
|
|
|
self::assertNotSame(
|
|
$wx_service->code2Session('code-a')['openid'],
|
|
$wx_service->code2Session('code-b')['openid']
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 生产环境开着 mock 必须抛异常
|
|
*
|
|
* mock 模式等于「任何人自报一个 code 就能登录任意账号」
|
|
* 靠人「记得关掉 mock」不可靠,一旦漏关就是全站身份可伪造
|
|
*/
|
|
public function testMockRejectedInProduction(): void
|
|
{
|
|
$wx_service = $this->createService(true, false);
|
|
|
|
$this->expectException(BusinessException::class);
|
|
$this->expectExceptionMessageMatches('/WX_MOCK/');
|
|
|
|
$wx_service->code2Session('any-code');
|
|
}
|
|
|
|
/** 真实模式但未配 appid/secret:应明确报「未配置」,而不是发出无效请求 */
|
|
public function testLiveModeRequiresCredentials(): void
|
|
{
|
|
$wx_service = $this->createService(false, false);
|
|
|
|
$this->expectException(BusinessException::class);
|
|
$this->expectExceptionMessageMatches('/WX_APPID/');
|
|
|
|
$wx_service->code2Session('any-code');
|
|
}
|
|
|
|
/** isMock 应如实反映配置 */
|
|
public function testIsMock(): void
|
|
{
|
|
self::assertTrue($this->createService(true, true)->isMock());
|
|
self::assertFalse($this->createService(false, false)->isMock());
|
|
}
|
|
|
|
/** 配置摘要不得泄漏 secret,appid 只回「是否已配置」 */
|
|
public function testConfigSummaryHidesSecret(): void
|
|
{
|
|
$summary = $this->createService(true, true)->getConfigSummary();
|
|
|
|
self::assertSame('mock', $summary['mode']);
|
|
self::assertSame('', $summary['appid']);
|
|
self::assertArrayNotHasKey('secret', $summary);
|
|
}
|
|
}
|