How to use reorder_items method in Pytest

Best Python code snippet using pytest

lesson.py

Source:lesson.py Github

copy

Full Screen

...23@blueprint.subdomain_route("/<course_slug>/lessons/reorder", methods=["POST"])24@login_required25@teacher_required26def reorder_lessons(user, course, course_slug=None, institute=""):27 return reorder_items(request, datamodels.Lesson, course.lessons)28@blueprint.subdomain_route("/<course_slug>/lessons/add_intro", methods=["POST"])29@login_required30@teacher_required31def course_add_edit_intro_lesson(user, course, course_slug, institute=""):32 form = AjaxCSRFTokenForm(request.form)33 intro_lesson = course.intro_lesson34 if form.validate() and "intro_lesson" in request.form:35 db = datamodels.get_session()36 slug = "intro-lesson"37 if (38 datamodels.get_lesson_by_slugs(course.slug, "intro-lesson") is not None39 and not intro_lesson40 ):41 slug = slug + "-" + str(uuid4())[:3]42 if intro_lesson:43 segment = intro_lesson.intro_segment44 set_segment_video_url(segment, request.form["segment_url"])45 html = ""46 else:47 intro_lesson = datamodels.Lesson(48 title="Intro lesson",49 slug=slug,50 description="Intro lesson video",51 order=0,52 course=course,53 )54 db.add(intro_lesson)55 segment = datamodels.Segment(56 lesson=intro_lesson,57 order=0,58 type="video",59 title="Introduction",60 barrier=SegmentBarrierEnum.normal,61 video_type=VideoTypeEnum.standard,62 url=request.form["segment_url"],63 duration_seconds=0,64 slug="intro-segment",65 )66 set_segment_video_url(segment, request.form["segment_url"])67 html = render_intro(segment)68 db.add(segment)69 db.commit()70 return jsonify(71 {72 "message": "Intro lesson {}".format("updated" if not html else "added"),73 "html": html,74 }75 )76 else:77 return jsonify({"message": "Couldn't create intro lesson"}), 40078@blueprint.subdomain_route("/<course_slug>/lessons/add", methods=["POST"])79@login_required80@teacher_required81def add(user, course, course_slug, lesson_id=None, institute=""):82 form = AddLessonForm(request.form)83 if form.validate():84 lesson = datamodels.Lesson(course=course, order=len(course.lessons) + 1)85 lesson.title = form.title.data86 lesson.description = form.description.data87 lesson.slug = slugify(form.title.data)88 db = datamodels.get_session()89 db.add(lesson)90 db.commit()91 return redirect("/course/{}/lessons/{}/edit".format(course.slug, lesson.id))92 else:93 for error in form.errors:94 flash(error)95 return redirect("/course/{}/edit".format(course.slug))96@blueprint.subdomain_route(97 "/<course_slug>/lessons/<int:lesson_id>/edit", methods=["POST"]98)99@login_required100@teacher_required101def edit(user, course, course_slug, lesson_id, institute=""):102 lesson = datamodels.Course.find_lesson_by_course_slug_and_id(course.slug, lesson_id)103 if not lesson:104 raise abort(404, "No such lesson")105 if not AjaxCSRFTokenForm(request.form).validate():106 return jsonify({"success": False, "message": "CSRF token required"}), 400107 if "title" in request.form:108 slug = slugify(request.form["title"])109 if datamodels.get_lesson_by_slugs(course_slug, slug) is not None:110 return (111 jsonify({"success": False, "message": "Use different lesson name"}),112 400,113 )114 lesson.title = request.form["title"]115 lesson.slug = slug116 if "description" in request.form:117 lesson.description = request.form["description"]118 if 3 > len(lesson.description) > 140:119 return (120 jsonify(121 {122 "success": False,123 "message": "Description should be no more than 140 characters.",124 }125 ),126 400,127 )128 if "further_reading" in request.form:129 lesson.further_reading = request.form["further_reading"]130 if "cover_image" in request.form:131 cover_image = request.files["file"]132 filename = generate_thumbnail(cover_image, "cover")133 lesson.cover_image = filename134 db = datamodels.get_session()135 db.add(lesson)136 db.commit()137 return jsonify({"success": True})138@blueprint.subdomain_route(139 "/<course_slug>/lessons/<int:lesson_id>/edit", methods=["GET"]140)141@login_required142@teacher_required143def retrieve(user, course, course_slug, lesson_id, institute=""):144 lesson = datamodels.Course.find_lesson_by_course_slug_and_id(course.slug, lesson_id)145 if not lesson:146 raise abort(404, "No such lesson")147 form = AddLessonForm(request.form, lesson)148 ordered_questions = datamodels.LessonQA.ordered_items_for_parent(149 parent=lesson, key="lesson_id"150 ).all()151 data = {152 "course": course,153 "lesson": lesson,154 "form": form,155 "introduction": lesson.intro_segment,156 "resources": lesson.ordered_resources,157 "teachers": [158 render_teacher(obj.user, course, lesson) for obj in lesson.teachers159 ],160 "segments": list(lesson.get_ordered_segments())[1:],161 "questions": [162 render_question_answer(course, lesson, question)163 for question in ordered_questions164 ],165 "resource_types": {r.name: r.value for r in ResourceTypeEnum},166 "resource_images": RESOURCE_CONTENT_IMG,167 "ajax_csrf_form": AjaxCSRFTokenForm(),168 "resource_form": AddResourceForm(),169 }170 return render_template("partials/course/_lesson.html", **data)171@blueprint.subdomain_route(172 "/<course_slug>/lessons/<int:lesson_id>/delete", methods=["POST"]173)174@login_required175@teacher_required176def course_delete_lesson(user, course, course_slug, lesson_id, institute=""):177 lesson = datamodels.Course.find_lesson_by_course_slug_and_id(course.slug, lesson_id)178 if lesson:179 db = datamodels.get_session()180 db.delete(lesson)181 db.commit()182 list_of_lessons = [183 l.id for l in datamodels.Lesson.get_ordered_items() if l.order != 0184 ]185 if list_of_lessons:186 datamodels.Lesson.reorder_items(list_of_lessons)187 return jsonify({"success_url": "/course/{}/edit".format(course_slug)})188 return jsonify({"success": False, "message": "Couldn't delete lesson"}), 400189@blueprint.subdomain_route("<course_slug>/<lesson_slug>")190@enrollment_required191def view(course_slug, lesson_slug, institute=""):192 """193 Retrieves and displays a particular course, with the specified lesson194 and its first segment set to be active.195 """196 lesson = datamodels.get_lesson_by_slugs(course_slug, lesson_slug)197 if lesson is None:198 return redirect("/404")199 course = lesson.course200 segment = lesson.segments[0] if lesson.segments else None201 data = {202 "students": get_students_progress(course),203 "active_lesson": lesson,204 "active_segment": segment,205 "course_progress": get_course_progress(course),206 "course": course,207 "form": AjaxCSRFTokenForm(), # need to pass this form in case of guest enrolled for a course208 }209 if course is None:210 return redirect("/404")211 return render_template("course.html", **data)212@blueprint.subdomain_route(213 "/<course_slug>/lessons/<int:lesson_id>/teacher/add", methods=["POST"]214)215@login_required216@teacher_required217def add_teacher(user, course, course_slug, lesson_id, institute=""):218 lesson = datamodels.Course.find_lesson_by_course_slug_and_id(course.slug, lesson_id)219 if not AjaxCSRFTokenForm(request.form).validate():220 return jsonify({"success": False, "message": "CSRF token required"}), 400221 if not lesson:222 return jsonify({"success": False, "message": "Wrong lesson or course"}), 400223 new_teacher = (224 datamodels.User.find_by_email(request.form["teacher_email"])225 if "teacher_email" in request.form226 else None227 )228 if not new_teacher:229 return (230 jsonify({"success": False, "message": "Can't find that email sorry!"}),231 400,232 )233 elif not new_teacher.teaches(course):234 return (235 jsonify({"success": False, "message": "This user is not a teacher."}),236 400,237 )238 if new_teacher.id in [teacher.id for teacher in lesson.teachers]:239 return jsonify({"success": False, "message": "Teacher already added"}), 400240 enrolment = datamodels.CourseEnrollment.find_by_course_and_student(241 course.id, new_teacher.id242 )243 if enrolment.access_level not in [CourseAccess.admin, CourseAccess.teacher]:244 return jsonify({"success": False, "message": "User must be a teacher"}), 400245 lesson.teachers.append(enrolment)246 db = datamodels.get_session()247 db.add(lesson)248 db.commit()249 return jsonify(250 {251 "success": True,252 "message": "Successfully added!",253 "teacher": render_teacher(new_teacher, course, lesson),254 }255 )256@blueprint.subdomain_route(257 "/<course_slug>/lessons/<int:lesson_id>/teacher/<int:teacher_id>/delete",258 methods=["POST"],259)260@login_required261@teacher_required262def delete_teacher(user, course, course_slug, lesson_id, teacher_id, institute=""):263 lesson = datamodels.Course.find_lesson_by_course_slug_and_id(course.slug, lesson_id)264 if not lesson:265 return jsonify({"success": False, "message": "Wrong lesson or course"}), 400266 if not datamodels.get_user(teacher_id):267 return jsonify({"success": False, "message": "No such teacher"}), 400268 removed = lesson.remove_teacher(teacher_id)269 return jsonify(270 {"success": removed, "teacher_id": teacher_id, "message": "Teacher removed"}271 )272@blueprint.subdomain_route(273 "/<course_slug>/lessons/<int:lesson_id>/qa/<int:qa_id>/edit", methods=["POST"]274)275@blueprint.subdomain_route(276 "/<course_slug>/lessons/<int:lesson_id>/qa/add", methods=["POST"]277)278@login_required279@teacher_required280def add_lesson_qa(user, course, course_slug, lesson_id, qa_id=None, institute=""):281 lesson = datamodels.Course.find_lesson_by_course_slug_and_id(course.slug, lesson_id)282 if not AjaxCSRFTokenForm(request.form).validate():283 return jsonify({"message": "CSRF token required"}), 400284 if not lesson:285 return jsonify({"message": "Wrong lesson or course"}), 400286 form = LessonQAForm(data=request.form)287 if form.validate():288 # get instance of LessonQA289 qa = datamodels.LessonQA.find_by_lesson_and_id(lesson_id, qa_id)290 if qa is None and qa_id:291 return jsonify({"message": "Wrong question or lesson"}), 400292 if not qa:293 qa = datamodels.LessonQA(lesson=lesson, order=len(lesson.questions) + 1)294 qa.answer = form.answer.data295 qa.question = form.question.data296 db = datamodels.get_session()297 db.add(qa)298 db.commit()299 return jsonify(300 {301 "message": "Question saved",302 "html": render_question_answer(course, lesson, qa),303 }304 )305 return jsonify({"message": "Error saving questions"}), 400306@blueprint.subdomain_route(307 "/<course_slug>/lessons/<int:lesson_id>/qa/<int:qa_id>/delete", methods=["POST"]308)309@login_required310@teacher_required311def delete_lesson_qa(user, course, course_slug, lesson_id, qa_id, institute=""):312 lesson = datamodels.Course.find_lesson_by_course_slug_and_id(course.slug, lesson_id)313 if not lesson:314 return jsonify({"success": False, "message": "Wrong lesson or course"}), 400315 qa = datamodels.LessonQA.find_by_lesson_and_id(lesson_id, qa_id)316 if qa is None and qa_id:317 return jsonify({"success": False, "message": "Wrong question or lesson"}), 400318 datamodels.LessonQA.delete(qa, lesson, "lesson_id")319 return jsonify(320 {321 "success": True,322 "message": "Question deleted",323 "success_url": "/course/{}/lessons/{}/edit".format(course_slug, lesson_id),324 }325 )326@blueprint.subdomain_route(327 "/<course_slug>/lessons/<int:lesson_id>/qa/reorder", methods=["POST"]328)329@login_required330@teacher_required331def reorder_lesson_qa(user, course, course_slug, lesson_id, institute=""):332 lesson = datamodels.Course.find_lesson_by_course_slug_and_id(course.slug, lesson_id)333 if not lesson:334 return jsonify({"success": False, "message": "Wrong lesson or course"}), 400...

Full Screen

Full Screen

reordering.py

Source:reordering.py Github

copy

Full Screen

1# *** Reordering Script ***2# This script allows automatic reordering of inventory items when the available count drops below the specified floor and reorders to the specified ceiling. 3# Set up: 4# 1. Install requests module `pip install requests`5# 2. Create a min and max field and set the value on all inventory items that need to be automatically reordered. 6# 3. Specify the min and max field names within this script.7# 4. Insert authentication credentials.8# 5. Set up a cron job for this script or run manually as desired. 9# Known script limitations: 10# 1. Orders with groups that require approvals will still need to be approved in order for the order to go through.11# 2. If items reordered are not yet in inventory when the script runs again, the script will reorder these items again.12# 3. The first available group is auto-assigned to the order.13# 4. This script does not filter for pending orders. So rerunning before accepting items into inventory could result in duplicates.14import json15import base6416import requests17# TODO specify min and max field names (add these as field definitions to any inventory items you would like reordered)18MIN_FIELD = 'Minimum'19MAX_FIELD = 'Maximum'20# TODO insert credentials for authentication (see https://apidocs.labfellows.com for instructions)21BASE_URL = "https://api.labfellows.com/v2/"22API_KEY = "<YOUR_API_KEY_HERE>"23email = "<YOUR_EMAIL_HERE>"24subdomain = "<YOUR_SUBDOMAIN_HERE>"25encoded_auth = base64.encodebytes(('%s:%s' % (email, API_KEY)).encode('utf8')).decode('utf8').replace('\n', '')26headers = {27 'content-type': "application/vnd.api+json",28 'accept': "application/vnd.api+json",29 'x-authorization': "Bearer organization %s" % subdomain,30 'Authorization': "Basic %s" % encoded_auth31}32try:33 print('get field definitions and id of min and max fields...')34 inventory_definitions_url = BASE_URL + 'inventory_field_definitions'35 inventory_definitions_request = requests.get(inventory_definitions_url, headers=headers)36 inventory_definitions_request.raise_for_status()37 inventory_definitions = inventory_definitions_request.json()38 max_field_definition = [el for el in inventory_definitions['data'] if el['name'] == MAX_FIELD]39 max_field_definition_id = max_field_definition[0]['id'] if len(max_field_definition) > 0 else None40 if not max_field_definition_id:41 print('max field needs to be defined for reordering!')42 exit()43 min_field_definition = [el for el in inventory_definitions['data'] if el['name'] == MIN_FIELD]44 min_field_definition_id = min_field_definition[0]['id'] if len(min_field_definition) > 0 else None45 print('get inventory items with the max field name...')46 inventory_url = BASE_URL + 'inventory_items?inventory_field_definition_id=%s' % max_field_definition_id47 inventory_request = requests.get(inventory_url, headers=headers)48 inventory_request.raise_for_status()49 inventory_items = inventory_request.json()50 req_id = None51 reorder_items = []52 # loop over each inventory item53 for val in inventory_items['data']:54 available = val['available']55 max_obj = [el for el in val['field_values'] if el['definition_id'] == max_field_definition_id]56 max_val = int(max_obj[0]['value']) # max value should always be present57 min_obj = [el for el in val['field_values'] if el['definition_id'] == min_field_definition_id]58 min_val = int(min_obj[0]['value']) if len(min_obj) > 0 else 0 # set min value to 0 if not set, but will be set to 0 if for some reason not present59 # Reorder items if available count drops below the minVal thresold or if the quantity available is 0)60 if min_val > available or available == 0:61 reorder_quantity = max_val - min_val62 item = val['name']63 print(f'reordering {item}: {reorder_quantity} units')64 reorder_items.append({65 'id': val['id'],66 'quantity_requested': max_val - min_val67 })68 if len(reorder_items) == 0:69 print('no items to reorder!')70 exit()71 print('submit items for reorder...')72 reorder_url = BASE_URL + 'inventory_items/reorder'73 reorder_request = requests.post(reorder_url, headers=headers, json={'items': reorder_items})74 reorder_request.raise_for_status()75 reorder_data = reorder_request.json()76 req_id = reorder_data['data'][0]['purchase_order']['requisition_id']77 print(f'requisition_id: {req_id}')78 print('get available groups...')79 groups_url = BASE_URL + 'groups/my'80 groups_request = requests.get(groups_url, headers=headers)81 groups_request.raise_for_status()82 groups = groups_request.json()83 if len(groups['data']) > 0:84 print('assign first group to requisition if user has groups...')85 assign_group_url = BASE_URL + 'requisitions/%s' % req_id86 assign_group_request = requests.patch(assign_group_url, headers=headers, json={87 "group_id": groups['data'][0]['id']88 })89 assign_group_request.raise_for_status()90 assign_group_response = assign_group_request.json()91 # print(assign_group_response)92 print('submit requisition...')93 submit_url = BASE_URL + 'requisitions/%s/submit' % req_id94 submit_request = requests.post(submit_url, headers=headers)95 submit_request.raise_for_status()96 submit_response = submit_request.json()97 # print(submit_response)98 print('done!')99except requests.exceptions.RequestException as e:100 print(e)...

Full Screen

Full Screen

ordered_table.py

Source:ordered_table.py Github

copy

Full Screen

...42 QtCore.Qt.GlobalColor.lightGray,43 )44 self.scene.addItem(f_item)45 self.item_list.append(f_item)46 def reorder_items(self, a_item_index, a_new_pos_y):47 f_list = self.item_list48 f_new_index = int(49 (a_new_pos_y / self.total_height) * len(self.item_list)50 )51 if f_new_index < 0:52 f_new_index = 053 elif f_new_index >= len(self.item_list):54 f_new_index = len(self.item_list) - 155 if a_item_index > f_new_index:56 f_list.insert(f_new_index, f_list.pop(a_item_index))57 elif a_item_index < f_new_index:58 f_list.insert(f_new_index + 1, f_list.pop(a_item_index))59 for f_i, f_item in zip(range(len(f_list)), f_list):60 f_item.setPos(0, f_i * self.item_height)61 f_item.index = f_i62class OrderedTableItem(QGraphicsRectItem):63 def __init__(64 self,65 a_text,66 a_height,67 a_width,68 a_y,69 a_index,70 a_parent,71 a_brush72 ):73 QGraphicsRectItem.__init__(self)74 self.text = str(a_text)75 self.text_item = QGraphicsTextItem(a_text, self)76 self.text_item.setDefaultTextColor(QtCore.Qt.GlobalColor.black)77 self.setRect(0., 0., float(a_width), float(a_height))78 self.setPos(0, a_y)79 self.default_brush = a_brush80 self.setBrush(a_brush)81 self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsMovable)82 self.index = self.orig_index = a_index83 self.parent = a_parent84 def mouseMoveEvent(self, a_event):85 QGraphicsRectItem.mouseMoveEvent(self, a_event)86 f_pos = a_event.scenePos()87 self.parent.reorder_items(self.index, f_pos.y())88def ordered_table_dialog(89 a_labels,90 a_list,91 a_item_height,92 a_item_width,93 a_parent=None,94):95 def ok_handler():96 f_dialog.retval = [97 a_list[x.orig_index]98 for x in f_table.item_list99 ]100 f_dialog.close()101 f_dialog = QDialog(a_parent)...

Full Screen

Full Screen

routes.py

Source:routes.py Github

copy

Full Screen

...59# takes one item which is the one the user repositioned, other item's position can be worked out from that60@bp.route('/reorder/', methods=['POST'])61@login_required62@cross_origin()63def reorder_items():64 data = request.get_json()65 item = data["item"]66 return shoppingItemDB.reorder_items(item["id"], item["position"])67 68# delete existing shopping item69@bp.route('/item/', methods=['DELETE'])70@login_required71@cross_origin()72def item_delete():73 data = request.get_json()74 item = data["item"]75 return shoppingItemDB.delete(item["id"])76@bp.route('/favicon.ico') 77def favicon(): ...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful