Best Python code snippet using pytest
structures.py
Source:structures.py
...159 func = args[0]160 is_class = inspect.isclass(func)161 if len(args) == 1 and (istestfunc(func) or is_class):162 if is_class:163 store_mark(func, self.mark)164 else:165 store_legacy_markinfo(func, self.mark)166 store_mark(func, self.mark)167 return func168 return self.with_args(*args, **kwargs)169def get_unpacked_marks(obj):170 """171 obtain the unpacked marks that are stored on an object172 """173 mark_list = getattr(obj, "pytestmark", [])174 if not isinstance(mark_list, list):175 mark_list = [mark_list]176 return [getattr(mark, "mark", mark) for mark in mark_list] # unpack MarkDecorator177def store_mark(obj, mark):178 """store a Mark on an object179 this is used to implement the Mark declarations/decorators correctly180 """181 assert isinstance(mark, Mark), mark182 # always reassign name to avoid updating pytestmark183 # in a reference that was only borrowed184 obj.pytestmark = get_unpacked_marks(obj) + [mark]185def store_legacy_markinfo(func, mark):186 """create the legacy MarkInfo objects and put them onto the function187 """188 if not isinstance(mark, Mark):189 raise TypeError("got {mark!r} instead of a Mark".format(mark=mark))190 holder = getattr(func, mark.name, None)191 if holder is None:...
views.py
Source:views.py
1# from . import forms2import random3import string4from django.http import JsonResponse5from django.contrib.auth.hashers import make_password, check_password6from django.shortcuts import redirect7from django.shortcuts import render8from django.views import View9from administrator.models import TableTimeliner, TableQuestionContent10from login import models11from login.forms import ForgetForm, ResetForm12from login.models import TableUser13from login.utils.email_send import send_register_email14from supervisor.models import TableEvaluation15from supervisor.models import TableOrganization16from administrator.models import TableTimeliner,TableQuestionResult17from login import models18import datetime19from django.db.models import Q20from django.http import JsonResponse21from django.shortcuts import render, HttpResponse, redirect22import xlwt23from io import BytesIO24from xlwt import Workbook25from django.utils.encoding import escape_uri_path26def user(request):27 user_name = request.session['user_name']28 current_eval = request.GET.get('evalname')29 print(user_name)30 orgid = \31 models.TableUser.objects.filter(table_user_col_name=user_name).values_list('table_user_col_organization')[0][0]32 orgname = \33 TableOrganization.objects.filter(table_organization_col_id=orgid).values_list('table_organization_col_name')[0][34 0]35 eval = TableEvaluation.objects.filter(table_evaluation_col_name=current_eval)36 if len(eval) != 0:37 questionaire_answer = set(38 TableQuestionContent.objects.filter(39 table_question_content_col_evalname=eval[0].table_evaluation_col_id).values_list(40 'table_question_content_col_indicator_id'))41 group = []42 for eachquestion in questionaire_answer:43 group.append(eachquestion)44 list = []45 for i in range(0, len(questionaire_answer)):46 list.append(TableQuestionContent.objects.filter(table_question_content_col_indicator_id=group[i][0]))47 user_id = TableUser.objects.get(table_user_col_name=user_name)48 if len(list) != 0:49 page = request.GET.get('page')50 question = []51 if page == None:52 for x in list[0]:53 question_id = x.table_question_content_col_question_id54 if TableQuestionResult.objects.filter(Q(table_question_result_col_user_id=user_id) & Q(55 table_question_result_col_question_id=question_id)).exists():56 question_answer = TableQuestionResult.objects.get(Q(table_question_result_col_user_id=user_id) & Q(table_question_result_col_question_id=question_id)).table_question_result_col_answer57 print(questionaire_answer)58 else:59 question_answer = "NOANSWER404"60 question.append({61 'question_id': x.table_question_content_col_question_id,62 'question_type': x.table_question_content_col_question_type,63 'content': x.table_question_content_col_content,64 'indicator_id': x.table_question_content_col_indicator_id,65 'question_class': x.table_question_content_col_question_class,66 'question_answer': question_answer,67 })68 page_num = 069 else:70 num = int(page)71 for x in list[num]:72 question_id = x.table_question_content_col_question_id73 if TableQuestionResult.objects.filter(Q(table_question_result_col_user_id=user_id) & Q(74 table_question_result_col_question_id=question_id)).exists():75 question_answer = TableQuestionResult.objects.get(Q(table_question_result_col_user_id=user_id) & Q(table_question_result_col_question_id=question_id)).table_question_result_col_answer76 print(question_answer)77 else:78 question_answer = "NOANSWER404"79 question.append({80 'question_id': x.table_question_content_col_question_id,81 'question_type': x.table_question_content_col_question_type,82 'content': x.table_question_content_col_content,83 'indicator_id': x.table_question_content_col_indicator_id,84 'question_class': x.table_question_content_col_question_class,85 'question_answer': question_answer,86 })87 page_num = num88 print(question)89 return render(request, 'user/user.html',90 { 'current_eval':current_eval,'question': question,91 'preview_length': len(list),92 'user': user_name, 'orgname': orgname, 'page_num': page_num})93 else:94 return render(request, 'user/user.html', {'current_eval':current_eval,'user': user_name, 'orgname': orgname})95 else:96 return render(request, 'user/user.html', {'current_eval':current_eval,'user': user_name, 'orgname': orgname})97def questionaire_submit(request):98 print(request.POST)99 return JsonResponse({'msg': 'success'})100def answer_save(request):101 user_name = request.session['user_name']102 print(user_name)103 if request.method == 'POST':104 question_class = request.POST['questionclass']105 question_type = request.POST['questiontype']106 print(question_type)107 if question_type == "填空é¢":108 store_answer = request.POST['send_info']109 store_answer = store_answer.replace('[', '')110 store_answer = store_answer.replace(']', '')111 store_answer = store_answer.replace('\"', '')112 store_answer = store_answer.split(",")113 for i in range(0, len(store_answer)):114 if len(store_answer[i]) == 0:115 return JsonResponse({'message': 'Done'})116 elif question_type == "éæ©é¢" or "ç®çé¢" or "ç©éµé¢":117 if question_class == "åé":118 store_answer = request.POST['send_info']119 else:120 store_answer = request.POST['send_info']121 store_answer = store_answer.replace('[', '')122 store_answer = store_answer.replace(']', '')123 store_answer = store_answer.replace('\"', '')124 store_answer = store_answer.split(",")125 print(store_answer)126 store_question_id = request.POST['questionid']127 store_mark = 0128 tmp = TableQuestionContent.objects.get(table_question_content_col_question_id=store_question_id).table_question_content_col_marks129 if len(tmp) != 0:130 store_mark = tmp131 store_user_id = models.TableUser.objects.get(table_user_col_name=user_name).table_user_col_id132 store_questionaire_id = TableQuestionContent.objects.get(table_question_content_col_question_id=store_question_id).table_question_content_col_indicator_id133 if TableQuestionResult.objects.filter(Q(table_question_result_col_user_id=store_user_id) & Q(table_question_result_col_question_id=store_question_id)).exists():134 TableQuestionResult.objects.filter(Q(table_question_result_col_user_id=store_user_id) & Q(table_question_result_col_question_id=store_question_id)).update(135 table_question_result_col_answer=store_answer,136 table_question_result_col_marks=store_mark,137 table_question_result_col_questionaire_id=store_questionaire_id138 )139 else:140 store_blank = ''.join(random.sample(string.ascii_letters + string.digits, 20)) # å建blankéæºå141 new_record = {142 "table_question_result_col_answer": store_answer,143 "table_question_result_col_marks": store_mark,144 "table_question_result_col_blank": store_blank,145 "table_question_result_col_user_id": store_user_id,146 "table_question_result_col_questionaire_id": store_questionaire_id,147 "table_question_result_col_question_id": store_question_id,148 }149 print(new_record)150 TableQuestionResult.objects.create(**new_record)151 return JsonResponse({'message': 'Done'})152# def visualization(request):153# check_app = request.GET.get('app')...
utils.py
Source:utils.py
1# coding=UTF-82import datetime3from apilib import get_tapi, TopError4from apps.common.utils.utils_log import log5from apps.subway.models_adgroup import adg_coll6from apps.subway.models_account import account_coll7from apps.subway.models_campaign import camp_coll8# from apps.ncrm.models import Customer9def batch_refresh_shopcatid(shop_id_list, is_force = False):10 # æ¹éå·æ°åºéºçç±»ç®ID11 def get_shop_cat(category_ids_list):12 cat_id = 013 if category_ids_list:14 tmp_dict = {}15 for category_ids in category_ids_list:16 tmp_cat_list = category_ids.split()[:1]17 for tmp_cat in tmp_cat_list:18 if not tmp_dict.has_key(tmp_cat):19 tmp_dict[tmp_cat] = 120 else:21 tmp_dict[tmp_cat] += 122 # å°åå
¸æåºææåºç°æ¬¡æ°æå¤çå
ç»æåº23 sorted_list = sorted(tmp_dict.iteritems(), key = lambda x:x[1], reverse = True)24 cat_id = sorted_list[0][0] # åªå第ä¸ä¸ª25 return cat_id26 temp_shop_dict = {}27 temp_cat_dict = {}28 if not is_force:29 shop_id_list = [ int(acc['_id']) for acc in account_coll.find({'_id':{'$in':shop_id_list}, '$or':[{'cat_id':None}, {'cat_id':0}, {'cat_id':''}]}, {'_id':1}) ]30 if not shop_id_list:31 return {}, 032 adg_cursor = adg_coll.find({'shop_id':{'$in':shop_id_list}}, {'category_ids':1, 'shop_id':1})33 for adg in adg_cursor:34 if adg:35 key = str(adg['shop_id'])36 if temp_shop_dict.has_key(key):37 temp_shop_dict[key].append(adg['category_ids'])38 else:39 temp_shop_dict[key] = [adg['category_ids']]40 for shop_id, category_ids_list in temp_shop_dict.items():41 cat_id = get_shop_cat(category_ids_list)42 key = str(cat_id)43 if temp_cat_dict.has_key(key):44 temp_cat_dict[key].append(int(shop_id))45 else:46 temp_cat_dict[key] = [int(shop_id)]47 count = 048 result = {}49 for cat_id, shop_id_list in temp_cat_dict.items():50 result_dict = account_coll.update({'_id':{'$in':shop_id_list}}, {'$set':{'cat_id':int(cat_id)}}, upsert = False, multi = True)51 # Customer.objects.filter(shop_id__in = shop_id_list).update(cat_id = int(cat_id))52# log.info('have already refreshed, cat_id = %s , shop_id_list = %s, result_dict=%s' % (cat_id, shop_id_list, json.dumps(result_dict)))53 if result_dict and result_dict.has_key('n'):54 count += result_dict['n']55 result_dict['cat_id'] = cat_id56 result = result_dict57 return result, count58# è·å¾shopæå¨çç±»ç®ï¼ç²ç¥å®ç°ä¸ºç¹å»æå¤çæ¨å¹¿ç»æå¨ç±»ç®59# ä¿®æ¹äºè¿éäºå®ç°ï¼éè¿æ¨å¹¿çææå®è´æ¥è·åå°ä¸»æ¨çç±»ç®60def refresh_shop_cat(shop_id, is_force = False):61 result, count = batch_refresh_shopcatid([shop_id], is_force = is_force)62 if count and result.has_key('cat_id'):63 return result['cat_id']64 return 065def batch_refresh_budgetStatus(shop_id_list):66 """éè¿åºéºæ¥å·æ°æ¥éé¢æ¯å¦è¶
åºç¶æ"""67 yestoday_time = datetime.datetime.now() - datetime.timedelta(days = 1)68 yestoday = datetime.datetime(yestoday_time.year, yestoday_time.month, yestoday_time.day)69 camp_cursor = camp_coll.find({ 'shop_id' : {'$in':shop_id_list} , 'rpt_list.date' : yestoday }, { '_id' : 1 , 'rpt_list.$' : 1 , 'budget' : 1 , 'budget_status' : 1 })70 # åå§å71 update_dict = { '0' : [] , '1' : [] }72 refresh_count = 073 for camp in camp_cursor:74 if camp and camp.has_key('rpt_list') and camp[ 'rpt_list' ] and camp[ 'budget' ]:75 camp_id = int(camp[ '_id' ])76 rpt = camp[ 'rpt_list' ][ -1 ]77 budget = camp[ 'budget' ]78 budget_statuts = camp.get('budget_status', None)79 store_mark = '0'80 if rpt['cost'] >= budget :81 store_mark = '1'82 if budget_statuts != store_mark:83 update_dict[ store_mark ].append(camp_id)84 refresh_count += 185 # æ´æ°æ°æ®86 for budget_status , camp_id_list in update_dict.items():87 if camp_id_list and budget_status:88 camp_coll.update({'_id' : { '$in' : camp_id_list } } , { '$set' : { 'budget_status' : budget_status } } , multi = True)89 if refresh_count:90 log.info('Updated budget_status of campaign completed. ')91 return True92 else:93 log.info('Campaign reports is no download or no data. ')94 return False95def reflash_budget_status(shop_id):96 """å·æ°åºéºçæ¥éé¢æ¯å¦è¶
åºç¶æ"""97 return batch_refresh_budgetStatus(shop_id_list = [shop_id])98def reset_crm_opareter_status(shop_id):99 """éç½®CRMæä½ç¶æ"""100 try:101 account_coll.update({'_id':shop_id, 'opar_status':{'$ne':0}}, {'$set':{'opar_status':0}}, multi = True)102 camp_coll.update({'shop_id':shop_id, 'opar_status':{'$ne':0}}, {'$set':{'opar_status':0}}, multi = True)103 adg_coll.update({'shop_id':shop_id, 'opar_status':{'$ne':0}}, {'$set':{'opar_status':0}}, multi = True)104 except Exception, e:105 log.error('reset crm opareter status error, error=%s' % e)106 return False107 return True108# å½åå
³é®è¯çæå109class KeywordCurrentPos():110 # æ¥è¯¢Itemå
³é®è¯æå¨çæåä½ç½®ãæ¾ä¸å°èªå·±ï¼è¿å0ï¼åºç°apiå¼å¸¸ï¼è¿å0111 @staticmethod112 def get_item_kw_current_order(user, item_id, word, ip):113 result_order = (word, 0, '', 0, 0, '')114 tapi = get_tapi(user)115 try:116 tobj = tapi.simba_tools_items_top_get(nick = user.nick, keyword = word, ip = ip) # åå¾ä¸ä¸ªå
³é®è¯çæ¨å¹¿ç»æåå表117 except TopError, e:118 log.error("tapi.simba_tools_items_top_get TopError, item_id=%s, word=%s, e=%s" % (item_id, word, e))119 return (word, 0, '', 0, 0, '') # å¨binder.pyä¸ï¼å·²éè¯å¤æ¬¡ï¼å¦æåºæ¥è¿å¤±è´¥ï¼åç´æ¥è¿åé误120 # å¹é
å®è´æå121 if tobj.rankeditems:122 item_list_top = tobj.rankeditems.ranked_item123 for item in item_list_top:124 if str(item_id) in item.link_url:125 result_order = (word, item.order, item.link_url, item.title)126 break127 # è¿åç»æ128 return result_order129 # æ¹éæ¥è¯¢å个å®è´å
³é®è¯çå½åæå,ç»æç¼åå¨å
³é®è¯çcurrent_orderå±æ§ä¸ï¼å¹¶æªæä¹
å130 @staticmethod131 def get_item_kws_current_order_list(user, item_id, kw_list, ip):132 for kw in kw_list:133 current_order = KeywordCurrentPos.get_item_kw_current_order(user, item_id, kw.word, ip)...
mark_service_test.py
Source:mark_service_test.py
...8student_service = StudentService()9course_service = CourseService()10class TestMarkService(unittest.TestCase):11 def test_store_student_mark_student_invalid(self):12 mark, errors = mark_service.store_mark(1, 1, 101)13 self.assertIsNotNone(errors)14 self.assertEqual(len(errors), 1)15 self.assertEqual(errors[0], 'student mark should be between 0 and 100')16 def test_student_not_exist(self):17 course_service.store_course(1, 'css', 100)18 mark, functional_error = mark_service.store_mark(1, 1, 50)19 self.assertEqual(functional_error[0], 'Student is not exist')20 def test_student_search(self):21 student_service.store_student(3, 'mike', 'MALE', 'ubaeida@gmail.com')22 student_service.store_student(4, 'moh', 'MALE', 'ubaeida@gmail.com')23 course_service.store_course(2, 'css', 100)24 mark, functional_error = mark_service.store_mark(5, 2, 50)25 self.assertIsNotNone(functional_error)26 self.assertEqual(len(functional_error), 1)27 self.assertEqual(functional_error[0], 'Student is not exist')28 def test_course_not_exist(self):29 student_service.store_student(6, 'mike', 'MALE', 'ubaeida@gmail.com')30 mark, functional_error = mark_service.store_mark(6, 1, 50)31 self.assertIsNotNone(functional_error)32 self.assertEqual(len(functional_error), 1)33 self.assertEqual(functional_error[0], 'Course is not exist')34 def test_course_search(self):35 student_service.store_student(7, 'mike', 'MALE', 'ubaeida@gmail.com')36 course_service.store_course(4, 'css', 100)37 course_service.store_course(5, 'html', 100)38 mark, functional_error = mark_service.store_mark(7, 3, 50)39 self.assertIsNotNone(functional_error)40 self.assertEqual(len(functional_error), 1)41 self.assertEqual(functional_error[0], 'Course is not exist')42 def test_mark_search(self):43 student_service.store_student(8, 'mike', 'MALE', 'ubaeida@gmail.com')44 course_service.store_course(6, 'css', 100)45 mark_service.store_mark(8, 6, 50)46 mark, functional_error = mark_service.store_mark(8, 6, 50)47 self.assertIsNotNone(functional_error)48 self.assertEqual(len(functional_error), 1)49 self.assertEqual(functional_error[0], 'These mark and student already exist')50 def test_marks_calculation(self):51 student_service.store_student(20, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')52 student_service.store_student(21, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')53 course_service.store_course(7, 'html', 100)54 course_service.store_course(8, 'css', 100)55 course_service.store_course(9, 'php', 100)56 course_service.store_course(10, 'java', 100)57 course_service.store_course(11, 'python', 100)58 course_service.store_course(12, 'c++', 100)59 course_service.store_course(13, 'delphi', 100)60 mark_service.store_mark(20, 7, 60)61 mark_service.store_mark(20, 8, 60)62 mark_service.store_mark(21, 10, 77)63 mark_service.store_mark(21, 11, 54)64 mark_service.store_mark(21, 12, 24)65 mark_service.store_mark(21, 13, 91)66 results = mark_service.student_GPA(21)67 print(results)68 # self.assertIsNotNone(results)69 # self.assertEqual(len(results), 1)70 def test_marks_calculation_withnostudnet(self):71 results = mark_service.student_GPA(22)72 self.assertIsNotNone(results)73 self.assertEqual(len(results), 1)74 self.assertEqual(results[0], 'Student not exist or has no marks')75 def test_course_average(self):76 student_service.store_student(24, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')77 student_service.store_student(25, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')78 student_service.store_student(26, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')79 student_service.store_student(27, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')80 student_service.store_student(28, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')81 student_service.store_student(29, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')82 course_service.store_course(7, 'html', 100)83 mark_service.store_mark(24, 7, 60)84 mark_service.store_mark(25, 7, 60)85 mark_service.store_mark(26, 7, 77)86 mark_service.store_mark(27, 7, 54)87 mark_service.store_mark(28, 7, 24)88 mark_service.store_mark(29, 7, 91)89 results = mark_service.get_course_avg(7)90 print(results)91 def test_mark_page(self):92 for idx in range(1, 10):93 student_service.store_student(idx, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')94 for idx in range(30, 40):95 course_service.store_course(idx, 'Course', 100)96 rand = random.Random()97 for i in range(1, 10):98 for j in range(30, 40):99 mark_service.store_mark(i, j, rand.randint(50, 99))100 mark_service.get_marks()101 for mark in mark_service.get_marks():102 print(mark)103 page1 = mark_service.get_marks_page(2, 5)104 print('------------------------------')105 m: Mark = page1[0]106 self.assertEqual(m.sid, 1)107 self.assertEqual(m.cid, 35)108 page1 = mark_service.get_marks_page(3, 17)109 print('------------------------------')110 m: Mark = page1[0]111 self.assertEqual(m.sid, 4)112 self.assertEqual(m.cid, 34)113 def test_lists(self):114 def page(page: int, limt: int, items):115 start_index = (page - 1) * limt116 end_index = start_index + limt117 print(start_index)118 print(end_index)119 print(items[start_index: end_index])120 l = [i for i in range(1, 16)]121 print(l)122 page(10, 5, l)123 def test_mark_custom_filter(self):124 for idx in range(1, 10):125 student_service.store_student(idx, 'mike', 'MALE', 'ubaeida.alkayal@gmail.com')126 for idx in range(30, 40):127 course_service.store_course(idx, 'Course', 100)128 rand = random.Random()129 for i in range(1, 10):130 for j in range(30, 40):131 mark_service.store_mark(i, j, rand.randint(50, 99))132 for mark in mark_service.custom_filter(35, '=', 50):133 print(mark)...
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.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!