Pest.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. use App\Models\AiModel;
  3. use App\Models\Channel;
  4. use App\Models\GroupInfo;
  5. use App\Models\GroupMember;
  6. use App\Models\Sentence;
  7. use App\Models\Share;
  8. use App\Models\UserInfo;
  9. use App\Services\AuthService;
  10. use Firebase\JWT\JWT;
  11. use Firebase\JWT\Key;
  12. use Illuminate\Foundation\Testing\RefreshDatabase;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Support\Str;
  15. use Tests\TestCase;
  16. /*
  17. |--------------------------------------------------------------------------
  18. | Test Case
  19. |--------------------------------------------------------------------------
  20. |
  21. | The closure you provide to your test functions is always bound to a specific PHPUnit test
  22. | case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
  23. | need to change it using the "pest()" function to bind different classes or traits.
  24. |
  25. */
  26. pest()->extend(TestCase::class)
  27. // ->use(RefreshDatabase::class)
  28. ->in('Feature');
  29. /*
  30. |--------------------------------------------------------------------------
  31. | Expectations
  32. |--------------------------------------------------------------------------
  33. |
  34. | When you're writing tests, you often need to check that values meet certain conditions. The
  35. | "expect()" function gives you access to a set of "expectations" methods that you can use
  36. | to assert different things. Of course, you may extend the Expectation API at any time.
  37. |
  38. */
  39. expect()->extend('toBeOne', function () {
  40. return $this->toBe(1);
  41. });
  42. /*
  43. |--------------------------------------------------------------------------
  44. | Functions
  45. |--------------------------------------------------------------------------
  46. |
  47. | While Pest is very powerful out-of-the-box, you may have some testing code specific to your
  48. | project that you don't want to repeat in every file. Here you can also expose helpers as
  49. | global functions to help you to reduce the number of lines of code in your test files.
  50. |
  51. */
  52. function something()
  53. {
  54. // ..
  55. }
  56. /**
  57. * 造一个用户 token。
  58. *
  59. * AuthService::current() 只解 JWT、不查库,所以测试里不必真的建用户;
  60. * payload 结构必须与 AuthService::getUserToken() 保持一致。
  61. */
  62. function userToken(string $userUid, int $userId = 1): string
  63. {
  64. return JWT::encode([
  65. 'nbf' => time(),
  66. 'exp' => time() + 3600,
  67. 'uid' => $userUid,
  68. 'id' => $userId,
  69. ], config('mint.app.jwt_secrets_key'), 'HS512');
  70. }
  71. /**
  72. * 解开一个 token 的 payload。
  73. */
  74. function decodeToken(string $token): object
  75. {
  76. return JWT::decode($token, new Key(config('mint.app.jwt_secrets_key'), 'HS512'));
  77. }
  78. /**
  79. * 把 token 交给 AuthService::current() 判定,返回 user_uid,无效则返回 false。
  80. *
  81. * 所有端点的鉴权都走这里,故用它来断言「token 是否还有效」。
  82. *
  83. * @return string|false
  84. */
  85. function currentUid(string $token)
  86. {
  87. $request = Request::create('/', 'GET');
  88. $request->headers->set('Authorization', 'Bearer '.$token);
  89. $user = AuthService::current($request);
  90. return $user ? $user['user_uid'] : false;
  91. }
  92. /**
  93. * 带用户 token 的请求头。
  94. */
  95. function authHeader(string $userUid): array
  96. {
  97. return ['Authorization' => 'Bearer '.userToken($userUid)];
  98. }
  99. /**
  100. * 建一个用户及其个人 studio,返回 user uid。
  101. *
  102. * StudioApi::getIdByName() 查的是 user_infos.username,所以 studio 名即用户名。
  103. */
  104. function makeStudio(string $username): string
  105. {
  106. $userId = (string) Str::uuid();
  107. (new UserInfo)->forceFill([
  108. 'userid' => $userId,
  109. 'username' => $username,
  110. 'nickname' => $username,
  111. 'password' => 'x',
  112. 'email' => $username.'@example.test',
  113. ])->save();
  114. return $userId;
  115. }
  116. /**
  117. * 建一个属于指定用户的 channel,返回 channel uid。
  118. *
  119. * channels.id 不是自增列,必须显式给值。
  120. */
  121. function makeChannel(string $ownerUid, string $name = 'test channel'): string
  122. {
  123. $uid = (string) Str::uuid();
  124. (new Channel)->forceFill([
  125. 'id' => random_int(1, PHP_INT_MAX),
  126. 'uid' => $uid,
  127. 'type' => 'translation',
  128. 'owner_uid' => $ownerUid,
  129. 'editor_id' => 0,
  130. 'name' => $name,
  131. 'lang' => 'zh-Hans',
  132. 'status' => 30,
  133. 'create_time' => time() * 1000,
  134. 'modify_time' => time() * 1000,
  135. ])->save();
  136. return $uid;
  137. }
  138. /**
  139. * 建一个句子,返回模型
  140. */
  141. function makeSentence(string $channelUid, int $book, int $para, int $wordStart, string $content): Sentence
  142. {
  143. $sentence = new Sentence;
  144. $sentence->forceFill([
  145. // sentences.id 不是自增列,必须显式给值
  146. 'id' => random_int(1, PHP_INT_MAX),
  147. 'uid' => (string) Str::uuid(),
  148. 'book_id' => $book,
  149. 'paragraph' => $para,
  150. 'word_start' => $wordStart,
  151. 'word_end' => $wordStart,
  152. 'channel_uid' => $channelUid,
  153. 'editor_uid' => (string) Str::uuid(),
  154. 'content' => $content,
  155. 'content_type' => 'markdown',
  156. 'strlen' => mb_strlen($content),
  157. 'status' => 30,
  158. 'create_time' => time() * 1000,
  159. 'modify_time' => time() * 1000,
  160. 'language' => 'zh-Hans',
  161. ])->save();
  162. return $sentence;
  163. }
  164. /**
  165. * 建一个团队(group),创建者以 owner(power 0)入团,返回 group uid。
  166. *
  167. * 与 v2 `GroupController@store` 写入的两行一致。
  168. */
  169. function makeGroup(string $ownerUid, string $name = 'test team'): string
  170. {
  171. $uid = (string) Str::uuid();
  172. (new GroupInfo)->forceFill([
  173. 'id' => random_int(1, PHP_INT_MAX),
  174. 'uid' => $uid,
  175. 'name' => $name,
  176. 'owner' => $ownerUid,
  177. 'create_time' => time() * 1000,
  178. 'modify_time' => time() * 1000,
  179. ])->save();
  180. addGroupMember($uid, $ownerUid, 0);
  181. return $uid;
  182. }
  183. /**
  184. * 把用户加进团队。power:0 owner、1 manager、2 普通成员(v2 口径)。
  185. */
  186. function addGroupMember(string $groupUid, string $userUid, int $power = 2, ?string $role = null): GroupMember
  187. {
  188. $member = new GroupMember;
  189. $member->forceFill(array_filter([
  190. 'id' => random_int(1, PHP_INT_MAX),
  191. 'user_id' => $userUid,
  192. 'group_id' => $groupUid,
  193. 'group_name' => GroupInfo::where('uid', $groupUid)->value('name'),
  194. 'power' => $power,
  195. 'role' => $role,
  196. ], fn ($value) => $value !== null))->save();
  197. return $member;
  198. }
  199. /**
  200. * 建一个团队并按角色放好人,返回 [团队 uid, 角色 => 用户 uid]。
  201. *
  202. * owner 走 v2 口径(power 0、role 为空),manager 也是 v2 口径(power 1),
  203. * editor / reader 是 v3 写入的(role 有值)——顺带覆盖 role 为空时按 power 推导。
  204. *
  205. * @return array{0: string, 1: array<string, string>}
  206. */
  207. function makeTeam(): array
  208. {
  209. $users = [];
  210. foreach (['owner', 'manager', 'editor', 'reader', 'outsider'] as $role) {
  211. $users[$role] = makeStudio($role.'-'.Str::random(6));
  212. }
  213. $team = makeGroup($users['owner']);
  214. addGroupMember($team, $users['manager'], 1);
  215. addGroupMember($team, $users['editor'], 2, 'editor');
  216. addGroupMember($team, $users['reader'], 2, 'reader');
  217. return [$team, $users];
  218. }
  219. function memberId(string $team, string $userUid): string
  220. {
  221. return (string) GroupMember::where('group_id', $team)->where('user_id', $userUid)->value('id');
  222. }
  223. /**
  224. * 把 channel 共享给某人或某团队。power:10 读、20 写内容、30 改信息。
  225. */
  226. function grantChannelShare(string $channelUid, string $cooperatorUid, int $power, bool $toTeam = false): void
  227. {
  228. (new Share)->forceFill([
  229. 'id' => random_int(1, PHP_INT_MAX),
  230. 'res_id' => $channelUid,
  231. 'res_type' => 2,
  232. 'cooperator_id' => $cooperatorUid,
  233. 'cooperator_type' => $toTeam ? 1 : 0,
  234. 'power' => $power,
  235. 'create_time' => time() * 1000,
  236. 'modify_time' => time() * 1000,
  237. ])->save();
  238. }
  239. /**
  240. * 建一个 AI 模型账号(ai_models 一行就是一个身份),返回它的 uid;用它的 token 测「只给人类」的写入。
  241. */
  242. function makeModelAccount(string $ownerUid): string
  243. {
  244. $uid = (string) Str::uuid();
  245. (new AiModel)->forceFill([
  246. 'id' => random_int(1, PHP_INT_MAX),
  247. 'uid' => $uid,
  248. 'name' => 'model',
  249. 'real_name' => 'model-'.Str::random(6),
  250. 'model' => 'gpt-4',
  251. 'owner_id' => $ownerUid,
  252. 'editor_id' => $ownerUid,
  253. ])->save();
  254. return $uid;
  255. }