teamBackgroundFile.test.js 53 KB

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