teamBackgroundFile.test.js 48 KB

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