Merge branch 'master' of http://git.zhenyangtang.com.cn/ZYT/zyt
This commit is contained in:
@@ -0,0 +1,378 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// These doubles are installed before autoload. No DB, HTTP socket, .env or patient image is used.
|
||||
namespace app\common\service {
|
||||
function config($key) { return $GLOBALS['tongueConfig']; }
|
||||
function is_readable($path): bool {
|
||||
// Windows sandbox ACL probes can report false for readable fixtures.
|
||||
return $path === ($GLOBALS['tongueReadableCa'] ?? null) || \is_readable($path);
|
||||
}
|
||||
function microtime($asFloat = false) { return $GLOBALS['tongueClock']; }
|
||||
function curl_init() { return (object) ['options' => [], 'status' => 0, 'errno' => 0]; }
|
||||
function curl_setopt_array($handle, array $options): bool { $handle->options = $options; return true; }
|
||||
function curl_exec($handle) {
|
||||
$GLOBALS['tongueCalls'][] = $handle->options;
|
||||
if ($GLOBALS['tongueReplies'] === []) throw new \RuntimeException('Unexpected upstream call');
|
||||
$reply = array_shift($GLOBALS['tongueReplies']);
|
||||
$handle->status = $reply['status'] ?? 200;
|
||||
$handle->errno = $reply['errno'] ?? 0;
|
||||
$GLOBALS['tongueClock'] += $reply['seconds'] ?? 0;
|
||||
$body = $reply['body'] ?? '{}';
|
||||
$written = ($handle->options[CURLOPT_WRITEFUNCTION])($handle, $body);
|
||||
return $written === strlen($body) && $handle->errno === 0;
|
||||
}
|
||||
function curl_getinfo($handle, $option) { return $handle->status; }
|
||||
function curl_errno($handle) { return $handle->errno; }
|
||||
function curl_close($handle): void { ++$GLOBALS['tongueClosed']; }
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\controller\tcm\DiagnosisController;
|
||||
use app\adminapi\http\middleware\AuthMiddleware;
|
||||
use app\adminapi\logic\tcm\TongueScreenshotLogic;
|
||||
use app\common\service\DifyTongueScreenshotService;
|
||||
use app\common\service\TongueScreenshotImage;
|
||||
use think\file\UploadedFile;
|
||||
|
||||
final class TongueAuthDouble {
|
||||
public static array $uris = [];
|
||||
public function __construct($adminId = 0) {}
|
||||
public function getAdminUri(): array { return self::$uris; }
|
||||
public function getAllUri(): array { throw new RuntimeException('Screenshot must not use the unregistered-route bypass'); }
|
||||
}
|
||||
final class TongueScopeDouble {
|
||||
public static array $seen = [];
|
||||
public static function canAccessDiagnosis(int $id, int $adminId, array $adminInfo): bool {
|
||||
self::$seen[] = [$id, $adminId]; return $id === 41 && $adminId === 7;
|
||||
}
|
||||
}
|
||||
final class TongueLoginDouble {
|
||||
public static function adminMustBindWorkWechat(array $info): bool { return false; }
|
||||
}
|
||||
class_alias(TongueAuthDouble::class, 'app\\common\\cache\\AdminAuthCache');
|
||||
class_alias(TongueScopeDouble::class, 'app\\adminapi\\logic\\firstvisit\\MyPatientLogic');
|
||||
class_alias(TongueLoginDouble::class, 'app\\adminapi\\logic\\LoginLogic');
|
||||
|
||||
final class TongueRequest extends \app\Request {
|
||||
public array $uploads = [];
|
||||
public function file(string $name = '') { return $name === '' ? $this->uploads : ($this->uploads[$name] ?? null); }
|
||||
}
|
||||
$request = (new TongueRequest())->withServer(['REQUEST_METHOD' => 'POST', 'REMOTE_ADDR' => '127.0.0.1']);
|
||||
$container = \think\Container::getInstance();
|
||||
$container->instance('request', $request);
|
||||
$container->instance(\think\Request::class, $request);
|
||||
$container->instance(\think\Cookie::class, new \think\Cookie($request));
|
||||
|
||||
$checks = 0;
|
||||
$expect = static function (bool $ok, string $label) use (&$checks): void {
|
||||
if (!$ok) throw new RuntimeException('FAIL: ' . $label);
|
||||
++$checks;
|
||||
};
|
||||
$config = ['enable' => true, 'base_url' => 'https://dify.fixture.test/v1',
|
||||
'models' => ['qwen' => ['api_key' => 'fixture-only-secret', 'label' => '千问'],
|
||||
'openai' => ['api_key' => 'fixture-only-openai-secret', 'label' => 'OpenAI']],
|
||||
'required_attachment_upload' => ['ca_file' => '']];
|
||||
$valid = ['image_quality' => 'limited', 'quality_note' => '舌头可见,舌根被遮挡',
|
||||
'features' => [['name' => '舌苔颜色', 'observation' => '可见部分偏白']], 'limitations' => ['舌根无法观察'],
|
||||
'tcm_diagnosis' => ['status' => 'possible_patterns', 'summary' => '仅供参考,可考虑寒湿方向,需结合问诊和脉象复核',
|
||||
'candidates' => [['name' => '寒湿倾向', 'basis' => ['舌苔颜色'], 'verify' => ['需询问有无畏寒并检查脉象']]],
|
||||
'missing_information' => ['缺少症状问诊和脉象检查']]];
|
||||
$reset = static function (array $replies = []) use ($config): void {
|
||||
$GLOBALS['tongueConfig'] = $config; $GLOBALS['tongueCalls'] = [];
|
||||
$GLOBALS['tongueReplies'] = $replies; $GLOBALS['tongueClock'] = 1000.0; $GLOBALS['tongueClosed'] = 0;
|
||||
$GLOBALS['tongueReadableCa'] = null;
|
||||
};
|
||||
$successReplies = static fn (): array => [['body' => '{"id":"synthetic-file-123"}', 'seconds' => 2],
|
||||
['body' => json_encode(['answer' => json_encode($valid, JSON_UNESCAPED_UNICODE)], JSON_UNESCAPED_UNICODE)]];
|
||||
$answerReply = static fn (string $answer, int $seconds = 0): array => [
|
||||
'body' => json_encode(['answer' => $answer], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), 'seconds' => $seconds];
|
||||
$paths = [];
|
||||
$upload = static function () use (&$paths): UploadedFile {
|
||||
$path = tempnam(sys_get_temp_dir(), 'tongue-contract-'); $paths[] = $path;
|
||||
$canvas = imagecreatetruecolor(128, 128);
|
||||
imagefill($canvas, 0, 0, imagecolorallocate($canvas, 170, 95, 95));
|
||||
imagejpeg($canvas, $path); imagedestroy($canvas);
|
||||
return new UploadedFile($path, 'patient-secret-name.jpg', 'image/jpeg', UPLOAD_ERR_OK, true);
|
||||
};
|
||||
$body = ['id' => '41', 'request_id' => '12345678-1234-4234-8234-123456789abc'];
|
||||
$controller = static function (array $params, array $files, string $method = 'POST', int $actor = 7, array $info = ['root' => 0]): array {
|
||||
$req = (new TongueRequest())->withServer(['REQUEST_METHOD' => $method])->withPost($params);
|
||||
$req->uploads = $files;
|
||||
$controller = (new ReflectionClass(DiagnosisController::class))->newInstanceWithoutConstructor();
|
||||
foreach (['request' => $req, 'adminId' => $actor, 'adminInfo' => $info] as $name => $value) {
|
||||
$prop = new ReflectionProperty($controller, $name); $prop->setAccessible(true); $prop->setValue($controller, $value);
|
||||
}
|
||||
return $controller->aiTongueScreenshot()->getData();
|
||||
};
|
||||
try {
|
||||
// Exercise the real controller, logic, image validation, payload, transport and parser together.
|
||||
TongueAuthDouble::$uris = ['tcm.diagnosis/aiAssistant']; $reset($successReplies());
|
||||
$file = $upload(); $digest = hash_file('sha256', $file->getPathname());
|
||||
$result = $controller($body, ['file' => $file]);
|
||||
$expect($result['code'] === 1 && $result['show'] === 0, 'standard success envelope');
|
||||
$expect($result['data'] === ['request_id' => $body['request_id'], 'diagnosis_id' => 41,
|
||||
'image_sha256' => $digest, 'analysis' => $valid, 'model' => 'qwen', 'model_label' => '千问'], 'exact request/image/diagnosis response contract and optional model defaults to qwen');
|
||||
$expect(!is_file($file->getPathname()), 'temporary JPEG removed after success');
|
||||
$expect(TongueScopeDouble::$seen === [[41, 7]], 'only requested diagnosis authorization queried');
|
||||
$expect(count($GLOBALS['tongueCalls']) === 2 && $GLOBALS['tongueClosed'] === 2, 'one upload and one model call with closed handles');
|
||||
[$up, $chat] = $GLOBALS['tongueCalls'];
|
||||
$expect($up[CURLOPT_URL] === $config['base_url'] . '/files/upload', 'private upload uses configured Dify endpoint');
|
||||
$expect($up[CURLOPT_POSTFIELDS]['file'] instanceof CURLFile
|
||||
&& $up[CURLOPT_POSTFIELDS]['file']->getPostFilename() === 'video-screenshot.jpg'
|
||||
&& $up[CURLOPT_POSTFIELDS]['file']->getMimeType() === 'image/jpeg', 'real JPEG bytes use neutral upload filename');
|
||||
$payload = json_decode($chat[CURLOPT_POSTFIELDS], true);
|
||||
$expect($chat[CURLOPT_URL] === $config['base_url'] . '/chat-messages'
|
||||
&& $payload['files'] === [['type' => 'image', 'transfer_method' => 'local_file', 'upload_file_id' => 'synthetic-file-123']], 'model must receive private uploaded image');
|
||||
$expect($payload['response_mode'] === 'blocking' && $payload['auto_generate_name'] === false
|
||||
&& !isset($payload['conversation_id']) && json_decode($chat[CURLOPT_POSTFIELDS])->inputs instanceof stdClass, 'no title task, conversation history or chart inputs');
|
||||
$expect($payload['user'] === $up[CURLOPT_POSTFIELDS]['user'] && preg_match('/\Atongue-screenshot-[a-f0-9]{32}\z/', $payload['user']) === 1,
|
||||
'request-local opaque Dify user links only this upload and analysis');
|
||||
$expect(!str_contains($chat[CURLOPT_POSTFIELDS], 'patient-secret') && !str_contains($chat[CURLOPT_POSTFIELDS], $body['request_id'])
|
||||
&& !str_contains($chat[CURLOPT_POSTFIELDS], 'fixture-only-secret'), 'no patient filename, native identity or secret in model body');
|
||||
foreach ([$up, $chat] as $options) {
|
||||
$expect(in_array('Authorization: Bearer fixture-only-secret', $options[CURLOPT_HTTPHEADER], true), 'default qwen profile owns upload and chat');
|
||||
$expect($options[CURLOPT_FOLLOWLOCATION] === false && $options[CURLOPT_PROXY] === ''
|
||||
&& $options[CURLOPT_SSL_VERIFYPEER] === true && $options[CURLOPT_SSL_VERIFYHOST] === 2, 'no redirect/proxy credential leak and TLS remains verified');
|
||||
$expect($options[CURLOPT_TIMEOUT_MS] > 0 && $options[CURLOPT_TIMEOUT_MS] <= 50000
|
||||
&& $options[CURLOPT_CONNECTTIMEOUT_MS] <= 8000, 'finite request and connect budgets');
|
||||
}
|
||||
$expect($chat[CURLOPT_TIMEOUT_MS] === 48000, 'upload time deducted from single total deadline');
|
||||
|
||||
foreach (['qwen' => '千问', 'openai' => 'GPT'] as $model => $label) {
|
||||
$uploadId = 'synthetic-' . $model . '-file';
|
||||
$replies = $successReplies(); $replies[0]['body'] = json_encode(['id' => $uploadId]);
|
||||
$reset($replies); $file = $upload(); $filePath = $file->getRealPath();
|
||||
$digest = hash_file('sha256', $filePath);
|
||||
$result = $controller(array_replace($body, ['model' => $model]), ['file' => $file]);
|
||||
$expect($result['code'] === 1 && $result['data']['model'] === $model
|
||||
&& $result['data']['model_label'] === $label && $result['data']['image_sha256'] === $digest
|
||||
&& $result['data']['analysis'] === $valid, 'explicit model returns its identity and image-bound tentative TCM response');
|
||||
$expect(count($GLOBALS['tongueCalls']) === 2 && !is_file($filePath), 'each model request performs only one upload and chat, with temporary JPEG cleanup');
|
||||
[$modelUpload, $modelChat] = $GLOBALS['tongueCalls'];
|
||||
foreach ([$modelUpload, $modelChat] as $options) {
|
||||
$expect(in_array('Authorization: Bearer ' . $config['models'][$model]['api_key'], $options[CURLOPT_HTTPHEADER], true),
|
||||
'selected model credentials used for both private upload and analysis');
|
||||
}
|
||||
$modelPayload = json_decode($modelChat[CURLOPT_POSTFIELDS], true);
|
||||
$expect($modelUpload[CURLOPT_POSTFIELDS]['file']->getFilename() === $filePath
|
||||
&& $modelPayload['files'] === [['type' => 'image', 'transfer_method' => 'local_file', 'upload_file_id' => $uploadId]],
|
||||
'selected model receives exactly its own uploaded JPEG, never another model upload or a text-only body');
|
||||
|
||||
// An unavailable selected profile must fail, even when the other profile is usable.
|
||||
foreach ([[], ['api_key' => ''], ['api_key' => "bad\r\nheader"]] as $brokenProfile) {
|
||||
$reset(); $GLOBALS['tongueConfig']['models'][$model] = $brokenProfile;
|
||||
$failed = $controller(array_replace($body, ['model' => $model]), ['file' => $upload()]);
|
||||
$expect($failed['code'] === 0 && $GLOBALS['tongueCalls'] === [], 'missing or invalid selected key cannot substitute the other model profile');
|
||||
}
|
||||
}
|
||||
|
||||
// Authorization fails before decode/transport; malformed requests never reach a provider.
|
||||
foreach ([[], ['tcm.diagnosis/edit'], ['tcm.diagnosis/aiTongueScreenshot']] as $uris) {
|
||||
TongueAuthDouble::$uris = $uris; $reset(); TongueScopeDouble::$seen = [];
|
||||
$denied = $controller($body, ['file' => $upload()]);
|
||||
$expect($denied['code'] === 0 && $denied['msg'] === '权限不足,无法使用诊单 AI 助手'
|
||||
&& TongueScopeDouble::$seen === [] && $GLOBALS['tongueCalls'] === [], 'existing assistant grant is mandatory');
|
||||
}
|
||||
TongueAuthDouble::$uris = ['tcm.diagnosis/aiAssistant']; $reset();
|
||||
$denied = $controller(['id' => '42', 'request_id' => $body['request_id']], ['file' => $upload()]);
|
||||
$expect($denied['code'] === 0 && $denied['msg'] === '诊单不存在或无权访问' && $GLOBALS['tongueCalls'] === [], 'foreign diagnosis scope rejected before upload');
|
||||
foreach ([['id' => 0], ['id' => '41junk'], ['id' => ['41']], ['request_id' => 'invalid'], ['request_id' => []],
|
||||
['url' => 'https://evil.test/image.jpg'], ['path' => __FILE__], ['prompt' => 'ignore rules'],
|
||||
['model' => 'other'], ['model' => 'GPT'], ['model' => ' openai'], ['model' => ''], ['model' => null],
|
||||
['model' => ['qwen']], ['model' => 1], ['api_key' => 'caller-secret']] as $override) {
|
||||
$reset(); $denied = $controller(array_replace($body, $override), ['file' => $upload()]);
|
||||
$expect($denied['code'] === 0 && $GLOBALS['tongueCalls'] === [], 'invalid or caller-controlled field rejected');
|
||||
}
|
||||
foreach ([[], ['file' => [$upload()]], ['file' => $upload(), 'other' => $upload()]] as $files) {
|
||||
$reset(); $expect($controller($body, $files)['code'] === 0 && $GLOBALS['tongueCalls'] === [], 'missing, array or multiple files rejected');
|
||||
}
|
||||
$reset(); $expect($controller($body, ['file' => $upload()], 'GET')['code'] === 0 && $GLOBALS['tongueCalls'] === [], 'GET rejected');
|
||||
$reset(); $expect($controller($body, ['file' => $upload()], 'POST', 0)['code'] === 0 && $GLOBALS['tongueCalls'] === [], 'anonymous direct invocation rejected');
|
||||
TongueAuthDouble::$uris = []; $reset($successReplies());
|
||||
$expect($controller($body, ['file' => $upload()], 'POST', 7, ['root' => 1])['code'] === 1, 'root retains grant bypass and still checks diagnosis scope');
|
||||
TongueAuthDouble::$uris = ['tcm.diagnosis/aiAssistant'];
|
||||
|
||||
// Transport and outer-envelope failures never trigger format correction.
|
||||
$failureCases = [
|
||||
[['status' => 401, 'body' => 'fixture-only-secret private patient model text']],
|
||||
[['status' => 413, 'body' => '{"error":"file rejected"}']],
|
||||
[['body' => '{"id":""}']],
|
||||
[['body' => '{"id":"synthetic-file-123"}', 'seconds' => 51]],
|
||||
[['body' => '{"id":"synthetic-file-123"}'], ['errno' => CURLE_OPERATION_TIMEDOUT]],
|
||||
[['body' => '{"id":"synthetic-file-123"}'], ['status' => 422, 'body' => 'invalid inputs: fixture-only-secret']],
|
||||
[['body' => '{"id":"synthetic-file-123"}'], ['body' => str_repeat('x', 65537)]],
|
||||
[['body' => '{"id":"synthetic-file-123"}'], ['status' => 401, 'body' => 'fixture-only-secret']],
|
||||
[['body' => '{"id":"synthetic-file-123"}'], ['body' => 'not-json']],
|
||||
[['body' => '{"id":"synthetic-file-123"}'], ['body' => 'null']],
|
||||
[['body' => '{"id":"synthetic-file-123"}'], ['body' => '{}']],
|
||||
[['body' => '{"id":"synthetic-file-123"}'], ['body' => '{"answer":42}']],
|
||||
[['body' => '{"id":"synthetic-file-123"}'], $answerReply(str_repeat('x', 32769))],
|
||||
];
|
||||
foreach ($failureCases as $replies) {
|
||||
$reset($replies); $file = $upload(); $failed = $controller($body, ['file' => $file]);
|
||||
$expect($failed['code'] === 0 && !str_contains(json_encode($failed), 'fixture-only-secret')
|
||||
&& !str_contains(json_encode($failed), 'private patient') && !is_file($file->getPathname()), 'safe failure envelope and local cleanup');
|
||||
$expect(count($GLOBALS['tongueCalls']) <= count($replies) && count($GLOBALS['tongueCalls']) <= 2, 'transport or envelope failure never starts correction or image-free fallback');
|
||||
}
|
||||
foreach (['qwen' => '千问', 'openai' => 'GPT'] as $profile => $label) {
|
||||
$reset([['body' => '{"id":"synthetic-file-123"}'], ['status' => 400, 'body' => json_encode([
|
||||
'code' => 'invalid_param', 'message' => 'Run failed: [models] Error: API request failed with status code 404: 404 page not found fixture-only-secret'])]]);
|
||||
$failed = $controller(array_replace($body, ['model' => $profile]), ['file' => $upload()]);
|
||||
$expect($failed['code'] === 0 && $failed['msg'] === $label . ' 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。'
|
||||
&& count($GLOBALS['tongueCalls']) === 2, 'known upstream model 404 receives actionable safe configuration message without provider detail or retry');
|
||||
}
|
||||
$absent = ['image_quality' => 'unusable', 'quality_note' => '主画面未见舌头', 'features' => [], 'limitations' => ['只显示脸部'],
|
||||
'tcm_diagnosis' => ['status' => 'insufficient', 'summary' => '图片依据不足,无法提出辨证方向',
|
||||
'candidates' => [], 'missing_information' => ['缺少清晰舌象、症状问诊和脉象检查']]];
|
||||
$reset([['body' => '{"id":"synthetic-file-123"}'], ['body' => json_encode(['answer' => json_encode($absent)])]]);
|
||||
$expect($controller($body, ['file' => $upload()])['data']['analysis'] === $absent, 'no tongue remains valid empty observation, not a fabricated finding');
|
||||
$unusableCandidate = $absent; $unusableCandidate['tcm_diagnosis'] = $valid['tcm_diagnosis'];
|
||||
$unsupportedBasis = $valid; $unsupportedBasis['tcm_diagnosis']['candidates'][0]['basis'] = ['舌体颜色'];
|
||||
$certainDiagnosis = $valid; $certainDiagnosis['tcm_diagnosis']['summary'] = '确诊为寒湿证';
|
||||
$inventedPulse = $valid; $inventedPulse['tcm_diagnosis']['summary'] = '患者伴有乏力,脉象为弦滑';
|
||||
$normalCandidate = $valid; $normalCandidate['tcm_diagnosis']['candidates'][0]['name'] = '正常';
|
||||
$clinicalLimitation = $valid; $clinicalLimitation['limitations'] = ['缺少脉象资料'];
|
||||
$invalidAnswers = ['诊断:湿热,建议用药'];
|
||||
foreach ([$unusableCandidate, $unsupportedBasis, $certainDiagnosis, $inventedPulse, $normalCandidate, $clinicalLimitation] as $invalid) {
|
||||
$invalidAnswers[] = json_encode($invalid, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
}
|
||||
foreach ($invalidAnswers as $invalidAnswer) {
|
||||
$reset([['body' => '{"id":"synthetic-file-123"}'], $answerReply($invalidAnswer), $answerReply($invalidAnswer)]);
|
||||
$file = $upload(); $failed = $controller(array_replace($body, ['model' => 'openai']), ['file' => $file]);
|
||||
$expect($failed['code'] === 0 && $failed['msg'] === '截图分析结果格式无效,请重新截图后重试'
|
||||
&& count($GLOBALS['tongueCalls']) === 3 && $GLOBALS['tongueClosed'] === 3 && !is_file($file->getPathname()),
|
||||
'invalid answer and invalid correction fail safely after exactly two chats, without fallback or retained image');
|
||||
}
|
||||
|
||||
// Parser rejection permits one same-image regeneration, without replaying model content.
|
||||
$rejectedMarker = 'fixture-only-rejected-answer-never-replay';
|
||||
$rejectedData = $normalCandidate; $rejectedData['quality_note'] = '舌头可见,' . $rejectedMarker;
|
||||
$rejectedAnswer = json_encode($rejectedData, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
$correctedAnswer = json_encode($valid, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
foreach (['qwen' => '千问', 'openai' => 'GPT'] as $model => $label) {
|
||||
$reset([['body' => '{"id":"synthetic-file-123"}', 'seconds' => 2],
|
||||
$answerReply($rejectedAnswer, 6), $answerReply($correctedAnswer)]);
|
||||
$file = $upload(); $digest = hash_file('sha256', $file->getPathname());
|
||||
$result = $controller(array_replace($body, ['model' => $model]), ['file' => $file]);
|
||||
$expect($result['code'] === 1 && $result['data'] === ['request_id' => $body['request_id'], 'diagnosis_id' => 41,
|
||||
'image_sha256' => $digest, 'analysis' => $valid, 'model' => $model, 'model_label' => $label],
|
||||
'valid correction preserves the exact image, request, model and result contract');
|
||||
$expect(count($GLOBALS['tongueCalls']) === 3 && $GLOBALS['tongueClosed'] === 3 && !is_file($file->getPathname()),
|
||||
'valid correction performs one upload and two closed model calls then removes the temporary image');
|
||||
[$up, $firstChat, $correctionChat] = $GLOBALS['tongueCalls'];
|
||||
$firstPayload = json_decode($firstChat[CURLOPT_POSTFIELDS], true);
|
||||
$correctionPayload = json_decode($correctionChat[CURLOPT_POSTFIELDS], true);
|
||||
$expect($correctionChat[CURLOPT_URL] === $firstChat[CURLOPT_URL]
|
||||
&& $firstPayload['files'] === $correctionPayload['files']
|
||||
&& $correctionPayload['user'] === $firstPayload['user']
|
||||
&& $correctionPayload['user'] === $up[CURLOPT_POSTFIELDS]['user']
|
||||
&& json_decode($correctionChat[CURLOPT_POSTFIELDS])->inputs instanceof stdClass
|
||||
&& !isset($correctionPayload['conversation_id']), 'correction reuses the same private upload and anonymous user without history');
|
||||
$expect(array_diff_key($correctionPayload, $firstPayload) === []
|
||||
&& array_diff_key($firstPayload, $correctionPayload) === []
|
||||
&& array_replace($correctionPayload, ['query' => $firstPayload['query']]) === $firstPayload,
|
||||
'only the fixed query changes between analysis and correction');
|
||||
$expect(str_starts_with($correctionPayload['query'], $firstPayload['query'] . "\n")
|
||||
&& str_contains($correctionPayload['query'], '唯一一次格式纠正')
|
||||
&& str_contains($correctionPayload['query'], 'limitations 只写')
|
||||
&& str_contains($correctionPayload['query'], 'tcm_diagnosis.missing_information')
|
||||
&& str_contains($correctionPayload['query'], '正常、健康、无异常')
|
||||
&& str_contains($correctionPayload['query'], '保留原图中实际可见的 features')
|
||||
&& !str_contains($correctionChat[CURLOPT_POSTFIELDS], $rejectedMarker),
|
||||
'fixed correction rules preserve clinical boundaries and never contain the rejected answer');
|
||||
$expect($firstChat[CURLOPT_TIMEOUT_MS] === 48000 && $correctionChat[CURLOPT_TIMEOUT_MS] === 42000,
|
||||
'both upload and initial analysis time are deducted from the unchanged total deadline');
|
||||
foreach ([$up, $firstChat, $correctionChat] as $options) {
|
||||
$expect(in_array('Authorization: Bearer ' . $config['models'][$model]['api_key'], $options[CURLOPT_HTTPHEADER], true)
|
||||
&& $options[CURLOPT_FOLLOWLOCATION] === false && $options[CURLOPT_PROXY] === ''
|
||||
&& $options[CURLOPT_SSL_VERIFYPEER] === true && $options[CURLOPT_SSL_VERIFYHOST] === 2,
|
||||
'correction keeps the selected profile credentials and transport protections');
|
||||
}
|
||||
}
|
||||
|
||||
foreach ([46, 48] as $analysisSeconds) {
|
||||
$reset([['body' => '{"id":"synthetic-file-123"}', 'seconds' => 2], $answerReply($rejectedMarker, $analysisSeconds)]);
|
||||
$file = $upload(); $failed = $controller($body, ['file' => $file]);
|
||||
$expect($failed['code'] === 0 && $failed['msg'] === '截图分析结果格式无效,请重新截图后重试'
|
||||
&& count($GLOBALS['tongueCalls']) === 2 && $GLOBALS['tongueClosed'] === 2 && !is_file($file->getPathname()),
|
||||
'less than three seconds remaining preserves the original parser error without another call');
|
||||
}
|
||||
$reset([['body' => '{"id":"synthetic-file-123"}', 'seconds' => 2],
|
||||
$answerReply($rejectedMarker, 45), $answerReply($correctedAnswer)]);
|
||||
$expect($controller($body, ['file' => $upload()])['code'] === 1
|
||||
&& count($GLOBALS['tongueCalls']) === 3 && $GLOBALS['tongueCalls'][2][CURLOPT_TIMEOUT_MS] === 3000,
|
||||
'exactly three seconds remaining permits a correction without extending the deadline');
|
||||
|
||||
foreach ([['status' => 401, 'body' => 'fixture-only-secret private patient model text'],
|
||||
['status' => 400, 'body' => json_encode(['code' => 'invalid_param',
|
||||
'message' => 'Run failed: [models] Error: status code 404 fixture-only-secret'])],
|
||||
['errno' => CURLE_OPERATION_TIMEDOUT], ['body' => 'not-json'], ['body' => '{"answer":null}'],
|
||||
$answerReply(str_repeat('x', 32769))] as $correctionFailure) {
|
||||
$reset([['body' => '{"id":"synthetic-file-123"}'], $answerReply($rejectedMarker), $correctionFailure]);
|
||||
$file = $upload(); $failed = $controller($body, ['file' => $file]);
|
||||
$expect($failed['code'] === 0 && count($GLOBALS['tongueCalls']) === 3 && $GLOBALS['tongueClosed'] === 3
|
||||
&& !is_file($file->getPathname()) && !str_contains(json_encode($failed), 'fixture-only-secret')
|
||||
&& !str_contains(json_encode($failed), 'private patient') && !str_contains(json_encode($failed), $rejectedMarker),
|
||||
'correction transport or envelope failure ends safely without a third chat or retained image');
|
||||
}
|
||||
|
||||
foreach ([['enable' => false], ['base_url' => 'https://evil.test/v1?leak=yes'],
|
||||
['base_url' => 'https://user:password@evil.test'], ['base_url' => 'file:///private'],
|
||||
['base_url' => 'https://example.test/v1/chat/completions'],
|
||||
['models' => ['qwen' => ['api_key' => "key\r\nX-Injection: yes"]]]] as $override) {
|
||||
$reset(); $GLOBALS['tongueConfig'] = array_replace($config, $override);
|
||||
$expect($controller($body, ['file' => $upload()])['code'] === 0 && $GLOBALS['tongueCalls'] === [], 'invalid service configuration fails before network');
|
||||
}
|
||||
$reset($successReplies());
|
||||
$GLOBALS['tongueConfig']['required_attachment_upload']['ca_file'] = __DIR__ . '/missing-optional-trust-store.pem';
|
||||
$expect($controller($body, ['file' => $upload()])['code'] === 1, 'stale optional CA path uses system trust like the original transport');
|
||||
foreach ($GLOBALS['tongueCalls'] as $call) {
|
||||
$expect(!isset($call[CURLOPT_CAINFO]) && $call[CURLOPT_SSL_VERIFYPEER] === true && $call[CURLOPT_SSL_VERIFYHOST] === 2,
|
||||
'system CA fallback preserves peer and hostname verification for upload and analysis');
|
||||
}
|
||||
$reset($successReplies());
|
||||
$GLOBALS['tongueReadableCa'] = __FILE__;
|
||||
$GLOBALS['tongueConfig']['required_attachment_upload']['ca_file'] = __FILE__;
|
||||
$expect($controller($body, ['file' => $upload()])['code'] === 1
|
||||
&& $GLOBALS['tongueCalls'][0][CURLOPT_CAINFO] === __FILE__ && $GLOBALS['tongueCalls'][1][CURLOPT_CAINFO] === __FILE__,
|
||||
'existing readable configured trust bundle is kept for both requests');
|
||||
foreach (['https://dify.fixture.test', 'https://dify.fixture.test/v1/chat-messages'] as $base) {
|
||||
$reset($successReplies()); $GLOBALS['tongueConfig']['base_url'] = $base;
|
||||
$expect($controller($body, ['file' => $upload()])['code'] === 1
|
||||
&& $GLOBALS['tongueCalls'][0][CURLOPT_URL] === 'https://dify.fixture.test/v1/files/upload', 'existing Dify base URL forms supported');
|
||||
}
|
||||
|
||||
// Real auth middleware, with menu lookup deliberately explosive: exact shared grant only.
|
||||
$route = new class {
|
||||
public array $adminInfo = ['admin_id' => 7, 'root' => 0, 'login_ip' => '127.0.0.1'];
|
||||
public object $controllerObject;
|
||||
public function __construct() { $this->controllerObject = new class { public function isNotNeedLogin(): bool { return false; } }; }
|
||||
public function controller(): string { return 'tcm.Diagnosis'; }
|
||||
public function action(): string { return 'aiTongueScreenshot'; }
|
||||
public function param($name, $default = null) { return $default; }
|
||||
};
|
||||
$middleware = new AuthMiddleware();
|
||||
foreach ([[], ['tcm.diagnosis/edit'], ['tcm.diagnosis/aiTongueScreenshot'], ['tcm.diagnosis/aiAssistant']] as $uris) {
|
||||
TongueAuthDouble::$uris = $uris;
|
||||
$result = $middleware->handle($route, static fn () => 'ALLOWED');
|
||||
$expect(($result === 'ALLOWED') === in_array('tcm.diagnosis/aiAssistant', $uris, true), 'middleware shares existing permission without menu-registration bypass');
|
||||
}
|
||||
$route->adminInfo['root'] = 1; TongueAuthDouble::$uris = [];
|
||||
$expect($middleware->handle($route, static fn () => 'ALLOWED') === 'ALLOWED', 'middleware root behavior preserved');
|
||||
|
||||
// If operation audit logging is re-enabled, this endpoint must still not persist model text or submitted parameters.
|
||||
$logRequest = (new \app\Request())->setController('tcm.Diagnosis')->setAction('aiTongueScreenshot');
|
||||
$container->instance('request', $logRequest);
|
||||
$expect((new \app\adminapi\listener\OperationLog())->handle(new stdClass()) === null, 'generic audit listener skips temporary screenshot analysis before reading any data');
|
||||
$logicSource = file_get_contents(dirname(__DIR__) . '/app/adminapi/logic/tcm/TongueScreenshotLogic.php');
|
||||
$expect(!preg_match('/DiagnosisLogic::detail|::save|->save|::insert|->insert|::update|->update|Log::|base64/', $logicSource), 'screenshot logic contains no chart aggregation, mutation or payload logging');
|
||||
} finally {
|
||||
foreach ($paths as $path) if (is_file($path)) unlink($path);
|
||||
}
|
||||
echo "Diagnosis tongue screenshot integration (no network): {$checks} checks OK\n";
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\common\service\TongueScreenshotAnalysis as Analysis;
|
||||
use app\common\service\TongueScreenshotImage as Image;
|
||||
use think\file\UploadedFile;
|
||||
|
||||
$checks = 0;
|
||||
$expect = static function (bool $ok, string $label) use (&$checks): void {
|
||||
if (!$ok) throw new RuntimeException('FAIL: ' . $label);
|
||||
++$checks;
|
||||
};
|
||||
$reject = static function (callable $call, string $label) use ($expect): void {
|
||||
try { $call(); } catch (DomainException $e) { $expect(true, $label); return; }
|
||||
$expect(false, $label);
|
||||
};
|
||||
$encode = static fn (array $data): string => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
$valid = ['image_quality' => 'usable', 'quality_note' => '主画面舌头可见,轮廓较清楚',
|
||||
'features' => [['name' => '舌苔颜色', 'observation' => '可见舌苔偏白']], 'limitations' => [],
|
||||
'tcm_diagnosis' => ['status' => 'possible_patterns', 'summary' => '仅供参考,可考虑寒湿方向,需问诊和脉诊复核,不能据此确诊',
|
||||
'candidates' => [['name' => '寒湿倾向', 'basis' => ['舌苔颜色'], 'verify' => ['需询问有无畏寒,并检查脉象是否沉迟']]],
|
||||
'missing_information' => ['尚缺症状问诊和脉象检查']]];
|
||||
$expect(Analysis::parse($encode($valid)) === $valid, 'observable feature returned without augmentation');
|
||||
$expect(Analysis::parse("<think>discard private reasoning</think>```json\n" . $encode($valid) . "\n```") === $valid, 'reasoning removed before exact JSON parsing');
|
||||
$limited = $valid; $limited['image_quality'] = 'limited'; $limited['limitations'] = ['舌根被遮挡'];
|
||||
$expect(Analysis::parse($encode($limited)) === $limited, 'limited quality retains only visible features');
|
||||
$insufficient = ['status' => 'insufficient', 'summary' => '图片依据不足,无法提出辨证方向',
|
||||
'candidates' => [], 'missing_information' => ['缺少清晰舌象、症状问诊和脉象检查']];
|
||||
$absent = ['image_quality' => 'unusable', 'quality_note' => '主画面未见舌头', 'features' => [],
|
||||
'limitations' => ['主画面只显示脸部'], 'tcm_diagnosis' => $insufficient];
|
||||
$expect(Analysis::parse($encode($absent)) === $absent, 'no tongue has empty observations and a reason');
|
||||
foreach (['quality' => 'uncertain', 'extra' => true] as $key => $value) {
|
||||
$data = $valid; $data[$key] = $value;
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'unknown root field ' . $key);
|
||||
}
|
||||
foreach (['blurred', null, 1, ['usable']] as $quality) {
|
||||
$data = $valid; $data['image_quality'] = $quality;
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'quality enum strictly typed');
|
||||
}
|
||||
foreach ([[], ['normal' => true], [['name' => '证型', 'observation' => '湿热']],
|
||||
[['name' => '舌苔颜色', 'observation' => '白', 'extra' => 'ignored']],
|
||||
array_fill(0, 8, $valid['features'][0]), array_fill(0, 2, $valid['features'][0])] as $features) {
|
||||
$data = $valid; $data['features'] = $features;
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'invalid or duplicate features rejected');
|
||||
}
|
||||
foreach (['舌象正常', '未见明显异常', '提示湿热证', '建议服用中药', '高血压风险', '<script>alert(1)</script>',
|
||||
'查看 https://bad.example/secret', '联系 13800138000', "偏白\n泄漏", str_repeat('白', 181), 'white', ''] as $text) {
|
||||
$data = $valid; $data['features'][0]['observation'] = $text;
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'unsafe, clinical or oversized observation rejected');
|
||||
}
|
||||
$data = $absent; $data['features'] = $valid['features'];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'unusable cannot invent normal-looking features');
|
||||
$data = $absent; $data['quality_note'] = '画面清晰'; $data['limitations'] = ['舌苔偏白'];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'unusable requires an actual visibility reason');
|
||||
$data = $valid; $data['quality_note'] = '主画面未见舌头';
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'no tongue note cannot contradict visible features');
|
||||
$data = $limited; $data['limitations'] = [];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'limited must explain its limits');
|
||||
$data = $valid; $data['quality_note'] = str_repeat('清', 241);
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'quality note bounded');
|
||||
$data = $valid; $data['limitations'] = array_fill(0, 7, '受光照影响');
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'limitation count bounded');
|
||||
$data = $valid; $data['limitations'] = [str_repeat('糊', 161)];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'limitation length bounded');
|
||||
foreach (['{}', '[]', 'not json', str_repeat('x', 32769), $encode($valid) . '附加报告'] as $text) {
|
||||
$reject(fn () => Analysis::parse($text), 'invalid response rejected');
|
||||
}
|
||||
$expect(str_contains(Analysis::prompt(), '主画面') && str_contains(Analysis::prompt(), '小窗医生')
|
||||
&& str_contains(Analysis::prompt(), 'features 必须为空数组'), 'prompt explicitly excludes inset and no-tongue hallucination');
|
||||
$expect(str_contains(Analysis::prompt(), '仅 tcm_diagnosis 区可使用中医术语')
|
||||
&& str_contains(Analysis::prompt(), '不能编造症状、脉象、既往史或患者自述')
|
||||
&& str_contains(Analysis::prompt(), '不能仅凭舌图确诊'), 'prompt separates tentative TCM direction from observed facts and unavailable clinical evidence');
|
||||
|
||||
// The schema binds proposed patterns to named observations; text guards catch known
|
||||
// unsafe forms, but tests do not claim they can verify a model\'s medical reasoning.
|
||||
$data = $valid; $data['tcm_diagnosis'] = $insufficient;
|
||||
$expect(Analysis::parse($encode($data)) === $data, 'visible tongue may still provide insufficient evidence for a pattern');
|
||||
$data = $valid; unset($data['tcm_diagnosis']);
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'TCM section is mandatory');
|
||||
foreach ([null, [], '寒湿'] as $diagnosis) {
|
||||
$data = $valid; $data['tcm_diagnosis'] = $diagnosis;
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'TCM section must be an object');
|
||||
}
|
||||
$data = $absent; $data['tcm_diagnosis'] = $valid['tcm_diagnosis'];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'unusable tongue cannot carry candidate patterns');
|
||||
foreach ([['status' => 'certain'], ['status' => null], ['status' => 'insufficient'], ['candidates' => []],
|
||||
['candidates' => array_fill(0, 4, $valid['tcm_diagnosis']['candidates'][0])],
|
||||
['missing_information' => []], ['missing_information' => array_fill(0, 7, '尚缺问诊')],
|
||||
['missing_information' => [str_repeat('问', 161)]], ['summary' => str_repeat('参', 241)], ['confidence' => 0.9]] as $override) {
|
||||
$data = $valid; $data['tcm_diagnosis'] = array_replace($valid['tcm_diagnosis'], $override);
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'TCM status, required arrays, exact fields and bounds enforced');
|
||||
}
|
||||
foreach ([['name' => str_repeat('湿', 41)], ['basis' => []], ['basis' => ['舌体颜色']], ['basis' => ['脉象']],
|
||||
['basis' => ['可见舌苔偏白']], ['basis' => ['舌苔颜色', '舌苔颜色']], ['basis' => [null]],
|
||||
['verify' => []], ['verify' => array_fill(0, 5, '需问诊核实')], ['verify' => [str_repeat('需', 161)]],
|
||||
['verify' => ['脉象为弦滑']], ['verify' => ['患者伴有口苦']], ['verify' => ['患者自诉乏力']],
|
||||
['confidence' => 98]] as $override) {
|
||||
$data = $valid; $data['tcm_diagnosis']['candidates'][0] = array_replace($data['tcm_diagnosis']['candidates'][0], $override);
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'candidate bounds, supported feature names and needed corroboration enforced');
|
||||
}
|
||||
foreach (['不能仅凭舌象确定证型,需结合问诊与脉诊', '尚未确诊,候选方向仍待核实', '不确定具体证型,需补充症状信息'] as $text) {
|
||||
$data = $valid; $data['tcm_diagnosis']['summary'] = $text;
|
||||
$expect(Analysis::parse($encode($data))['tcm_diagnosis']['summary'] === $text, 'explicit uncertainty is not mistaken for a definitive diagnosis');
|
||||
}
|
||||
foreach (['确诊为寒湿证', '不能仅凭舌象确诊,但可以确定是寒湿证', '诊断为脾虚证', '患者伴有口苦,脉象为弦滑', '既往有高血压',
|
||||
'置信度百分之九十', '可能性为90%', '建议服用中药', '治疗采用清热法', '建议黄芪30克', '保证身体健康'] as $text) {
|
||||
$data = $valid; $data['tcm_diagnosis']['summary'] = $text;
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'known certainty, invented clinical facts and treatment forms rejected');
|
||||
}
|
||||
$data = $valid; $data['features'][0]['observation'] = '寒湿倾向';
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'TCM terms allowed only in diagnosis, not observations');
|
||||
$data = $valid; $data['tcm_diagnosis']['missing_information'] = [];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'image-only response can never claim complete clinical evidence');
|
||||
|
||||
foreach (['未见舌根,舌尖可见', '未见舌体边缘,中央舌面可见', '未见舌尖,舌面中部可见', '未见舌苔,舌体清晰可见'] as $limited) {
|
||||
$data = $valid; $data['limitations'] = [$limited];
|
||||
$expect(Analysis::parse($encode($data)) === $data, 'partially unobserved anatomy is not mistaken for an absent tongue');
|
||||
}
|
||||
foreach (['主画面未见舌头', '看不到患者的舌体', '没有舌,只有脸部'] as $absentNote) {
|
||||
$data = $valid; $data['quality_note'] = $absentNote;
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'whole tongue absence still conflicts with nonempty features');
|
||||
}
|
||||
foreach (['目前难以确定具体证候方向,需结合问诊与脉诊', '无法仅凭一张舌图确定证型,需结合问诊与脉诊'] as $uncertain) {
|
||||
$data = $valid; $data['tcm_diagnosis']['summary'] = $uncertain;
|
||||
$expect(Analysis::parse($encode($data)) === $data, 'bounded uncertainty variants are accepted');
|
||||
}
|
||||
$data = $valid; $data['tcm_diagnosis']['summary'] = '无法仅凭一张舌图确定,但可以确定是寒湿证';
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'negated clause cannot bypass a following certain assertion');
|
||||
$data = $valid; $data['tcm_diagnosis']['candidates'][0]['verify'] = ['口渴吗?'];
|
||||
$expect(Analysis::parse($encode($data)) === $data, 'explicit question ending is valid needed verification');
|
||||
$data['tcm_diagnosis']['candidates'][0]['verify'] = ['患者伴有口苦吗?'];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'question punctuation does not bypass the existing assertion guard');
|
||||
|
||||
// Information needed for the consultation is distinct from an asserted fact or treatment.
|
||||
foreach (['缺少既往用药史', '需补充近期用药情况和药物过敏史', '尚缺患者自述症状资料', '患者自述的症状信息'] as $missing) {
|
||||
$data = $valid; $data['tcm_diagnosis']['missing_information'] = [$missing];
|
||||
$expect(Analysis::parse($encode($data)) === $data, 'missing information category preserved without treating it as advice or a symptom assertion');
|
||||
}
|
||||
foreach (['需询问既往有无相关病史', '需询问是否服用药物', '需询问近期服药情况', '睡眠和二便是否正常?', '有无排便异常?', '请问近期睡眠如何?'] as $question) {
|
||||
$data = $valid; $data['tcm_diagnosis']['candidates'][0]['verify'] = [$question];
|
||||
$expect(Analysis::parse($encode($data)) === $data, 'explicit question remains a question rather than a health or medication conclusion');
|
||||
}
|
||||
foreach (['缺少既往用药信息,建议服药', '缺少用药史,建议黄芪30克', '患者自述乏力', '患者自述症状资料,患者伴有口苦', '既往有高血压', '睡眠和二便正常', '明确诊断为寒湿证'] as $badMissing) {
|
||||
$data = $valid; $data['tcm_diagnosis']['missing_information'] = [$badMissing];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'information category exception cannot hide appended advice or invented facts');
|
||||
}
|
||||
foreach (['需询问既往有无相关病史,既往有高血压', '是否服用药物,建议继续服药', '是否用药,建议黄芪30克', '是否正常,但可以确定是寒湿证', '是否大便正常,小便正常', '需询问近期用药情况,脉象为弦滑'] as $badQuestion) {
|
||||
$data = $valid; $data['tcm_diagnosis']['candidates'][0]['verify'] = [$badQuestion];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'question exception is bounded to its clause and keeps remaining guards');
|
||||
}
|
||||
foreach (['未见舌头后部,舌尖可见', '未见舌体后部,舌面中央可见', '未见舌体全貌,舌面中央可见'] as $partial) {
|
||||
$data = $valid; $data['limitations'] = [$partial];
|
||||
$expect(Analysis::parse($encode($data)) === $data, 'unobserved posterior or complete outline does not mean no tongue is visible');
|
||||
}
|
||||
foreach (['不能做出确定诊断,需结合问诊和脉诊', '无法明确诊断,需结合问诊和脉诊', '不能仅凭本次截图确定证型,需结合问诊和脉诊', '不能仅凭单张舌头照片确定证型,需结合问诊和脉诊'] as $uncertain) {
|
||||
$data = $valid; $data['tcm_diagnosis']['summary'] = $uncertain;
|
||||
$expect(Analysis::parse($encode($data)) === $data, 'bounded negated diagnosis is allowed');
|
||||
$data['tcm_diagnosis']['summary'] .= ',但可以确定是寒湿证';
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'negated diagnosis does not hide a following positive diagnosis');
|
||||
}
|
||||
foreach (['缺少患者自述症状资料', '缺少脉象资料,无法进一步辨证', '舌下未拍摄,无法判断血瘀'] as $wrongField) {
|
||||
$data = $valid; $data['limitations'] = [$wrongField];
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'clinical missing information is still prohibited in pure imaging limitations');
|
||||
}
|
||||
$data = $valid; $data['tcm_diagnosis']['candidates'][0]['name'] = '正常舌象';
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'normal appearance cannot become a clinical candidate');
|
||||
$expect(str_contains(Analysis::prompt(), 'limitations 只能写') && str_contains(Analysis::prompt(), '缺少既往用药史')
|
||||
&& str_contains(Analysis::prompt(), '不要将“正常舌象”'), 'prompt matches field roles and avoids the observed repeated Qwen failures');
|
||||
foreach (['图像清晰,白平衡正常,舌面细节可见', '曝光正常,舌面存在反光', '光线正常,舌根被遮挡'] as $camera) {
|
||||
$data = $valid; $data['quality_note'] = $camera;
|
||||
$expect(Analysis::parse($encode($data)) === $data, 'camera conditions are not mistaken for a clinical normality claim');
|
||||
foreach ([',舌象正常', ',表明患者健康', ',未见明显异常', ',提示湿热证'] as $claim) {
|
||||
$data['quality_note'] = $camera . $claim;
|
||||
$reject(fn () => Analysis::parse($encode($data)), 'camera exception does not hide an appended clinical conclusion');
|
||||
}
|
||||
}
|
||||
|
||||
$paths = [];
|
||||
$make = static function (string $format = 'jpeg', int $width = 128, int $height = 128) use (&$paths): UploadedFile {
|
||||
$path = tempnam(sys_get_temp_dir(), 'tongue-synthetic-'); $paths[] = $path;
|
||||
$canvas = imagecreatetruecolor($width, $height);
|
||||
imagefill($canvas, 0, 0, imagecolorallocate($canvas, 160, 100, 100));
|
||||
if ($format === 'jpeg') imagejpeg($canvas, $path, 80); else imagepng($canvas, $path);
|
||||
imagedestroy($canvas);
|
||||
return new UploadedFile($path, 'untrusted-client-name.jpg', 'image/jpeg', UPLOAD_ERR_OK, true);
|
||||
};
|
||||
try {
|
||||
$file = $make(); $digest = hash_file('sha256', $file->getPathname());
|
||||
$image = Image::fromUpload($file);
|
||||
$expect($image->sha256() === $digest && $image->path() === $file->getRealPath(), 'digest binds exact original JPEG bytes');
|
||||
$image->release(); $expect(!is_file($file->getPathname()), 'temporary screenshot removed explicitly');
|
||||
$reject(fn () => Image::fromUpload('https://example.test/photo.jpg'), 'URL cannot become upload');
|
||||
$reject(fn () => Image::fromUpload(['path' => __FILE__]), 'arbitrary path cannot become upload');
|
||||
$reject(fn () => Image::fromUpload($make('png')), 'client MIME/name cannot disguise PNG');
|
||||
$reject(fn () => Image::fromUpload($make('jpeg', 32, 128)), 'too-small JPEG rejected');
|
||||
$reject(fn () => Image::fromUpload($make('jpeg', 8193, 64)), 'oversized dimension rejected before decode');
|
||||
$file = $make(); $source = file_get_contents($file->getPathname());
|
||||
file_put_contents($file->getPathname(), substr($source, 0, -2));
|
||||
$reject(fn () => Image::fromUpload($file), 'truncated JPEG rejected');
|
||||
$file = $make(); $handle = fopen($file->getPathname(), 'ab'); ftruncate($handle, Image::MAX_BYTES + 1); fclose($handle);
|
||||
clearstatcache(true, $file->getPathname());
|
||||
$reject(fn () => Image::fromUpload($file), 'actual file size enforces 10 MiB cap');
|
||||
$file = $make();
|
||||
$reject(fn () => Image::fromUpload(new UploadedFile($file->getPathname(), 'photo.jpg', 'image/jpeg')), 'ordinary local file is not an HTTP upload');
|
||||
$reject(fn () => Image::fromUpload(new UploadedFile($file->getPathname(), 'photo.jpg', 'image/jpeg', UPLOAD_ERR_PARTIAL, true)), 'partial upload rejected');
|
||||
} finally {
|
||||
foreach ($paths as $path) if (is_file($path)) unlink($path);
|
||||
}
|
||||
echo "Tongue screenshot image and response contract: {$checks} checks OK\n";
|
||||
Reference in New Issue
Block a user