teamBackgroundFile.test.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464
  1. const assert = require('node:assert/strict')
  2. const fs = require('node:fs')
  3. const path = require('node:path')
  4. const { pathToFileURL } = require('node:url')
  5. const vm = require('node:vm')
  6. const rules = require('../utils/teamBackgroundFile')
  7. assert.equal(rules.validateEnterpriseWebsite(' 无 '), '')
  8. assert.equal(rules.validateEnterpriseWebsite('https://example.com'), '')
  9. assert.match(rules.validateEnterpriseWebsite('ftp://example.com'), /http/)
  10. assert.equal(rules.validateBackgroundFile({ name: 'brief.PDF', size: 1 }), '')
  11. assert.match(rules.validateBackgroundFile({ name: 'brief.zip', size: 1 }), /类型/)
  12. assert.match(rules.validateBackgroundFile({ name: 'brief.pdf', size: 50 * 1024 * 1024 + 1 }), /50MB/)
  13. assert.equal(rules.validateBackgroundFile({ name: 'brief.pdf', size: 50 * 1024 * 1024 }), '')
  14. assert.equal(rules.validateBackgroundFile({ name: `${'a'.repeat(251)}.pdf`, size: 1 }), '')
  15. assert.match(rules.validateBackgroundFile({ name: `${'a'.repeat(252)}.pdf`, size: 1 }), /255/)
  16. assert.match(rules.validateBackgroundFile({ name: 'empty.pdf', size: 0 }), /非空/)
  17. const backendExpiry = '2026-07-21 15:30:00'
  18. const explicitOffsetExpiry = '2026-07-21T15:30:00+08:00'
  19. const utcExpiry = '2026-07-21T07:30:00.250Z'
  20. assert.equal(rules.parseSessionExpiresAt(backendExpiry), Date.UTC(2026, 6, 21, 7, 30, 0))
  21. assert.equal(rules.parseSessionExpiresAt(explicitOffsetExpiry), Date.UTC(2026, 6, 21, 7, 30, 0))
  22. assert.equal(rules.parseSessionExpiresAt(utcExpiry), Date.UTC(2026, 6, 21, 7, 30, 0, 250))
  23. assert.equal(rules.getSessionRemainingSeconds(backendExpiry, Date.UTC(2026, 6, 21, 7, 29, 59, 1)), 1)
  24. assert.equal(rules.getSessionRemainingSeconds(backendExpiry, Date.UTC(2026, 6, 21, 7, 30, 1)), 0)
  25. assert.equal(rules.getSessionRemainingSeconds('2026-07-21T15:30:00', 0), 0)
  26. assert.equal(rules.getSessionRemainingSeconds('not-a-date', 0), 0)
  27. const validQueueItem = rules.createBackgroundQueueItem(
  28. { name: 'brief.pdf', path: '/tmp/brief.pdf', size: 1 },
  29. 'valid-file'
  30. )
  31. const invalidQueueItem = rules.createBackgroundQueueItem(
  32. { name: 'archive.zip', path: '/tmp/archive.zip', size: 1 },
  33. 'invalid-file'
  34. )
  35. assert.equal(validQueueItem.status, 'pending')
  36. assert.equal(validQueueItem.progress, 0)
  37. assert.equal(validQueueItem.validationError, '')
  38. assert.equal(invalidQueueItem.status, 'failed')
  39. assert.match(invalidQueueItem.validationError, /类型/)
  40. validQueueItem.status = 'success'
  41. const uploadFailure = {
  42. id: 'upload-failure',
  43. status: 'failed',
  44. validationError: '',
  45. error: '上传失败'
  46. }
  47. assert.deepEqual(
  48. rules.getUploadableBackgroundFiles([validQueueItem, invalidQueueItem, uploadFailure]),
  49. [uploadFailure]
  50. )
  51. const originalTeam = {
  52. id: 12,
  53. teamName: '研发团队',
  54. enterpriseWebsite: ' https://example.com/team ',
  55. coachId: 3,
  56. uploaderId: 4,
  57. source: 'WECHAT'
  58. }
  59. const teamSubmitPayload = rules.createTeamSubmitPayload(originalTeam)
  60. assert.equal(teamSubmitPayload.id, 12)
  61. assert.equal(teamSubmitPayload.enterpriseWebsite, 'https://example.com/team')
  62. assert.equal(Object.hasOwn(teamSubmitPayload, 'coachId'), false)
  63. assert.equal(Object.hasOwn(teamSubmitPayload, 'uploaderId'), false)
  64. assert.equal(Object.hasOwn(teamSubmitPayload, 'source'), false)
  65. assert.equal(originalTeam.coachId, 3, 'payload creation must not mutate the displayed detail')
  66. const textPreviewState = rules.createTextPreviewState({
  67. mode: 'text',
  68. fileName: '背景说明.md',
  69. content: '# 团队背景',
  70. truncated: true
  71. }, 'fallback.md')
  72. assert.deepEqual(textPreviewState, {
  73. visible: true,
  74. fileName: '背景说明.md',
  75. content: '# 团队背景',
  76. truncated: true
  77. })
  78. assert.deepEqual(rules.createEmptyTextPreviewState(), {
  79. visible: false,
  80. fileName: '',
  81. content: '',
  82. truncated: false
  83. })
  84. assert.notEqual(rules.createEmptyTextPreviewState(), rules.createEmptyTextPreviewState())
  85. const creationState = rules.createTeamCreationState()
  86. assert.deepEqual(creationState, {
  87. createdTeamId: '',
  88. submitting: false,
  89. stage: 'idle',
  90. completed: false,
  91. teamPayloadSnapshot: '',
  92. teamQuestionnaireId: '',
  93. publishResult: null,
  94. resumeStage: ''
  95. })
  96. const firstPayloadSnapshot = rules.createTeamPayloadSnapshot({
  97. teamName: '团队', enterpriseWebsite: ' https://example.com ', coachId: 7
  98. })
  99. const equivalentPayloadSnapshot = rules.createTeamPayloadSnapshot({
  100. enterpriseWebsite: 'https://example.com', teamName: '团队'
  101. })
  102. assert.equal(firstPayloadSnapshot, equivalentPayloadSnapshot)
  103. assert.notEqual(firstPayloadSnapshot, rules.createTeamPayloadSnapshot({
  104. teamName: '团队', enterpriseWebsite: 'https://changed.example.com'
  105. }))
  106. assert.equal(rules.beginTeamSubmission(creationState), true)
  107. assert.equal(rules.beginTeamSubmission(creationState), false, 'a second submission must be locked')
  108. assert.equal(rules.rememberCreatedTeam(creationState, 88), 88)
  109. assert.equal(rules.rememberCreatedTeam(creationState, 99), 88, 'the first server team id must be retained')
  110. rules.setTeamSubmissionStage(creationState, 'upload')
  111. assert.equal(creationState.stage, 'upload')
  112. rules.finishTeamSubmission(creationState)
  113. assert.equal(creationState.submitting, false)
  114. assert.equal(rules.beginTeamSubmission(creationState), true, 'a failed later stage can resume')
  115. rules.finishTeamSubmission(creationState, true)
  116. assert.equal(creationState.completed, true)
  117. assert.equal(rules.beginTeamSubmission(creationState), false, 'a completed flow cannot be scheduled twice')
  118. assert.equal(rules.hasUnresolvedBackgroundFiles([
  119. { status: 'success', validationError: '' },
  120. { status: 'failed', validationError: '文件类型不支持' }
  121. ]), false)
  122. for (const item of [
  123. { status: 'pending', validationError: '' },
  124. { status: 'uploading', validationError: '' },
  125. { status: 'failed', validationError: '' }
  126. ]) {
  127. assert.equal(rules.hasUnresolvedBackgroundFiles([item]), true)
  128. }
  129. console.log('team background rules: PASS')
  130. const transportPath = path.join(__dirname, '../http/teamBackgroundFile.js')
  131. async function loadTransport({ api = {}, uni = {}, wx = {} } = {}) {
  132. const source = fs.readFileSync(transportPath, 'utf8')
  133. const context = vm.createContext({ uni, wx })
  134. const baseApiModule = new vm.SyntheticModule(['BaseApi'], function () {
  135. this.setExport('BaseApi', 'https://api.example.test/app')
  136. }, { context, identifier: 'test:baseApi' })
  137. const apiModule = new vm.SyntheticModule(['default'], function () {
  138. this.setExport('default', api)
  139. }, { context, identifier: 'test:api' })
  140. const transportModule = new vm.SourceTextModule(source, {
  141. context,
  142. identifier: pathToFileURL(transportPath).href
  143. })
  144. await transportModule.link(specifier => {
  145. if (specifier === './baseApi.js') return baseApiModule
  146. if (specifier === './index.js') return apiModule
  147. throw new Error(`unexpected transport import: ${specifier}`)
  148. })
  149. await transportModule.evaluate()
  150. return transportModule.namespace
  151. }
  152. function assertNoIdentityFields(value) {
  153. if (!value || typeof value !== 'object') return
  154. for (const [key, child] of Object.entries(value)) {
  155. assert.ok(!['source', 'coachId', 'uploaderId'].includes(key), `unexpected identity field: ${key}`)
  156. assertNoIdentityFields(child)
  157. }
  158. }
  159. async function createUploadHarness(response, progress = 37) {
  160. let request
  161. const progressValues = []
  162. const uni = {
  163. getStorageSync(key) {
  164. assert.equal(key, 'token')
  165. return 'token-123'
  166. },
  167. uploadFile(options) {
  168. request = options
  169. return {
  170. onProgressUpdate(callback) {
  171. callback({ progress })
  172. setImmediate(() => options.success(response))
  173. }
  174. }
  175. }
  176. }
  177. const transport = await loadTransport({ uni })
  178. return {
  179. request: () => request,
  180. progressValues,
  181. promise: transport.uploadTeamBackgroundFile(12, '/tmp/brief.pdf', value => progressValues.push(value))
  182. }
  183. }
  184. async function testUploadTransport() {
  185. const stringHarness = await createUploadHarness({
  186. statusCode: 200,
  187. data: JSON.stringify({ code: 0, data: { id: 7 } })
  188. })
  189. assert.equal((await stringHarness.promise).id, 7)
  190. assert.equal(stringHarness.request().url, 'https://api.example.test/app/core/user/team/12/background-files')
  191. assert.equal(stringHarness.request().filePath, '/tmp/brief.pdf')
  192. assert.equal(stringHarness.request().name, 'file')
  193. assert.equal(stringHarness.request().header.token, 'token-123')
  194. assert.deepEqual(stringHarness.progressValues, [37])
  195. assertNoIdentityFields(stringHarness.request())
  196. const objectHarness = await createUploadHarness({ statusCode: 200, data: { code: 0, data: { id: 8 } } })
  197. assert.equal((await objectHarness.promise).id, 8)
  198. const statusHarness = await createUploadHarness({ statusCode: 500, data: { code: 0 } })
  199. await assert.rejects(statusHarness.promise, /上传失败,请重试/)
  200. const codeHarness = await createUploadHarness({ statusCode: 200, data: { code: 9, msg: '上传业务失败' } })
  201. await assert.rejects(codeHarness.promise, /上传业务失败/)
  202. const invalidJsonHarness = await createUploadHarness({ statusCode: 200, data: '<invalid-json>' })
  203. await assert.rejects(invalidJsonHarness.promise, /上传失败,请重试/)
  204. }
  205. async function testApiTransport() {
  206. const calls = []
  207. const api = {
  208. get(...args) {
  209. calls.push(['get', ...args])
  210. return Promise.resolve({ data: { code: 0, data: [{ id: 1 }] } })
  211. },
  212. del(...args) {
  213. calls.push(['del', ...args])
  214. return Promise.resolve({ data: { code: 0, data: true } })
  215. },
  216. post(...args) {
  217. calls.push(['post', ...args])
  218. return Promise.resolve({ data: { code: 0, data: { sessionId: 'session-1' } } })
  219. }
  220. }
  221. const transport = await loadTransport({ api })
  222. assert.deepEqual(await transport.listTeamBackgroundFiles(12), [{ id: 1 }])
  223. assert.equal(await transport.disableTeamBackgroundFile(12, 34), true)
  224. assert.deepEqual(await transport.createTeamBackgroundSession(12), { sessionId: 'session-1' })
  225. assert.equal(calls[0][0], 'get')
  226. assert.equal(calls[0][1], '/core/user/team/12/background-files')
  227. assert.equal(calls[1][0], 'del')
  228. assert.equal(calls[1][1], '/core/user/team/12/background-files/34')
  229. assert.equal(calls[2][0], 'post')
  230. assert.equal(calls[2][1], '/core/user/team/12/background-upload-session')
  231. for (const call of calls) {
  232. assert.equal(Object.keys(call[2]).length, 0)
  233. assert.equal(call[3], false)
  234. assertNoIdentityFields(call)
  235. }
  236. const failingTransport = await loadTransport({
  237. api: {
  238. get: () => Promise.resolve({ data: { code: 3, msg: '列表业务失败' } })
  239. }
  240. })
  241. await assert.rejects(failingTransport.listTeamBackgroundFiles(12), /列表业务失败/)
  242. assert.equal(transport.uploadTeamBackgroundFile.length, 2)
  243. assert.equal(transport.listTeamBackgroundFiles.length, 1)
  244. assert.equal(transport.disableTeamBackgroundFile.length, 2)
  245. assert.equal(transport.createTeamBackgroundSession.length, 1)
  246. assert.equal(transport.downloadTeamBackgroundFile.length, 2)
  247. }
  248. const TEXT_PREVIEW_LIMIT = 256 * 1024
  249. async function createDownloadHarness({ result, responseHeaders, downloadError, openError,
  250. fileSize, fileContent = '', fileInfoError, readError, withHeadersListener = true } = {}) {
  251. let request
  252. let openRequest
  253. let fileInfoRequest
  254. let readRequest
  255. let fileSystemManagerCalls = 0
  256. const resolvedFileSize = fileSize === undefined
  257. ? Buffer.byteLength(fileContent, 'utf8')
  258. : fileSize
  259. const uni = {
  260. getStorageSync(key) {
  261. assert.equal(key, 'token')
  262. return 'token-456'
  263. },
  264. downloadFile(options) {
  265. request = options
  266. setImmediate(() => {
  267. if (downloadError) options.fail(downloadError)
  268. else options.success(result)
  269. })
  270. if (!withHeadersListener) return {}
  271. return {
  272. onHeadersReceived(callback) {
  273. if (responseHeaders) callback({ header: responseHeaders })
  274. }
  275. }
  276. }
  277. }
  278. const wx = {
  279. openDocument(options) {
  280. openRequest = options
  281. setImmediate(() => {
  282. if (openError) options.fail(openError)
  283. else options.success('opened')
  284. })
  285. },
  286. getFileSystemManager() {
  287. fileSystemManagerCalls += 1
  288. return {
  289. getFileInfo(options) {
  290. fileInfoRequest = options
  291. setImmediate(() => {
  292. if (fileInfoError) options.fail(fileInfoError)
  293. else options.success({ size: resolvedFileSize })
  294. })
  295. },
  296. readFile(options) {
  297. readRequest = options
  298. setImmediate(() => {
  299. if (readError) options.fail(readError)
  300. else options.success({ data: fileContent })
  301. })
  302. }
  303. }
  304. }
  305. }
  306. const transport = await loadTransport({ uni, wx })
  307. return {
  308. request: () => request,
  309. openRequest: () => openRequest,
  310. fileInfoRequest: () => fileInfoRequest,
  311. readRequest: () => readRequest,
  312. fileSystemManagerCalls: () => fileSystemManagerCalls,
  313. promise: transport.downloadTeamBackgroundFile(12, 34)
  314. }
  315. }
  316. async function testDownloadTransport() {
  317. const successHarness = await createDownloadHarness({
  318. result: { statusCode: 200, tempFilePath: '/tmp/download.pdf' },
  319. responseHeaders: {
  320. 'cOnTeNt-TyPe': 'application/pdf',
  321. 'CONTENT-disPOSITION': 'attachment; filename="download.pdf"'
  322. }
  323. })
  324. const documentPreview = await successHarness.promise
  325. assert.equal(documentPreview.mode, 'document')
  326. assert.equal(documentPreview.fileName, 'download.pdf')
  327. assert.equal(documentPreview.filePath, '/tmp/download.pdf')
  328. assert.equal(successHarness.request().url, 'https://api.example.test/app/core/user/team/12/background-files/34/download')
  329. assert.equal(successHarness.request().header.token, 'token-456')
  330. assert.equal(successHarness.openRequest(), undefined, 'transport must not open a document before component context checks')
  331. assertNoIdentityFields(successHarness.request())
  332. const resultHeaderHarness = await createDownloadHarness({
  333. result: {
  334. statusCode: 200,
  335. tempFilePath: '/tmp/result-header.docx',
  336. header: {
  337. 'content-type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  338. 'content-disposition': 'attachment; filename="result-header.docx"'
  339. }
  340. },
  341. withHeadersListener: false
  342. })
  343. const resultHeaderPreview = await resultHeaderHarness.promise
  344. assert.equal(resultHeaderPreview.mode, 'document')
  345. assert.equal(resultHeaderPreview.fileName, 'result-header.docx')
  346. assert.equal(resultHeaderPreview.filePath, '/tmp/result-header.docx')
  347. assert.equal(resultHeaderHarness.openRequest(), undefined)
  348. assert.equal(resultHeaderHarness.fileSystemManagerCalls(), 0)
  349. const txtHarness = await createDownloadHarness({
  350. result: {
  351. statusCode: 200,
  352. tempFilePath: '/tmp/text-preview.txt',
  353. headers: {
  354. 'Content-Type': 'text/plain; charset=UTF-8',
  355. 'Content-Disposition': 'attachment; filename="fallback.txt"; '
  356. + "filename*=UTF-8''%E8%83%8C%E6%99%AF%20%E8%B5%84%E6%96%99.txt"
  357. }
  358. },
  359. fileSize: 5,
  360. fileContent: 'hello',
  361. withHeadersListener: false
  362. })
  363. const txtPreview = await txtHarness.promise
  364. assert.equal(txtHarness.openRequest(), undefined, 'txt must not call openDocument')
  365. assert.equal(txtPreview.mode, 'text')
  366. assert.equal(txtPreview.fileName, '背景 资料.txt')
  367. assert.equal(txtPreview.content, 'hello')
  368. assert.equal(txtPreview.truncated, false)
  369. assert.equal(txtHarness.fileInfoRequest().filePath, '/tmp/text-preview.txt')
  370. assert.equal(txtHarness.readRequest().filePath, '/tmp/text-preview.txt')
  371. assert.equal(txtHarness.readRequest().encoding, 'utf8')
  372. assert.equal(txtHarness.readRequest().position, 0)
  373. assert.equal(txtHarness.readRequest().length, 5)
  374. const emptyTextHarness = await createDownloadHarness({
  375. result: { statusCode: 200, tempFilePath: '/tmp/empty.txt' },
  376. responseHeaders: {
  377. 'Content-Type': 'text/plain',
  378. 'Content-Disposition': 'attachment; filename="empty.txt"'
  379. },
  380. fileSize: 0
  381. })
  382. const emptyTextPreview = await emptyTextHarness.promise
  383. assert.equal(emptyTextPreview.mode, 'text')
  384. assert.equal(emptyTextPreview.fileName, 'empty.txt')
  385. assert.equal(emptyTextPreview.content, '')
  386. assert.equal(emptyTextPreview.truncated, false)
  387. assert.equal(emptyTextHarness.readRequest(), undefined)
  388. const invalidEncodedNameHarness = await createDownloadHarness({
  389. result: { statusCode: 200, tempFilePath: '/tmp/fallback.txt' },
  390. responseHeaders: {
  391. 'Content-Type': 'text/plain',
  392. 'Content-Disposition': 'attachment; filename="fallback.txt"; '
  393. + "filename*=UTF-8''%E0%A4%A"
  394. },
  395. fileSize: 8,
  396. fileContent: 'fallback'
  397. })
  398. const invalidEncodedNamePreview = await invalidEncodedNameHarness.promise
  399. assert.equal(invalidEncodedNamePreview.fileName, 'fallback.txt')
  400. assert.equal(invalidEncodedNamePreview.content, 'fallback')
  401. const mdContent = 'm'.repeat(TEXT_PREVIEW_LIMIT)
  402. const mdHarness = await createDownloadHarness({
  403. result: { statusCode: 200, tempFilePath: '/tmp/guide.md' },
  404. responseHeaders: {
  405. 'Content-Type': 'text/markdown; charset=UTF-8',
  406. 'Content-Disposition': 'attachment; filename="guide.md"'
  407. },
  408. fileSize: 50 * 1024 * 1024,
  409. fileContent: mdContent
  410. })
  411. const mdPreview = await mdHarness.promise
  412. assert.equal(mdHarness.openRequest(), undefined)
  413. assert.equal(mdPreview.mode, 'text')
  414. assert.equal(mdPreview.fileName, 'guide.md')
  415. assert.equal(mdPreview.content.length, TEXT_PREVIEW_LIMIT)
  416. assert.equal(mdPreview.truncated, true)
  417. assert.equal(mdHarness.readRequest().length, TEXT_PREVIEW_LIMIT)
  418. const csvContent = 'c'.repeat(TEXT_PREVIEW_LIMIT)
  419. const csvHarness = await createDownloadHarness({
  420. result: { statusCode: 200, tempFilePath: '/tmp/data.csv' },
  421. responseHeaders: {
  422. 'Content-Type': 'text/csv',
  423. 'Content-Disposition': 'attachment; filename=data.csv'
  424. },
  425. fileSize: TEXT_PREVIEW_LIMIT,
  426. fileContent: csvContent
  427. })
  428. const csvPreview = await csvHarness.promise
  429. assert.equal(csvHarness.openRequest(), undefined)
  430. assert.equal(csvPreview.mode, 'text')
  431. assert.equal(csvPreview.fileName, 'data.csv')
  432. assert.equal(csvPreview.content.length, TEXT_PREVIEW_LIMIT)
  433. assert.equal(csvPreview.truncated, false)
  434. assert.equal(csvHarness.readRequest().length, TEXT_PREVIEW_LIMIT)
  435. const fileInfoFailureHarness = await createDownloadHarness({
  436. result: { statusCode: 200, tempFilePath: '/tmp/file-info-failure.txt' },
  437. responseHeaders: {
  438. 'Content-Type': 'text/plain',
  439. 'Content-Disposition': 'attachment; filename="file-info-failure.txt"'
  440. },
  441. fileInfoError: new Error('getFileInfo failed')
  442. })
  443. await assert.rejects(fileInfoFailureHarness.promise, /文件读取失败,请重试/)
  444. assert.equal(fileInfoFailureHarness.openRequest(), undefined)
  445. assert.equal(fileInfoFailureHarness.readRequest(), undefined)
  446. const readFailureHarness = await createDownloadHarness({
  447. result: { statusCode: 200, tempFilePath: '/tmp/read-failure.md' },
  448. responseHeaders: {
  449. 'Content-Type': 'text/markdown',
  450. 'Content-Disposition': 'attachment; filename="read-failure.md"'
  451. },
  452. fileSize: 10,
  453. readError: new Error('readFile failed')
  454. })
  455. await assert.rejects(readFailureHarness.promise, /文件读取失败,请重试/)
  456. assert.equal(readFailureHarness.openRequest(), undefined)
  457. const unknownExtensionHarness = await createDownloadHarness({
  458. result: { statusCode: 200, tempFilePath: '/tmp/unknown-file' },
  459. responseHeaders: {
  460. 'Content-Type': 'application/octet-stream',
  461. 'Content-Disposition': 'attachment; filename="archive.zip"'
  462. }
  463. })
  464. await assert.rejects(unknownExtensionHarness.promise, /文件类型不支持预览/)
  465. assert.equal(unknownExtensionHarness.openRequest(), undefined)
  466. assert.equal(unknownExtensionHarness.fileSystemManagerCalls(), 0)
  467. const jsonHarness = await createDownloadHarness({
  468. result: { statusCode: 200, tempFilePath: '/tmp/error.json' },
  469. responseHeaders: {
  470. 'Content-Type': 'application/json;charset=UTF-8',
  471. 'Content-Disposition': 'attachment; filename="error.json"'
  472. }
  473. })
  474. await assert.rejects(jsonHarness.promise, /下载失败,请重试/)
  475. assert.equal(jsonHarness.openRequest(), undefined)
  476. const htmlHarness = await createDownloadHarness({
  477. result: { statusCode: 200, tempFilePath: '/tmp/error.html' },
  478. responseHeaders: {
  479. 'content-type': 'text/html; charset=UTF-8',
  480. 'content-disposition': 'attachment; filename="error.html"'
  481. }
  482. })
  483. await assert.rejects(htmlHarness.promise, /下载失败,请重试/)
  484. assert.equal(htmlHarness.openRequest(), undefined)
  485. const missingHeadersHarness = await createDownloadHarness({
  486. result: { statusCode: 200, tempFilePath: '/tmp/unknown.pdf' },
  487. withHeadersListener: false
  488. })
  489. await assert.rejects(missingHeadersHarness.promise, /下载失败,请重试/)
  490. assert.equal(missingHeadersHarness.openRequest(), undefined)
  491. const statusHarness = await createDownloadHarness({ result: { statusCode: 500 } })
  492. await assert.rejects(statusHarness.promise, /下载失败,请重试/)
  493. assert.equal(statusHarness.openRequest(), undefined)
  494. const downloadError = new Error('download network error')
  495. const downloadFailureHarness = await createDownloadHarness({ downloadError })
  496. await assert.rejects(downloadFailureHarness.promise, /download network error/)
  497. const noTransportOpenHarness = await createDownloadHarness({
  498. result: { statusCode: 200, tempFilePath: '/tmp/download.pdf' },
  499. responseHeaders: {
  500. 'Content-Type': 'application/pdf',
  501. 'Content-Disposition': 'attachment; filename="download.pdf"'
  502. },
  503. openError: new Error('must not be reached')
  504. })
  505. assert.equal((await noTransportOpenHarness.promise).mode, 'document')
  506. assert.equal(noTransportOpenHarness.openRequest(), undefined)
  507. }
  508. function readSfcScript(filePath) {
  509. const source = fs.readFileSync(filePath, 'utf8')
  510. const openingTag = '<script>'
  511. const start = source.indexOf(openingTag)
  512. const end = source.indexOf('</script>', start + openingTag.length)
  513. if (start < 0 || end < 0) throw new Error(`missing script block: ${filePath}`)
  514. return source.slice(start + openingTag.length, end)
  515. }
  516. async function loadVueComponent(filePath, {
  517. http = {}, uni = {}, wx = {}, apiRules = rules, timers = {}
  518. } = {}) {
  519. const context = vm.createContext({
  520. uni,
  521. wx,
  522. Date,
  523. Promise,
  524. String,
  525. Number,
  526. Boolean,
  527. Object,
  528. Array,
  529. setInterval: timers.setInterval || setInterval,
  530. clearInterval: timers.clearInterval || clearInterval,
  531. setTimeout: timers.setTimeout || setTimeout,
  532. clearTimeout: timers.clearTimeout || clearTimeout
  533. })
  534. const vueStub = new vm.SyntheticModule(['default'], function () {
  535. this.setExport('default', {})
  536. }, { context, identifier: 'test:vue-component' })
  537. const rulesStub = new vm.SyntheticModule(['default'], function () {
  538. this.setExport('default', apiRules)
  539. }, { context, identifier: 'test:team-background-rules' })
  540. const httpNames = [
  541. 'createTeamBackgroundSession',
  542. 'disableTeamBackgroundFile',
  543. 'downloadTeamBackgroundFile',
  544. 'listTeamBackgroundFiles',
  545. 'uploadTeamBackgroundFile'
  546. ]
  547. const httpStub = new vm.SyntheticModule(httpNames, function () {
  548. for (const name of httpNames) {
  549. this.setExport(name, http[name] || (() => Promise.resolve()))
  550. }
  551. }, { context, identifier: 'test:team-background-http' })
  552. const componentModule = new vm.SourceTextModule(readSfcScript(filePath), {
  553. context,
  554. identifier: pathToFileURL(filePath).href
  555. })
  556. await componentModule.link(specifier => {
  557. if (specifier === '@/http/teamBackgroundFile.js') return httpStub
  558. if (specifier === '@/utils/teamBackgroundFile.js') return rulesStub
  559. if (specifier.endsWith('.vue')) return vueStub
  560. throw new Error(`unexpected component import: ${specifier}`)
  561. })
  562. await componentModule.evaluate()
  563. return componentModule.namespace.default
  564. }
  565. function instantiateComponent(component, overrides = {}) {
  566. const base = Object.assign({ initialCount: 0 }, overrides)
  567. const data = typeof component.data === 'function' ? component.data.call(base) : {}
  568. const instance = Object.assign(base, data, overrides)
  569. for (const [name, method] of Object.entries(component.methods || {})) {
  570. instance[name] = method.bind(instance)
  571. }
  572. return instance
  573. }
  574. function createDeferred() {
  575. let resolve
  576. let reject
  577. const promise = new Promise((resolvePromise, rejectPromise) => {
  578. resolve = resolvePromise
  579. reject = rejectPromise
  580. })
  581. return { promise, resolve, reject }
  582. }
  583. function createFakeTimers() {
  584. let nextId = 1
  585. const pending = new Map()
  586. return {
  587. setTimeout(callback) {
  588. const id = nextId++
  589. pending.set(id, callback)
  590. return id
  591. },
  592. clearTimeout(id) {
  593. pending.delete(id)
  594. },
  595. count() {
  596. return pending.size
  597. },
  598. runNext() {
  599. const entry = pending.entries().next().value
  600. if (!entry) return false
  601. pending.delete(entry[0])
  602. entry[1]()
  603. return true
  604. },
  605. runAll() {
  606. while (this.runNext()) {}
  607. }
  608. }
  609. }
  610. async function flushPromises() {
  611. await Promise.resolve()
  612. await new Promise(resolve => setImmediate(resolve))
  613. }
  614. const backgroundComponentPath = path.join(__dirname, '../components/CusTeamBackgroundFiles/index.vue')
  615. const teamFillComponentPath = path.join(__dirname, '../components/CusTeamInfoFill/index.vue')
  616. const createTeamPagePath = path.join(__dirname, '../pagesPublish/fillTeamInfo.vue')
  617. const createListComponentPath = path.join(__dirname, '../pagesHome/components/createList.vue')
  618. const teamEditPagePath = path.join(__dirname, '../pagesMy/teamEdit.vue')
  619. const headerComponentPath = path.join(__dirname, '../components/CusHeader/index.vue')
  620. async function testDeferredPcSelectionSurvivesSessionFailure() {
  621. let createCalls = 0
  622. const firstRequest = createDeferred()
  623. const component = await loadVueComponent(backgroundComponentPath, {
  624. http: {
  625. createTeamBackgroundSession() {
  626. createCalls += 1
  627. if (createCalls === 1) return firstRequest.promise
  628. return Promise.resolve({
  629. code: '123456', uploadUrl: 'https://upload.example/retry', expiresAt: '2099-01-01 00:00:00'
  630. })
  631. }
  632. }
  633. })
  634. const instance = instantiateComponent(component, {
  635. teamId: '',
  636. editable: true,
  637. boundTeamId: 12,
  638. pcUploadDeferred: true,
  639. $showToast() {},
  640. $emit() {}
  641. })
  642. const first = instance.waitForDeferredPcUpload(12)
  643. const second = instance.waitForDeferredPcUpload(12)
  644. assert.equal(first, second, 'the whole deferred flow must expose one shared waiter')
  645. assert.equal(createCalls, 1)
  646. firstRequest.reject(new Error('session unavailable'))
  647. const failed = await Promise.allSettled([first, second])
  648. assert.deepEqual(failed.map(result => result.status), ['rejected', 'rejected'])
  649. assert.match(failed[0].reason.message, /session unavailable/)
  650. assert.equal(instance.pcUploadDeferred, true)
  651. assert.equal(instance.pcDialogVisible, false)
  652. assert.equal(instance.deferredPcResolve, null)
  653. assert.equal(instance.deferredPcWaitPromise, null)
  654. const retry = instance.waitForDeferredPcUpload(12)
  655. await flushPromises()
  656. assert.equal(createCalls, 2, 'a failed shared waiter must be retryable')
  657. assert.equal(typeof instance.deferredPcResolve, 'function')
  658. instance.skipDeferredPcUpload()
  659. await retry
  660. }
  661. async function testSessionRefreshFailureKeepsOldTimer() {
  662. const component = await loadVueComponent(backgroundComponentPath, {
  663. http: {
  664. createTeamBackgroundSession: () => Promise.reject(new Error('refresh failed'))
  665. }
  666. })
  667. const instance = instantiateComponent(component, {
  668. teamId: '', editable: true, boundTeamId: 12, $showToast() {}, $emit() {}
  669. })
  670. const oldSession = { code: '111111', expiresAt: '2099-01-01 00:00:00' }
  671. const oldTimer = setInterval(() => {}, 60 * 1000)
  672. instance.session = oldSession
  673. instance.sessionTimer = oldTimer
  674. try {
  675. await assert.rejects(instance.openPcSession(12), /refresh failed/)
  676. assert.equal(instance.session, oldSession)
  677. assert.equal(instance.sessionTimer, oldTimer)
  678. } finally {
  679. clearInterval(oldTimer)
  680. instance.sessionTimer = null
  681. }
  682. }
  683. async function testPcSessionCreationIsSingleFlightPerTeam() {
  684. const firstRequest = createDeferred()
  685. let createCalls = 0
  686. const component = await loadVueComponent(backgroundComponentPath, {
  687. http: {
  688. createTeamBackgroundSession() {
  689. createCalls += 1
  690. return firstRequest.promise
  691. }
  692. }
  693. })
  694. const instance = instantiateComponent(component, {
  695. teamId: '', editable: true, $showToast() {}, $emit() {}
  696. })
  697. instance.resetTeamContext(12)
  698. const first = instance.openPcSession(12)
  699. const second = instance.openPcSession(12)
  700. assert.equal(createCalls, 1, 'same-team callers must share one session POST')
  701. assert.equal(instance.sessionCreating, true)
  702. instance.refreshPcSession()
  703. assert.equal(createCalls, 1, 'disabled regenerate must not create another POST')
  704. instance.resetTeamContext(13)
  705. assert.equal(instance.sessionCreating, false, 'creating state follows the active team')
  706. firstRequest.resolve({
  707. code: '123456', uploadUrl: 'https://upload.example/', expiresAt: '2099-01-01 00:00:00'
  708. })
  709. assert.equal(await first, null)
  710. assert.equal(await second, null)
  711. assert.equal(instance.session, null, 'a stale context must not display the resolved session')
  712. assert.equal(instance.pcDialogVisible, false)
  713. }
  714. async function testPcSessionSingleFlightSurvivesSameTeamReset() {
  715. const request = createDeferred()
  716. let createCalls = 0
  717. const component = await loadVueComponent(backgroundComponentPath, {
  718. http: {
  719. createTeamBackgroundSession() {
  720. createCalls += 1
  721. return request.promise
  722. }
  723. }
  724. })
  725. const instance = instantiateComponent(component, {
  726. teamId: '', editable: true, $showToast() {}, $emit() {}
  727. })
  728. instance.resetTeamContext(21)
  729. const staleCaller = instance.openPcSession(21)
  730. instance.resetTeamContext(21)
  731. assert.equal(instance.sessionCreating, true, 'same-team reset must retain the network lock')
  732. const currentCaller = instance.openPcSession(21)
  733. assert.equal(createCalls, 1, 'same-team reset must reuse the raw network promise')
  734. const rawSession = {
  735. code: '654321', uploadUrl: 'https://upload.example/current', expiresAt: '2099-01-01 00:00:00'
  736. }
  737. request.resolve(rawSession)
  738. assert.equal(await staleCaller, null)
  739. assert.equal(await currentCaller, rawSession)
  740. assert.equal(instance.session, rawSession)
  741. assert.equal(instance.pcDialogVisible, true)
  742. assert.equal(instance.sessionCreating, false)
  743. instance.closePcDialog()
  744. }
  745. async function testPcSessionFailureClearsSingleFlightForRetry() {
  746. let createCalls = 0
  747. const component = await loadVueComponent(backgroundComponentPath, {
  748. http: {
  749. createTeamBackgroundSession() {
  750. createCalls += 1
  751. if (createCalls === 1) return Promise.reject(new Error('session unavailable'))
  752. return Promise.resolve({
  753. code: '222222', uploadUrl: 'https://upload.example/retry', expiresAt: '2099-01-01 00:00:00'
  754. })
  755. }
  756. }
  757. })
  758. const instance = instantiateComponent(component, {
  759. teamId: '', editable: true, $showToast() {}, $emit() {}
  760. })
  761. instance.resetTeamContext(22)
  762. await assert.rejects(instance.openPcSession(22), /session unavailable/)
  763. assert.equal(instance.sessionCreating, false)
  764. const session = await instance.openPcSession(22)
  765. assert.equal(createCalls, 2)
  766. assert.equal(session.code, '222222')
  767. assert.equal(instance.sessionCreating, false)
  768. instance.closePcDialog()
  769. }
  770. async function testDeferredPcFinishWaitsForListRefresh() {
  771. const component = await loadVueComponent(backgroundComponentPath, {
  772. http: {
  773. createTeamBackgroundSession: () => Promise.resolve({
  774. code: '123456',
  775. uploadUrl: 'https://upload.example/',
  776. expiresAt: '2099-01-01 00:00:00'
  777. }),
  778. listTeamBackgroundFiles: () => Promise.reject(new Error('list refresh failed'))
  779. }
  780. })
  781. const instance = instantiateComponent(component, {
  782. teamId: '', editable: true, boundTeamId: 12, pcUploadDeferred: true,
  783. $showToast() {}, $emit() {}
  784. })
  785. const waiting = instance.waitForDeferredPcUpload(12)
  786. await new Promise(resolve => setImmediate(resolve))
  787. assert.equal(typeof instance.deferredPcResolve, 'function')
  788. await instance.finishDeferredPcUpload()
  789. await assert.rejects(waiting, /list refresh failed/)
  790. }
  791. async function testDeferredPcWaiterSingleFlightFinishesAllCallers() {
  792. let createCalls = 0
  793. const sessionRequest = createDeferred()
  794. const component = await loadVueComponent(backgroundComponentPath, {
  795. http: {
  796. createTeamBackgroundSession() {
  797. createCalls += 1
  798. return sessionRequest.promise
  799. },
  800. listTeamBackgroundFiles: () => Promise.resolve([])
  801. }
  802. })
  803. const instance = instantiateComponent(component, {
  804. teamId: '', editable: true, boundTeamId: 12, pcUploadDeferred: true,
  805. $showToast() {}, $emit() {}
  806. })
  807. const first = instance.waitForDeferredPcUpload(12)
  808. const second = instance.waitForDeferredPcUpload(12)
  809. assert.equal(first, second)
  810. assert.equal(createCalls, 1)
  811. let settled = false
  812. first.then(() => { settled = true })
  813. sessionRequest.resolve({
  814. code: '654321', uploadUrl: 'https://upload.example/', expiresAt: '2099-01-01 00:00:00'
  815. })
  816. await flushPromises()
  817. assert.equal(settled, false, 'session creation must not settle the dialog waiter')
  818. await instance.finishDeferredPcUpload()
  819. await Promise.all([first, second])
  820. assert.equal(settled, true)
  821. assert.equal(instance.deferredPcWaitPromise, null)
  822. }
  823. async function testTeamContextResetAndUploadIsolation() {
  824. const uploads = []
  825. const component = await loadVueComponent(backgroundComponentPath, {
  826. http: {
  827. uploadTeamBackgroundFile(teamId, filePath, onProgress) {
  828. const deferred = createDeferred()
  829. uploads.push({ teamId, filePath, onProgress, deferred })
  830. return deferred.promise
  831. },
  832. listTeamBackgroundFiles: () => Promise.resolve([])
  833. }
  834. })
  835. let resolverCalls = 0
  836. const instance = instantiateComponent(component, {
  837. teamId: '',
  838. editable: true,
  839. $showToast() {},
  840. $emit() {}
  841. })
  842. instance.resetTeamContext(1)
  843. const oldItem = rules.createBackgroundQueueItem(
  844. { name: 'old.pdf', path: '/tmp/old.pdf', size: 1 }, 'old'
  845. )
  846. instance.queue.push(oldItem)
  847. instance.deferredPcResolve = () => { resolverCalls += 1 }
  848. const oldFlush = instance.flushPendingFiles(1)
  849. await new Promise(resolve => setImmediate(resolve))
  850. assert.equal(uploads.length, 1)
  851. instance.files = [{ id: 11, fileName: 'old.pdf' }]
  852. instance.count = 1
  853. instance.filesReady = true
  854. instance.session = { code: '111111' }
  855. instance.pcDialogVisible = true
  856. instance.textPreview = rules.createTextPreviewState({ fileName: 'old.txt', content: 'old' })
  857. instance.resetTeamContext(2)
  858. assert.equal(instance.boundTeamId, 2)
  859. assert.equal(instance.files.length, 0)
  860. assert.equal(instance.count, 0)
  861. assert.equal(instance.queue.length, 0)
  862. assert.equal(instance.filesReady, false)
  863. assert.equal(instance.session, null)
  864. assert.equal(instance.pcDialogVisible, false)
  865. assert.equal(instance.textPreview.content, '')
  866. assert.equal(resolverCalls, 1)
  867. const newItem = rules.createBackgroundQueueItem(
  868. { name: 'new.pdf', path: '/tmp/new.pdf', size: 1 }, 'new'
  869. )
  870. instance.queue.push(newItem)
  871. const newFlush = instance.flushPendingFiles(2)
  872. await new Promise(resolve => setImmediate(resolve))
  873. assert.equal(uploads.length, 2, 'the new team must not reuse the old upload promise')
  874. assert.deepEqual(uploads.map(item => item.teamId), [1, 2])
  875. uploads[0].onProgress(75)
  876. assert.equal(oldItem.progress, 0, 'stale upload progress must not mutate the old item after reset')
  877. uploads[0].deferred.resolve({ id: 101 })
  878. await oldFlush
  879. assert.equal(newItem.status, 'uploading')
  880. uploads[1].deferred.resolve({ id: 202 })
  881. await newFlush
  882. assert.equal(newItem.status, 'success')
  883. }
  884. async function testFileActionsWaitForCurrentListAndDocumentContext() {
  885. const listDeferred = createDeferred()
  886. const downloadDeferred = createDeferred()
  887. const opened = []
  888. const toasts = []
  889. let downloadCalls = 0
  890. const wx = {
  891. openDocument(options) {
  892. opened.push(options.filePath)
  893. setImmediate(() => options.success())
  894. }
  895. }
  896. const component = await loadVueComponent(backgroundComponentPath, {
  897. wx,
  898. http: {
  899. listTeamBackgroundFiles: () => listDeferred.promise,
  900. downloadTeamBackgroundFile: () => {
  901. downloadCalls += 1
  902. return downloadDeferred.promise
  903. }
  904. }
  905. })
  906. const instance = instantiateComponent(component, {
  907. teamId: '',
  908. editable: true,
  909. $showToast(message) { toasts.push(message) },
  910. $emit() {}
  911. })
  912. instance.resetTeamContext(3)
  913. const oldFile = { id: 31, fileName: 'old.pdf' }
  914. instance.files = [oldFile]
  915. instance.filesReady = true
  916. const refresh = instance.refreshFiles(3)
  917. await instance.previewFile(oldFile)
  918. assert.equal(downloadCalls, 0, 'old file ids must be disabled while the current list is loading')
  919. listDeferred.resolve([oldFile])
  920. await refresh
  921. const latePreview = instance.previewFile(oldFile)
  922. assert.equal(downloadCalls, 1)
  923. instance.resetTeamContext(4)
  924. downloadDeferred.resolve({ mode: 'document', fileName: 'old.pdf', filePath: '/tmp/old.pdf' })
  925. await latePreview
  926. assert.deepEqual(opened, [], 'a stale download must not open a native document')
  927. const validComponent = await loadVueComponent(backgroundComponentPath, {
  928. wx,
  929. http: {
  930. downloadTeamBackgroundFile: () => Promise.resolve({
  931. mode: 'document', fileName: 'current.pdf', filePath: '/tmp/current.pdf'
  932. })
  933. }
  934. })
  935. const validInstance = instantiateComponent(validComponent, {
  936. teamId: '', editable: true, $showToast(message) { toasts.push(message) }, $emit() {}
  937. })
  938. validInstance.resetTeamContext(5)
  939. const currentFile = { id: 51, fileName: 'current.pdf' }
  940. validInstance.files = [currentFile]
  941. validInstance.filesReady = true
  942. await validInstance.previewFile(currentFile)
  943. assert.deepEqual(opened, ['/tmp/current.pdf'])
  944. const failingComponent = await loadVueComponent(backgroundComponentPath, {
  945. wx: {
  946. openDocument(options) { setImmediate(() => options.fail(new Error('open failed'))) }
  947. },
  948. http: {
  949. downloadTeamBackgroundFile: () => Promise.resolve({
  950. mode: 'document', fileName: 'broken.pdf', filePath: '/tmp/broken.pdf'
  951. })
  952. }
  953. })
  954. const failingInstance = instantiateComponent(failingComponent, {
  955. teamId: '', editable: true, $showToast(message) { toasts.push(message) }, $emit() {}
  956. })
  957. failingInstance.resetTeamContext(6)
  958. const brokenFile = { id: 61, fileName: 'broken.pdf' }
  959. failingInstance.files = [brokenFile]
  960. failingInstance.filesReady = true
  961. await failingInstance.previewFile(brokenFile)
  962. assert.ok(toasts.some(message => String(message).includes('open failed')))
  963. }
  964. async function testTeamFillFlushesBeforeEmitAndLocks() {
  965. const component = await loadVueComponent(teamFillComponentPath)
  966. const flushDeferred = createDeferred()
  967. let flushCalls = 0
  968. let emitCalls = 0
  969. const instance = instantiateComponent(component, {
  970. teamId: 12,
  971. qtype: false,
  972. $props: { qtype: false },
  973. $showToast() {},
  974. $emit() { emitCalls += 1 },
  975. $refs: {
  976. backgroundRef: {
  977. flushPendingFiles() { flushCalls += 1; return flushDeferred.promise },
  978. hasUnresolvedFiles() { return false }
  979. }
  980. }
  981. })
  982. instance.teamInfo = {
  983. teamName: '团队', enterpriseName: '公司', enterpriseWebsite: '无',
  984. districtId: 1, industryId: 2, functionIds: [], orgIds: []
  985. }
  986. const first = instance.handleConfirm()
  987. const second = instance.handleConfirm()
  988. assert.equal(flushCalls, 1)
  989. assert.equal(emitCalls, 0)
  990. flushDeferred.resolve({ success: 1, failed: 0 })
  991. await Promise.all([first, second])
  992. assert.equal(emitCalls, 1)
  993. }
  994. async function testCreatedTeamResumeAndSubmitLock() {
  995. const component = await loadVueComponent(createTeamPagePath)
  996. let teamPostCalls = 0
  997. let flushCalls = 0
  998. const toasts = []
  999. const instance = instantiateComponent(component, {
  1000. $api: {
  1001. post(url) {
  1002. assert.equal(url, '/core/user/team')
  1003. teamPostCalls += 1
  1004. return Promise.resolve({ data: { code: 0, data: { teamId: 88 } } })
  1005. }
  1006. },
  1007. $showToast(message) { toasts.push(message) },
  1008. $showModal: () => Promise.resolve(),
  1009. $refs: {
  1010. teamRef: {
  1011. flushBackgroundFiles() {
  1012. flushCalls += 1
  1013. if (flushCalls === 1) return Promise.reject(new Error('列表刷新失败'))
  1014. return Promise.resolve({ success: 0, failed: 0 })
  1015. },
  1016. hasUnresolvedBackgroundFiles: () => false,
  1017. hasDeferredPcUpload: () => false
  1018. }
  1019. }
  1020. })
  1021. let continuations = 0
  1022. instance.continueAfterTeamCreated = async teamId => {
  1023. assert.equal(teamId, 88)
  1024. continuations += 1
  1025. }
  1026. await instance.handleConfirm({ teamName: '团队' })
  1027. assert.equal(teamPostCalls, 1)
  1028. assert.equal(instance.creationState.createdTeamId, 88)
  1029. assert.ok(toasts.some(message => String(message).includes('背景资料')))
  1030. await instance.handleConfirm({ teamName: '团队' })
  1031. assert.equal(teamPostCalls, 1, 'retry after a later-stage failure must not POST a second team')
  1032. assert.equal(continuations, 1)
  1033. const lockedPost = createDeferred()
  1034. const lockedInstance = instantiateComponent(component, {
  1035. $api: { post: () => { teamPostCalls += 1; return lockedPost.promise } },
  1036. $showToast() {},
  1037. $showModal: () => Promise.resolve(),
  1038. $refs: { teamRef: {} }
  1039. })
  1040. const lockedFirst = lockedInstance.handleConfirm({ teamName: '团队' })
  1041. const callsAfterFirst = teamPostCalls
  1042. const lockedSecond = lockedInstance.handleConfirm({ teamName: '团队' })
  1043. assert.equal(teamPostCalls, callsAfterFirst, 'concurrent submission must be ignored')
  1044. lockedPost.resolve({ data: { code: 1, msg: '保存接口失败' } })
  1045. await Promise.all([lockedFirst, lockedSecond])
  1046. }
  1047. async function testCreatedTeamNavigationIsAwaitableAndResumable() {
  1048. const timers = createFakeTimers()
  1049. let navigationOptions
  1050. let teamPostCalls = 0
  1051. let publishCalls = 0
  1052. let teamPutCalls = 0
  1053. let flushCalls = 0
  1054. const toasts = []
  1055. const uni = {
  1056. getStorageSync(key) {
  1057. assert.equal(key, 'userInfo')
  1058. return JSON.stringify({ id: 7 })
  1059. },
  1060. removeStorageSync() {},
  1061. navigateTo(options) { navigationOptions = options }
  1062. }
  1063. const component = await loadVueComponent(createTeamPagePath, { uni, timers })
  1064. const originalFormat = Date.prototype.Format
  1065. Date.prototype.Format = () => '2026-07-21 12:00:00'
  1066. try {
  1067. const instance = instantiateComponent(component, {
  1068. next: '1', questionnaireId: 66, type: 'survey', title: '问卷',
  1069. $api: {
  1070. post(url, payload) {
  1071. if (url === '/core/user/team') {
  1072. teamPostCalls += 1
  1073. assert.equal(payload.enterpriseWebsite, 'https://old.example')
  1074. return Promise.resolve({ data: { code: 0, data: { teamId: 88 } } })
  1075. }
  1076. assert.equal(url, '/core/team/questionnaire/publish')
  1077. assert.deepEqual(Object.keys(payload).sort(), [
  1078. 'answerSetting', 'coachId', 'endTime', 'questionnaireId',
  1079. 'startTime', 'teamId', 'type'
  1080. ].sort())
  1081. publishCalls += 1
  1082. return Promise.resolve({ data: { code: 0, data: 321 } })
  1083. },
  1084. put(url, payload) {
  1085. teamPutCalls += 1
  1086. assert.equal(url, '/core/user/team')
  1087. assert.equal(payload.id, 88)
  1088. assert.equal(payload.enterpriseWebsite, 'https://new.example')
  1089. if (teamPutCalls === 1) {
  1090. return Promise.resolve({ data: { code: 9, msg: '官网更新失败' } })
  1091. }
  1092. return Promise.resolve({ data: { code: 0, data: true } })
  1093. }
  1094. },
  1095. $showToast(message) { toasts.push(message) },
  1096. $showModal: () => Promise.resolve(),
  1097. $refs: {
  1098. teamRef: {
  1099. flushBackgroundFiles() { flushCalls += 1; return Promise.resolve({ success: 0, failed: 0 }) },
  1100. hasUnresolvedBackgroundFiles: () => false,
  1101. hasDeferredPcUpload: () => false
  1102. }
  1103. }
  1104. })
  1105. const first = instance.handleConfirm({
  1106. teamName: '团队', enterpriseWebsite: 'https://old.example'
  1107. })
  1108. await flushPromises()
  1109. assert.equal(teamPostCalls, 1)
  1110. assert.equal(publishCalls, 1)
  1111. assert.equal(flushCalls, 1)
  1112. assert.equal(instance.creationState.teamQuestionnaireId, 321)
  1113. assert.equal(instance.creationState.completed, false)
  1114. assert.equal(instance.creationState.submitting, true)
  1115. assert.equal(timers.count(), 1)
  1116. timers.runNext()
  1117. await flushPromises()
  1118. assert.ok(navigationOptions)
  1119. assert.equal(instance.creationState.completed, false, 'navigation callback must settle first')
  1120. navigationOptions.fail({ errMsg: 'navigateTo:fail route missing' })
  1121. await first
  1122. assert.equal(instance.creationState.completed, false)
  1123. assert.equal(instance.creationState.submitting, false)
  1124. assert.equal(instance.creationState.stage, 'navigate')
  1125. assert.ok(toasts.some(message => String(message).includes('页面跳转失败')))
  1126. navigationOptions = null
  1127. const failedUpdate = instance.handleConfirm({
  1128. teamName: '团队', enterpriseWebsite: 'https://new.example'
  1129. })
  1130. await failedUpdate
  1131. assert.equal(teamPostCalls, 1)
  1132. assert.equal(publishCalls, 1)
  1133. assert.equal(flushCalls, 1)
  1134. assert.equal(teamPutCalls, 1)
  1135. assert.equal(instance.creationState.stage, 'update')
  1136. assert.ok(toasts.some(message => String(message).includes('团队更新失败:官网更新失败')))
  1137. assert.equal(timers.count(), 0)
  1138. const retry = instance.handleConfirm({
  1139. teamName: '团队', enterpriseWebsite: 'https://new.example'
  1140. })
  1141. await flushPromises()
  1142. assert.equal(teamPostCalls, 1, 'retry must reuse the created team id')
  1143. assert.equal(publishCalls, 1, 'retry after publish success must not publish again')
  1144. assert.equal(flushCalls, 1, 'navigate-stage retry must not repeat file processing')
  1145. assert.equal(teamPutCalls, 2, 'changed sanitized payload must update the same team')
  1146. assert.equal(timers.count(), 1)
  1147. timers.runNext()
  1148. await flushPromises()
  1149. assert.ok(navigationOptions)
  1150. assert.equal(instance.creationState.completed, false)
  1151. navigationOptions.success({})
  1152. await retry
  1153. assert.equal(instance.creationState.completed, true)
  1154. assert.equal(instance.creationState.submitting, false)
  1155. } finally {
  1156. if (originalFormat) Date.prototype.Format = originalFormat
  1157. else delete Date.prototype.Format
  1158. }
  1159. }
  1160. async function testCreatedTeamUnloadCancelsLateNavigation() {
  1161. const timers = createFakeTimers()
  1162. let navigateBackCalls = 0
  1163. const uni = {
  1164. navigateBack() { navigateBackCalls += 1 }
  1165. }
  1166. const component = await loadVueComponent(createTeamPagePath, { uni, timers })
  1167. const instance = instantiateComponent(component, {
  1168. $api: {
  1169. post: () => Promise.resolve({ data: { code: 0, data: { teamId: 89 } } })
  1170. },
  1171. $showToast() {},
  1172. $showModal: () => Promise.resolve(),
  1173. getOpenerEventChannel: () => ({ emit() {} }),
  1174. $refs: {
  1175. teamRef: {
  1176. flushBackgroundFiles: () => Promise.resolve({ success: 0, failed: 0 }),
  1177. hasUnresolvedBackgroundFiles: () => false,
  1178. hasDeferredPcUpload: () => false
  1179. }
  1180. }
  1181. })
  1182. const submission = instance.handleConfirm({ teamName: '团队', enterpriseWebsite: '无' })
  1183. await flushPromises()
  1184. assert.equal(timers.count(), 1)
  1185. component.onUnload.call(instance)
  1186. assert.equal(timers.count(), 0)
  1187. timers.runAll()
  1188. await submission
  1189. assert.equal(navigateBackCalls, 0)
  1190. assert.equal(instance.creationState.completed, false)
  1191. assert.equal(instance.creationState.submitting, false)
  1192. }
  1193. async function testTeamEditRedirectIsLockedAndResumable() {
  1194. const timers = createFakeTimers()
  1195. let redirectOptions
  1196. let putCalls = 0
  1197. let navigateBackCalls = 0
  1198. const toasts = []
  1199. const uni = {
  1200. redirectTo(options) { redirectOptions = options },
  1201. navigateBack() { navigateBackCalls += 1 }
  1202. }
  1203. const component = await loadVueComponent(teamEditPagePath, { uni, timers })
  1204. const instance = instantiateComponent(component, {
  1205. submitDto: { id: 12, teamName: '团队', enterpriseWebsite: 'https://old.example' },
  1206. show: true,
  1207. $api: {
  1208. put(url, payload) {
  1209. putCalls += 1
  1210. assert.equal(url, '/core/user/team')
  1211. assert.equal(payload.id, 12)
  1212. assert.equal(Object.hasOwn(payload, 'coachId'), false)
  1213. assert.equal(Object.hasOwn(payload, 'uploaderId'), false)
  1214. assert.equal(Object.hasOwn(payload, 'source'), false)
  1215. assert.equal(payload.enterpriseWebsite,
  1216. putCalls === 1 ? 'https://old.example' : 'https://new.example')
  1217. return Promise.resolve({ data: { code: 0, data: true } })
  1218. }
  1219. },
  1220. $showToast(message) { toasts.push(message) }
  1221. })
  1222. const first = instance.editConfirm()
  1223. await flushPromises()
  1224. assert.equal(putCalls, 1)
  1225. assert.equal(instance.saveSucceeded, true)
  1226. assert.equal(instance.saving, true, 'save lock must cover the redirect delay')
  1227. assert.equal(timers.count(), 1)
  1228. instance.editConfirm()
  1229. instance.requestBack()
  1230. assert.equal(putCalls, 1, 'confirm during redirect delay must not PUT again')
  1231. assert.equal(navigateBackCalls, 0, 'back during redirect delay must stay locked')
  1232. assert.ok(toasts.some(message => String(message).includes('正在保存')))
  1233. timers.runNext()
  1234. await flushPromises()
  1235. assert.ok(redirectOptions)
  1236. assert.equal(instance.saving, true, 'redirect callback must settle before unlock')
  1237. redirectOptions.fail({ errMsg: 'redirectTo:fail route missing' })
  1238. await first
  1239. assert.equal(instance.saving, false)
  1240. assert.equal(instance.saveSucceeded, true)
  1241. assert.equal(instance.saveStage, 'navigate')
  1242. redirectOptions = null
  1243. const retry = instance.editConfirm()
  1244. await flushPromises()
  1245. assert.equal(putCalls, 1, 'redirect retry must reuse the successful PUT')
  1246. assert.equal(instance.saving, true)
  1247. assert.equal(timers.count(), 1)
  1248. timers.runNext()
  1249. await flushPromises()
  1250. assert.ok(redirectOptions)
  1251. redirectOptions.fail({ errMsg: 'redirectTo:fail still missing' })
  1252. await retry
  1253. assert.equal(putCalls, 1)
  1254. redirectOptions = null
  1255. instance.handleConfirm({
  1256. id: 12,
  1257. teamName: '团队',
  1258. enterpriseWebsite: ' https://new.example ',
  1259. coachId: 7,
  1260. uploaderId: 8,
  1261. source: 'WECHAT'
  1262. })
  1263. const changedRetry = instance.editConfirm()
  1264. await flushPromises()
  1265. assert.equal(putCalls, 2, 'a changed payload must update the saved team before redirect')
  1266. assert.equal(instance.saving, true)
  1267. assert.equal(timers.count(), 1)
  1268. timers.runNext()
  1269. await flushPromises()
  1270. assert.ok(redirectOptions)
  1271. redirectOptions.success({})
  1272. await changedRetry
  1273. assert.equal(putCalls, 2)
  1274. assert.equal(instance.saving, false)
  1275. }
  1276. async function testTeamEditUnloadCancelsLateRedirect() {
  1277. const timers = createFakeTimers()
  1278. let redirectCalls = 0
  1279. const component = await loadVueComponent(teamEditPagePath, {
  1280. timers,
  1281. uni: { redirectTo() { redirectCalls += 1 } }
  1282. })
  1283. const instance = instantiateComponent(component, {
  1284. submitDto: { id: 12 },
  1285. $api: { put: () => Promise.resolve({ data: { code: 0, data: true } }) },
  1286. $showToast() {}
  1287. })
  1288. const saving = instance.editConfirm()
  1289. await flushPromises()
  1290. assert.equal(timers.count(), 1)
  1291. component.onUnload.call(instance)
  1292. assert.equal(timers.count(), 0)
  1293. timers.runAll()
  1294. await saving
  1295. assert.equal(redirectCalls, 0)
  1296. assert.equal(instance.saving, false)
  1297. }
  1298. async function testCloseAndBackRequirePendingUploadConfirmation() {
  1299. let modalOptions
  1300. let navigateBackCalls = 0
  1301. const uni = {
  1302. showModal(options) { modalOptions = options },
  1303. navigateBack() { navigateBackCalls += 1 }
  1304. }
  1305. const createList = await loadVueComponent(createListComponentPath, { uni })
  1306. const createListInstance = instantiateComponent(createList, {
  1307. $imgBase: 'https://image.example/',
  1308. teamInfoShow: true,
  1309. $refs: {
  1310. teamRef: {
  1311. hasUnresolvedBackgroundFiles: () => true,
  1312. isBackgroundUploadActive: () => false
  1313. }
  1314. }
  1315. })
  1316. createListInstance.requestCloseTeamInfo()
  1317. assert.equal(createListInstance.teamInfoShow, true)
  1318. modalOptions.success({ confirm: false })
  1319. assert.equal(createListInstance.teamInfoShow, true)
  1320. createListInstance.requestCloseTeamInfo()
  1321. modalOptions.success({ confirm: true })
  1322. assert.equal(createListInstance.teamInfoShow, false)
  1323. const teamEdit = await loadVueComponent(teamEditPagePath, { uni })
  1324. const teamEditInstance = instantiateComponent(teamEdit, {
  1325. $refs: {
  1326. teamRef: {
  1327. hasUnresolvedBackgroundFiles: () => true,
  1328. isBackgroundUploadActive: () => true
  1329. }
  1330. }
  1331. })
  1332. teamEditInstance.requestBack()
  1333. assert.equal(navigateBackCalls, 0)
  1334. modalOptions.success({ confirm: false })
  1335. assert.equal(navigateBackCalls, 0)
  1336. teamEditInstance.requestBack()
  1337. modalOptions.success({ confirm: true })
  1338. assert.equal(navigateBackCalls, 1)
  1339. let headerBackEvents = 0
  1340. const header = await loadVueComponent(headerComponentPath, { uni })
  1341. const headerInstance = instantiateComponent(header, {
  1342. interceptBack: true,
  1343. $emit(name) { if (name === 'back') headerBackEvents += 1 }
  1344. })
  1345. headerInstance.toBack('')
  1346. assert.equal(headerBackEvents, 1)
  1347. assert.equal(navigateBackCalls, 1, 'intercepted header back must not navigate directly')
  1348. }
  1349. async function main() {
  1350. const loadedTransport = await loadTransport()
  1351. assert.equal(typeof loadedTransport.downloadTeamBackgroundFile, 'function')
  1352. await testUploadTransport()
  1353. await testApiTransport()
  1354. await testDownloadTransport()
  1355. await testDeferredPcSelectionSurvivesSessionFailure()
  1356. await testSessionRefreshFailureKeepsOldTimer()
  1357. await testPcSessionCreationIsSingleFlightPerTeam()
  1358. await testPcSessionSingleFlightSurvivesSameTeamReset()
  1359. await testPcSessionFailureClearsSingleFlightForRetry()
  1360. await testDeferredPcFinishWaitsForListRefresh()
  1361. await testDeferredPcWaiterSingleFlightFinishesAllCallers()
  1362. await testTeamContextResetAndUploadIsolation()
  1363. await testFileActionsWaitForCurrentListAndDocumentContext()
  1364. await testTeamFillFlushesBeforeEmitAndLocks()
  1365. await testCreatedTeamResumeAndSubmitLock()
  1366. await testCreatedTeamNavigationIsAwaitableAndResumable()
  1367. await testCreatedTeamUnloadCancelsLateNavigation()
  1368. await testTeamEditRedirectIsLockedAndResumable()
  1369. await testTeamEditUnloadCancelsLateRedirect()
  1370. await testCloseAndBackRequirePendingUploadConfirmation()
  1371. console.log('team background transport: PASS')
  1372. console.log('team background component behavior: PASS')
  1373. }
  1374. main().catch(error => {
  1375. console.error(error)
  1376. process.exitCode = 1
  1377. })