Best Python code snippet using playwright-python
migrate_to_xml.py
Source:migrate_to_xml.py  
1#	Script written on Python 3.62# 	Author : Parag Fulzele3#	Description : Main script to convert shelter old database data into XML files4#5import os6import sys7from common import *8from ra_survey import *9from rhs_survey import *10from ff_survey import *11from kobotoolbox_upload import *12city_option = {13	'1': 'Pune',14	'2': 'PCMC',15	'3': 'Kolhapur',16	'4' : 'NMMC'17}18survey_type_option = {19	'1': 'Rapid Infrastructure Mapping(RIM)',20	'2': 'Rapid Household Survey(RHS)',21	'3': 'Family Factsheet',22}23select_option = {24	'city': None,25	'survey_type': None,26	'action': None,27}28#Project id as per old DB29city_mapping = {30	'1' : 4, # Pune31	'2' : 5, # PCMC32	'3' : 7, # Kolhapur33	'4' : 8, #NMMC34}35#Survey id as per old DB36city_survey_mapping = {37	# Pune38	'1': {39		'1': 13, # RA40		'2': [46, 17], # RHS41		'3': 18, # FF42	},43	# PCMC44	'2': { 45		'1': 16, # RA46		'2': [36], # RHS47		'3': 35, # FF48	},49	#Kolhapur50	'3' : {51		'1':41,52		'2' : ['40'],53		'3' : 42,54	},55	#NMMC56	'4' : {57		'1' : 47, #RA    - invalid58		'2' : [47], #RHS - invalid59		'3' : 47, #FF    - valid60	},61}62#Folders where excel sheet mappings are kept63mapped_excel_path_mapping = {64	# Pune65	'1': {66		'1': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_Pune', 'RA_Old_New_QuestionMapping_Parag.xlsx'), # RA67		'2': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_Pune', 'RHS_Old_New_QuestionMapping_Parag.xlsx'), # RHS68		'3': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_Pune', 'FF_Old_New_QuestionMapping_Parag.xlsx'), # FF69	},70	# PCMC71	'2': { 72		'1': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_PCMC', 'RA_Old_New_QuestionMapping_Parag.xlsx'), # RA73		'2': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_PCMC', 'RHS_Old_New_QuestionMapping_Parag.xlsx'), # RHS74		'3': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_PCMC', 'FF_Old_New_QuestionMapping_Parag.xlsx'), # FF75	},76	#Kolhapur77	'3': {78		'1': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_KMC', 'RA_Old_New_QuestionMapping_Parag.xlsx'), # RA79		'2': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_KMC', 'RHS_Old_New_QuestionMapping.xlsx'), # RHS80		'3': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_KMC', 'FF_Old_New_QuestionMapping_Parag.xlsx'), # FF81	},82	#NMMC83	'4': {84		'1': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_NMMC', 'RA_Old_New_QuestionMapping.xlsx'), # RA85		'2': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_NMMC', 'RHS_Old_New_QuestionMapping.xlsx'), # RHS86		'3': os.path.join(root_folder_path, 'FilesToRead', 'MappedExcel_NMMC', 'FF_Old_New_QuestionMapping.xlsx'), # FF87	},88}89survey_xml_value_mapping = {90	# RA/RIM91	'1': {92		'xml_root': 'aQPuZBqwRijfvAwaStCxaB',93		'xml_root_attr_id': 'aQPuZBqwRijfvAwaStCxaB',94		'xml_root_attr_version': 'vFj7RvJEym3fLv6SXxRpob',95		'formhub_uuid': 'ea15aac487e7498e883a0447e0bce41c',96	},97	# RHS98	'2': { 99		'xml_root': 'aJWGCEUXe4DcsJzETwMptL',100		'xml_root_attr_id': 'aJWGCEUXe4DcsJzETwMptL',101		'xml_root_attr_version': 'vcsF9qpeD5gsrFXsRVkbws',102		'formhub_uuid': 'b12051466e154c5396876c33b634bd0b',103	},104	# FF105	'3': {106		'xml_root': 'abfdvNf9EaZBJgzehbUMdt',107		'xml_root_attr_id': 'abfdvNf9EaZBJgzehbUMdt',108		'xml_root_attr_version': 'vbAo9r8ss5FfYK6odv74ZL',109		'formhub_uuid': 'e6b36c0f8955436c8c7310e8c6639fe9',110		# 'xml_root': 'agwoHCvSkxLrR3MnMsdpzJ',111		# 'xml_root_attr_id': 'agwoHCvSkxLrR3MnMsdpzJ',112		# 'xml_root_attr_version': 'vvpjs6JozyurWDtjR3EePL',113		# 'formhub_uuid': '74fb7be83af348c7b870920829b13dc1',114	},115}116survey_photo_mapping = {117	# List of key/xml element which has photo name118	'1': None, 	# RA119	'2': None, 	# RHS120	'3': ['Family_Photo', 'Toilet_Photo'],  # FF121}122root_output_folder = os.path.join(root_folder_path, 'xml_output')123def back_menu():124	choice = ''125	126	print('\n')127	print('b \t Back to survey type selection')128	print('n \t New migration')129	print('q \t Quit migration')130	print('\n')131	132	while choice != 'q':133		choice = input('Select option: ')134		if choice == 'b':135			select_option['survey_type'] = None136			choice = '2'137			break;138		elif choice == 'n':139			select_option['city'] = None140			select_option['survey_type'] = None141			choice = '1'142			break;143		elif choice == 'q':144			break;145		else:146			print('Invalid option.')147			148	return choice;149def display_menu(choice):150	if choice:151		if sys.platform == 'win32':152			os.system('cls')153		elif sys.platform == 'linux':154			os.system('clear')155	156	print('\n')157	print('Shelter Database migration to XML')158	print('\n')159	160	city = select_option['city']161	survey_type = select_option['survey_type']162	action = select_option['action']163	164	if action:165		if action == '1': # create xml166			print('selected action: Generate XML files')167		elif action == '2': # upload xml to kobo tool box168			print('selected action: Upload XML files to KoboToolBox')169		elif action == '3': # delete previously created xml 170			print('selected action: Delete existing XML files')171		172	if city:173		print('selected city: ', city_option[city])174	175	if survey_type:176		print('selected survey for : ', survey_type_option[survey_type])177	178	return choice;179def select_city(bmenu = True):180	print("\n")181	182	for opt, city in city_option.items():183		print('%s \t %s' % (opt, city))184	185	if bmenu:186		print('b \t Back to action selection')187		print('q \t Quit Program')188		189	print("\n")190	191	return_choice = ''192	choice = ''193	while choice != 'q':194		choice = input('Select city for migration: ')195		196		if choice in city_option.keys():197			select_option['city'] = choice198			return_choice = '2' # select survey type199			break;200		elif bmenu and choice == 'q':201			return_choice = 'q' # exit program 202			break;203		elif bmenu and choice == 'b':204			select_option['action'] = None205			return_choice = '3' # select action 206			break;207		else:208			print('Invalid city option.')209			choice = ''210	211	return return_choice;212def select_survey_type(bmenu = True):213	print("\n")214	215	for opt, survey in survey_type_option.items():216		print('%s \t %s' % (opt, survey))217	218	print('b \t Back to city selection')219	220	if bmenu:221		print('q \t Quit Program')222		223	print("\n")224	225	return_choice = ''226	choice = ''227	while choice != 'q':228		choice = input('Select survey type for migration: ')229		if choice in survey_type_option.keys():230			select_option['survey_type'] = choice231			232			if select_option['action'] == '1':233				return_choice = '4' # generate xml234			elif select_option['action'] == '2':235				return_choice = '5' # upload xml236			elif select_option['action'] == '3':237				return_choice = '6' # delete xml238			break;239			240		elif choice == 'b':241			select_option['city'] = None242			return_choice = '1' # select city 243			break;244			245		elif bmenu and choice == 'q':246			return_choice = 'q' # select city 247			break;248			249		else:250			print('Invalid survey type option.')251			choice = ''252	253	return return_choice;254def select_action():255	print('m \t Generate data into xml format')256	print('u \t Upload files into Kobo Tool Box')257	print('d \t Delete existing data from last action')258	print('q \t Quit migration')259	print('\n')260	261	return_choice = ''262	choice = ''263	while choice != 'q':264		choice = input('Confirm migration: ')265		if choice == 'm':266			select_option['action'] = '1'267			break;268			269		elif choice == 'u':270			select_option['action'] = '2' 271			break;272			273		elif choice == 'd':274			select_option['action'] = '3' 275			break;276			277		elif choice == 'q':278			return_choice = 'q' # exit program279			break;280		else:281			print('Invalid action option.')282	283	select_option['city'] = None284	select_option['survey_type'] = None285	286	if select_option['action'] == '3':287		return_choice = '6' # delete288	elif return_choice != 'q':289		return_choice = '1' # select city290	291	292	return return_choice;293def confirm_migration():294	print('\n')295	print('y \t Yes')296	print('n \t No')297	print('s \t Back to survey type selection')298	print('c \t Back to city selection')299	print('q \t Quit migration')300	print('\n')301	302	return_choice = ''303	choice = ''304	while choice != 'q':305		choice = input('Confirm migration: ')306		if choice == 'y':307			return_choice = 'yb' # start migration308			break;309		elif choice == 'n':310			return_choice = '3' # go to back menu311			break;312		elif choice == 's':313			select_option['survey_type'] = None314			return_choice = '2' # select survey type315			break;316		elif choice == 'c':317			select_option['city'] = None318			select_option['survey_type'] = None319			return_choice = '1' #select city 320			break;321		elif choice == 'q':322			return_choice = 'q' # exit program323			break;324		else:325			print('Invalid survey type option.')326	327	return return_choice;328	329def migrate():330	331	choice = confirm_migration()332	333	if choice == 'yb':334		display_menu('r')335		print('\nExecuting acutal migration program')336		city = select_option['city']337		survey = select_option['survey_type']338		339		if city:340			city_id = city_mapping[city]341			city_name = city_option[city]342		else:343			print('Cannot migrate data. Please contact administrator - city error')344		345		if city_id and survey:346			survey_map = city_survey_mapping[city]347			if survey == '2':348				survey_id = survey_map[survey][0]349				survey_id2 = survey_map[survey][1] if len(survey_map[survey]) == 2 else None350			else:351				survey_id = survey_map[survey]352				survey_id2 = None353			354			survey_name = survey_type_option[survey]355		else:356			print('Cannot migrate data. Please contact administrator - survey error')357		358		if city_id and survey_id:359			log_folder_path = os.path.join(root_output_folder, city_name, 'log')360			361			mapped_excelFile = mapped_excel_path_mapping[city][survey]362			output_folder_path = os.path.join(root_output_folder, city_name, survey_name)363			364			xml_root = survey_xml_value_mapping[survey]['xml_root']365			xml_root_attr_id = survey_xml_value_mapping[survey]['xml_root_attr_id']366			xml_root_attr_version = survey_xml_value_mapping[survey]['xml_root_attr_version']367			formhub_uuid = survey_xml_value_mapping[survey]['formhub_uuid']368			369			set_survey_log_path_option(log_folder_path)370			371			set_survey_option(city_id, survey_id, mapped_excelFile, survey_id2)372			set_survey_xml_option(xml_root, xml_root_attr_id, xml_root_attr_version, formhub_uuid)373			374			set_survey_output_path_option(output_folder_path)375			376			#print(options_dict)377			378			if survey == '1':379				print('Generating xml for RA')380				create_ra_xml(options_dict)381			elif survey == '2':382				print('Generating xml for RHS')383				create_rhs_xml(options_dict)384			elif survey == '3':385				print('Generating xml for FF')386				create_ff_xml(options_dict)387			388			reset_survey_option()389			390			print('\nDone Migration of %s for %s city \n' % (survey_name, city_name))391	392	return choice;393	394def confirm_upload_xml():395	print('\n')396	print('y \t Yes')397	print('n \t No')398	print('s \t Back to survey type selection')399	print('c \t Back to city selection')400	print('q \t Quit migration')401	print('\n')402	403	return_choice = ''404	choice = ''405	while choice != 'q':406		choice = input('Confirm upload: ')407		if choice == 'y':408			return_choice = 'yb' # start migration409			break;410		elif choice == 'n':411			return_choice = '3' # go to back menu412			break;413		elif choice == 's':414			select_option['survey_type'] = None415			return_choice = '2' # select survey type416			break;417		elif choice == 'c':418			select_option['city'] = None419			select_option['survey_type'] = None420			return_choice = '1' #select city 421			break;422		elif choice == 'q':423			return_choice = 'q' # exit program424			break;425		else:426			print('Invalid survey type option.')427	428	return return_choice;429	430def upload_xml():431	global survey_photo_mapping432	global select_option433	choice = confirm_upload_xml()434	435	if choice == 'yb':436		display_menu('r')437		print('\nExecuting acutal file upload program')438		city = select_option['city']439		survey = select_option['survey_type']440		441		if city and survey:442			city_name = city_option[city]443			survey_name = survey_type_option[survey]444			445			log_folder_path = os.path.join(root_output_folder, city_name, 'log')446			447			output_folder_path = os.path.join(root_output_folder, city_name, survey_name)448			449			set_survey_log_path_option(log_folder_path)450			451			set_survey_output_path_option(output_folder_path)452			453			upload_to_kobotoolbox(survey_photo_mapping, select_option)454			455			reset_survey_option()456			457			print('\nDone Migration upload of %s for %s city \n' % (survey_name, city_name))458		459	return choice;460def view_generated_data_list():461	result = True462	463	if os.path.exists(root_output_folder):464		for cid, city in city_option.items():465			if os.path.exists(os.path.join(root_output_folder, city)):466				survey_list = [];467				468				for sid, survey in survey_type_option.items():469					if os.path.exists(os.path.join(root_output_folder, city, survey)):470						survey_list.append(survey)471				472				if survey_list:473					print("Found following survey for '%s' city: " % city)474					for survey in survey_list:475						print("- ",survey)476					print("\n")477	else:478		result = False479		print("No data exists/generated.")480	481	482		483	return result;484def confirm_file_deletion():485	print('\n')486	print('y \t Yes')487	print('n \t No')488	print('b \t Back to action selection')489	print('q \t Quit migration')490	print('\n')491	492	return_choice = ''493	choice = ''494	while choice != 'q':495		choice = input('Confirm deletion : ')496		if choice == 'y':497			return_choice = 'yb' # start deletion498			break;499		elif choice == 'n':500			select_option['action'] = None501			select_option['city'] = None502			select_option['survey_type'] = None503			return_choice = '3' # go to back menu504			break;505		elif choice == 'b':506			select_option['action'] = None507			select_option['city'] = None508			select_option['survey_type'] = None509			return_choice = '3' # select action510			break;511		elif choice == 'q':512			return_choice = 'q' # exit program513			break;514		else:515			print('Invalid survey type option.')516	517	return return_choice;518def select_delete_option():519	choice = None520	# check if found existing records then ask for deletion521	if view_generated_data_list():522		print('a \t Delete All')523		print('c \t Delete for selected city')524		print('s \t Delete for selected survey')525		print('b \t Back to action selection')526		print('q \t Quit migration')527		print('\n')528		529		while choice != 'q':530			choice = input('Select deletion option: ')531		532			if choice == 'a':533				select_option['action'] = '3'534				break;535			elif choice == 'c':536				select_option['action'] = '3'537				538				display_menu('0')539				print("\nDelete existing data for selected city")540				541				if not select_option['city']:542					select_city(False)543				break;544			elif choice == 's':545				select_option['action'] = '3'546				547				display_menu('0')548				print("Delete existing data for selected city and survey")549				550				if not select_option['city']:551					select_city(False)552				553				display_menu('0')554				print("Delete existing data for selected city and survey")555				556				if not select_option['survey_type']:557					select_survey_type(False)558					559				break;560			elif choice == 'b':561				break;562			elif choice == 'q':563				break;564			else:565				print('Invalid deletion option.')566	else:567		choice = 'b'568		569	return choice;570def delete_existing_files():571	select_choice = ''572	573	while select_choice != 'q':574		select_choice = select_delete_option()575		576		if select_choice == 'b':577			choice = '3' # back to main menu selection578			break;579		elif select_choice == 'q':580			choice = 'q' # quit program581			break;582		elif select_choice in ['a', 'c', 's']:583			display_menu('0')584			585			if select_choice == 'a':586				print("\nDelete all existing data")587				588			confirm = confirm_file_deletion()589			590			display_menu('0')591			592			if confirm == 'yb':593				del_folder_path = ""594				595				city = select_option['city']596				survey_type = select_option['survey_type']597				598				if select_choice == 's':599					del_folder_path = os.path.join(root_output_folder, city_option[city], survey_type_option[survey_type])600				elif select_choice == 'c':601					del_folder_path = os.path.join(root_output_folder, city_option[city])602				else:603					del_folder_path = os.path.join(root_output_folder, 'temp')604					605				if del_folder_path:606					if select_choice != 'a':607						select_choice = ''608						609						if os.path.exists(del_folder_path):610							shutil.rmtree(del_folder_path, ignore_errors=True)611							choice = '3' # back to main menu selection612							break;613						else:614							print("\nData not found for selected option. Please select again\n")615							select_option['city'] = None616							select_option['survey_type'] = None617					elif select_choice == 'a':618						619						select_choice = ''620						621						city_name = ""622						for cid, city in city_option.items():623							del_folder_path = os.path.join(root_output_folder, city)624							625							if os.path.exists(del_folder_path):626								shutil.rmtree(del_folder_path, ignore_errors=True)627							else:628								city_name += city+', '629						630						if city_name:631							print("\nData not found for '%s' cites. Please select again\n" % city_name[:-2])632						else:633							choice = '3' # back to main menu selection634							break;635			else:636				select_choice = ''637		else:638			display_menu('0')639	640	select_option['city'] = None641	select_option['survey_type'] = None642	select_option['action'] = None643	644	return choice;645def run_program():646	choice = ''647	648	start_option = '3' # show selection menu649	650	# check if data exists for previous migration 651	for cid, city in city_option.items():652		del_folder_path = os.path.join(root_output_folder, city)653		654		if os.path.exists(del_folder_path):655			start_option = '6' # delete existing data first656			break;657	658	choice = display_menu(start_option)659	while choice != 'q':660		#print('choice --> ', choice)661		662		if choice == '1': # select city 663			choice = select_city()664			665		elif choice == '2': # select survey666			choice = select_survey_type()667			668		elif choice == '3': #select action669			choice = select_action()670			671		elif choice == '4': # migrate to xml672			migreate_choice = migrate()673			if migreate_choice == 'yb':674				choice = back_menu()675			#elif migreate_choice == 'nb':676			#	display_menu(choice)677			#	choice = back_menu()678			else:679				choice = migreate_choice680				681		elif choice == '5': # upload xml file682			upload_choice = upload_xml()683			if upload_choice == 'yb':684				choice = back_menu()685			else:686				choice = upload_choice687				688		elif choice == '6': # delete data689			delete_choice = delete_existing_files()690			if delete_choice == 'yb':691				choice = back_menu()692			else:693				choice = delete_choice694		else:695			print('Invalid option')696		697		if choice == 'q':698			select_option['city'] = None699			select_option['survey_type'] = None700			select_option['action'] = None701			702		display_menu(choice)703		704		if choice == 'q':705			print('Program Terminated')706	return;707if __name__ == "__main__":708	run_program()...test_master_admin_add_rep_case.py
Source:test_master_admin_add_rep_case.py  
...38        self.wait_for_element_contains_text('.field-client .errorlist', 'This field is required.')39        self.wait_for_element_contains_text('.field-owners .errorlist', 'This field is required.')40        self.wait_for_element_contains_text('.field-physician .errorlist', 'This field is required')41        self.wait_for_element_contains_text('.field-procedure_date .errorlist', 'This field is required.')42        self.select_option('select#id_client', 'EA')43        self.wait_for_element_contains_text('.field-owners', 'admin@ea.com')44        self.select_option('select#id_client', 'UVMC')45        self.wait_for(lambda: self.assert_elements_count('.field-owners select#id_owners > option', 0))46        self.assert_owners_not_found()47        self.select_option('select#id_client', 'NSINC')48        self.wait_for_element_contains_text('.field-owners', 'admin@nsinc.com')49        self.select_option('select#id_owners', 'admin@nsinc.com')50        self.select_option('select#id_owners', 'doctor@nsinc.com')51        self.select_option('select#id_physician', 'doctor@nsinc.com')52        self.find_link('Today').click()53        self.click_save_and_continue()54        rep_case = f'New case at NSINC on {datetime.utcnow().date()}'55        self.wait_for_success_message(f'The rep case "{rep_case}" was added successfully. You may edit it again below.')56        self.wait_for_element_contains_text('.field-client', 'NSINC')57        self.assert_options_are_selected('select#id_owners', ['admin@nsinc.com', 'doctor@nsinc.com'])58        self.assert_option_is_selected('select#id_physician', 'doctor@nsinc.com')59class RepCaseItemsAdminTestCase(MasterAdminTestCase):60    def setUp(self):61        super().setUp()62        self.log_in_master_admin()63        self.client = ClientFactory(name='NSINC')64        self.product_1 = ProductFactory(name='Accolade VR', manufacturer=ManufacturerFactory(short_name='MDT'))65        self.product_2 = ProductFactory(name='Evera MRI XT', manufacturer=ManufacturerFactory(short_name='BIO'))66        ClientPriceFactory(67            client=self.client, product=self.product_1, system_cost=100, discounts=[68                DiscountFactory(name='CCO', cost_type=SYSTEM_COST, discount_type=PERCENT_DISCOUNT, percent=20, order=2,69                                apply_type=ON_DOCTOR_ORDER),70                DiscountFactory(name='Repless', cost_type=SYSTEM_COST, discount_type=VALUE_DISCOUNT, value=20, order=1,71                                apply_type=ON_DOCTOR_ORDER),72            ]73        )74        bulk_discount = DiscountFactory(name='Bulk', cost_type=UNIT_COST, discount_type=VALUE_DISCOUNT, value=50,75                                        order=1, apply_type=PRE_DOCTOR_ORDER)76        ClientPriceFactory(77            client=self.client, product=self.product_2, unit_cost=200, discounts=[78                DiscountFactory(name='Repless', cost_type=UNIT_COST, percent=10, order=1, apply_type=ON_DOCTOR_ORDER),79                bulk_discount80            ]81        )82        device = Device.objects.get(client=self.client, product=self.product_2)83        item = ItemFactory(device=device, is_used=False, serial_number='SER1234', discounts=[bulk_discount],84                           cost_type=UNIT_COST, purchased_date=date(2018, 1, 1))85        self.assertEqual(item.cost, 150)86        physician = AccountFactory(role=RoleFactory(priority=RolePriority.PHYSICIAN.value), client=self.client)87        self.rep_case = RepCaseFactory(88            client=self.client,89            owners=[physician],90            physician=physician,91            procedure_date=date(2018, 9, 10)92        )93        self.visit_reverse('admin:tracker_repcase_change', self.rep_case.id)94        self.wait_for_element_contains_text('#content h1', 'Change rep case')95    def test_new_repcase_change_view(self):96        self.assert_elements_count('.form-row.has_original', 0)97    def test_add_invalid_item_to_repcase(self):98        self.find_link('Add another Item').click()99        self.assert_elements_count('.form-row.dynamic-item_set', 1)100        self.wait_for(lambda: self.assert_elements_count('#id_item_set-0-discounts select option', 0))101        self.click_save_and_continue()102        self.wait_for_error_message(message='Please correct the error below.')103        self.wait_for_element_contains_text('.field-identifier', 'This field is required.')104    def test_products_and_discounts_for_item(self):105        def assert_created_item(index, **attrs):106            self.assert_option_is_selected(f'#item_set-{index} .item-device > select', attrs['product'])107            self.assert_option_is_selected(f'#item_set-{index} .item-purchase_type > select', attrs['purchase_type'])108            self.assert_option_is_selected(f'#id_item_set-{index}-identifier', attrs['identifier'])109            self.assert_option_is_selected(f'#id_item_set-{index}-cost_type', attrs['cost_type'])110            self.assert_options_are_selected(f'#id_item_set-{index}-discounts', attrs['discounts'])111        self.find_link('Add another Item').click()112        self.assert_elements_count('.form-row.dynamic-item_set', 1)113        self.select_option('.item-specialty > select', self.product_1.category.specialty.name)114        self.select_option('.item-category > select', self.product_1.category.name)115        self.select_option('.item-manufacturer > select', self.product_1.manufacturer.short_name)116        self.select_option('.item-device > select', self.product_1.name)117        self.select_option('.item-purchase_type > select', 'Consignment')118        self.find_element('.item-identifier .select2-container').click()119        self.find_elements('.select2-search__field')[-1].send_keys('Accolade', Keys.ENTER)120        self.select_option('select#id_item_set-0-cost_type', 'System cost')121        self.wait_for_element_contains_text('.field-discounts', 'CCO')122        self.select_option('.field-discounts select', 'CCO')123        self.select_option('.field-discounts select', 'Repless')124        self.select_option('#id_item_set-0-not_implanted_reason', 'Dropped')125        self.find_link('Add another Item').click()126        self.assert_elements_count('.form-row.dynamic-item_set', 2)127        self.select_option('#item_set-1 .item-specialty > select', self.product_2.category.specialty.name)128        self.select_option('#item_set-1 .item-category > select', self.product_2.category.name)129        self.select_option('#item_set-1 .item-manufacturer > select', self.product_2.manufacturer.short_name)130        self.select_option('#item_set-1 .item-device > select', self.product_2.name)131        self.select_option('#item_set-1 .item-identifier select', 'SER1234')132        self.select_option('#item_set-1 .field-discounts select', 'Repless')133        self.select_option('#id_item_set-1-not_implanted_reason', 'Wrong device')134        self.click_save_and_continue()135        self.wait_for_success_message('The rep case "New case at NSINC on 2018-09-10" was changed successfully.')136        self.assert_elements_count('.form-row.has_original', 2)137        assert_created_item(0, identifier='SER1234', product='Evera MRI XT', cost_type='Unit cost',138                            purchase_type='Bulk', discounts=['Repless'])139        assert_created_item(1, identifier='Accolade', product='Accolade VR', cost_type='System cost',140                            purchase_type='Consignment', discounts=['CCO', 'Repless'])141        bulk_item = Item.objects.get(identifier='SER1234')142        consignment_item = Item.objects.get(identifier='Accolade')143        self.assertEqual(bulk_item.cost, 130)144        self.assertEqual(bulk_item.get_not_implanted_reason_display(), 'Wrong device')145        self.assertEqual(consignment_item.cost, 64)146        self.assertEqual(consignment_item.get_not_implanted_reason_display(), 'Dropped')147    def test_add_duplicated_serial_number_item(self):148        item = ItemFactory(rep_case=self.rep_case, device=self.client.device_set.get(product=self.product_1))149        ItemFactory(rep_case=self.rep_case, device=self.client.device_set.get(product=self.product_2))150        self.visit_reverse('admin:tracker_repcase_change', self.rep_case.id)151        self.wait_for_element_contains_text('#content h1', 'Change rep case')152        self.assert_elements_count('.form-row.dynamic-item_set', 2)153        self.find_link('Add another Item').click()154        self.select_option('#item_set-2 .item-purchase_type > select', 'Consignment')155        self.find_element('#item_set-2 .item-identifier .select2-container').click()156        self.find_elements('.select2-search__field')[-1].send_keys(item.identifier, Keys.ENTER)157        self.click_save_and_continue()158        self.wait_for_error_message(message='Please correct the error below.')159        self.wait_for_element_contains_text('#item_set-2 .field-identifier',160                                            f'Item with this identifier {item.identifier} exists')161        self.find_element('#item_set-2 .item-identifier .select2-container').click()162        self.find_elements('.select2-search__field')[-1].send_keys('NEW SERIAL', Keys.ENTER)163        self.click_save_and_continue()164        self.wait_for_success_message('The rep case "New case at NSINC on 2018-09-10" was changed successfully.')...index_shop_method.py
Source:index_shop_method.py  
...12        self.click_until_visiable(Index_page.create_order_button)  # ç¹å»å建订åæé®13        self.send_keys_until_visiable(Create_order_page.name, 'èªå¨åèæ¬å建ç订å')  # æ¶è´§äºº14        self.send_keys_until_visiable(Create_order_page.mobile, '99999999')  # æ¶è´§äººææº15        self.click_until_visiable(Create_order_page.area_province)16        self.select_option(Create_order_page.area_province_ul, 1)  # éæ©ç份17        self.click_until_visiable(Create_order_page.area_city)18        self.select_option(Create_order_page.area_city_ul, 1)  # éæ©åå¸19        self.click_until_visiable(Create_order_page.area_county)20        self.select_option(Create_order_page.area_county_ul, 1)  # éæ©åºå¿21        self.send_keys_until_visiable(Create_order_page.street, 'æµè¯è¡é' + self.add_random())  # å¡«åè¡é22        self.send_keys_until_visiable(Create_order_page.seller_note, '------------autoTest----------')  # å家夿³¨23        self.click_until_visiable(Create_order_page.express_selection)24        self.select_option(Create_order_page.express_selection_ul, 1)  # éæ©å¿«é25        self.send_keys_until_visiable(Create_order_page.buyer_id, '2333333333333')  # ä¹°å®¶id26        sleep(2)27        self.click_until_visiable(Create_order_page.texture)28        self.select_option(Create_order_page.texture_ul, 1)  # éæ©æè´¨29        self.click_until_visiable(Create_order_page.color)30        self.select_option(Create_order_page.color_ul, 3)  # éæ©é¢è²31        self.click_until_visiable(Create_order_page.mobile_mode)32        self.send_keys_until_visiable(Create_order_page.mobile_mode, 'iphone12')33        self.select_option(Create_order_page.mobile_mode_ul, 1)  # éæ©åå·'''34        self.click_until_visiable(Create_order_page.picture_num)35        self.send_keys_until_visiable(Create_order_page.picture_num, 'éªè½¦å¥¥ç¹æ¼')36        self.select_option(Create_order_page.picture_num_ul, 1)  # éæ©å¾çç¼ç 37        self.turn_down_element(Create_order_page.confirm_button)  # 䏿»è³ç¡®å®æé®åºç°38        self.click_until_visiable(Create_order_page.confirm_button)  # ç¡®å®39    # æå¨æå40    def manual_order_method(self):41        self.click_until_visiable(Index_page.manual_pull_button)  # æå¨æå42        # self.click_until_visiable(Index_page.order_num_radio)  # çµå订åå·43        self.click_until_visiable(Manual_order_page.shop_type_selectBox)  # ç¹å»åºéºç±»å44        self.select_option(Manual_order_page.shop_type_ul, 1)  # éæ©åºéºç±»å45        self.click_until_visiable(Manual_order_page.download_shop_selectBox)  # ç¹å»ä¸è½½åºéº46        self.select_option(Manual_order_page.download_shop_ul, 1)  # éæ©ä¸è½½åºéº47        self.click_fixed_area(800, 300)  # ç¹å»å
¶ä»åºå48        # self.click_until_visiable(Manual_order_page.close_download_button)  # ç¹å»å
³é49        self.click_until_visiable(Manual_order_page.start_download_button)  # ç¹å»å¼å§50        sleep(40)  # çå¾
æ§è¡40s51        self.element_text_is(Manual_order_page.start_download_button,52                             '宿')  # 夿æé®æåãå®æã                                                          #夿æé®æåæ¯ä¸æ¯ã宿ã53        self.click_until_visiable(Manual_order_page.start_download_button)  # ç¹å»å®æ54    # éè¿ååIDæç´¢è®¢å55    def search_list_order_by_orderID(self, file_path):56        data = self.split_text(Index_page.search_list_order_num, 4, -1)  # è·åç¬¬ä¸æ¡ç订åå·57        YamlHandler(file_path).write_yaml({'order_num': data})  # åå·åå
¥yaml58        self.send_keys_until_visiable(Index_page.paste_order_num, data)  # å¡«å
¥æç´¢æ¡59        sleep(2)60        self.click_until_visiable(Index_page.search_button)  # ç¹å»æç´¢61        #self.click_until_visiable(Index_page.order_checkBox_all)  # å
¨é订å62        # self.get_text_is(actual_text=self.split_text(Index_page.search_list_order_num))  # 夿æç´¢63    # éè¿ä¹°å®¶IDæç´¢è®¢å64    def search_list_order_by_buyerID(self, buyer_id):65        self.send_keys_until_visiable(Index_page.buyer_id_input, buyer_id)  # å¡«å
¥ä¹°å®¶IDè¾å
¥æ¡66        sleep(2)67        self.click_until_visiable(Index_page.search_button)  # ç¹å»æç´¢68    # è®¢åæ¨é69    def push_order(self):70        sleep(10)71        self.click_until_visiable(Index_page.data_list_limit)  # ç¹å»å±ç¤ºæ°æ®é
ç½®é项72        self.select_option(Index_page.data_list_limit_ul, 7)  # éæ©500æ¡73        sleep(10)74        self.click_until_visiable(Index_page.order_checkBox_all)  # éä¸å
¨é¨è®¢å75        self.click_until_visiable(Index_page.push_order_button)  # è®¢åæ¨é76        sleep(5)77        self.click_until_visiable(Index_page.confirm_button)  # 确认78    # æ´å¤æä½79    ##  1. é¢åè´§80    def pre_shipping_method(self):81        self.click_until_visiable(Index_page.order_checkBox1)  # éä¸è®¢å82        self.click_until_visiable(Index_page.more_operate)  # æ´å¤æä½83        self.click_until_visiable(More_operate.pre_shipping)  # é¢åè´§84        self.click_until_visiable(Index_page.confirm_button)  # 确认85    ##  2. å并订å86    def merge_order_method(self):...credit.py
Source:credit.py  
1#!/usr/bin/env python23import os,sys,json4from utils.handler import CreditCarHandler5from utils.handler import ShoppingHandler6from credit_auth import login7from utils.Logging import logger89sh_handler = ShoppingHandler("./db/shoplist")10sh_dict = sh_handler.get_shop_name_price_dict1112msg = """13 欢è¿ç»éæåé¶è¡APP14    0) åºæ¬ä¿¡æ¯15    1) ç¨æ·æ¶è´¹16    2) ç¨æ·è¿æ¬¾17    3) ç¨æ·è½¬è´¦18    4) ç¨æ·åç°19    5ï¼è´ç©è½¦ç»ç®20"""2122class CreditCar(object):23    @login24    def __init__(self,username=None):25        self.username = username26        if self.username == "anonumous":27            pass28        else:29            self.credit_card_file = os.path.join("./user_credit_card",self.username)30            self.user_obj = CreditCarHandler(self.credit_card_file)31            self.user_shop_car_file = os.path.join("./user_shop_car", self.username)32            self.user_shop_car_dict = json.load(open(self.user_shop_car_file))3334    def userinfo(self):35        if self.username == "anonumous":36            print("åªè½çå°åºæ¬é¡µé¢")37        else:38            print(self.user_obj.data)3940    def consume(self,money):41        if self.username == "anonumous":42            print("åªè½çå°æ¶è´¹é¡µé¢")43        else:44            self.user_obj.subtraction(money)45            self.user_obj.save()46            logger("info", "[%s] æ¶è´¹äºï¼ [%s]" %(self.username,money) , self.username)4748    def repay(self,money):49        if self.username == "anonumous":50            print("åªè½çå°è¿æ¬¾é¡µé¢")51        else:52            self.user_obj.plus(money)53            self.user_obj.save()54            logger("info", "[%s] è¿æ¬¾ï¼ [%s]" % (self.username, money), self.username)5556    def transfer(self,recipient,money):57        if self.username == "anonumous":58            print("åªè½æ¥çå°è½¬é±é¡µé¢")59        else:60            recipient_credit_card_file = os.path.join("./user_credit_card",recipient)61            recipient_obj = CreditCarHandler(recipient_credit_card_file)62            self.user_obj.subtraction(money)63            recipient_obj.plus(money)64            self.user_obj.save()65            recipient_obj.save()66            logger("info", "[%s] æ¶å° [%s] ç转账 [%s]" % (recipient,self.username,money), recipient)67            logger("info", "[%s] è½¬ç» [%s] é颿¯ [%s]" % (self.username,recipient,money), self.username)6869    def withdraw(self,money):70        if self.username == "anonumous":71            print("åªè½æ¥çå°æç°é¡µé¢")72        else:73            amount = money + money * 0.0574            self.user_obj.subtraction(amount)75            if self.user_obj.data.get("cash"):76                self.user_obj.data["cash"] += money77            else:78                self.user_obj.data["cash"] = money79            self.user_obj.save()80            logger("info", "[%s] æç°çé颿¯ï¼ [%s]" % (self.username, money), self.username)8182    def shopping_paid(self):83        print(self.user_shop_car_dict)84        option = input("请è¾å
¥ä½ æ³ç»ç®çåååç§°åæ°éï¼ç¨éå·åå¼")85        brand_name,brand_number = option.split(",")86        brand_price = sh_dict[brand_name]87        self.consume(int(brand_price) * int(brand_number))88        self.user_shop_car_dict["not_paid"][brand_name] = int(self.user_shop_car_dict["not_paid"][brand_name]) - int(brand_number)89        print(self.user_shop_car_dict["not_paid"][brand_name])90        fd = open(self.user_shop_car_file,"w")91        json.dump(self.user_shop_car_dict,fd)92        fd.close()9394if __name__ == "__main__":95    print(msg)96    print("请å
ç»éæåçæ´»APP".center(50,"*"))97    obj = CreditCar()98    while True:99        select_option = input("è¯·éæ©ç¼å·ï¼éåºè¯·æ[q]ï¼å¸®å©è¯·æ[h]")100        if select_option == "q":101            break102        elif select_option == "h":103            print(msg)104        elif select_option == "0":105            obj.userinfo()106        elif select_option == "1":107            money = input("请è¾å
¥æ¶è´¹éé¢")108            obj.consume(int(money))109        elif select_option == "2":110            money = input("请è¾å
¥è¿æ¬¾éé¢")111            obj.repay(int(money))112        elif select_option == "3":113            recipient = input("请è¾å
¥è½¬è´¦ç»è°")114            money = input("请è¾å
¥è½¬è´¦éé¢")115            obj.transfer(recipient,int(money))116        elif select_option == "4":117            money = input("请è¾å
¥æç°éé¢")118            obj.withdraw(int(money))119        elif select_option == "5":120            obj.shopping_paid()121        else:122            print("对ä¸èµ·ï¼ä½ éæ©çç¼å·ä¸å¯¹ï¼è¯·éæ°è¾å
¥ï¼")123124
...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
