Skip to content

Commit 0438b60

Browse files
committed
fix Attachment tests
1 parent 4158716 commit 0438b60

File tree

8 files changed

+112
-100
lines changed

8 files changed

+112
-100
lines changed

mock-api/app.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ app.get('/v5/resources', (req, res) => {
6161
const challengeId = req.query.challengeId
6262
winston.info(`Get resources of challenge id ${challengeId}`)
6363

64+
const memberId = req.query.memberId
65+
6466
const resources = [{
6567
id: '22ba038e-48da-487b-96e8-8d3b99b6d181',
6668
challengeId,
@@ -82,8 +84,16 @@ app.get('/v5/resources', (req, res) => {
8284
roleId: '732339e7-8e30-49d7-9198-cccf9451e221'
8385
}]
8486

87+
let ret
88+
if (memberId) {
89+
// filter with memberId
90+
ret = _.filter(resources, r => r.memberId === memberId)
91+
} else {
92+
ret = resources
93+
}
94+
8595
winston.info(`Challenge resources: ${JSON.stringify(resources, null, 4)}`)
86-
res.json(resources)
96+
res.json(ret)
8797
})
8898

8999
// get challenges member can access to

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
"license": "MIT",
2929
"repository": "https://github.com/topcoder-platform/challenge-api",
3030
"devDependencies": {
31+
"aws-sdk-mock": "^6.2.1",
3132
"chai": "^4.2.0",
3233
"chai-http": "^4.2.1",
3334
"mocha": "^11.1.0",

src/common/challenge-helper.js

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -392,15 +392,16 @@ class ChallengeHelper {
392392
if (type) {
393393
challenge.type = type.name;
394394
}
395-
396-
challenge.metadata = challenge.metadata.map((m) => {
397-
try {
398-
m.value = JSON.stringify(JSON.parse(m.value)); // when we update how we index data, make this a JSON field
399-
} catch (err) {
400-
// do nothing
401-
}
402-
return m;
403-
});
395+
if (challenge.metadata) {
396+
challenge.metadata = challenge.metadata.map((m) => {
397+
try {
398+
m.value = JSON.stringify(JSON.parse(m.value)); // when we update how we index data, make this a JSON field
399+
} catch (err) {
400+
// do nothing
401+
}
402+
return m;
403+
});
404+
}
404405
}
405406

406407
static convertDateToISOString(startDate) {

src/common/helper.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,16 @@ AWS.config.update({
2929
// secretAccessKey: config.AMAZON.AWS_SECRET_ACCESS_KEY,
3030
region: config.AMAZON.AWS_REGION,
3131
});
32-
const s3 = new AWS.S3();
32+
33+
let s3
34+
35+
// lazy initialization of S3 instance
36+
function getS3() {
37+
if (!s3) {
38+
s3 = new AWS.S3();
39+
}
40+
return s3
41+
}
3342

3443
/**
3544
* Wrap async function to standard express function
@@ -194,7 +203,7 @@ async function downloadFromFileStack(url) {
194203
* @return {Promise} promise resolved to downloaded data
195204
*/
196205
async function downloadFromS3(bucket, key) {
197-
const file = await s3.getObject({ Bucket: bucket, Key: key }).promise();
206+
const file = await getS3().getObject({ Bucket: bucket, Key: key }).promise();
198207
return {
199208
data: file.Body,
200209
mimetype: file.ContentType,
@@ -208,7 +217,7 @@ async function downloadFromS3(bucket, key) {
208217
* @return {Promise} promise resolved to deleted data
209218
*/
210219
async function deleteFromS3(bucket, key) {
211-
return s3.deleteObject({ Bucket: bucket, Key: key }).promise();
220+
return getS3().deleteObject({ Bucket: bucket, Key: key }).promise();
212221
}
213222

214223
/**

src/services/AttachmentService.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ const helper = require("../common/helper");
99
const s3ParseUrl = require("../common/s3ParseUrl");
1010
const logger = require("../common/logger");
1111
const constants = require("../../app-constants");
12+
const {
13+
enrichChallengeForResponse
14+
} = require("../common/challenge-helper");
15+
const prismaHelper = require('../common/prisma-helper');
1216

1317
const bucketWhitelist = config.AMAZON.BUCKET_WHITELIST.split(",").map((bucketName) =>
1418
bucketName.trim()
@@ -43,8 +47,11 @@ async function _getChallengeAttachment(challengeId, attachmentId) {
4347
const challenge = await prisma.challenge.findUnique({ where: { id: challengeId } })
4448
const attachment = await prisma.attachment.findUnique({ where: { id: attachmentId } })
4549
if (!challenge || !challenge.id || !attachment || attachment.challengeId !== challengeId) {
46-
throw errors.NotFoundError(`Attachment ${attachmentId} not found in challenge ${challengeId}`)
50+
throw new errors.NotFoundError(`Attachment ${attachmentId} not found in challenge ${challengeId}`)
4751
}
52+
// convert challenge data
53+
enrichChallengeForResponse(challenge)
54+
prismaHelper.convertModelToResponse(challenge)
4855
return { challenge, attachment };
4956
}
5057

test/testHelper.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ let phase
1212
let phase2
1313
let timelineTemplate
1414
let challenge
15+
let taskChallenge
1516

1617
/**
1718
* function to deeply compare arrays regardeless of the order
@@ -30,6 +31,7 @@ const phase1Id = uuid()
3031
const phase2Id = uuid()
3132
const timelineTemplateId = uuid()
3233
const challengeId = uuid()
34+
const taskChallengeId = uuid()
3335

3436
/**
3537
* Create test data
@@ -129,6 +131,27 @@ async function createData () {
129131
updatedBy: 'admin'
130132
}
131133
challenge = await prisma.challenge.create({ data: challengeData })
134+
135+
taskChallenge = await prisma.challenge.create({ data: {
136+
id: taskChallengeId,
137+
taskIsTask: true,
138+
taskIsAssigned: true,
139+
name: 'Task',
140+
description: 'desc',
141+
privateDescription: 'private description',
142+
descriptionFormat: 'html',
143+
timelineTemplate: { connect: { id: timelineTemplate.id } },
144+
type: { connect: { id: challengeTypeId } },
145+
track: { connect: { id: challengeTrackId } },
146+
tags: ['tag1'],
147+
projectId: 111,
148+
legacyId: 222,
149+
startDate: new Date(),
150+
status: constants.challengeStatuses.Completed.toUpperCase(),
151+
createdAt: new Date(),
152+
createdBy: 'admin',
153+
updatedBy: 'admin'
154+
}})
132155
}
133156

134157
const defaultProjectTerms = [
@@ -163,7 +186,7 @@ const additionalTerm = {
163186
*/
164187
async function clearData () {
165188
await prisma.challenge.deleteMany({
166-
where: { id: { in: [challengeId] } }
189+
where: { id: { in: [challengeId, taskChallengeId] } }
167190
})
168191
await prisma.timelineTemplate.deleteMany({ where: { id: timelineTemplateId } })
169192
await prisma.phase.deleteMany({ where: { id: { in: [phase1Id, phase2Id] } } })
@@ -182,6 +205,7 @@ function getData () {
182205
phase2,
183206
timelineTemplate,
184207
challenge,
208+
taskChallenge,
185209
defaultProjectTerms,
186210
additionalTerm,
187211
mockTerms

test/unit/AttachmentService.test.js

Lines changed: 41 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -7,106 +7,64 @@ const fs = require('fs')
77
const path = require('path')
88
const uuid = require('uuid/v4')
99
const chai = require('chai')
10-
const service = require('../../src/services/AttachmentService')
10+
const awsMock = require('aws-sdk-mock')
1111
const testHelper = require('../testHelper')
12+
const prisma = require('../../src/common/prisma').getClient()
1213

1314
const should = chai.should()
1415

1516
const attachmentContent = fs.readFileSync(path.join(__dirname, '../attachment.txt'))
1617

17-
/*
18+
let service
19+
1820
describe('attachment service unit tests', () => {
1921
// created attachment id
2022
let id
2123
// generated data
2224
let data
25+
// attachment for task challenge
26+
let id2
2327
const notFoundId = uuid()
2428

2529
before(async () => {
30+
// mock S3 before creating S3 instance
31+
awsMock.mock('S3', 'getObject', (params, callback) => {
32+
callback(null, { Body: Buffer.from(attachmentContent) });
33+
});
34+
// import service after setting up S3 mock
35+
service = require('../../src/services/AttachmentService')
2636
await testHelper.createData()
2737
data = testHelper.getData()
28-
})
29-
30-
after(async () => {
31-
await testHelper.clearData()
32-
})
33-
34-
describe('upload attachment tests', () => {
35-
it('upload attachment successfully', async () => {
36-
const result = await service.uploadAttachment({
37-
isMachine: true
38-
}, data.challenge.id, {
39-
attachment: {
40-
data: attachmentContent,
41-
mimetype: 'text/plain',
42-
name: 'attachment.txt',
43-
size: attachmentContent.length
44-
}
45-
})
46-
should.exist(result.id)
47-
id = result.id
48-
should.equal(result.fileSize, attachmentContent.length)
49-
should.equal(result.fileName, 'attachment.txt')
50-
should.equal(result.challengeId, data.challenge.id)
51-
})
52-
53-
it('upload attachment - forbidden', async () => {
54-
try {
55-
await service.uploadAttachment({
56-
roles: ['user']
57-
}, data.challenge.id, {
58-
attachment: {
59-
data: attachmentContent,
60-
mimetype: 'text/plain',
61-
name: 'attachment.txt',
62-
size: attachmentContent.length
63-
}
64-
})
65-
} catch (e) {
66-
should.equal(e.message, 'You are not allowed to upload attachment of the challenge.')
67-
return
38+
// create attachment
39+
const createdAttachment = await prisma.attachment.create({
40+
data: {
41+
name: 'attachment.txt',
42+
url: 'http://s3.amazonaws.com/topcoder_01/attachment.txt',
43+
fileSize: 1024,
44+
createdBy: 'testdata',
45+
updatedBy: 'testdata',
46+
challenge: { connect: { id: data.challenge.id } }
6847
}
69-
throw new Error('should not reach here')
7048
})
71-
72-
it('upload attachment - file too large', async () => {
73-
try {
74-
await service.uploadAttachment({
75-
isMachine: true
76-
}, data.challenge.id, {
77-
attachment: {
78-
truncated: true,
79-
data: attachmentContent,
80-
mimetype: 'text/plain',
81-
name: 'attachment.txt',
82-
size: attachmentContent.length
83-
}
84-
})
85-
} catch (e) {
86-
should.equal(e.message.indexOf('attachment is too large') >= 0, true)
87-
return
49+
id = createdAttachment.id
50+
const taskAttachment = await prisma.attachment.create({
51+
data: {
52+
name: 'attachment.txt',
53+
url: 'http://s3.amazonaws.com/topcoder_01/attachment.txt',
54+
fileSize: 1024,
55+
createdBy: 'testdata',
56+
updatedBy: 'testdata',
57+
challenge: { connect: { id: data.taskChallenge.id } }
8858
}
89-
throw new Error('should not reach here')
9059
})
60+
id2 = taskAttachment.id
61+
})
9162

92-
it('upload attachment - challenge not found', async () => {
93-
try {
94-
await service.uploadAttachment({
95-
isMachine: true
96-
}, notFoundId, {
97-
attachment: {
98-
data: attachmentContent,
99-
mimetype: 'text/plain',
100-
name: 'attachment.txt',
101-
size: attachmentContent.length
102-
}
103-
})
104-
} catch (e) {
105-
should.equal(e.message, `Challenge with id: ${notFoundId} doesn't exist`)
106-
return
107-
}
108-
throw new Error('should not reach here')
109-
})
63+
after(async () => {
64+
await testHelper.clearData()
65+
await prisma.attachment.deleteMany({ where: { id }})
66+
// restore S3
67+
awsMock.restore('S3');
11068
})
11169

11270
describe('download attachment tests', () => {
@@ -118,9 +76,9 @@ describe('attachment service unit tests', () => {
11876

11977
it('download attachment - forbidden', async () => {
12078
try {
121-
await service.downloadAttachment({ roles: ['user'], userId: 678678 }, data.challenge.id, id)
79+
await service.downloadAttachment({ roles: ['user'], userId: 678678 }, data.taskChallenge.id, id2)
12280
} catch (e) {
123-
should.equal(e.message, 'You are not allowed to download attachment of the challenge.')
81+
should.equal(e.message, 'You don\'t have access to view this challenge')
12482
return
12583
}
12684
throw new Error('should not reach here')
@@ -130,7 +88,7 @@ describe('attachment service unit tests', () => {
13088
try {
13189
await service.downloadAttachment({ isMachine: true }, data.challenge.id, notFoundId)
13290
} catch (e) {
133-
should.equal(e.message, `Attachment with id: ${notFoundId} doesn't exist`)
91+
should.equal(e.message, `Attachment ${notFoundId} not found in challenge ${data.challenge.id}`)
13492
return
13593
}
13694
throw new Error('should not reach here')
@@ -140,7 +98,7 @@ describe('attachment service unit tests', () => {
14098
try {
14199
await service.downloadAttachment({ isMachine: true }, notFoundId, id)
142100
} catch (e) {
143-
should.equal(e.message, 'The attachment challengeId does not match the path challengeId.')
101+
should.equal(e.message, `Attachment ${id} not found in challenge ${notFoundId}`)
144102
return
145103
}
146104
throw new Error('should not reach here')
@@ -167,5 +125,3 @@ describe('attachment service unit tests', () => {
167125
})
168126
})
169127
})
170-
171-
*/

test/unit/ChallengeService.test.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,11 @@ describe('challenge service unit tests', () => {
373373
page: 1,
374374
perPage: 10,
375375
id: id,
376+
<<<<<<< HEAD
376377

378+
=======
379+
380+
>>>>>>> bf8ac4b (fix Attachment tests)
377381
typeId: testChallengeData.typeId,
378382
name: testChallengeData.name.substring(2).trim(),
379383
description: testChallengeData.description,

0 commit comments

Comments
 (0)