Skip to content

Commit bca233d

Browse files
Merge pull request #470 from tcet-opensource/hotfix
testcase problem resolution
2 parents 5c58edd + 820501f commit bca233d

File tree

9 files changed

+126
-82
lines changed

9 files changed

+126
-82
lines changed

.husky/pre-commit

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44
# npm test
55
npx lint-staged
66

7-
if [ "$(uname)" == "Darwin" ]; then
7+
if [ "$(uname)" = "Darwin" ]; then
88
npm run test
9-
elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
9+
elif [ "$(expr substr $(uname -s) 1 5)" = "Linux" ]; then
1010
npm run test
11-
elif [ "$(expr substr $(uname -s) 1 5)" == "MINGW" ]; then
11+
elif [ "$(expr substr $(uname -s) 1 5)" = "MINGW" ]; then
1212
npm run testWin
1313
fi

controller/attendance.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {
66
} from "#services/attendance";
77
import { logger } from "#util";
88
import { isEntityIdValid } from "#middleware/entityIdValidation";
9-
import Student from "#models/attendance";
9+
import Student from "#models/student";
1010
import Course from "#models/course";
1111

1212
async function addAttendance(req, res) {
@@ -26,6 +26,7 @@ async function addAttendance(req, res) {
2626
res.status(400).json({
2727
error: "Invalid Id",
2828
});
29+
return;
2930
}
3031
const attendance = await addNewAttendance(
3132
student,

controller/faculty.js

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import mongoose from "mongoose";
2+
import { commitWithRetry } from "#constant";
23
import {
34
createFaculty,
45
facultyList,
@@ -63,7 +64,6 @@ async function addFaculty(req, res) {
6364
const session = await mongoose.startSession();
6465
session.startTransaction();
6566
try {
66-
6767
if (!isDepartmentValid || !isPreferredSubjectsValid) {
6868
res.status(400).json({
6969
error: `Invalid IDs: Department: ${isDepartmentValid}, PreferredSubjects: ${isPreferredSubjectsValid}}`,
@@ -78,7 +78,6 @@ async function addFaculty(req, res) {
7878
}
7979
const ERPID = `F${randomLetter}${randomNumber}`;
8080

81-
8281
const newFaculty = await createFaculty(
8382
ERPID,
8483
dateOfJoining,
@@ -103,18 +102,14 @@ async function addFaculty(req, res) {
103102
addNewEmployeeCurrent(employeeCurrentDetails, session),
104103
createEmployeeBank(employeeBankDetails, session),
105104
]);
105+
await commitWithRetry(session);
106106
res.json({
107107
res: `added faculty ${newFaculty.ERPID}`,
108108
id: newFaculty.ERPID,
109109
});
110-
await session.commitTransaction();
111-
session.endSession();
112110
}
113-
114-
115111
} catch (error) {
116112
await session.abortTransaction();
117-
session.endSession();
118113
logger.error("Error while inserting", error);
119114
res.status(500);
120115
res.json({ err: "Error while inserting in DB" });

controller/organization.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,26 @@ import Accreditation from "#models/accreditation";
1010
import Parent from "#models/organization";
1111

1212
async function addOrganization(req, res) {
13-
const { parent, startDate, name, accreditation } = req.body;
14-
const isAccreditationValid = await isEntityIdValid(accreditation, Accreditation);
13+
const { parent, startDate, name, accreditations } = req.body;
14+
const isAccreditationsValid = await isEntityIdValid(
15+
accreditations,
16+
Accreditation,
17+
);
1518
const isParentValid = await isEntityIdValid(parent, Parent);
1619
try {
17-
if (!isAccreditationValid || !isParentValid) {
20+
if (!isAccreditationsValid || !isParentValid) {
21+
console.log(isAccreditationsValid);
22+
console.log(isParentValid);
1823
res.status(400).json({
1924
error: "Invalid Id",
2025
});
26+
return;
2127
}
2228
const organization = await addNewOrganization(
2329
parent,
2430
startDate,
2531
name,
26-
accreditation,
32+
accreditations,
2733
);
2834
res.json({
2935
res: `added organization${organization.name}`,

controller/student.js

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import { logger } from "#util";
1414
import { isEntityIdValid } from "#middleware/entityIdValidation";
1515
import Department from "#models/department";
1616
import Course from "#models/course";
17-
import { departmentAbbrev, departmentNames } from "#constant";
17+
import { departmentAbbrev, departmentNames , commitWithRetry } from "#constant";
1818

1919
async function addStudent(req, res) {
2020
const {
@@ -198,9 +198,9 @@ async function addStudent(req, res) {
198198
const year = joiningYear.toString().slice(-2);
199199
let randomNumber = Math.floor(Math.random() * 1000).toString();
200200
if (randomNumber.length === 2) {
201-
randomNumber = `0${ randomNumber}`;
201+
randomNumber = `0${randomNumber}`;
202202
}
203-
const ERPID = `S${ abbrev }${year }${randomNumber}`;
203+
const ERPID = `S${abbrev}${year}${randomNumber}`;
204204

205205
const session = await mongoose.startSession();
206206
session.startTransaction();
@@ -392,16 +392,13 @@ async function addStudent(req, res) {
392392
},
393393
session,
394394
);
395-
await session.commitTransaction();
396-
res.json({
395+
await commitWithRetry(session);
396+
res.status(200).json({
397397
res: `added user ${newStudent.id} ${newStdBank.bankAccount} ,${newstdCollege.enrollmentNo}, ${newStdEduHistory.uid},${newStdMedHistory.uid},${newStdPersonal.uid}`,
398398
id: newStudent.id,
399399
});
400400
} catch (err) {
401401
await session.abortTransaction();
402-
console.log(`aborted by catch + ${err}`);
403-
} finally {
404-
session.endSession();
405402
}
406403
} else {
407404
let error = ""; // eslint-disable-line prefer-const

misc/constant.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,16 @@ export const departmentAbbrev = [
3838
"AGD",
3939
"DA",
4040
];
41+
42+
export async function commitWithRetry(session) {
43+
let i = 0;
44+
while (i < 3) {
45+
try {
46+
session.commitTransaction(); // Uses write concern set at transaction start.
47+
break;
48+
} catch (error) {
49+
console.log(error);
50+
i += 1;
51+
}
52+
}
53+
}

services/organization.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ export async function addNewOrganization(
55
parent,
66
startDate,
77
name,
8-
accreditation,
8+
accreditations,
99
) {
1010
const newOrganization = await Organization.create({
1111
parent,
1212
startDate,
1313
name,
14-
accreditation,
14+
accreditations,
1515
});
1616
if (newOrganization.name === name) {
1717
return newOrganization;

test/routes/attendance.test.js

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,29 @@
11
import { jest } from "@jest/globals"; // eslint-disable-line import/no-extraneous-dependencies
22
import attendanceModel from "#models/attendance";
33
import connector from "#models/databaseUtil";
4+
import courseModel from "#models/course";
5+
import studentModel from "#models/student";
46

57
jest.mock("#util");
68
const { agent } = global;
9+
let courseId;
10+
let studentId;
11+
12+
/* eslint-disable no-underscore-dangle */
13+
async function getIds(callback) {
14+
courseId = await courseModel.read({}, 1);
15+
courseId = courseId.data[0]._id;
16+
studentId = await studentModel.read({}, 1);
17+
studentId = studentId.data[0]._id;
18+
callback();
19+
}
20+
21+
beforeAll((done) => {
22+
getIds(done);
23+
});
724

825
function cleanUp(callback) {
9-
attendanceModel.remove({ student: "64fc3c8bde9fa947ea1f412f" }).then(() => {
26+
attendanceModel.remove({ monthlyAttended: 123456 }).then(() => {
1027
connector.disconnect((DBerr) => {
1128
if (DBerr) console.log("Database dissconnnect error: ", DBerr);
1229
callback();
@@ -21,9 +38,9 @@ afterAll((done) => {
2138
describe("checking attendance functions", () => {
2239
it("create attendance", async () => {
2340
const response = await agent.post("/attendance/add").send({
24-
student: "64fc3c8bde9fa947ea1f412f",
25-
course: "64fc3c8bde9fa947ea1f412f",
26-
monthlyAttended: 123,
41+
student: studentId,
42+
course: courseId,
43+
monthlyAttended: 123456,
2744
monthlyOccured: 123,
2845
cumulativeAttended: 123,
2946
cumulativeOccured: 123,
@@ -35,9 +52,9 @@ describe("checking attendance functions", () => {
3552
let id;
3653
beforeEach(async () => {
3754
id = await agent.post("/attendance/add").send({
38-
student: "64fc3c8bde9fa947ea1f412f",
39-
course: "64fc3c8bde9fa947ea1f412f",
40-
monthlyAttended: 123,
55+
student: studentId,
56+
course: courseId,
57+
monthlyAttended: 123456,
4158
monthlyOccured: 123,
4259
cumulativeAttended: 123,
4360
cumulativeOccured: 123,
@@ -46,21 +63,21 @@ describe("checking attendance functions", () => {
4663
});
4764

4865
afterEach(async () => {
49-
await attendanceModel.remove({ student: "64fc3c8bde9fa947ea1f412f" });
66+
await attendanceModel.remove({ student: studentId });
5067
});
5168

5269
it("read attendance", async () => {
5370
const response = await agent
5471
.get("/attendance/list")
55-
.send({ student: "64fc3c8bde9fa947ea1f412f" });
72+
.send({ student: studentId });
5673
expect(response.status).toBe(200);
5774
expect(response.body.res).toBeDefined();
5875
});
5976

6077
it("update attendance", async () => {
6178
const response = await agent
6279
.post(`/attendance/update/${id}`)
63-
.send({ student: "64fc3c8bde9fa947ea1f412f" });
80+
.send({ student: studentId });
6481
expect(response.headers["content-type"]).toMatch(/json/);
6582
expect(response.status).toBe(200);
6683
expect(response.body.res).toMatch(/attendance updated/);

test/routes/organization.test.js

Lines changed: 62 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import { jest } from "@jest/globals"; // eslint-disable-line import/no-extraneous-dependencies
22
import organizationModel from "#models/organization";
33
import connector from "#models/databaseUtil";
4+
import accreditationModel from "#models/accreditation";
45

56
jest.mock("#util");
67
const { agent } = global;
8+
let accreditationIds;
9+
let parentId;
710

811
function cleanUp(callback) {
912
organizationModel.remove({ startDate: "2023-06-18T14:11:30Z" }).then(() => {
@@ -15,60 +18,72 @@ function cleanUp(callback) {
1518
});
1619
});
1720
}
21+
/* eslint-disable no-underscore-dangle */
22+
async function getIds(callback) {
23+
accreditationIds = await accreditationModel.read({}, 1);
24+
accreditationIds = accreditationIds.data[0]._id;
25+
parentId = await organizationModel.read({}, 1);
26+
parentId = parentId.data[0]._id;
27+
callback();
28+
}
29+
30+
beforeAll((done) => {
31+
getIds(done);
32+
});
1833

1934
afterAll((done) => {
2035
cleanUp(done);
2136
});
2237

2338
describe("Organization API", () => {
24-
it("should create organization", async () => {
25-
const response = await agent.post("/organization/add").send({
26-
parent: "60a0e7e9a09c3f001c834e06",
27-
startDate:"2023-06-18T14:11:30Z",
28-
name:"my org",
29-
accreditations: "60a0e7e9a09c3f001c834e06",
30-
});
31-
32-
expect(response.status).toBe(200);
33-
expect(response.body.res).toMatch(/added organization/);
39+
it("should create organization", async () => {
40+
const response = await agent.post("/organization/add").send({
41+
parent: parentId,
42+
startDate: "2023-06-18T14:11:30Z",
43+
name: "my org",
44+
accreditations: accreditationIds,
3445
});
35-
36-
describe("after adding organization", () => {
37-
let id;
38-
beforeEach(async () => {
39-
id = await agent.post("/organization/add").send({
40-
parent: "60a0e7e9a09c3f001c834e06",
41-
startDate:"2023-06-18T14:11:30Z",
42-
name:"my org",
43-
accreditations: "60a0e7e9a09c3f001c834e06",
44-
});
45-
id = JSON.parse(id.res.text).id;
46-
});
47-
48-
afterEach(async () => {
49-
await organizationModel.remove({
50-
parent: "60a0e7e9a09c3f001c834e06",
51-
startDate:"2023-06-18T14:11:30Z",
52-
name:"my org",
53-
accreditations: "60a0e7e9a09c3f001c834e06",
54-
});
55-
});
56-
57-
it("should read organization", async () => {
58-
const response = await agent
59-
.get("/organization/list")
60-
.send({ name:"my org" });
61-
expect(response.status).toBe(200);
62-
expect(response.body.res).toBeDefined();
46+
47+
expect(response.status).toBe(200);
48+
expect(response.body.res).toMatch(/added organization/);
49+
});
50+
51+
describe("after adding organization", () => {
52+
let id;
53+
beforeEach(async () => {
54+
id = await agent.post("/organization/add").send({
55+
parent: parentId,
56+
startDate: "2023-06-18T14:11:30Z",
57+
name: "my org",
58+
accreditations: accreditationIds,
6359
});
64-
65-
it("should update organization", async () => {
66-
const response = await agent
67-
.post(`/organization/update/${id}`)
68-
.send({ name: "your org" });
69-
70-
expect(response.status).toBe(200);
71-
expect(response.body.res).toMatch(/organization updated/);
60+
id = JSON.parse(id.res.text).id;
61+
});
62+
63+
afterEach(async () => {
64+
await organizationModel.remove({
65+
parent: parentId,
66+
startDate: "2023-06-18T14:11:30Z",
67+
name: "my org",
68+
accreditations: accreditationIds,
7269
});
7370
});
74-
});
71+
72+
it("should read organization", async () => {
73+
const response = await agent
74+
.get("/organization/list")
75+
.send({ name: "my org" });
76+
expect(response.status).toBe(200);
77+
expect(response.body.res).toBeDefined();
78+
});
79+
80+
it("should update organization", async () => {
81+
const response = await agent
82+
.post(`/organization/update/${id}`)
83+
.send({ name: "your org" });
84+
85+
expect(response.status).toBe(200);
86+
expect(response.body.res).toMatch(/organization updated/);
87+
});
88+
});
89+
});

0 commit comments

Comments
 (0)