materialCache.fileCache.test.js
8.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
const assert = require('assert')
function createUni(options = {}) {
const storage = new Map()
const calls = { downloadFile: 0, saveFile: 0, removeSavedFile: 0, getFileInfo: 0, request: 0, arrayBufferToBase64: 0 }
const pendingDownloads = []
const savedFiles = new Set()
let savedIndex = 0
const api = {
calls,
storage,
getNetworkType({ success }) { success({ networkType: 'wifi' }) },
getStorage({ key, success, fail }) {
if (storage.has(key)) success({ data: storage.get(key) })
else fail({ errMsg: 'not found' })
},
setStorage({ key, data, success }) {
storage.set(key, data)
success({})
},
removeStorage({ key, success }) {
storage.delete(key)
success({})
},
downloadFile({ url, success }) {
calls.downloadFile++
const complete = () => success({ statusCode: 200, tempFilePath: `_doc/temp/${encodeURIComponent(url)}.jpg` })
if (options.deferDownloads) pendingDownloads.push(complete)
else complete()
},
saveFile({ tempFilePath, success, fail }) {
calls.saveFile++
if (options.failSaveCount > 0) {
options.failSaveCount--
fail({ errMsg: 'disk full' })
return
}
savedIndex++
const savedFilePath = `_doc/uniapp_save/material-${savedIndex}.jpg`
savedFiles.add(savedFilePath)
success({ savedFilePath, tempFilePath })
},
getFileInfo({ filePath, success, fail }) {
calls.getFileInfo++
if (savedFiles.has(filePath)) success({ size: 1 })
else fail({ errMsg: 'file not found' })
},
removeSavedFile({ filePath, success }) {
calls.removeSavedFile++
savedFiles.delete(filePath)
success({})
},
request() {
calls.request++
throw new Error('素材图片不应再通过 arraybuffer 下载')
},
arrayBufferToBase64() {
calls.arrayBufferToBase64++
throw new Error('素材图片不应再转换为 Base64')
}
}
api.releaseDownloads = () => pendingDownloads.splice(0).forEach(complete => complete())
api.removeSavedFileFromSystem = filePath => savedFiles.delete(filePath)
return api
}
async function run() {
global.uni = createUni()
const modulePath = require.resolve('../utils/materialCache.js')
delete require.cache[modulePath]
const materialCache = require(modulePath)
const sourceKey = materialCache.getSourceKey('shop-1', 'scene-1', { brandId: 10, subBrandId: 20 })
const url = 'https://example.test/large.jpg'
const base = {
id: 'source-1',
moduleList: [{ id: 101, contentPicUrl: url }],
toolList: []
}
await materialCache.cacheMaterialImages(sourceKey, base)
const display = await materialCache.hydrateSourceImages(sourceKey, base, {
moduleIds: [101],
toolIds: [],
isCurrent: () => true
})
assert.equal(uni.calls.downloadFile, 1, '首次缓存应下载一次文件')
assert.equal(uni.calls.saveFile, 1, '首次缓存应保存一次文件')
assert.equal(uni.calls.request, 0, '不应使用 arraybuffer 下载')
assert.equal(uni.calls.arrayBufferToBase64, 0, '不应进行 Base64 转码')
assert.equal(display.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-1.jpg')
assert.ok([...uni.storage.values()].every(value => !String(value).startsWith('data:image/')), 'storage 不应保存 Base64 图片')
await materialCache.cacheMaterialImages(sourceKey, base)
assert.equal(uni.calls.downloadFile, 1, '同一地址再次缓存应复用已保存文件')
const missingFilePath = display.moduleList[0].contentPicUrl
uni.removeSavedFileFromSystem(missingFilePath)
materialCache.clearImageMemory()
const missingDisplay = await materialCache.hydrateSourceImages(sourceKey, base, {
moduleIds: [101],
toolIds: [],
isCurrent: () => true
})
assert.equal(missingDisplay.moduleList[0].contentPicUrl, url, '文件被系统清理后不应继续返回失效路径')
const repairedDisplay = await materialCache.hydrateSourceImages(sourceKey, base, {
moduleIds: [101],
toolIds: [],
allowDownload: true,
isCurrent: () => true
})
assert.equal(uni.calls.downloadFile, 2, '文件被系统清理后在线读取应自动重新下载')
assert.equal(repairedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-2.jpg')
uni.removeSavedFileFromSystem(repairedDisplay.moduleList[0].contentPicUrl)
materialCache.clearImageMemory()
await materialCache.cacheMaterialImages(sourceKey, base)
assert.equal(uni.calls.downloadFile, 3, '后台缓存发现文件被系统清理后应重新下载')
const savedPathKey = [...uni.storage.keys()].find(key => key.startsWith('material_file_v1_'))
assert.ok(savedPathKey, '应保存图片文件路径')
uni.storage.delete(savedPathKey)
materialCache.clearImageMemory()
await materialCache.cacheMaterialImages(sourceKey, base)
assert.equal(uni.calls.downloadFile, 4, '文件路径记录丢失后应重新下载修复')
assert.equal(uni.calls.removeSavedFile, 2, '修复成功后应清理旧文件')
const changed = JSON.parse(JSON.stringify(base))
changed.moduleList[0].contentPicUrl = 'https://example.test/large-v2.jpg'
await materialCache.cacheMaterialImages(sourceKey, changed)
const changedDisplay = await materialCache.hydrateSourceImages(sourceKey, changed, {
moduleIds: [101], toolIds: [], isCurrent: () => true
})
assert.equal(uni.calls.downloadFile, 5, '图片地址变化后应下载新文件')
assert.equal(uni.calls.removeSavedFile, 3, '新文件成功后应删除旧文件')
assert.equal(changedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-5.jpg')
const withoutImages = { id: 'source-1', moduleList: [], toolList: [] }
await materialCache.cacheMaterialImages(sourceKey, withoutImages)
assert.equal(uni.calls.removeSavedFile, 4, '接口删除图片后应清理不再使用的文件')
const failOptions = { failSaveCount: 1 }
global.uni = createUni(failOptions)
delete require.cache[modulePath]
const retryCache = require(modulePath)
const retryKey = retryCache.getSourceKey('shop-2', 'scene-1', { brandId: 10, subBrandId: 20 })
await retryCache.cacheMaterialImages(retryKey, base)
assert.equal(uni.calls.downloadFile, 1)
assert.equal(uni.calls.saveFile, 1)
await retryCache.cacheMaterialImages(retryKey, base)
assert.equal(uni.calls.downloadFile, 2, '保存失败后再次缓存必须重试下载')
assert.equal(uni.calls.saveFile, 2, '保存失败后再次缓存必须重试保存')
global.uni = createUni({ deferDownloads: true })
delete require.cache[modulePath]
const concurrentCache = require(modulePath)
const concurrentKey = concurrentCache.getSourceKey('shop-3', 'scene-1', { brandId: 10, subBrandId: 20 })
const older = concurrentCache.cacheMaterialImages(concurrentKey, base)
await new Promise(resolve => setImmediate(resolve))
const newer = concurrentCache.cacheMaterialImages(concurrentKey, base)
await new Promise(resolve => setImmediate(resolve))
assert.equal(uni.calls.downloadFile, 1, '连续切换时同一图片应共享一次下载')
uni.releaseDownloads()
await Promise.all([older, newer])
concurrentCache.clearImageMemory()
const concurrentDisplay = await concurrentCache.hydrateSourceImages(concurrentKey, base, {
moduleIds: [101], toolIds: [], isCurrent: () => true
})
assert.equal(concurrentDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-1.jpg',
'过期任务不能删除新任务正在复用的文件')
assert.equal(uni.calls.removeSavedFile, 0, '共享文件不应被过期任务清理')
global.uni = createUni({ deferDownloads: true })
delete require.cache[modulePath]
const switchedCache = require(modulePath)
const switchedKey = switchedCache.getSourceKey('shop-4', 'scene-1', { brandId: 10, subBrandId: 20 })
const oldBrand = switchedCache.cacheMaterialImages(switchedKey, base)
await new Promise(resolve => setImmediate(resolve))
const newBrand = JSON.parse(JSON.stringify(base))
newBrand.moduleList[0].contentPicUrl = 'https://example.test/other-brand.jpg'
await switchedCache.saveSourceCache(switchedKey, newBrand)
uni.releaseDownloads()
await oldBrand
assert.equal(uni.calls.removeSavedFile, 1, '新配置保存后应清理过期下载文件')
const newBrandTask = switchedCache.cacheMaterialImages(switchedKey, newBrand)
await new Promise(resolve => setImmediate(resolve))
assert.equal(uni.calls.downloadFile, 2, '新配置应下载自己的图片')
uni.releaseDownloads()
await newBrandTask
switchedCache.clearImageMemory()
const switchedDisplay = await switchedCache.hydrateSourceImages(switchedKey, newBrand, {
moduleIds: [101], toolIds: [], isCurrent: () => true
})
assert.equal(switchedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-2.jpg')
assert.equal(uni.calls.removeSavedFile, 1, '清理过期文件时不应误删新文件')
console.log('PASS material file cache')
}
run().catch(error => {
console.error(error.stack || error)
process.exitCode = 1
})