Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BD-26] Fix end exam button bug when timer reaches 00:00 #53

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/data/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ const BASE_API_URL = '/api/edx_proctoring/v1/proctored_exam/attempt';

export async function fetchExamAttemptsData(courseId, sequenceId) {
const url = new URL(
`${getConfig().LMS_BASE_URL}${BASE_API_URL}/course_id/${courseId}/content_id/${sequenceId}?is_learning_mfe=true`,
`${getConfig().LMS_BASE_URL}${BASE_API_URL}/course_id/${courseId}`,
);
if (sequenceId) {
url.searchParams.append('content_id', sequenceId);
}
url.searchParams.append('is_learning_mfe', true);
const { data } = await getAuthenticatedHttpClient().get(url.href);
return data;
}
Expand Down
41 changes: 38 additions & 3 deletions src/data/redux.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
describe('Data layer integration tests', () => {
const exam = Factory.build('exam', { attempt: Factory.build('attempt') });
const { course_id: courseId, content_id: contentId, attempt } = exam;
const fetchExamAttemptsDataUrl = `${getConfig().LMS_BASE_URL}${BASE_API_URL}/course_id/${courseId}/content_id/${contentId}?is_learning_mfe=true`;
const fetchExamAttemptsDataUrl = `${getConfig().LMS_BASE_URL}${BASE_API_URL}/course_id/${courseId}`
+ `?content_id=${encodeURIComponent(contentId)}&is_learning_mfe=true`;
const updateAttemptStatusUrl = `${getConfig().LMS_BASE_URL}${BASE_API_URL}/${attempt.attempt_id}`;
let store;

Expand Down Expand Up @@ -186,7 +187,7 @@ describe('Data layer integration tests', () => {
it('Should stop exam, and update attempt and exam', async () => {
axiosMock.onGet(fetchExamAttemptsDataUrl).replyOnce(200, { exam, active_attempt: attempt });
axiosMock.onGet(fetchExamAttemptsDataUrl).reply(200, { exam: readyToSubmitExam, active_attempt: {} });
axiosMock.onPost(updateAttemptStatusUrl).reply(200, { exam_attempt_id: readyToSubmitAttempt.attempt_id });
axiosMock.onPut(updateAttemptStatusUrl).reply(200, { exam_attempt_id: readyToSubmitAttempt.attempt_id });

await executeThunk(thunks.getExamAttemptsData(courseId, contentId), store.dispatch);
let state = store.getState();
Expand All @@ -197,6 +198,40 @@ describe('Data layer integration tests', () => {
expect(state.examState.exam.attempt.attempt_status).toBe(ExamStatus.READY_TO_SUBMIT);
});

it('Should stop exam, and redirect to sequence if no exam attempt', async () => {
const { location } = window;
delete window.location;
window.location = {
href: '',
};

axiosMock.onGet(fetchExamAttemptsDataUrl).replyOnce(200, { exam: {}, active_attempt: attempt });
axiosMock.onPut(updateAttemptStatusUrl).reply(200, { exam_attempt_id: readyToSubmitAttempt.attempt_id });

await executeThunk(thunks.getExamAttemptsData(courseId, contentId), store.dispatch);
const state = store.getState();
expect(state.examState.activeAttempt.attempt_status).toBe(ExamStatus.STARTED);

await executeThunk(thunks.stopExam(), store.dispatch, store.getState);
expect(axiosMock.history.put[0].url).toEqual(updateAttemptStatusUrl);
expect(window.location.href).toEqual(attempt.exam_url_path);

window.location = location;
});

it('Should fail to fetch if error occurs', async () => {
axiosMock.onGet(fetchExamAttemptsDataUrl).replyOnce(200, { exam: {}, active_attempt: attempt });
axiosMock.onPut(updateAttemptStatusUrl).networkError();

await executeThunk(thunks.getExamAttemptsData(courseId, contentId), store.dispatch);
let state = store.getState();
expect(state.examState.activeAttempt.attempt_status).toBe(ExamStatus.STARTED);

await executeThunk(thunks.stopExam(), store.dispatch, store.getState);
state = store.getState();
expect(state.examState.apiErrorMsg).toBe('Network Error');
});

it('Should fail to fetch if no active attempt', async () => {
axiosMock.onGet(fetchExamAttemptsDataUrl).reply(200, { exam: Factory.build('exam'), active_attempt: {} });
axiosMock.onGet(updateAttemptStatusUrl).reply(200, { exam_attempt_id: readyToSubmitAttempt.attempt_id });
Expand Down Expand Up @@ -305,7 +340,7 @@ describe('Data layer integration tests', () => {

const state = store.getState();
expect(loggingService.logError).toHaveBeenCalled();
expect(state.examState.apiErrorMsg).toBe('Failed to submit exam. No attempt id was found.');
expect(state.examState.apiErrorMsg).toBe('Failed to submit exam. No active attempt was found.');
});
});

Expand Down
56 changes: 42 additions & 14 deletions src/data/thunks.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
fetchExamReviewPolicy,
resetAttempt,
declineAttempt,
endExamWithFailure,
} from './api';
import { isEmpty } from '../helpers';
import {
Expand Down Expand Up @@ -231,13 +232,19 @@ export function stopExam() {
}

const { attempt_id: attemptId, exam_url_path: examUrl } = activeAttempt;
if (!exam.attempt || attemptId !== exam.attempt.attempt_id) {
try {
await stopAttempt(attemptId);
window.location.href = examUrl;
} catch (error) {
handleAPIError(error, dispatch);
}
return;
}

await updateAttemptAfter(
exam.course_id, exam.content_id, stopAttempt(attemptId), true,
)(dispatch);

if (attemptId !== exam.attempt.attempt_id) {
window.location.href = examUrl;
}
};
}

Expand Down Expand Up @@ -280,18 +287,36 @@ export function resetExam() {
export function submitExam() {
return async (dispatch, getState) => {
const { exam, activeAttempt } = getState().examState;
const attemptId = exam.attempt.attempt_id;
const { desktop_application_js_url: workerUrl } = activeAttempt || {};
const useWorker = window.Worker && activeAttempt && workerUrl;

if (!attemptId) {
logError('Failed to submit exam. No attempt id.');
if (!activeAttempt) {
logError('Failed to submit exam. No active attempt.');
handleAPIError(
{ message: 'Failed to submit exam. No attempt id was found.' },
{ message: 'Failed to submit exam. No active attempt was found.' },
dispatch,
);
return;
}

const { attempt_id: attemptId, exam_url_path: examUrl } = activeAttempt;
if (!exam.attempt || attemptId !== exam.attempt.attempt_id) {
try {
await submitAttempt(attemptId);
window.location.href = examUrl;
if (useWorker) {
workerPromiseForEventNames(actionToMessageTypesMap.submit, workerUrl)()
.catch(() => handleAPIError(
{ message: 'Something has gone wrong submitting your exam. Please double-check that the application is running.' },
dispatch,
));
}
} catch (error) {
handleAPIError(error, dispatch);
}
return;
}

await updateAttemptAfter(exam.course_id, exam.content_id, submitAttempt(attemptId))(dispatch);

if (useWorker) {
Expand Down Expand Up @@ -320,7 +345,7 @@ export function expireExam() {
}

await updateAttemptAfter(
exam.course_id, exam.content_id, submitAttempt(attemptId),
activeAttempt.course_id, exam.content_id, submitAttempt(attemptId),
)(dispatch);
dispatch(expireExamAttempt());

Expand All @@ -340,12 +365,15 @@ export function expireExam() {
* @param workerUrl - location of the worker from the provider
*/
export function pingAttempt(timeoutInSeconds, workerUrl) {
return async (dispatch) => {
return async (dispatch, getState) => {
await pingApplication(timeoutInSeconds, workerUrl)
.catch((error) => handleAPIError(
{ message: error ? error.message : 'Worker failed to respond.' },
dispatch,
));
.catch(async (error) => {
const { exam, activeAttempt } = getState().examState;
const message = error ? error.message : 'Worker failed to respond.';
await updateAttemptAfter(
exam.course_id, exam.content_id, endExamWithFailure(activeAttempt.attempt_id, message),
)(dispatch);
});
};
}

Expand Down
3 changes: 2 additions & 1 deletion src/exam/Exam.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const Exam = ({ isTimeLimited, children }) => {
const {
isLoading, activeAttempt, showTimer, stopExam, exam,
expireExam, pollAttempt, apiErrorMsg, pingAttempt,
getVerificationData, getProctoringSettings,
getVerificationData, getProctoringSettings, submitExam,
} = state;

const { type: examType, id: examId } = exam || {};
Expand Down Expand Up @@ -55,6 +55,7 @@ const Exam = ({ isTimeLimited, children }) => {
<ExamTimerBlock
attempt={activeAttempt}
stopExamAttempt={stopExam}
submitExam={submitExam}
expireExamAttempt={expireExam}
pollExamAttempt={pollAttempt}
pingAttempt={pingAttempt}
Expand Down
8 changes: 6 additions & 2 deletions src/exam/ExamWrapper.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,16 @@ const ExamWrapper = ({ children, ...props }) => {

ExamWrapper.propTypes = {
sequence: PropTypes.shape({
id: PropTypes.string.isRequired,
id: PropTypes.string,
isTimeLimited: PropTypes.bool,
allowProctoringOptOut: PropTypes.bool,
}).isRequired,
}),
courseId: PropTypes.string.isRequired,
children: PropTypes.element.isRequired,
};

ExamWrapper.defaultProps = {
sequence: {},
};

export default ExamWrapper;
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const EntranceProctoredExamInstructions = ({ skipProctoredExam }) => {
<p>
<FormattedMessage
id="exam.ReadyToResumeProctoredExamInstructions.text"
ddefaultMessage="You will have {totalTime} to complete your exam."
defaultMessage="You will have {totalTime} to complete your exam."
values={{ totalTime }}
/>
</p>
Expand Down
4 changes: 2 additions & 2 deletions src/timer/CountDownTimer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ const CountDownTimer = injectIntl((props) => {
})}
>
{isShowTimer
? <Icon data-testid="hide-timer" src={Visibility} onClick={hideTimer} />
: <Icon data-testid="show-timer" src={VisibilityOff} onClick={showTimer} />}
? <Icon data-testid="hide-timer" src={VisibilityOff} onClick={hideTimer} />
: <Icon data-testid="show-timer" src={Visibility} onClick={showTimer} />}
</span>
</div>
);
Expand Down
21 changes: 19 additions & 2 deletions src/timer/ExamTimerBlock.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,49 @@ import {
TIMER_IS_CRITICALLY_LOW,
TIMER_IS_LOW,
TIMER_LIMIT_REACHED,
TIMER_REACHED_NULL,
} from './events';

/**
* Exam timer block component.
*/
const ExamTimerBlock = injectIntl(({
attempt, stopExamAttempt, expireExamAttempt, pollExamAttempt, intl, pingAttempt,
attempt, stopExamAttempt, expireExamAttempt,
pollExamAttempt, intl, pingAttempt, submitExam,
}) => {
const [isShowMore, showMore, showLess] = useToggle(false);
const [alertVariant, setAlertVariant] = useState('info');
const [timeReachedNull, setTimeReachedNull] = useState(false);

if (!attempt || !IS_STARTED_STATUS(attempt.attempt_status)) {
return null;
}

const onLowTime = () => setAlertVariant('warning');
const onCriticalLowTime = () => setAlertVariant('danger');
const onTimeReachedNull = () => setTimeReachedNull(true);

const handleEndExamClick = () => {
// if timer reached 00:00 submit exam right away
// instead of trying to move user to ready_to_submit page
if (timeReachedNull) {
submitExam();
} else {
stopExamAttempt();
}
};

useEffect(() => {
Emitter.once(TIMER_IS_LOW, onLowTime);
Emitter.once(TIMER_IS_CRITICALLY_LOW, onCriticalLowTime);
Emitter.once(TIMER_LIMIT_REACHED, expireExamAttempt);
Emitter.once(TIMER_REACHED_NULL, onTimeReachedNull);

return () => {
Emitter.off(TIMER_IS_LOW, onLowTime);
Emitter.off(TIMER_IS_CRITICALLY_LOW, onCriticalLowTime);
Emitter.off(TIMER_LIMIT_REACHED, expireExamAttempt);
Emitter.off(TIMER_REACHED_NULL, onTimeReachedNull);
};
}, []);

Expand Down Expand Up @@ -95,7 +111,7 @@ const ExamTimerBlock = injectIntl(({

{attempt.attempt_status !== ExamStatus.READY_TO_SUBMIT
&& (
<Button className="mr-3" variant="outline-primary" onClick={stopExamAttempt}>
<Button className="mr-3" variant="outline-primary" onClick={handleEndExamClick}>
<FormattedMessage
id="exam.examTimer.endExamBtn"
defaultMessage="End My Exam"
Expand Down Expand Up @@ -123,6 +139,7 @@ ExamTimerBlock.propTypes = {
}),
stopExamAttempt: PropTypes.func.isRequired,
expireExamAttempt: PropTypes.func.isRequired,
submitExam: PropTypes.func.isRequired,
};

export default ExamTimerBlock;