Skip to content

Commit

Permalink
add test uuid #1 (comment)
Browse files Browse the repository at this point in the history
  • Loading branch information
jiangxuan committed Oct 6, 2019
1 parent c3b3225 commit bc34ce0
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 22 deletions.
23 changes: 20 additions & 3 deletions backend/config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { isArray, isInteger } = require('lodash')
const { isArray, isInteger, isString } = require('lodash')
const Oss = require('ali-oss')

class AppConfig {
Expand All @@ -12,8 +12,10 @@ class AppConfig {
* region: string,
* accessKeyId: string,
* accessKeySecret: string,
* bucket: string
* }
* bucket: string,
* secure: boolean
* },
* imageNameSuffix: string?
* }} config 配置参数
*/
constructor (config) {
Expand All @@ -29,6 +31,21 @@ class AppConfig {
AppConfig.instance = this
}

/**
* 设置图片名称后缀
* @param {string} suffix 后缀
*/
_setImageNameSuffix (suffix) {
if (!isString(suffix)) {
throw new TypeError('期望 suffix 参数为字符串')
}
this.config.imageNameSuffix = suffix
}

getImageNameSuffix () {
return this.config.imageNameSuffix
}

/**
* 设置 oss 客户端
* **Notes** 该方法只提供给 e2e 测试, 一般不会在程序中调用, 所以该函数以 _ 开头
Expand Down
10 changes: 10 additions & 0 deletions backend/config.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,14 @@ describe('app config', () => {
expect(isInteger(hoursNumber)).toEqual(true)
expect(isInteger(hoursAllow)).toEqual(true)
})

it('_setImageNameSuffix 函数接收 suffix 参数, 期望为字符串', () => {
expect(() => {
AppConfig._setImageNameSuffix({})
}).toThrow('期望 suffix 参数为字符串')
})
it('getImageNameSuffix 函数返回正确的值', () => {
AppConfig._setImageNameSuffix('test')
expect(AppConfig.getImageNameSuffix()).toEqual('test')
})
})
72 changes: 56 additions & 16 deletions backend/e2e/post.images.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const { promisify } = require('util')
const request = require('supertest')
const mongoose = require('mongoose')
const Oss = require('ali-oss')
const uuidV1 = require('uuid/v1')
const UploadImages = require('../modals/uploadImages')
const appConfig = require('../config')
const app = require('../app')
Expand All @@ -15,6 +16,20 @@ const promisifyFsExists = promisify(fs.exists)

const uploadImagesFolderPath = path.resolve(__dirname, '../upload_images')

/**
* 图片名称生成器
* @param {string} md5 文件的 md5
* @param {string?} imageNameSuffix 文件名后缀
* @param {string} ext 文件后缀, **带有 . 字符**
*/
const imageNameGenerateHelper = (md5, ext, { suffix = '' }) => {
if (suffix !== '') {
return `${md5}-${suffix}${ext}`
} else {
return `${md5}${ext}`
}
}

describe('post images 上传图片', () => {
const testAliOssClient = new Oss({
region: 'oss-cn-hangzhou',
Expand All @@ -23,13 +38,18 @@ describe('post images 上传图片', () => {
bucket: 'tuchuang-space-test1',
secure: true
})
const imageNameSuffix = uuidV1()
const imageNameSuffixBackup = appConfig.getImageNameSuffix()
console.log(`imageNameSuffix: ${imageNameSuffix}`)
beforeAll(async () => {
await mongoose.connect(global.__MONGO_URI__, { useNewUrlParser: true })
appConfig._setOssClient(testAliOssClient)
appConfig._setImageNameSuffix(imageNameSuffix)
})

afterAll(async () => {
await mongoose.disconnect()
appConfig._setImageNameSuffix(imageNameSuffixBackup)
})

afterEach(async () => {
Expand Down Expand Up @@ -103,14 +123,16 @@ describe('post images 上传图片', () => {
})
})

it('上传的文件命名为 [文件的 md5].[ext]', async () => {
it('上传的文件命名为 [文件的 md5]-[suffix].[ext]', async () => {
const filePath = path.resolve(__dirname, '../../shared/test_images/png.png')
const fileMd5 = '637e2ee416a2de90cf6e76b6f4cc8c89'
const res = await request(app)
.post('/api/1.0.0/images')
.attach('images', filePath)

const isFsExist = await promisifyFsExists(path.resolve(uploadImagesFolderPath, `${fileMd5}.png`))
const isFsExist = await promisifyFsExists(
path.resolve(uploadImagesFolderPath, imageNameGenerateHelper(fileMd5, '.png', { suffix: imageNameSuffix }))
)

expect(isFsExist).toEqual(true)
})
Expand All @@ -122,14 +144,18 @@ describe('post images 上传图片', () => {
const res = await request(app)
.post('/api/1.0.0/images')
.attach('images', filePath)
const isFsExist = await promisifyFsExists(path.resolve(uploadImagesFolderPath, `${fileMd5}.png`))
const isFsExist = await promisifyFsExists(
path.resolve(uploadImagesFolderPath, imageNameGenerateHelper(fileMd5, '.png', { suffix: imageNameSuffix }))
)
expect(isFsExist).toEqual(true)
expect(res.status).toEqual(200)
expect(res.body).toHaveProperty('images')
expect(res.body.images).toHaveProperty(['png.png'])
expect(res.body.images['png.png'].mimetype).toEqual('image/png')
expect(res.body.images['png.png'].md5).toEqual(fileMd5)
expect(res.body.images['png.png'].fileName).toEqual(`${fileMd5}.png`)
expect(res.body.images['png.png'].fileName).toEqual(
imageNameGenerateHelper(fileMd5, '.png', { suffix: imageNameSuffix })
)
expect(res.body.images['png.png'].deleteKey).toEqual(
'2436b48115486de952296f2b5295aeb90d284761278661102e7dda990c3f67022133080fb1bcd99d7f94678a991c57f1'
)
Expand All @@ -142,14 +168,18 @@ describe('post images 上传图片', () => {
const res = await request(app)
.post('/api/1.0.0/images')
.attach('images', filePath)
const isFsExist = await promisifyFsExists(path.resolve(uploadImagesFolderPath, `${fileMd5}.webp`))
const isFsExist = await promisifyFsExists(
path.resolve(uploadImagesFolderPath, imageNameGenerateHelper(fileMd5, '.webp', { suffix: imageNameSuffix }))
)
expect(isFsExist).toEqual(true)
expect(res.status).toEqual(200)
expect(res.body).toHaveProperty('images')
expect(res.body.images).toHaveProperty(['webp.webp'])
expect(res.body.images['webp.webp'].mimetype).toEqual('image/webp')
expect(res.body.images['webp.webp'].md5).toEqual(fileMd5)
expect(res.body.images['webp.webp'].fileName).toEqual(`${fileMd5}.webp`)
expect(res.body.images['webp.webp'].fileName).toEqual(
imageNameGenerateHelper(fileMd5, '.webp', { suffix: imageNameSuffix })
)
expect(res.body.images['webp.webp'].deleteKey).toEqual(
'5a6e6b1918ff3836a0733de79ae1d05c50411a2097b50c8e0a4342ed7b345f225cee3bded7d2a55f5a4d985c222feeb2'
)
Expand All @@ -162,14 +192,18 @@ describe('post images 上传图片', () => {
const res = await request(app)
.post('/api/1.0.0/images')
.attach('images', filePath)
const isFsExist = await promisifyFsExists(path.resolve(uploadImagesFolderPath, `${fileMd5}.jpeg`))
const isFsExist = await promisifyFsExists(
path.resolve(uploadImagesFolderPath, imageNameGenerateHelper(fileMd5, '.jpeg', { suffix: imageNameSuffix }))
)
expect(isFsExist).toEqual(true)
expect(res.status).toEqual(200)
expect(res.body).toHaveProperty('images')
expect(res.body.images).toHaveProperty(['jpeg.jpeg'])
expect(res.body.images['jpeg.jpeg'].mimetype).toEqual('image/jpeg')
expect(res.body.images['jpeg.jpeg'].md5).toEqual(fileMd5)
expect(res.body.images['jpeg.jpeg'].fileName).toEqual(`${fileMd5}.jpeg`)
expect(res.body.images['jpeg.jpeg'].fileName).toEqual(
imageNameGenerateHelper(fileMd5, '.jpeg', { suffix: imageNameSuffix })
)
expect(res.body.images['jpeg.jpeg'].deleteKey).toEqual(
'0e9f92caf299d793456c1428379eba1b289eff723c2611274d77c537a3b6db87499ab4edede74c331d9ff91e1c35cc8c'
)
Expand All @@ -186,14 +220,18 @@ describe('post images 上传图片', () => {
const res = await request(app)
.post('/api/1.0.0/images')
.attach('images', filePath)
const isFsExist = await promisifyFsExists(path.resolve(uploadImagesFolderPath, `${fileMd5}.jpg`))
const isFsExist = await promisifyFsExists(
path.resolve(uploadImagesFolderPath, imageNameGenerateHelper(fileMd5, '.jpg', { suffix: imageNameSuffix }))
)
expect(isFsExist).toEqual(true)
expect(res.status).toEqual(200)
expect(res.body).toHaveProperty('images')
expect(res.body.images).toHaveProperty(['jpg.jpg'])
expect(res.body.images['jpg.jpg'].mimetype).toEqual('image/jpeg')
expect(res.body.images['jpg.jpg'].md5).toEqual(fileMd5)
expect(res.body.images['jpg.jpg'].fileName).toEqual(`${fileMd5}.jpg`)
expect(res.body.images['jpg.jpg'].fileName).toEqual(
imageNameGenerateHelper(fileMd5, '.jpg', { suffix: imageNameSuffix })
)
expect(res.body.images['jpg.jpg'].deleteKey).toEqual(
'c8f992f096ea480f851b73ec3ae6dc40a7f0091871703b0f33ab63db599542b81e5bdfd82b24b349a0af0a3974feea6a'
)
Expand All @@ -206,14 +244,14 @@ describe('post images 上传图片', () => {
const res = await request(app)
.post('/api/1.0.0/images')
.attach('images', filePath)
const isFsExist = await promisifyFsExists(path.resolve(uploadImagesFolderPath, `${fileMd5}.svg`))
const isFsExist = await promisifyFsExists(path.resolve(uploadImagesFolderPath, imageNameGenerateHelper(fileMd5, '.svg', { suffix: imageNameSuffix })))
expect(isFsExist).toEqual(true)
expect(res.status).toEqual(200)
expect(res.body).toHaveProperty('images')
expect(res.body.images).toHaveProperty(['svg.svg'])
expect(res.body.images['svg.svg'].mimetype).toEqual('image/svg+xml')
expect(res.body.images['svg.svg'].md5).toEqual(fileMd5)
expect(res.body.images['svg.svg'].fileName).toEqual(`${fileMd5}.svg`)
expect(res.body.images['svg.svg'].fileName).toEqual(imageNameGenerateHelper(fileMd5, '.svg', { suffix: imageNameSuffix }))
expect(res.body.images['svg.svg'].deleteKey).toEqual(
'19a8d1691fa874b0635ce4f259619667d1e96d30d595128485670c3316d511ad78b33f2c2d56d0197cf542b0da520ab3'
)
Expand All @@ -226,14 +264,14 @@ describe('post images 上传图片', () => {
const res = await request(app)
.post('/api/1.0.0/images')
.attach('images', filePath)
const isFsExist = await promisifyFsExists(path.resolve(uploadImagesFolderPath, `${fileMd5}.gif`))
const isFsExist = await promisifyFsExists(path.resolve(uploadImagesFolderPath, imageNameGenerateHelper(fileMd5, '.gif', { suffix: imageNameSuffix })))
expect(isFsExist).toEqual(true)
expect(res.status).toEqual(200)
expect(res.body).toHaveProperty('images')
expect(res.body.images).toHaveProperty(['gif.gif'])
expect(res.body.images['gif.gif'].mimetype).toEqual('image/gif')
expect(res.body.images['gif.gif'].md5).toEqual(fileMd5)
expect(res.body.images['gif.gif'].fileName).toEqual(`${fileMd5}.gif`)
expect(res.body.images['gif.gif'].fileName).toEqual(imageNameGenerateHelper(fileMd5, '.gif', { suffix: imageNameSuffix }))
expect(res.body.images['gif.gif'].deleteKey).toEqual(
'a642f37bf90cad0004b26ac14c6e4bed8cdce95b522c91e3fac28bebb74a05a71596df62585c340a2a0ac9f0ce0cb852'
)
Expand Down Expand Up @@ -377,9 +415,11 @@ describe('post images 上传图片', () => {
const res = await request(app)
.post('/api/1.0.0/images')
.attach('images', filePath)
await testAliOssClient.get(`${fileMd5}.svg`)
await testAliOssClient.get(imageNameGenerateHelper(fileMd5, '.svg', { suffix: imageNameSuffix }))
expect(res.body.images['svg.svg']).toHaveProperty('ossPath')
expect(res.body.images['svg.svg'].ossPath).toEqual(`https://tuchuang-space-test1.oss-cn-hangzhou.aliyuncs.com/${fileMd5}.svg`)
expect(res.body.images['svg.svg'].ossPath).toEqual(`https://tuchuang-space-test1.oss-cn-hangzhou.aliyuncs.com/${
imageNameGenerateHelper(fileMd5, '.svg', { suffix: imageNameSuffix })
}`)
})
})
})
3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"nodemon": "^1.19.2",
"rimraf": "^3.0.0",
"standard": "^14.3.1",
"supertest": "^4.0.2"
"supertest": "^4.0.2",
"uuid": "^3.3.3"
},
"dependencies": {
"ali-oss": "^6.1.1",
Expand Down
6 changes: 4 additions & 2 deletions backend/version_one_api_router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const makeDir = require('make-dir')
const baseAuth = require('./middlewares/baseAuth')
const uploadImagesToAliOss = require('./middlewares/uploadImagesToAliOss')
const saveLogToDb = require('./middlewares/saveLogToDb')
const appConfig = require('../config')

const { aes192Crypto } = require('../utils')
const { TuChuangSpaceError } = require('./errors')
Expand Down Expand Up @@ -132,10 +133,11 @@ VersionOneApiRouter.route('/images')
})
})
const fileExtname = path.extname(originalname) === '.jpg' ? '.jpg' : MIMETYPE_2_EXT[mimetype]
const imageNameSuffix = appConfig.getImageNameSuffix() === '' ? '' : appConfig.getImageNameSuffix()
// Step 2: 用复制的方式修改文件名
await promisifyFsCopyFile(
filePath,
path.resolve(imagesFileStorageDestFolderPath, `${fileHash}${fileExtname}`)
path.resolve(imagesFileStorageDestFolderPath, `${fileHash}-${imageNameSuffix}${fileExtname}`)
)
// Step 3: 移除原来的文件
await promisifyFsUnlink(filePath)
Expand All @@ -145,7 +147,7 @@ VersionOneApiRouter.route('/images')
md5: fileHash,
ext: fileExtname,
originalname,
fileName: `${fileHash}${fileExtname}`,
fileName: `${fileHash}-${imageNameSuffix}${fileExtname}`,
deleteKey: aes192Crypto(fileHash, 'foo')
}
})
Expand Down
5 changes: 5 additions & 0 deletions backend/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5993,6 +5993,11 @@ uuid@^3.2.1, uuid@^3.3.2:
resolved "https://registry.npm.taobao.org/uuid/download/uuid-3.3.3.tgz?cache=0&sync_timestamp=1566221202613&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fuuid%2Fdownload%2Fuuid-3.3.3.tgz#4568f0216e78760ee1dbf3a4d2cf53e224112866"
integrity sha1-RWjwIW54dg7h2/Ok0s9T4iQRKGY=

uuid@^3.3.3:
version "3.3.3"
resolved "https://registry.npm.taobao.org/uuid/download/uuid-3.3.3.tgz#4568f0216e78760ee1dbf3a4d2cf53e224112866"
integrity sha1-RWjwIW54dg7h2/Ok0s9T4iQRKGY=

v8-compile-cache@^2.0.3:
version "2.1.0"
resolved "https://registry.npm.taobao.org/v8-compile-cache/download/v8-compile-cache-2.1.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fv8-compile-cache%2Fdownload%2Fv8-compile-cache-2.1.0.tgz#e14de37b31a6d194f5690d67efc4e7f6fc6ab30e"
Expand Down

0 comments on commit bc34ce0

Please sign in to comment.