Best Python code snippet using Airtest
reports.py
Source:reports.py
...21 def __exit__(self, exc_type, exc_val, exc_tb):22 return type is None232425 def __convert_report_data(self, report_data, convert_to):26 if convert_to == "back":27 new_report_data = {28 "teacher_name" : report_data["nameTeacher"],29 "subject_name" : report_data["nameSubject"],30 "subject_duration" : report_data["durationSubject"],31 "subject_type" : report_data["typeSubject"],32 "group_name" : report_data["nameGroup"],33 "report_type" : report_data["typeReport"]34 }35 return new_report_data3637 elif convert_to == "front":38 new_report_data = {39 "nameTeacher" : report_data["teacher_name"],40 "nameSubject" : report_data["subject_name"],41 "durationSubject" : report_data["subject_duration"],42 "typeSubject" : report_data["subject_type"],43 "nameGroup" : report_data["group_name"],44 "typeReport" : report_data["report_type"]45 }46 return new_report_data4748 else:49 return None5051 #-------------/ READ AND WRITE /-------------------------------------------------------------5253 # def __write_book(self, report_id, book):54 # path = RP_BOOKS_FOLDER + str(report_id) + '.xlsx'55 # book.save(path)565758 # def __read_book(self, report_id):59 # path = RP_BOOKS_FOLDER + str(report_id) + '.xlsx'60 # if os.path.isfile(path):61 # book = openpyxl.load_workbook(path)62 # return book63 # else:64 # print("[INFO] Book {} not found in \"{}\"".format(report_id, path))65 # return None666768 def __write_report(self, report_id, report):69 path = RP_REPORTS_FOLDER + str(report_id) + '.json'7071 with open(path, 'w', encoding='utf-8') as f:72 json.dump(report, f, ensure_ascii=False, indent=4)737475 def __read_report(self, report_id):76 path = RP_REPORTS_FOLDER + str(report_id) + '.json'7778 if os.path.isfile(path):79 with open(path, 'r', encoding="utf-8") as f:80 report = json.load(f)81 return report82 else:83 print("[INFO] Report {} not found in \"{}\"".format(report_id, path))84 return None85868788 #-------------/ CREATE /-------------------------------------------------------------89 90 def __load_report(self, report_id):91 return self.__read_report(report_id)92 9394 def __save_report(self, report_id, report):95 self.__write_report(report_id, report)969798 def __get_dates_times(self, report_data, schedule):99 pattern = [[], [], [], [], [], [],100 [], [], [], [], [], []]101102 print(report_data)103 for day in schedule:104 for lesson in day:105 #[FEATURE] add type106 print(lesson)107 if (lesson["name"] == report_data["subject_name"]) and \108 (lesson["duration"] == report_data["subject_duration"]) and \109 (lesson["type"] == report_data["subject_type"]) and \110 (report_data["group_name"] in lesson["groups"]):111 112 time = dates.parse_time(lesson["time"])113 even = lesson["even"]114 wday = lesson["wday"]115116 if even == 0:117 pattern[wday].append(time)118 pattern[6 + wday].append(time)119 else:120 pattern[6*(even - 1) + wday].append(time)121122 for d in pattern:123 d.sort()124125 duration = dates.parse_duration(report_data["subject_duration"])126 dates_times = dates.get_dates_times(pattern, duration)127128 return dates_times129130131 def __get_thead(self, report_data):132 report_type = report_data["report_type"]133 template = RP_TEMPLATES[report_type]134135 cur_data = dates.get_cur_date()136 cur_col = -1;137138 thead = []139 for h in template:140 if h["name"] == "Dates":141 with DB() as db:142 teacher_id = db.get_teacher_id(report_data["teacher_name"])143 schedule = db.get_schedule(teacher_id)["data"]144 dt_list = self.__get_dates_times(report_data, schedule)145 146 for dt in dt_list:147 date_h = h.copy()148 date_h["name"] = dt149 thead.append(date_h)150 else:151 thead.append(h)152153 return thead154155156 def __get_meta(self, report_data, thead):157 report_type = report_data["report_type"]158 meta = RP_METAS[report_type]159 160161162163 if (report_type == "att") or (report_type == "score"):164 cur_data = dates.get_cur_date()165 cur_col = -1166 first_col = meta["firstCol"]167168 for th in thead[first_col:]:169 if (th["name"][:10] > cur_data[:10]):170 cur_col = thead.index(th) - 1171 break172 if cur_col == -1:173 cur_col = len(thead) - 1174 elif cur_col < first_col:175 cur_col = first_col176177 meta["curCol"] = cur_col178179 return meta180181182 def __get_xlsx(self, report_data, thead):183 with DB() as db:184 students = db.get_students(report_data["group_name"])["data"]185186 187 heads = [th["name"] for th in thead]188 rows = [ [ "" for j in range(0, len(heads))] for i in range(0, len(students))]189 for i in range(0, len(students)):190 rows[i][0] = students[i]["id"]191 rows[i][1] = students[i]["name"]192193 df = pd.DataFrame(rows, columns=heads)194 xlsx = json.loads(df.to_json(orient="split"))195196 return xlsx197198199 def __create_report(self, report_data):200 thead = self.__get_thead(report_data)201 meta = self.__get_meta(report_data, thead)202 xlsx = self.__get_xlsx(report_data, thead)203 204 report = {205 "report_data" : self.__convert_report_data(report_data, convert_to="front"),206 "thead": thead,207 "meta" : meta,208 "xlsx" : xlsx209 }210211 with DB() as db:212 report_id = db.get_report_id(report_data) # dont't use SCOPE_IDENTITY (synchronization)213 self.__save_report(report_id, report)214215 return report216217218 #----------------/ INTERFACE /----------------------------------------------------------------219220 def get(self, report_data):221 report_data = self.__convert_report_data(report_data, convert_to="back")222223 with DB() as db:224 report_id = db.get_report_id(report_data)225226 if report_id:227 report = self.__load_report(report_id)228 if not report:229 report = self.__create_report(report_data)230231 else:232 with DB() as db:233 db.insert_report(report_data)234 report = self.__create_report(report_data)235236237 # report["meta"].update(self.__get_meta(report_data, report["thead"]))238239 return report240241242243 def set(self, report):244 report_data = self.__convert_report_data(report["report_data"], convert_to="back")245246 with DB() as db:247 report_id = db.get_report_id(report_data)248249 if report_id:250 self.__save_report(report_id, report)251 return True252 else:253 return None254255#-------------------------------------------------------------------------------256#-------------------------------------------------------------------------------257#-------------------------------------------------------------------------------258#-------------------------------------------------------------------------------259#-------------------------------------------------------------------------------260261262# from server.config import *263# from .db import *264# from .modules import Dates as dates265# import os266# import json267268# # [FEATURE] check type of lesson too!!!269# class RM():270# def __init__(self):271# pass272273274# def __enter__(self):275# return self276277278# def __exit__(self, exc_type, exc_val, exc_tb):279# return type is None280281282# def __convert_report_data(self, report_data, convert_to):283# if convert_to == "back":284# new_report_data = {285# "teacher_name" : report_data["nameTeacher"],286# "subject_name" : report_data["nameSubject"],287# "subject_duration" : report_data["durationSubject"],288# "subject_type" : report_data["typeSubject"],289# "group_name" : report_data["nameGroup"],290# "report_type" : report_data["typeReport"]291# }292# return new_report_data293294# elif convert_to == "front":295# new_report_data = {296# "nameTeacher" : report_data["teacher_name"],297# "nameSubject" : report_data["subject_name"],298# "durationSubject" : report_data["subject_duration"],299# "typeSubject" : report_data["subject_type"],300# "nameGroup" : report_data["group_name"],301# "typeReport" : report_data["report_type"]302# }303# return new_report_data304305# else:306# return None307308# #-------------/ READ AND WRITE /-------------------------------------------------------------309310# def __write_report(self, report_id, report):311# # [FEATURE] write json as bytes, save space312# path = RP_FOLDER + str(report_id) + '.json'313314# with open(path, 'w', encoding='utf-8') as f:315# json.dump(report, f, ensure_ascii=False, indent=4)316317318# def __read_report(self, report_id):319# path = RP_FOLDER + str(report_id) + '.json'320321# if os.path.isfile(path):322# with open(path, 'r', encoding="utf-8") as f:323# report = json.load(f)324# return report325# else:326# print("[INFO] Report {} not found in \"{}\"".format(report_id, path))327# return None328329330# def __read_templates(self, report_type):331# path = RP_TEMPLATES_FOLDER + "templates" + ".json"332# if os.path.isfile(path):333# with open(path, 'r', encoding="utf-8") as f:334# templates = json.load(f)335# else:336# print("[INFO] Templates not found in \"{}\"".format(path))337338# return templates339340# #-------------/ CREATE /-------------------------------------------------------------341 342# def __get_dates_times(self, report_data, schedule):343# pattern = [[], [], [], [], [], [],344# [], [], [], [], [], []]345346# for day in schedule:347# for lesson in day:348# #[FEATURE] add type349# if (lesson["name"] == report_data["subject_name"]) and \350# (lesson["duration"] == report_data["subject_duration"]) and \351# (lesson["type"] == report_data["subject_type"]) and \352# (report_data["group_name"] in lesson["groups"]):353 354# time = dates.parse_time(lesson["time"])355# even = lesson["even"]356# wday = lesson["wday"]357358# if even == 0:359# pattern[wday].append(time)360# pattern[6 + wday].append(time)361# else:362# pattern[6*(even - 1) + wday].append(time)363364# for d in pattern:365# d.sort()366367# duration = dates.parse_duration(report_data["subject_duration"])368# dates_times = dates.get_dates_times(pattern, duration)369370# return dates_times371372373# def __get_thead(self, report_data):374# report_type = report_data["report_type"]375# templates = self.__read_templates(report_type)376# thead_scheme = templates[report_type]377378# thead = []379# for h in thead_scheme:380# if h == "dates":381# with DB() as db:382# teacher_id = db.get_teacher_id(report_data["teacher_name"])383# schedule = db.get_schedule(teacher_id)["data"]384# dates_times = self.__get_dates_times(report_data, schedule)385# thead.extend(dates_times)386# else:387# thead.append(h)388389# return thead390391392# def __get_rows(self, report_data, thead):393# with DB() as db:394# students = db.get_students(report_data["group_name"])["data"]395396# rows = []397# rows.extend([ [] for i in range(0, len(students))])398399# for h in thead:400# if h == "â":401# for i, s in enumerate(students):402# rows[i].append(s["id"])403# elif h == "ФÐÐ":404# for i, s in enumerate(students):405# rows[i].append(s["name"])406# else:407# for i, s in enumerate(students):408# rows[i].append("")409410# return rows411412413# def __create_report(self, report_data):414# thead = self.__get_thead(report_data)415# data = self.__get_rows(report_data, thead)416417# front_report_data = self.__convert_report_data(report_data, convert_to="front")418# report = {419# "thead" : thead,420# "data" : data421# }422# report.update(front_report_data)423424# print_json(report)425# return report426427428# #----------------/ INTERFACE /----------------------------------------------------------------429430# def get(self, report_data):431# report_data = self.__convert_report_data(report_data, convert_to="back")432433# with DB() as db:434# report_id = db.get_report_id(report_data)435436# if report_id:437# report = self.__read_report(report_id)438# if not report:439# report = self.__create_report(report_data)440# self.__write_report(report_id, report)441442# return report443# else:444# report = self.__create_report(report_data)445446# with DB() as db:447# db.insert_report(report_data)448# report_id = db.get_report_id(report_data) # dont't use SCOPE_IDENTITY (synchronization)449450# self.__write_report(report_id, report)451452# return report453454455456# def set(self, report):457# report_data = self.__convert_report_data(report, convert_to="back")458459# with DB() as db:460# report_id = db.get_report_id(report_data)461462# if report_id:463# self.__write_report(report_id, report)464# return True465# else:466# return None467468469
...
test_xblock_poll.py
Source:test_xblock_poll.py
...77 """78 Test generate_report_data iterator with no limit.79 """80 user_states = self.mock_user_states()81 report_data = self.poll_block.generate_report_data(user_states)82 report_data = list(report_data)83 self.assertEqual(len(report_data), 4)84 self.assertEqual(report_data[0],85 ('edx', {'Question': self.poll_block.question,86 'Answer': 'Red',87 'Submissions count': 1}))88 self.assertNotIn('audit', [username for username, _ in report_data])89 self.assertNotIn('student', [username for username, _ in report_data])90 def test_generate_report_data_limit_responses(self):91 """92 Test generate_report_data iterator with limit.93 """94 user_states = self.mock_user_states()95 report_data = self.poll_block.generate_report_data(user_states, limit_responses=2)96 report_data = list(report_data)97 self.assertEqual(len(report_data), 2)98 self.assertEqual(report_data[0],99 ('edx', {'Question': self.poll_block.question,100 'Answer': 'Red',101 'Submissions count': 1}))102 report_data = self.poll_block.generate_report_data(user_states, limit_responses=0)103 report_data = list(report_data)104 self.assertEqual(len(report_data), 0)105 def test_indexing(self):106 self.assertEqual(107 self.poll_block.index_dictionary(),108 {109 'content': {110 'display_name': 'My Poll',111 'question': 'What is your favorite color?',112 'option_0': 'Red',113 'option_1': 'Blue',114 'option_2': 'Green',115 'option_3': 'Other',116 },117 'content_type': 'Poll'118 }119 )120class TestSurveyBlock(unittest.TestCase):121 """122 Tests for XBlock Survey.123 """124 def setUp(self):125 """126 Test case setup127 """128 super(TestSurveyBlock, self).setUp()129 self.runtime = MockRuntime()130 self.survery_data = {131 'display_name': 'My Survey',132 'questions': [133 ['enjoy', {'label': 'Are you enjoying the course?'}],134 ['recommend', {'label': 'Would you recommend this course to your friends?'}],135 ['learn', {'label': 'Do you think you will learn a lot?'}]136 ],137 'answers': [138 ['Y', 'Yes'],139 ['N', 'No'],140 ['M', 'Maybe']141 ],142 'submissions_count': 5,143 'max_submissions': 1,144 'private_results': False,145 'feedback': 'My Feedback',146 'block_name': 'My Block Name',147 }148 self.survey_block = SurveyBlock(149 self.runtime,150 DictFieldData(self.survery_data),151 None152 )153 def test_student_view_data(self):154 """155 Test the student_view_data results.156 """157 expected_survery_data = {158 'questions': self.survery_data['questions'],159 'answers': self.survery_data['answers'],160 'max_submissions': self.survery_data['max_submissions'],161 'private_results': self.survery_data['private_results'],162 'feedback': self.survery_data['feedback'],163 'block_name': self.survery_data['block_name'],164 }165 student_view_data = self.survey_block.student_view_data()166 self.assertEqual(student_view_data, expected_survery_data)167 def test_student_view_user_state_handler(self):168 """169 Test the student_view_user_state handler results.170 """171 response = json.loads(172 self.survey_block.handle(173 'student_view_user_state',174 make_request('', method='GET')175 ).body.decode('utf-8')176 )177 expected_response = {178 u'choices': None,179 u'submissions_count': 5,180 u'tally': {181 u'enjoy': {u'M': 0, u'N': 0, u'Y': 0},182 u'learn': {u'M': 0, u'N': 0, u'Y': 0},183 u'recommend': {u'M': 0, u'N': 0, u'Y': 0},184 },185 }186 self.assertEqual(response, expected_response)187 @classmethod188 def mock_user_states(cls):189 return (190 Mock(191 username='edx',192 state={193 'submissions_count': 1,194 'choices': {'enjoy': 'Y', 'recommend': 'N', 'learn': 'M'}195 }196 ),197 Mock(198 username='verified',199 state={200 'submissions_count': 1,201 'choices': {'enjoy': 'M', 'recommend': 'N', 'learn': 'Y'}202 }203 ),204 Mock(205 username='staff',206 state={207 'submissions_count': 1,208 'choices': {'enjoy': 'N', 'recommend': 'N', 'learn': 'N'}209 }210 ),211 Mock(212 username='honor',213 state={214 'submissions_count': 1,215 'choices': {'enjoy': 'Y', 'recommend': 'N', 'learn': 'M'}216 }217 ),218 Mock(219 username='audit',220 state={221 'submissions_count': 1,222 }223 ),224 Mock(225 username='student',226 state={227 'submissions_count': 1,228 'choices': None,229 }230 ),231 )232 def test_generate_report_data_dont_limit_responses(self):233 """234 Test generate_report_data iterator with no limit.235 """236 user_states = self.mock_user_states()237 report_data = self.survey_block.generate_report_data(user_states)238 report_data = list(report_data)239 self.assertEqual(len(report_data), 12)240 # each choice of a user gets its own row241 # so the first three rows should be edx's choices242 self.assertEqual(['edx', 'edx', 'edx', 'verified'],243 [username for username, _ in report_data[:4]])244 self.assertEqual(245 set(['Yes', 'No', 'Maybe']),246 set([data['Answer'] for _, data in report_data[:4]])247 )248 self.assertNotIn('audit', [username for username, _ in report_data])249 self.assertNotIn('student', [username for username, _ in report_data])250 def test_generate_report_data_limit_responses(self):251 """252 Test generate_report_data iterator with limit.253 """254 user_states = self.mock_user_states()255 report_data = self.survey_block.generate_report_data(user_states, limit_responses=2)256 report_data = list(report_data)257 self.assertEqual(len(report_data), 2)258 # each choice of a user gets its own row259 # so the first two rows should be edx's choices260 self.assertEqual(['edx', 'edx'],261 [username for username, _ in report_data])262 self.assertTrue(263 set([data['Answer'] for _, data in report_data[:3]]) <= set(['Yes', 'No', 'Maybe'])264 )265 report_data = self.survey_block.generate_report_data(user_states, limit_responses=0)266 report_data = list(report_data)267 self.assertEqual(len(report_data), 0)268 def test_indexing(self):269 self.assertEqual(270 self.survey_block.index_dictionary(),271 {272 'content': {273 'display_name': 'My Survey',274 'question_0': 'Are you enjoying the course?',275 'question_1': 'Would you recommend this course to your friends?',276 'question_2': 'Do you think you will learn a lot?',277 'option_0': 'Yes',278 'option_1': 'No',279 'option_2': 'Maybe',...
get_iperf_tcp_statistics.py
Source:get_iperf_tcp_statistics.py
1import json2import os3import re4import sys5src_grp = sys.argv[1]6dest_grp = sys.argv[2]7fileid = sys.argv[3]8filedir = os.getcwd()9def get_list_of_filenames():10 file_list = []11 p = re.compile(ur'tcptesttrafficclient*%s.*%s.*%s' %(src_grp, dest_grp, fileid))12 for file in os.listdir(filedir):13 if re.search(p, file):14 file_list.append(file)15 return file_list16def process_files(file_list):17 out = {}18 for file in file_list:19 out[file] = get_test_results(file)20 return out21def get_test_results(file):22 """23 For a given test output file, return a tuple of the following format24 (bandwidth_loss dict wth keys interval_time, transferred, bandwidth, 25 jitter, loss_datagram, total_datagram, loss_percent)26 """27 28 bandwidth_stats = \29 {'interval_time': '', # NOQA30 'transferred': '', # NOQA31 'bandwidth': ''} # NOQA32 #'retr': ''} # NOQA33 reportflag = False34 f = open(file, 'r')35 for line in f:36 #if "--" in line:37 # reportflag = True38 if "[ ID]" in line:39 #print "inside for loop", reportflag40 report = f.next()41 report_data = report.split(']')[1].split(' ')42 # also want packets transmitted, packets received, % packet loss43 #if str(report_data[2]) == 'sec':44 #interval_time = str(report_data[1]) + " " + str(report_data[2])45 interval_time = str(report_data[1])46 transferred = str(report_data[2])47 bandwidth = str(report_data[3]).split('\n')[0]48 #if report_data[5] == '':49 # retr = str(report_data[5]) + str(report_data[6]) # NOQA50 #else:51 # retr = str(report_data[5])52 #else:53 # interval_time = str(report_data[1])54 # transferred = str(report_data[2])55 # bandwidth = str(report_data[3])56 # if report_data[4] == '':57 # retr = str(report_data[4]) + str(report_data[5]) # NOQA58 # else:59 # retr = str(report_data[4])60 61 bandwidth_stats = \62 {'interval_time': interval_time, # NOQA63 'transferred': transferred, # NOQA64 'bandwidth': bandwidth} # NOQA65 # 'retr': retr} # NOQA66 67 test_results = {'bandwidth_stats': bandwidth_stats}68 #print "test_results.....", test_results69 return test_results70def main():71 file_list = get_list_of_filenames()72 script_output = process_files(file_list)73 json_output = json.JSONEncoder().encode(script_output)74 # sample output75 # {'test.txt': ({'packet_loss': '0%'},76 # {'rtt_min': '4.3', 'rtt_avg': '5.5', 'rtt_max': '6.3'})}77 print json_output78 #return script_ouput79if __name__ == '__main__':...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!