code
stringlengths
41
2.04k
label_name
stringclasses
2 values
label
int64
0
1
$.each(postData, (index, value) => { let input = $(document.createElement('input')); input.attr('type', 'hidden'); input.attr('name', index); input.val(value); form.append(input); });
CWE-352
0
$scope.reset = function() { bootbox.confirm('Are you sure you want to reset the foreign source definition to the default ?', function(ok) { if (ok) { RequisitionsService.startTiming(); RequisitionsService.deleteForeignSourceDefinition($scope.foreignSource).then( function() { // success growl.success('The foreign source definition for ' + $scope.foreignSource + 'has been reseted.'); $scope.initialize(); }, $scope.errorHandler ); } }); };
CWE-352
0
wp.updates.updateError = function( response ) { var $card = $( '.plugin-card-' + response.slug ), $message, $button, name, error_message; wp.updates.updateDoneSuccessfully = false; if ( response.errorCode && response.errorCode == 'unable_to_connect_to_filesystem' && wp.updates.shouldRequestFilesystemCredentials ) { wp.updates.credentialError( response, 'update-plugin' ); return; } error_message = wp.updates.l10n.updateFailed.replace( '%s', response.error ); if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) { $message = $( '[data-plugin="' + response.plugin + '"]' ).next().find( '.update-message' ); $message.html( error_message ).removeClass( 'updating-message' ); } else if ( 'plugin-install' === pagenow ) { $button = $card.find( '.update-now' ); name = $button.data( 'name' ); $card .addClass( 'plugin-card-update-failed' ) .append( '<div class="notice notice-error is-dismissible"><p>' + error_message + '</p></div>' ); $button .attr( 'aria-label', wp.updates.l10n.updateFailedLabel.replace( '%s', name ) ) .html( wp.updates.l10n.updateFailedShort ).removeClass( 'updating-message' ); $card.on( 'click', '.notice.is-dismissible .notice-dismiss', function() { // Use same delay as the total duration of the notice fadeTo + slideUp animation. setTimeout( function() { $card .removeClass( 'plugin-card-update-failed' ) .find( '.column-name a' ).focus(); }, 200 ); }); } wp.a11y.speak( error_message, 'assertive' ); /* * The lock can be released since this failure was * after the credentials form. */ wp.updates.updateLock = false; $(document).trigger( 'wp-plugin-update-error', response ); wp.updates.queueChecker(); };
CWE-352
0
success: function (data) { mydata = jQuery.parseJSON(data); $.ajax({ type: 'GET', url: '/manage/get_nodes_sw_versions', data: {"nodes": nodes.join(",")}, timeout: pcs_timeout, success: function(data) { versions = jQuery.parseJSON(data); update_create_cluster_dialog(mydata, versions); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("ERROR: Unable to contact server"); } }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("ERROR: Unable to contact server"); } }); }
CWE-384
1
$scope.refresh = function(requisition) { RequisitionsService.startTiming(); RequisitionsService.updateDeployedStatsForRequisition(requisition).then( function() { // success growl.success('The deployed statistics for ' + requisition.foreignSource + ' has been updated.'); }, $scope.errorHandler ); };
CWE-352
0
function create_resource(form, update, stonith) { dataString = $(form).serialize(); var resourceID = $(form).find("[name='name']").val(); url = get_cluster_remote_url() + $(form).attr("action"); var name; if (stonith) name = "fence device"; else name = "resource" $.ajax({ type: "POST", url: url, data: dataString, dataType: "json", success: function(returnValue) { $('input.apply_changes').show(); if (returnValue["error"] == "true") { alert(returnValue["stderr"]); } else { Pcs.update(); if (!update) { if (stonith) $('#add_stonith').dialog('close'); else $('#add_resource').dialog('close'); } else { reload_current_resource(); } } }, error: function(xhr, status, error) { if (update) { alert( "Unable to update " + name + " " + ajax_simple_error(xhr, status, error) ); } else { alert( "Unable to add " + name + " " + ajax_simple_error(xhr, status, error) ); } $('input.apply_changes').show(); } }); }
CWE-384
1
this.disableChatSoundAdmin = function(inst) { if (inst.prop('tagName') != 'I') { inst = inst.find('> i.material-icons'); } if (inst.text() == 'volume_off'){ $.get(this.wwwDir+ 'user/setsettingajax/chat_message/1'); confLH.new_message_sound_admin_enabled = 1; inst.text('volume_up'); } else { $.get(this.wwwDir+ 'user/setsettingajax/chat_message/0'); confLH.new_message_sound_admin_enabled = 0; inst.text('volume_off'); } return false; };
CWE-352
0
function create_group() { var num_nodes = 0; var node_names = ""; $("#resource_list :checked").parent().parent().each(function (index,element) { if (element.getAttribute("nodeID")) { num_nodes++; node_names += element.getAttribute("nodeID") + " " } }); if (num_nodes == 0) { alert("You must select at least one resource to add to a group"); return; } $("#resources_to_add_to_group").val(node_names); $("#add_group").dialog({ title: 'Create Group', modal: true, resizable: false, buttons: { Cancel: function() { $(this).dialog("close"); }, "Create Group": function() { var data = $('#add_group > form').serialize(); var url = get_cluster_remote_url() + "add_group"; $.ajax({ type: "POST", url: url, data: data, success: function() { Pcs.update(); $("#add_group").dialog("close"); }, error: function (xhr, status, error) { alert( "Error creating group " + ajax_simple_error(xhr, status, error) ); $("#add_group").dialog("close"); } }); } } }); }
CWE-384
1
data: {config_calibre_dir: $("#config_calibre_dir").val(), csrf_token: $("input[name='csrf_token']").val()}, success: function success(data) { if ( data.change ) { if ( data.valid ) { confirmDialog( "db_submit", "GeneralChangeModal", 0, changeDbSettings ); } else { $("#InvalidDialog").modal('show'); } } else { changeDbSettings(); } } }); });
CWE-352
0
function genericAjaxPopupClose($layer, $event) { $popup = genericAjaxPopupFetch($layer); if(null != $popup) { try { if(null != $event) $popup.trigger($event); } catch(e) { if(window.console) console.log(e); } try { $popup.dialog('close'); } catch(e) { if(window.console) console.log(e); } return true; } return false; }
CWE-352
0
$scope.save = function() { var form = this.nodeForm; RequisitionsService.startTiming(); RequisitionsService.saveNode($scope.node).then( function() { // success growl.success('The node ' + $scope.node.nodeLabel + ' has been saved.'); $scope.foreignId = $scope.node.foreignId; form.$dirty = false; }, $scope.errorHandler ); };
CWE-352
0
message: app.vtranslate('JS_LBL_ARE_YOU_SURE_YOU_WANT_TO_DELETE_FILTER') }).done((e) => { app.openUrlMethodPost(thisInstance.getSelectOptionFromChosenOption(liElement).data('deleteurl')); }); event.stopPropagation(); });
CWE-352
0
$scope.addRequisition = function() { bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) { if (foreignSource) { RequisitionsService.addRequisition(foreignSource).then( function() { // success RequisitionsService.synchronizeRequisition(foreignSource, false).then( function() { growl.success('The requisition ' + foreignSource + ' has been created and synchronized.'); $scope.foreignSources.push(foreignSource); }, $scope.errorHandler ); }, $scope.errorHandler ); } else { window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ? } }); };
CWE-352
0
$scope.delete = function(foreignSource) { bootbox.confirm('Are you sure you want to remove the requisition ' + foreignSource + '?', function(ok) { if (ok) { RequisitionsService.startTiming(); RequisitionsService.deleteRequisition(foreignSource).then( function() { // success growl.success('The requisition ' + foreignSource + ' has been deleted.'); }, $scope.errorHandler ); } }); };
CWE-352
0
"Create Group": function() { var data = $('#add_group > form').serialize(); var url = get_cluster_remote_url() + "add_group"; $.ajax({ type: "POST", url: url, data: data, success: function() { Pcs.update(); $("#add_group").dialog("close"); }, error: function (xhr, status, error) { alert( "Error creating group " + ajax_simple_error(xhr, status, error) ); $("#add_group").dialog("close"); } }); }
CWE-384
1
wp.updates.decrementCount = function( upgradeType ) { var count, pluginCount, $adminBarUpdateCount = $( '#wp-admin-bar-updates .ab-label' ), $dashboardNavMenuUpdateCount = $( 'a[href="update-core.php"] .update-plugins' ), $pluginsMenuItem = $( '#menu-plugins' ); count = $adminBarUpdateCount.text(); count = parseInt( count, 10 ) - 1; if ( count < 0 || isNaN( count ) ) { return; } $( '#wp-admin-bar-updates .ab-item' ).removeAttr( 'title' ); $adminBarUpdateCount.text( count ); $dashboardNavMenuUpdateCount.each( function( index, elem ) { elem.className = elem.className.replace( /count-\d+/, 'count-' + count ); } ); $dashboardNavMenuUpdateCount.removeAttr( 'title' ); $dashboardNavMenuUpdateCount.find( '.update-count' ).text( count ); if ( 'plugin' === upgradeType ) { pluginCount = $pluginsMenuItem.find( '.plugin-count' ).eq(0).text(); pluginCount = parseInt( pluginCount, 10 ) - 1; if ( pluginCount < 0 || isNaN( pluginCount ) ) { return; } $pluginsMenuItem.find( '.plugin-count' ).text( pluginCount ); $pluginsMenuItem.find( '.update-plugins' ).each( function( index, elem ) { elem.className = elem.className.replace( /count-\d+/, 'count-' + pluginCount ); } ); if (pluginCount > 0 ) { $( '.subsubsub .upgrade .count' ).text( '(' + pluginCount + ')' ); } else { $( '.subsubsub .upgrade' ).remove(); } } };
CWE-352
0
rcube_webmail.prototype.managesieve_setget = function() { var id = this.filtersets_list.get_single_selection(), script = this.env.filtersets[id]; location.href = this.env.comm_path+'&_action=plugin.managesieve-action&_act=setget&_set='+urlencode(script); };
CWE-352
0
$scope.refresh = function(requisition) { RequisitionsService.startTiming(); RequisitionsService.updateDeployedStatsForRequisition(requisition).then( function() { // success growl.success('The deployed statistics for ' + requisition.foreignSource + ' has been updated.'); }, $scope.errorHandler ); };
CWE-352
0
this.disableChatSoundUser = function(inst) { if (inst.find('> i').text() == 'volume_off') { $.get(this.wwwDir+ 'user/setsettingajax/chat_message/1'); confLH.new_message_sound_user_enabled = 1; inst.find('> i').text('volume_up'); } else { $.get(this.wwwDir+ 'user/setsettingajax/chat_message/0'); confLH.new_message_sound_user_enabled = 0; inst.find('> i').text('volume_off'); }; if (!!window.postMessage && parent) { if (inst.find('> i').text() == 'volume_off') { parent.postMessage("lhc_ch:s:0", '*'); } else { parent.postMessage("lhc_ch:s:1", '*'); } }; return false; };
CWE-352
0
this.disableNewChatSoundAdmin = function(inst) { if (inst.prop('tagName') != 'I') { inst = inst.find('> i.material-icons'); } if (inst.text() == 'volume_off'){ $.get(this.wwwDir+ 'user/setsettingajax/new_chat_sound/1'); confLH.new_chat_sound_enabled = 1; inst.text('volume_up'); } else { $.get(this.wwwDir+ 'user/setsettingajax/new_chat_sound/0'); confLH.new_chat_sound_enabled = 0; inst.text('volume_off'); } return false; };
CWE-352
0
registerApproveFilterClickEvent: function () { const thisInstance = this; const listViewFilterBlock = this.getFilterBlock(); if (listViewFilterBlock != false) { listViewFilterBlock.on('mouseup', '.js-filter-approve', (event) => { //to close the dropdown thisInstance.getFilterSelectElement().data('select2').close(); const liElement = $(event.currentTarget).closest('.select2-results__option'); app.openUrlMethodPost(thisInstance.getSelectOptionFromChosenOption(liElement).data('approveurl')); event.stopPropagation(); }); } },
CWE-352
0
$scope.removeAllNodes = function(foreignSource) { bootbox.confirm('Are you sure you want to remove all the nodes from ' + foreignSource + '?', function(ok) { if (ok) { RequisitionsService.startTiming(); RequisitionsService.removeAllNodesFromRequisition(foreignSource).then( function() { // success growl.success('All the nodes from ' + foreignSource + ' have been removed, and the requisition has been synchronized.'); var req = $scope.requisitionsData.getRequisition(foreignSource); req.reset(); }, $scope.errorHandler ); } }); };
CWE-352
0
function node_link_action(link_selector, url, label) { var node = $.trim($("#node_info_header_title_name").text()); fade_in_out(link_selector); $.ajax({ type: 'POST', url: url, data: {"name": node}, success: function() { }, error: function (xhr, status, error) { alert( "Unable to " + label + " node '" + node + "' " + ajax_simple_error(xhr, status, error) ); } }); }
CWE-384
1
$scope.provision = function() { $scope.isSaving = true; growl.info($sanitize('The node ' + $scope.node.nodeLabel + ' is being added to requisition ' + $scope.node.foreignSource + '. Please wait...')); var successMessage = $sanitize('The node ' + $scope.node.nodeLabel + ' has been added to requisition ' + $scope.node.foreignSource); RequisitionsService.quickAddNode($scope.node).then( function() { // success $scope.reset(); bootbox.dialog({ message: successMessage, title: 'Success', buttons: { main: { label: 'Ok', className: 'btn-secondary' } } }); }, $scope.errorHandler ); };
CWE-352
0
$scope.clone = function(foreignSource) { var availableForeignSources = []; angular.forEach($scope.requisitionsData.requisitions, function(r) { if (r.foreignSource !== foreignSource) { availableForeignSources.push(r.foreignSource); } }); var modalInstance = $uibModal.open({ backdrop: 'static', keyboard: false, controller: 'CloneForeignSourceController', templateUrl: cloneForeignsourceView, resolve: { foreignSource: function() { return foreignSource; }, availableForeignSources: function() { return availableForeignSources; } } }); modalInstance.result.then(function(targetForeignSource) { bootbox.confirm('This action will override the existing foreign source definition for the requisition named ' + targetForeignSource + ', using ' + foreignSource + ' as a template. Are you sure you want to continue ? This cannot be undone.', function(ok) { if (!ok) { return; } RequisitionsService.startTiming(); RequisitionsService.cloneForeignSourceDefinition(foreignSource, targetForeignSource).then( function() { // success growl.success('The foreign source definition for ' + foreignSource + ' has been cloned to ' + targetForeignSource); }, $scope.errorHandler ); }); }); };
CWE-352
0
wp.updates.queueChecker = function() { if ( wp.updates.updateLock || wp.updates.updateQueue.length <= 0 ) { return; } var job = wp.updates.updateQueue.shift(); wp.updates.updatePlugin( job.data.plugin, job.data.slug ); };
CWE-352
0
wp.updates.keydown = function( event ) { if ( 27 === event.keyCode ) { wp.updates.requestForCredentialsModalCancel(); } else if ( 9 === event.keyCode ) { // #upgrade button must always be the last focusable element in the dialog. if ( event.target.id === 'upgrade' && ! event.shiftKey ) { $( '#hostname' ).focus(); event.preventDefault(); } else if ( event.target.id === 'hostname' && event.shiftKey ) { $( '#upgrade' ).focus(); event.preventDefault(); } } };
CWE-352
0
this.switch_task = function(task) { if (this.task === task && task != 'mail') return; var url = this.get_task_url(task); if (task == 'mail') url += '&_mbox=INBOX'; else if (task == 'logout' && !this.env.server_error) { url += '&_token=' + this.env.request_token; this.clear_compose_data(); } this.redirect(url); };
CWE-352
0
$scope.deleteNode = function(node) { bootbox.confirm('Are you sure you want to remove the node ' + node.nodeLabel + '?', function(ok) { if (ok) { RequisitionsService.startTiming(); RequisitionsService.deleteNode(node).then( function() { // success var index = -1; for(var i = 0; i < $scope.filteredNodes.length; i++) { if ($scope.filteredNodes[i].foreignId === node.foreignId) { index = i; } } if (index > -1) { $scope.filteredNodes.splice(index,1); } growl.success('The node ' + node.nodeLabel + ' has been deleted.'); }, $scope.errorHandler ); } }); };
CWE-352
0
$scope.initialize = function() { growl.success('Retrieving definition for requisition ' + $scope.foreignSource + '...'); RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then( function(foreignSourceDef) { // success $scope.foreignSourceDef = foreignSourceDef; // Updating pagination variables for detectors. $scope.filteredDetectors = $scope.foreignSourceDef.detectors; $scope.updateFilteredDetectors(); // Updating pagination variables for policies. $scope.filteredPolicies = $scope.foreignSourceDef.policies; $scope.updateFilteredPolicies(); }, $scope.errorHandler ); };
CWE-352
0
$scope.delete = function(foreignSource) { bootbox.confirm('Are you sure you want to remove the requisition ' + foreignSource + '?', function(ok) { if (ok) { RequisitionsService.startTiming(); RequisitionsService.deleteRequisition(foreignSource).then( function() { // success growl.success('The requisition ' + foreignSource + ' has been deleted.'); }, $scope.errorHandler ); } }); };
CWE-352
0
static void print_buttons(HttpRequest req, HttpResponse res, Service_T s) { if (is_readonly(req)) { // A read-only REMOTE_USER does not get access to these buttons return; } StringBuffer_append(res->outputbuffer, "<table id='buttons'><tr>"); /* Start program */ if (s->start) StringBuffer_append(res->outputbuffer, "<td><form method=POST action=%s>" "<input type=hidden value='start' name=action>" "<input type=submit value='Start service'></form></td>", s->name); /* Stop program */ if (s->stop) StringBuffer_append(res->outputbuffer, "<td><form method=POST action=%s>" "<input type=hidden value='stop' name=action>" "<input type=submit value='Stop service'></form></td>", s->name); /* Restart program */ if ((s->start && s->stop) || s->restart) StringBuffer_append(res->outputbuffer, "<td><form method=POST action=%s>" "<input type=hidden value='restart' name=action>" "<input type=submit value='Restart service'></form></td>", s->name); /* (un)monitor */ StringBuffer_append(res->outputbuffer, "<td><form method=POST action=%s>" "<input type=hidden value='%s' name=action>" "<input type=submit value='%s'></form></td></tr></table>", s->name, s->monitor ? "unmonitor" : "monitor", s->monitor ? "Disable monitoring" : "Enable monitoring"); }
CWE-352
0
static void handle_run(HttpRequest req, HttpResponse res) { const char *action = get_parameter(req, "action"); if (action) { if (is_readonly(req)) { send_error(req, res, SC_FORBIDDEN, "You do not have sufficient privileges to access this page"); return; } if (IS(action, "validate")) { LogInfo("The Monit http server woke up on user request\n"); do_wakeupcall(); } else if (IS(action, "stop")) { LogInfo("The Monit http server stopped on user request\n"); send_error(req, res, SC_SERVICE_UNAVAILABLE, "The Monit http server is stopped"); Engine_stop(); return; } } LOCK(Run.mutex) do_runtime(req, res); END_LOCK; }
CWE-352
0
void set_header(HttpResponse res, const char *name, const char *value) { HttpHeader h = NULL; ASSERT(res); ASSERT(name); NEW(h); h->name = Str_dup(name); h->value = Str_dup(value); if (res->headers) { HttpHeader n, p; for (n = p = res->headers; p; n = p, p = p->next) { if (IS(p->name, name)) { FREE(p->value); p->value = Str_dup(value); destroy_entry(h); return; } } n->next = h; } else { res->headers = h; } }
CWE-352
0
static void doGet(HttpRequest req, HttpResponse res) { set_content_type(res, "text/html"); if (ACTION(HOME)) { LOCK(Run.mutex) do_home(res); END_LOCK; } else if (ACTION(RUN)) { handle_run(req, res); } else if (ACTION(TEST)) { is_monit_running(res); } else if (ACTION(VIEWLOG)) { do_viewlog(req, res); } else if (ACTION(ABOUT)) { do_about(res); } else if (ACTION(FAVICON)) { printFavicon(res); } else if (ACTION(PING)) { do_ping(res); } else if (ACTION(GETID)) { do_getid(res); } else if (ACTION(STATUS)) { print_status(req, res, 1); } else if (ACTION(STATUS2)) { print_status(req, res, 2); } else if (ACTION(SUMMARY)) { print_summary(req, res); } else if (ACTION(REPORT)) { _printReport(req, res); } else if (ACTION(DOACTION)) { handle_do_action(req, res); } else { handle_action(req, res); } }
CWE-352
0
void set_content_type(HttpResponse res, const char *mime) { set_header(res, "Content-Type", mime); }
CWE-352
0
static void handle_action(HttpRequest req, HttpResponse res) { char *name = req->url; Service_T s = Util_getService(++name); if (! s) { send_error(req, res, SC_NOT_FOUND, "There is no service named \"%s\"", name ? name : ""); return; } const char *action = get_parameter(req, "action"); if (action) { if (is_readonly(req)) { send_error(req, res, SC_FORBIDDEN, "You do not have sufficient privileges to access this page"); return; } Action_Type doaction = Util_getAction(action); if (doaction == Action_Ignored) { send_error(req, res, SC_BAD_REQUEST, "Invalid action \"%s\"", action); return; } s->doaction = doaction; const char *token = get_parameter(req, "token"); if (token) { FREE(s->token); s->token = Str_dup(token); } LogInfo("'%s' %s on user request\n", s->name, action); Run.flags |= Run_ActionPending; /* set the global flag */ do_wakeupcall(); } do_service(req, res, s); }
CWE-352
0
def test_invoice_payment_is_still_pending_for_registration_codes(self): """ test generate enrollment report enroll a user in a course using registration code whose invoice has not been paid yet """ course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) test_user1 = UserFactory() self.register_with_redemption_code(test_user1, course_registration_code.code) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) self.client.login(username=self.instructor.username, password='test') url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertIn('The detailed enrollment report is being created.', response.content)
CWE-352
0
def test_modify_access_allow_with_uname(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_instructor.username, 'rolename': 'staff', 'action': 'allow', }) self.assertEqual(response.status_code, 200)
CWE-352
0
def test_get_student_progress_url_nostudent(self): """ Test that the endpoint 400's when requesting an unknown email. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400)
CWE-352
0
def test_post_only(self): """ Verify that we can't call the view when we aren't using POST. """ self.client.login(username=self.staff_user.username, password='test') response = self.call_add_users_to_cohorts('', method='GET') self.assertEqual(response.status_code, 405)
CWE-352
0
def test_list_entrance_exam_instructor_tasks_all_student(self): """ Test list task history for entrance exam AND all student. """ url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) # check response tasks = json.loads(response.content)['tasks'] self.assertEqual(len(tasks), 0)
CWE-352
0
def list_course_role_members(request, course_id): """ List instructors and staff. Requires instructor access. rolename is one of ['instructor', 'staff', 'beta', 'ccx_coach'] Returns JSON of the form { "course_id": "some/course/id", "staff": [ { "username": "staff1", "email": "[email protected]", "first_name": "Joe", "last_name": "Shmoe", } ] } """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) course = get_course_with_access( request.user, 'instructor', course_id, depth=None ) rolename = request.GET.get('rolename') if rolename not in ROLES: return HttpResponseBadRequest() def extract_user_info(user): """ convert user into dicts for json view """ return { 'username': user.username, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name, } response_payload = { 'course_id': course_id.to_deprecated_string(), rolename: map(extract_user_info, list_with_level( course, rolename )), } return JsonResponse(response_payload)
CWE-352
0
def test_get_delete_dataobj(test_app, client: FlaskClient, note_fixture): response = client.get("/dataobj/delete/1") assert response.status_code == 302
CWE-352
0
def test_list_entrance_exam_instructor_with_invalid_exam_key(self): """ Test list task history for entrance exam failure if course has invalid exam. """ url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course_with_invalid_ee.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 400)
CWE-352
0
def test_course_has_entrance_exam_in_student_attempts_reset(self): """ Test course has entrance exam id set while resetting attempts""" url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'all_students': True, 'delete_module': False, }) self.assertEqual(response.status_code, 400)
CWE-352
0
def test_show_student_extensions(self): self.test_change_due_date() url = reverse('show_student_extensions', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {'student': self.user1.username}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(json.loads(response.content), { u'data': [{u'Extended Due Date': u'2013-12-30 00:00', u'Unit': self.week1.display_name}], u'header': [u'Unit', u'Extended Due Date'], u'title': u'Due date extensions for %s (%s)' % ( self.user1.profile.name, self.user1.username)})
CWE-352
0
def test_list_course_role_members_staff(self): url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'rolename': 'staff', }) self.assertEqual(response.status_code, 200) # check response content expected = { 'course_id': self.course.id.to_deprecated_string(), 'staff': [ { 'username': self.other_staff.username, 'email': self.other_staff.email, 'first_name': self.other_staff.first_name, 'last_name': self.other_staff.last_name, } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected)
CWE-352
0
def test_reset_student_attempts_single(self): """ Test reset single student attempts. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # make sure problem attempts have been reset. changed_module = StudentModule.objects.get(pk=self.module_to_reset.pk) self.assertEqual( json.loads(changed_module.state)['attempts'], 0 )
CWE-352
0
def test_reset_nonexistent_extension(self): url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), }) self.assertEqual(response.status_code, 400, response.content)
CWE-352
0
def test_reset_date(self): self.test_change_due_date() url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), }) self.assertEqual(response.status_code, 200, response.content) self.assertEqual( None, get_extended_due(self.course, self.week1, self.user1) )
CWE-352
0
def test_list_course_role_members_noparams(self): """ Test missing all query parameters. """ url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400)
CWE-352
0
def test_get_ora2_responses_success(self): url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)}) with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task: mock_submit_ora2_task.return_value = True response = self.client.get(url, {}) success_status = "The ORA data report is being generated." self.assertIn(success_status, response.content)
CWE-352
0
def test_reset_extension_to_deleted_date(self): """ Test that we can delete a due date extension after deleting the normal due date, without causing an error. """ url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), 'due_datetime': '12/30/2013 00:00' }) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc), get_extended_due(self.course, self.week1, self.user1)) self.week1.due = None self.week1 = self.store.update_item(self.week1, self.user1.id) # Now, week1's normal due date is deleted but the extension still exists. url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), }) self.assertEqual(response.status_code, 200, response.content) self.assertEqual( None, get_extended_due(self.course, self.week1, self.user1) )
CWE-352
0
def test_modify_access_with_inactive_user(self): self.other_user.is_active = False self.other_user.save() # pylint: disable=no-member url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_user.username, 'rolename': 'beta', 'action': 'allow', }) self.assertEqual(response.status_code, 200) expected = { 'unique_student_identifier': self.other_user.username, 'inactiveUser': True, } res_json = json.loads(response.content) self.assertEqual(res_json, expected)
CWE-352
0
def test_certificates_features_against_status(self): """ Test certificates with status 'downloadable' should be in the response. """ url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)}) # firstly generating downloadable certificates with 'honor' mode certificate_count = 3 for __ in xrange(certificate_count): self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.generating) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 0) # Certificates with status 'downloadable' should be in response. self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 1)
CWE-352
0
def test_calculate_report_csv_success(self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs): kwargs = {'course_id': unicode(self.course.id)} kwargs.update(extra_instructor_api_kwargs) url = reverse(instructor_api_endpoint, kwargs=kwargs) success_status = "The {report_type} report is being created.".format(report_type=report_type) if report_type == 'problem responses': with patch(task_api_endpoint): response = self.client.get(url, {'problem_location': ''}) self.assertIn(success_status, response.content) else: CourseFinanceAdminRole(self.course.id).add_users(self.instructor) with patch(task_api_endpoint): response = self.client.get(url, {}) self.assertIn(success_status, response.content)
CWE-352
0
def test_list_entrance_exam_instructor_tasks_student(self): """ Test list task history for entrance exam AND student. """ # create a re-score entrance exam task url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # check response tasks = json.loads(response.content)['tasks'] self.assertEqual(len(tasks), 1) self.assertEqual(tasks[0]['status'], _('Complete'))
CWE-352
0
def qute_settings(url): """Handler for qute://settings. View/change qute configuration.""" if url.path() == '/set': return _qute_settings_set(url) src = jinja.render('settings.html', title='settings', configdata=configdata, confget=config.instance.get_str) return 'text/html', src
CWE-352
0
def test_change_to_invalid_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), 'due_datetime': '01/01/2009 00:00' }) self.assertEqual(response.status_code, 400, response.content) self.assertEqual( None, get_extended_due(self.course, self.week1, self.user1) )
CWE-352
0
def assert_update_forum_role_membership(self, current_user, identifier, rolename, action): """ Test update forum role membership. Get unique_student_identifier, rolename and action and update forum role. """ url = reverse('update_forum_role_membership', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get( url, { 'unique_student_identifier': identifier, 'rolename': rolename, 'action': action, } ) # Status code should be 200. self.assertEqual(response.status_code, 200) user_roles = current_user.roles.filter(course_id=self.course.id).values_list("name", flat=True) if action == 'allow': self.assertIn(rolename, user_roles) elif action == 'revoke': self.assertNotIn(rolename, user_roles)
CWE-352
0
def test_modify_access_with_fake_user(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': 'GandalfTheGrey', 'rolename': 'staff', 'action': 'revoke', }) self.assertEqual(response.status_code, 200) expected = { 'unique_student_identifier': 'GandalfTheGrey', 'userDoesNotExist': True, } res_json = json.loads(response.content) self.assertEqual(res_json, expected)
CWE-352
0
def require_post_params(*args, **kwargs): """ Checks for required parameters or renders a 400 error. (decorator with arguments) Functions like 'require_query_params', but checks for POST parameters rather than GET parameters. """ required_params = [] required_params += [(arg, None) for arg in args] required_params += [(key, kwargs[key]) for key in kwargs] # required_params = e.g. [('action', 'enroll or unenroll'), ['emails', None]] def decorator(func): # pylint: disable=missing-docstring def wrapped(*args, **kwargs): # pylint: disable=missing-docstring request = args[0] error_response_data = { 'error': 'Missing required query parameter(s)', 'parameters': [], 'info': {}, } for (param, extra) in required_params: default = object() if request.POST.get(param, default) == default: error_response_data['parameters'].append(param) error_response_data['info'][param] = extra if len(error_response_data['parameters']) > 0: return JsonResponse(error_response_data, status=400) else: return func(*args, **kwargs) return wrapped return decorator
CWE-352
0
def test_get_anon_ids(self): """ Test the CSV output for the anonymized user ids. """ url = reverse('get_anon_ids', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertEqual(response['Content-Type'], 'text/csv') body = response.content.replace('\r', '') self.assertTrue(body.startswith( '"User ID","Anonymized User ID","Course Specific Anonymized User ID"' '\n"{user_id}","41","42"\n'.format(user_id=self.students[0].id) )) self.assertTrue( body.endswith('"{user_id}","41","42"\n'.format(user_id=self.students[-1].id)) )
CWE-352
0
def test_rescore_problem_all(self, act): """ Test rescoring for all students. """ url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'all_students': True, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called)
CWE-352
0
def test_get_students_features_cohorted(self, is_cohorted): """ Test that get_students_features includes cohort info when the course is cohorted, and does not when the course is not cohorted. """ url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)}) set_course_cohort_settings(self.course.id, is_cohorted=is_cohorted) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertEqual('cohort' in res_json['feature_names'], is_cohorted)
CWE-352
0
def test_modify_access_revoke_not_allowed(self): """ Test revoking access that a user does not have. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'instructor', 'action': 'revoke', }) self.assertEqual(response.status_code, 200)
CWE-352
0
def test_rescore_entrance_exam_single_student(self, act): """ Test re-scoring of entrance exam for single student. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called)
CWE-352
0
def test_get_ora2_responses_already_running(self): url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)}) with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task: mock_submit_ora2_task.side_effect = AlreadyRunningError() response = self.client.get(url, {}) already_running_status = "An ORA data report generation task is already in progress." self.assertIn(already_running_status, response.content)
CWE-352
0
def test_modify_access_revoke_self(self): """ Test that an instructor cannot remove instructor privelages from themself. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.instructor.email, 'rolename': 'instructor', 'action': 'revoke', }) self.assertEqual(response.status_code, 200) # check response content expected = { 'unique_student_identifier': self.instructor.username, 'rolename': 'instructor', 'action': 'revoke', 'removingSelfAsInstructor': True, } res_json = json.loads(response.content) self.assertEqual(res_json, expected)
CWE-352
0
def test_list_report_downloads(self): url = reverse('list_report_downloads', kwargs={'course_id': self.course.id.to_deprecated_string()}) with patch('instructor_task.models.LocalFSReportStore.links_for') as mock_links_for: mock_links_for.return_value = [ ('mock_file_name_1', 'https://1.mock.url'), ('mock_file_name_2', 'https://2.mock.url'), ] response = self.client.get(url, {}) expected_response = { "downloads": [ { "url": "https://1.mock.url", "link": "<a href=\"https://1.mock.url\">mock_file_name_1</a>", "name": "mock_file_name_1" }, { "url": "https://2.mock.url", "link": "<a href=\"https://2.mock.url\">mock_file_name_2</a>", "name": "mock_file_name_2" } ] } res_json = json.loads(response.content) self.assertEqual(res_json, expected_response)
CWE-352
0
def test_entrance_exam_sttudent_delete_state(self): """ Test delete single student entrance exam state. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'delete_module': True, }) self.assertEqual(response.status_code, 200) # make sure the module has been deleted changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules) self.assertEqual(changed_modules.count(), 0)
CWE-352
0
def test_get_delete_dataobj_not_found(test_app, client: FlaskClient): response = client.get("/dataobj/delete/1") assert response.status_code == 302
CWE-352
0
def test_dir(self, tmpdir): url = QUrl.fromLocalFile(str(tmpdir)) req = QNetworkRequest(url) reply = filescheme.handler(req) # The URL will always use /, even on Windows - so we force this here # too. tmpdir_path = str(tmpdir).replace(os.sep, '/') assert reply.readAll() == filescheme.dirbrowser_html(tmpdir_path)
CWE-352
0
def test_modify_access_noparams(self): """ Test missing all query parameters. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400)
CWE-352
0
def test_certificates_features_csv(self): """ Test for certificate csv features. """ url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)}) url += '?csv=true' # firstly generating downloadable certificates with 'honor' mode certificate_count = 3 for __ in xrange(certificate_count): self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) current_date = datetime.date.today().strftime("%B %d, %Y") response = self.client.get(url) self.assertEqual(response['Content-Type'], 'text/csv') self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}'.format('issued_certificates.csv')) self.assertEqual( response.content.strip(), '"CourseID","Certificate Type","Total Certificates Issued","Date Report Run"\r\n"' + str(self.course.id) + '","honor","3","' + current_date + '"' )
CWE-352
0
def test_get_sale_records_features_json(self): """ Test that the response from get_sale_records is in json format. """ for i in range(5): course_registration_code = CourseRegistrationCode( code='sale_invoice{}'.format(i), course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) course_registration_code.save() url = reverse('get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('sale', res_json) for res in res_json['sale']: self.validate_sale_records_response( res, course_registration_code, self.sale_invoice_1, 0, invoice_item=self.invoice_item )
CWE-352
0
def wrapped(*args, **kwargs): # pylint: disable=missing-docstring request = args[0] error_response_data = { 'error': 'Missing required query parameter(s)', 'parameters': [], 'info': {}, } for (param, extra) in required_params: default = object() if request.GET.get(param, default) == default: error_response_data['parameters'].append(param) error_response_data['info'][param] = extra if len(error_response_data['parameters']) > 0: return JsonResponse(error_response_data, status=400) else: return func(*args, **kwargs)
CWE-352
0
def shutdown(): task = int(request.args.get("parameter").strip()) showtext = {} if task in (0, 1): # valid commandos received # close all database connections calibre_db.dispose() ub.dispose() if task == 0: showtext['text'] = _(u'Server restarted, please reload page') else: showtext['text'] = _(u'Performing shutdown of server, please close window') # stop gevent/tornado server web_server.stop(task == 0) return json.dumps(showtext) if task == 2: log.warning("reconnecting to calibre database") calibre_db.reconnect_db(config, ub.app_DB_path) showtext['text'] = _(u'Reconnect successful') return json.dumps(showtext) showtext['text'] = _(u'Unknown command') return json.dumps(showtext), 400
CWE-352
0
def test_qute_settings_persistence(short_tmpdir, request, quteproc_new): """Make sure settings from qute://settings are persistent.""" args = _base_args(request.config) + ['--basedir', str(short_tmpdir)] quteproc_new.start(args) quteproc_new.open_path( 'qute://settings/set?option=search.ignore_case&value=always') assert quteproc_new.get_setting('search.ignore_case') == 'always' quteproc_new.send_cmd(':quit') quteproc_new.wait_for_quit() quteproc_new.start(args) assert quteproc_new.get_setting('search.ignore_case') == 'always'
CWE-352
0
def test_list_instructor_tasks_running(self, act): """ Test list of all running tasks. """ act.return_value = self.tasks url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()}) mock_factory = MockCompletionInfo() with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) # check response self.assertTrue(act.called) expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content)['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) self.assertEqual(actual_tasks, expected_tasks)
CWE-352
0
def test_list_course_role_members_beta(self): url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'rolename': 'beta', }) self.assertEqual(response.status_code, 200) # check response content expected = { 'course_id': self.course.id.to_deprecated_string(), 'beta': [] } res_json = json.loads(response.content) self.assertEqual(res_json, expected)
CWE-352
0
def reset_due_date(request, course_id): """ Rescinds a due date extension for a student on a particular unit. """ course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id)) student = require_student_from_identifier(request.GET.get('student')) unit = find_unit(course, request.GET.get('url')) set_due_date_extension(course, unit, student, None) if not getattr(unit, "due", None): # It's possible the normal due date was deleted after an extension was granted: return JsonResponse( _("Successfully removed invalid due date extension (unit has no due date).") ) original_due_date_str = unit.due.strftime('%Y-%m-%d %H:%M') return JsonResponse(_( 'Successfully reset due date for student {0} for {1} ' 'to {2}').format(student.profile.name, _display_unit(unit), original_due_date_str))
CWE-352
0
def test_reset_entrance_exam_student_attempts_single(self): """ Test reset single student attempts for entrance exam. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # make sure problem attempts have been reset. changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules) for changed_module in changed_modules: self.assertEqual( json.loads(changed_module.state)['attempts'], 0 )
CWE-352
0
def test_show_unit_extensions(self): self.test_change_due_date() url = reverse('show_unit_extensions', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {'url': self.week1.location.to_deprecated_string()}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(json.loads(response.content), { u'data': [{u'Extended Due Date': u'2013-12-30 00:00', u'Full Name': self.user1.profile.name, u'Username': self.user1.username}], u'header': [u'Username', u'Full Name', u'Extended Due Date'], u'title': u'Users with due date extensions for %s' % self.week1.display_name})
CWE-352
0
def test_rescore_entrance_exam_all_student_and_single(self): """ Test re-scoring with both all students and single student parameters. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'all_students': True, }) self.assertEqual(response.status_code, 400)
CWE-352
0
def add_security_headers(resp): resp.headers['Content-Security-Policy'] = "default-src 'self' 'unsafe-inline' 'unsafe-eval';" if request.endpoint == "editbook.edit_book": resp.headers['Content-Security-Policy'] += "img-src * data:" resp.headers['X-Content-Type-Options'] = 'nosniff' resp.headers['X-Frame-Options'] = 'SAMEORIGIN' resp.headers['X-XSS-Protection'] = '1; mode=block' resp.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' # log.debug(request.full_path) return resp
CWE-352
0
def test_change_nonexistent_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week3.location.to_deprecated_string(), 'due_datetime': '12/30/2013 00:00' }) self.assertEqual(response.status_code, 400, response.content) self.assertEqual( None, get_extended_due(self.course, self.week3, self.user1) )
CWE-352
0
def test_change_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), 'due_datetime': '12/30/2013 00:00' }) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc), get_extended_due(self.course, self.week1, self.user1))
CWE-352
0
def test_list_instructor_tasks_problem(self, act): """ Test list task history for problem. """ act.return_value = self.tasks url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()}) mock_factory = MockCompletionInfo() with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.get(url, { 'problem_location_str': self.problem_urlname, }) self.assertEqual(response.status_code, 200) # check response self.assertTrue(act.called) expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content)['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) self.assertEqual(actual_tasks, expected_tasks)
CWE-352
0
def get_student_progress_url(request, course_id): """ Get the progress url of a student. Limited to staff access. Takes query paremeter unique_student_identifier and if the student exists returns e.g. { 'progress_url': '/../...' } """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) user = get_student_from_identifier(request.GET.get('unique_student_identifier')) progress_url = reverse('student_progress', kwargs={'course_id': course_id.to_deprecated_string(), 'student_id': user.id}) response_payload = { 'course_id': course_id.to_deprecated_string(), 'progress_url': progress_url, } return JsonResponse(response_payload)
CWE-352
0
def test_reset_entrance_exam_all_student_attempts(self, act): """ Test reset all student attempts for entrance exam. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'all_students': True, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called)
CWE-352
0
def list_entrance_exam_instructor_tasks(request, course_id): # pylint: disable=invalid-name """ List entrance exam related instructor tasks. Takes either of the following query parameters - unique_student_identifier is an email or username - all_students is a boolean """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) course = get_course_by_id(course_id) student = request.GET.get('unique_student_identifier', None) if student is not None: student = get_student_from_identifier(student) try: entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id) except InvalidKeyError: return HttpResponseBadRequest(_("Course has no valid entrance exam section.")) if student: # Specifying for a single student's entrance exam history tasks = instructor_task.api.get_entrance_exam_instructor_task_history(course_id, entrance_exam_key, student) else: # Specifying for all student's entrance exam history tasks = instructor_task.api.get_entrance_exam_instructor_task_history(course_id, entrance_exam_key) response_payload = { 'tasks': map(extract_task_features, tasks), } return JsonResponse(response_payload)
CWE-352
0
def test_entrance_exam_delete_state_with_staff(self): """ Test entrance exam delete state failure with staff access. """ self.client.logout() staff_user = StaffFactory(course_key=self.course.id) self.client.login(username=staff_user.username, password='test') url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'delete_module': True, }) self.assertEqual(response.status_code, 403)
CWE-352
0
def test_reset_entrance_exam_student_attempts_deletall(self): """ Make sure no one can delete all students state on entrance exam. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'all_students': True, 'delete_module': True, }) self.assertEqual(response.status_code, 400)
CWE-352
0
def test_modify_access_revoke_with_username(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.username, 'rolename': 'staff', 'action': 'revoke', }) self.assertEqual(response.status_code, 200)
CWE-352
0
def test_get_student_progress_url_noparams(self): """ Test that the endpoint 404's without the required query params. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400)
CWE-352
0
def test_entrance_exam_reset_student_attempts_nonsense(self): """ Test failure with both unique_student_identifier and all_students. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'all_students': True, }) self.assertEqual(response.status_code, 400)
CWE-352
0
def test_get_students_features_teams(self, has_teams): """ Test that get_students_features includes team info when the course is has teams enabled, and does not when the course does not have teams enabled """ if has_teams: self.course = CourseFactory.create(teams_configuration={ 'max_size': 2, 'topics': [{'topic-id': 'topic', 'name': 'Topic', 'description': 'A Topic'}] }) course_instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=course_instructor.username, password='test') url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertEqual('team' in res_json['feature_names'], has_teams)
CWE-352
0
def test_get_student_progress_url_from_uname(self): """ Test that progress_url is in the successful response. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) url += "?unique_student_identifier={}".format( quote(self.students[0].username.encode("utf-8")) ) response = self.client.get(url) self.assertEqual(response.status_code, 200) res_json = json.loads(response.content) self.assertIn('progress_url', res_json)
CWE-352
0