--- /dev/null
+from latest_rootstrap import *
+from read_csv import *
+import re
+from header_file_location import *
+from validate_api import *
+
+def updateCMakeFile(TC_WRITE_DIR, MODULE_NAME, file_name):
+ with open(TC_WRITE_DIR + "/" + MODULE_NAME + "/" + f"{'CMakeLists.txt'}", "r+") as myfile:
+ buf = myfile.readlines()
+ with open(TC_WRITE_DIR + "/" + MODULE_NAME + "/" + f"{'CMakeLists.txt'}", "w+") as out_file:
+ for line in buf:
+ if line == "SET(TC_SOURCES\n":
+ line = line + " " + file_name + "\n"
+ ## print("checking the line ", line)
+ out_file.write(line)
+ return out_file
\ No newline at end of file
--- /dev/null
+Hello, this is a guide for TC Assistant tool.
+
+
+## Please follow this guide for TC Assistant tool execution.
+
+# Pre-requisites -
+
+ Python 3.6 or above, PIP 21.3.1 or above version, Tkinter
+
+# Command to launch the tool -
+ Python tct_assistance.py
+
+
+1. Packages which needs to be installed before running the application -
+
+ 1. PyTorch - sudo pip3 install torch
+ 2. Numpy - sudo pip3 install numpy
+ 3. Pandas - sudo pip3 install pandas
+ 4. Regular Expression - sudo pip3 install regex
+ 5. Transformers - sudo pip3 install transformers==3.1.0
+ 6. Matplotlib - sudo pip3 install matplotlib
+ 7. Scikit Learn - sudo pip3 install scikit-learn
+ 8. Json - sudo pip3 install jsonlib
+ 9. TextDistance - sudo pip3 install textdistance
+ 10. PIL - sudo pip3 install pillow(after installing pillow run the below command sudo apt-get install python3-pil python3-pil.imagetk)
+
+2. If tool gives error in the first response itself then run command 'python trainedmodel.py'. This command trains model again with our dataset
+
+3. Suppost has been provide to add TCs in existing module and create a complete new module
+
+4. Before starting the tool make sure that permission has been given to the whole folder and module entry is there in Module_Header_Mapping.csv file for a existing module. Entry should be there in format of: Module_Name, Folder_Name/Header_File1.h, Folder_Name/Header_File2.h, ....
+
+ **For example**, if we need to create test cases for data-control module then make entry in csv file as below -:
+
+ data-control, appfw/data_control.h, appfw/data_control_provider.h
+
+5. Latest rootstrap need to installed in user's pc as this tool searches for entered header files inside latest rootstrap.
+
+ **For example:**
+
+ If user has entered webrtc module then tool will search for its header file media/webrtc.h in tizeniot-8.0-device.core.private.20230823_131527 rootstrap.
+ > Header file should be present at path /home/sri/tizen-studio/platforms/tizen-8.0/tizeniot/rootstraps/tizeniot-8.0-device.core.private.20230823_131527/usr/include, otherwise tool will run into error.
+
+6. API's for which you need to create TCs, those api's declaration need to be present in the header files mentioned in Module_Header_Mapping.csv file
+
+
+
+
+# Steps to use the tool -:
+
+1. At first tool provides two options whether to write tcs for new module or existing module. Type "new" for new module case and "existing" for existing module case.
+
+2. **Existing module case** : In next step we need to enter Module name in the format of Module name: webrtc
+ Make sure module name header files entry is there in csv file
+
+3. **New module case** : In next step we need to enter Module name in the format of Module name: webrtc
+ After entering module name, you need to enter header file which is required for this module in the format of
+
+ Header File: Header_File_1.h Header_File_2.h
+
+4. In next step you need to enter api names for which you need to create TCs.
+
+ **For example :**
+
+ API Names: camera_attr_get_focus_level_range => for single api
+ API Names: camera_create camera_attr_get_focus_level_range camera_attr_set_focus_level => for multiple api
+
+5. In the next step you will be asked to enter feature for the module in the format of
+
+ feature name:http://tizen.org/feature/camera
+
+6. Next you will be asked to enter pre/post apis for all the entered API's. Suppose user has entered 5 target api's then you need to enter pre/post apis for every target api.
+
+ **For example -:**
+
+ Pre: camera_attr_get_focus_level_range camera_attr_set_focus_level Post: camera_create
+
+ If there are multiple pre/ post apis then yoy need to enter them space separated. And there is no pre/post api for a particular target api then you need to simply write pre: and press enter
+
+7. After entering pre/post apis for all the APIs, you will be asked to select whether you want to increase the coverage by automatically including negative tcs. If user enter "Yes" the negative tcs will be automatically included.
+
+8. After entering all the above information you will be asked to enter file name among all the listed files in which you need to write your created TCs.
+
+ **For example -:**
+
+ FILE name: utc-alarm.c
+
+ Here if you write name of file which is already prsent in utc then tool will append TC in same file, if not present then tool will create new file in the same folder.
+
+9. After Tcs are successfully created. You will be asked whether to build module or not. Type "Yes" if you want to build the TCs
+
+10. If build is successfull the type "Yes" to install TCs and launch tct manager for further execution
+
+
+
+
+
+
+
+
--- /dev/null
+Key,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value
+alarm,appfw/app_alarm.h,appfw/app_alarm_internal.h,appfw/app_alarm_extension.h,appfw/app_control.h,appfw/app_common.hpp,appfw/app_control_internal.h,,,,,,,,,,,,,,,,
+application,appfw/app.h,appfw/app_manager.h,appfw/app_control.h,appfw/app_control_uri.h,appfw/app_event.h,appfw/app_resource_manager.h,appfw/app_preference.h,,,,,,,,,,,,,,,
+app-manager,appfw/app_manager.h,appwf/app_context.h,appfw/app_info.h,appfw/app.h,,,,,,,,,,,,,,,,,,
+asp,asp/asp.h,,,,,,,,,,,,,,,,,,,,,
+attach-panel,attach-panel/attach_panel.h,,,,,,,,,,,,,,,,,,,,,
+audio-io,media/audio_io.h,,,,,,,,,,,,,,,,,,,,,
+badge,badge/badge.h,,,,,,,,,,,,,,,,,,,,,
+base-utils,base/utils_i18n.h,,,,,,,,,,,,,,,,,,,,,
+battery-monitor,battery_monitor.h,,,,,,,,,,,,,,,,,,,,,
+cairo,cairo/cairo.h,cairo/cairo-evas-gl.h,evas-1/Evas_GL.h,elementary-1/Elementary.h,,,,,,,,,,,,,,,,,,
+calendar-service2,calendar-service2/calendar.h,,,,,,,,,,,,,,,,,,,,,
+camera,media/camera.h,,,,,,,,,,,,,,,,,,,,,
+capi-maps-service,map_error.h,maps_address,maps_service.h,maps_area.h,maps_coordinates.h,maps_place_attribute.h,maps_place_category.h,maps_place.h,maps_place_contact.h,maps_place_editorial.h,maps_place_filter.h,maps_place_image.h,maps_place_link_object.h,maps_place_media.h,maps_place_rating.h,maps_place_review.h,maps_place_url.h,maps_preference.h,maps_route.h,maps_route_maneuver.h,maps_route_segment.h,maps_view.h
+capi-media-streamer,media/media_streamer.h,,,,,,,,,,,,,,,,,,,,,
+capi-media-vision,media/mv_barcode.h,image_util.h,storage.h,,media/mv_face.h,media/mv_image.h,media/mv_inference.h,media/mv_survillance.h,media/mv_3d.h,media/mv_3d_type.h,,,,,,,,,,,,
+capi-message-port,appfw/message_port.h,,,,,,,,,,,,,,,,,,,,,
+capi-system-system-settings,system/system_settings.h,,,,,,,,,,,,,,,,,,,,,
+bluetooth,network/bluetooth.h,,,,,,,,,,,,,,,,,,,,,
+webrtc,media/webrtc.h,,,,,,,,,,,,,,,,,,,,,
+nsd,nsd/dns-sd.h,nsd/dns-sd-internal.h,nsd/ssdp.h,,,,,,,,,,,,,,,,,,,
+email,messaging/email.h,storage/storage.h,,,,,,,,,,,,,,,,,,,,
+bundle,bundle.h,,,,,,,,,,,,,,,,,,,,,
+media-controller,media/media_controller_client.h,media/media_controller_server.h,,,,,,,,,,,,,,,,,,,,
+mediaeditor,media/media_editor.h,elementary-1/Elementary.h,,,,,,,,,,,,,,,,,,,,
+capi-media-vision-dl,media/mv_face_recognition.h,media/mv_common.h,media/mv_inference.h,,,,,,,,,,,,,,,,,,,
+minicontrol,minicontrol/minicontrol-viewer.h,,,,,,,,,,,,,,,,,,,,,
+media-content,media-content/Media_Content.h,media-content/Media_Content_type.h,storage/storage.h,,,,,,,,,,,,,,,,,,,
+phonenumber-utils,phonenumber-utils/phone_number_types.h,phonenumber-utils/phone_number.h,,,,,,,,,,,,,,,,,,,,
+player-display,media/player.h,media/sound_manager.h,media/player_internal.h,,,,,,,,,,,,,,,,,,,
+tbm,tbm_surface.h,,,,,,,,,,,,,,,,,,,,,
+nfc,network/nfc.h,,,,,,,,,,,,,,,,,,,,,
+iotcon,iotcon/iotcon-client.h,iotcon/iotcon.h,system/system_info.h,network/wifi-manager.h,network/net_connection.h,,,,,,,,,,,,,,,,,
+wav-player,media/wav_player.h,media/sound_manager.h,,,,,,,,,,,,,,,,,,,,
+accounts-svc,account.h,account-types.h,account-error.h,account_internal.h,account-error.h,,,,,,,,,,,,,,,,,
+appcore-agent,appcore-agent/service_app.h,appcore-agent/service_app_internal.h,appcore-agent/service_app_extension.h,,,,,,,,,,,,,,,,,,,
+appcore-widget,appfw/widget_app.h,appfw/widget_app_internal.h,appfw/widget_app_efl.h,widget_viewer_evas/widget_viewer_evas.h,,,,,,,,,,,,,,,,,,
+capi-ui-autofill,autofill.h,appfw/app_common.h,autofill_common.h,autofill_service.h,,,,,,,,,,,,,,,,,,
+capi-ui-inputmethod,elementary-1/Elementary.h,inputmethod.h,,,,,,,,,,,,,,,,,,,,
+capi-ui-inputmethod-manager,inputmethod_manager.h,,,,,,,,,,,,,,,,,,,,,
+capi-ui-sticker,sticker_data.h,sticker_provider.h,sticker_consumer.h,,,,,,,,,,,,,,,,,,,
+cion,cion/cion.h,appfw/app_common.h,,,,,,,,,,,,,,,,,,,,
+component-based-application,component_based/efl_base/api/component_based_app.h,appfw/component_manager.h,appfw/app_control.h,appfw/message_port.h,component_based/base/api/component_common.h,,,,,,,,,,,,,,,,,
+component-manager,appfw/app_control.h,appfw/component_manager.h,bundle.h,message_port.h,,,,,,,,,,,,,,,,,,
+connection,network/net_connection.h,time.h,,,,,,,,,,,,,,,,,,,,
+contacts-service2,contacts-svc/contacts.h,account.h,storage/storage.h,system/system_info.h,telephony/telephony.h,,,,,,,,,,,,,,,,,
+context,context-service/context_history.h,context-service/context_trigger.h,,,,,,,,,,,,,,,,,,,,
+data-control,appfw/data_control_provider.h,appfw/data_control.h,bundle.h,appfw/data_control_sql.h,appfw/data_control_noti.h,,,,,,,,,,,,,,,,,
+device,device/battery.h,device/callback.h,device/display.h,device/haptic.h,device/ir.h,system/system_info.h,device/led.h,tizen.h,device/power.h,device/temperature.h,,,,,,,,,,,,
+dlog,dlog/dlog.h,,,,,,,,,,,,,,,,,,,,,
+efl-extension,efl-extension/efl_extension.h,,,,,,,,,,,,,,,,,,,,,
+efl-util,ui/efl_util.h,,,,,,,,,,,,,,,,,,,,,
+fido-client,fido.h,,,,,,,,,,,,,,,,,,,,,
+geofence-manager,geofence/geofence_manager.h,,,,,,,,,,,,,,,,,,,,,
+http,network/net_connection.h,network/http.h,,,,,,,,,,,,,,,,,,,,
+image-util,media/image_util.h,storage/storage.h,,,,,,,,,,,,,,,,,,,,
+intelligent-network-monitoring,network/inm.h,,,,,,,,,,,,,,,,,,,,,
+job-scheduler,appfw/job_scheduler.h,,,,,,,,,,,,,,,,,,,,,
+key-manager,ckmc/ckmc-manager.h,ckmc/ckmc-type.h,ckmc/ckmc-error.h,,,,,,,,,,,,,,,,,,,
+libfeedback,feedback/feedback.h,,,,,,,,,,,,,,,,,,,,,
+libstorage,storage/storage.h,,,,,,,,,,,,,,,,,,,,,
+libstorage64,storage/storage.h,,,,,,,,,,,,,,,,,,,,,
+location-manager,location/locations.h,,,,,,,,,,,,,,,,,,,,,
+mediacodec,media/media_codec.h,,,,,,,,,,,,,,,,,,,,,
+mediademuxer,media/mediademuxer.h,media/media_packet.h,media/media_format.h,storage/storage.h,glib-2.0/glib.h,,,,,,,,,,,,,,,,,
+media-key,system/media_key.h,,,,,,,,,,,,,,,,,,,,,
+mediamuxer,media/mediamuxer.h,,,,,,,,,,,,,,,,,,,,,
+mediatool,media/media_packet.h,media/media_format.h,media/media_packet_pool.h,,,,,,,,,,,,,,,,,,,
+messages,messaging/messages.h,,,,,,,,,,,,,,,,,,,,,
+metadata-editor,metadata-editor/metadata_editor.h,,,,,,,,,,,,,,,,,,,,,
+metadata-extractor,media/metadata_extractor.h,,,,,,,,,,,,,,,,,,,,,
+mime-type,content/mime_type.h,appfw/app.h,,,,,,,,,,,,,,,,,,,,
+mtp,mtp.h,,,,,,,,,,,,,,,,,,,,,
+multi-assistant,multi_assistant.h,multi_assistant_common.h,,,,,,,,,,,,,,,,,,,,
+native-common,tizen_error.h,pthread.h,,,,,,,,,,,,,,,,,,,,
+nnstreamer,nnstreamer/nnstreamer.h,nnstreamer/nnstreamer-single.h,,,,,,,,,,,,,,,,,,,,
+nntrainer,nntrainer/nntrainer.h,,,,,,,,,,,,,,,,,,,,,
+notification,appfw/app.h,notification/notification.h,appcore-agent/service_app.h,appfw/app_control.h,notification-ex/api/notification_ex.h,appfw/app_manager.h,,,,,,,,,,,,,,,,
+oauth2,oauth2.h,,,,,,,,,,,,,,,,,,,,,
+openal,AL/al.h,AL/alc.h,media/sound_manager.h,,,,,,,,,,,,,,,,,,,
+package-manager,appfw/package_manager.h,appfw/package_archive_info.h,appfw/app_common.h,,,,,,,,,,,,,,,,,,,
+player,media/player.h,media/sound_manager.h,media/media_packet.h,media/media_format.h,curl/curl.h,,,,,,,,,,,,,,,,,
+privilege-info,privilege_information.h,,,,,,,,,,,,,,,,,,,,,
+push,push-service.h,appfw/app_control.h,network/net_connection.h,,,,,,,,,,,,,,,,,,,
+radio,media/radio.h,,,,,,,,,,,,,,,,,,,,,
+recorder,media/recorder.h,media/sound_manager.h,,,,,,,,,,,,,,,,,,,,
+resource-monitor,system/resource-monitor.h,,,,,,,,,,,,,,,,,,,,,
+rpc-port,linux/limits.h,appfw/app_manager.h,rpc-port/rpc-port-parcel.h,rpc-port/rpc-port.h,,,,,,,,,,,,,,,,,,
+runtime-info,system/runtime_info.h,,,,,,,,,,,,,,,,,,,,,
+screen-mirroring,media/scmirroring_sink.h,media/scmirroring_type.h,,,,,,,,,,,,,,,,,,,,
+sdl2,SDL2/SDL.h,vulkan/vulkan.h,sys/stat.h,,,,,,,,,,,,,,,,,,,
+sensor,sensor/sensor.h,,,,,,,,,,,,,,,,,,,,,
+shortcut,shortcut/shortcut_manager.h,,,,,,,,,,,,,,,,,,,,,
+smartcard,smartcard.h,,,,,,,,,,,,,,,,,,,,,
+softap,network/softap.h,,,,,,,,,,,,,,,,,,,,,
+sound-manager,media/sound_manager.h,,,,,,,,,,,,,,,,,,,,,
+sound-pool,media/sound_pool.h,,,,,,,,,,,,,,,,,,,,,
+stc,network/stc.h,,,,,,,,,,,,,,,,,,,,,
+streamrecorder,media/streamrecorder.h,media/media_packet.h,,,,,,,,,,,,,,,,,,,,
+stt,stt.h,appfw/package_manager.h,,,,,,,,,,,,,,,,,,,,
+sync-manager,account.h,account-types.h,account-error.h,sync_adapter.h,sync_manager.h,sync-error.h,,,,,,,,,,,,,,,,
+system-info,system/system_info.h,,,,,,,,,,,,,,,,,,,,,
+telephony,telephony/telephony.h,,,,,,,,,,,,,,,,,,,,,
+thumbnail-util,media/thumbnail_util.h,,,,,,,,,,,,,,,,,,,,,
+tone-player,media/sound_manager.h,media/tone_player.h,,,,,,,,,,,,,,,,,,,,
+trace,trace.h,,,,,,,,,,,,,,,,,,,,,
+tts,tts.h,ecore-1/Ecore.h,ttse.h,,,,,,,,,,,,,,,,,,,
+tzsh-quickpanel,tzsh/tzsh_quickpanel.h,,,,,,,,,,,,,,,,,,,,,
+ua ,user-awareness.h,,,,,,,,,,,,,,,,,,,,,
+url-download,web/download.h,appfw/app_control.h,,,,,,,,,,,,,,,,,,,,
+usb-host,usb_host.h,linux/usb/ch9.h,,,,,,,,,,,,,,,,,,,,
+voice-control,voice_control.h,voice_control_command.h,voice_control_common.h,vce.h,,,,,,,,,,,,,,,,,,
+voice-control-elm,voice_control_elm.h,,,,,,,,,,,,,,,,,,,,,
+vpn,sys/types.h,sys/socket.h,vpn_service.h,,,,,,,,,,,,,,,,,,,
+watchface-complication,appcore-agent/service_app.h,,,,,,,,,,,,,,,,,,,,,
+webkit2,eina-1/Eina.h,edje-1/Edje.h,ecore-evas-1/Ecore_Evas.h,ecore-1/Ecore.h,elementary-1/Elementary.h,chromium-ewk/EWebKit.h,,,,,,,,,,,,,,,,
+webrtc-display,media/webrtc.h,,,,,,,,,,,,,,,,,,,,,
+widget_service,widget_service/widget_errno.h,widget_service/widget_service.h,widget_viewer_evas/widget_viewer_evas.h,,,,,,,,,,,,,,,,,,,
+widget_viewer_evas,widget_service/widget_errno.h,widget_service/widget_service.h,widget_viewer_evas/widget_viewer_evas.h,,,,,,,,,,,,,,,,,,,
+wifi-direct,wifi-direct/wifi-direct.h,,,,,,,,,,,,,,,,,,,,,
+wifi-manager,network/wifi-manager.h,,,,,,,,,,,,,,,,,,,,,
+yaca,linux/stddef.h,yaca/yaca_crypto.h,yaca/yaca_error.h,yaca/yaca_key.h,yaca/yaca_sign.h,yaca/yaca_encrypt.h,yaca/yaca_digest.h,yaca/yaca_simple.h,yaca/yaca_types.h,yaca/yaca_rsa.h,yaca/yaca_seal.h,yaca/yaca_sign.h,yaca/yaca_simple.h,,,,,,,,,
--- /dev/null
+# Version 0.1
+
+## Please follow this guide for TC Assistant tool execution.
+
+# Pre-requisites -
+
+ Python 3.6 or above, PIP 21.3.1 or above version, Tkinter
+
+# Command to launch the tool -
+ Python tct_assistance.py
+
+
+1. Packages which needs to be installed before running the application -
+
+ 1. PyTorch - sudo pip3 install torch
+ 2. Numpy - sudo pip3 install numpy
+ 3. Pandas - sudo pip3 install pandas
+ 4. Regular Expression - sudo pip3 install regex
+ 5. Transformers - sudo pip3 install transformers==3.1.0
+ 6. Matplotlib - sudo pip3 install matplotlib
+ 7. Scikit Learn - sudo pip3 install scikit-learn
+ 8. Json - sudo pip3 install jsonlib
+ 9. TextDistance - sudo pip3 install textdistance
+ 10. PIL - sudo pip3 install pillow(after installing pillow run the below command sudo apt-get install python3-pil python3-pil.imagetk)
+
+2. If tool gives error in the first response itself then run command 'python trainedmodel.py'. This command trains model again with our dataset
+
+3. Suppost has been provide to add TCs in existing module and create a complete new module
+
+4. Before starting the tool make sure that permission has been given to the whole folder and module entry is there in Module_Header_Mapping.csv file for a existing module. Entry should be there in format of: Module_Name, Folder_Name/Header_File1.h, Folder_Name/Header_File2.h, ....
+
+ **For example**, if we need to create test cases for data-control module then make entry in csv file as below -:
+
+ data-control, appfw/data_control.h, appfw/data_control_provider.h
+
+5. Latest rootstrap need to installed in user's pc as this tool searches for entered header files inside latest rootstrap.
+
+ **For example:**
+
+ If user has entered webrtc module then tool will search for its header file media/webrtc.h in tizeniot-8.0-device.core.private.20230823_131527 rootstrap.
+ > Header file should be present at path /home/sri/tizen-studio/platforms/tizen-8.0/tizeniot/rootstraps/tizeniot-8.0-device.core.private.20230823_131527/usr/include, otherwise tool will run into error.
+
+6. API's for which you need to create TCs, those api's declaration need to be present in the header files mentioned in Module_Header_Mapping.csv file
+
+
+
+
+# Steps to use the tool -:
+
+1. At first tool provides two options whether to write tcs for new module or existing module. Type "new" for new module case and "existing" for existing module case.
+
+2. **Existing module case** : In next step we need to enter Module name in the format of Module name: webrtc
+ Make sure module name header files entry is there in csv file
+
+3. **New module case** : In next step we need to enter Module name in the format of Module name: webrtc
+ After entering module name, you need to enter header file which is required for this module in the format of
+
+ Header File: Header_File_1.h Header_File_2.h
+
+4. In next step you need to enter api names for which you need to create TCs.
+
+ **For example :**
+
+ API Names: camera_attr_get_focus_level_range => for single api
+ API Names: camera_create camera_attr_get_focus_level_range camera_attr_set_focus_level => for multiple api
+
+5. In the next step you will be asked to enter feature for the module in the format of
+
+ feature name:http://tizen.org/feature/camera
+
+6. Next you will be asked to enter pre/post apis for all the entered API's. Suppose user has entered 5 target api's then you need to enter pre/post apis for every target api.
+
+ **For example -:**
+
+ Pre: camera_attr_get_focus_level_range camera_attr_set_focus_level Post: camera_create
+
+ If there are multiple pre/ post apis then yoy need to enter them space separated. And there is no pre/post api for a particular target api then you need to simply write pre: and press enter
+
+7. After entering pre/post apis for all the APIs, you will be asked to select whether you want to increase the coverage by automatically including negative tcs. If user enter "Yes" the negative tcs will be automatically included.
+
+8. After entering all the above information you will be asked to enter file name among all the listed files in which you need to write your created TCs.
+
+ **For example -:**
+
+ FILE name: utc-alarm.c
+
+ Here if you write name of file which is already prsent in utc then tool will append TC in same file, if not present then tool will create new file in the same folder.
+
+9. After Tcs are successfully created. You will be asked whether to build module or not. Type "Yes" if you want to build the TCs
+
+10. If build is successfull the type "Yes" to install TCs and launch tct manager for further execution
+
+
+
+
+
+
+
+
--- /dev/null
+from latest_rootstrap import *\r
+from read_csv import *\r
+import re\r
+from validate_api import *\r
+\r
+\r
+def get_latest_rootstrap():\r
+ latest_rootstrap_dir = latest_rootstrap()\r
+ DIR = latest_rootstrap_dir + "//" + "usr/include"\r
+ return DIR\r
+\r
+def get_api_list():\r
+ list_all_apis = list_apis()\r
+ return list_all_apis\r
+\r
+def get_api_parameters(API_NAMES):\r
+ params_dict = {}\r
+ api_list_all = get_api_list()\r
+ initial_val = 0\r
+ for apis in api_list_all:\r
+ all_params = []\r
+ apis.strip()\r
+ apis = apis.replace(';', ' ')\r
+ pos_left = apis.index('(')\r
+ pos_right = apis.index(')')\r
+ list_pos_comma = [i for i in range(len(apis)) if apis.startswith(',', i)]\r
+ list_pos_comma.insert(0, pos_left)\r
+ list_pos_comma.append(pos_right)\r
+ if len(list_pos_comma) > 0:\r
+ for i in range(len(list_pos_comma)-1):\r
+ all_params.append(apis[list_pos_comma[i]+1:list_pos_comma[i+1]].strip())\r
+ else:\r
+ all_params.append(apis[pos_left:pos_right].strip())\r
+ if initial_val < len(API_NAMES):\r
+ params_dict[API_NAMES[initial_val]] = all_params\r
+ initial_val = initial_val + 1\r
+ return params_dict\r
+\r
+\r
+def get_api_return_values():\r
+ return_type_dict = {}\r
+ api_return_all = get_api_list()\r
+ for apis_ret_value in api_return_all:\r
+ if apis_ret_value != '':\r
+ apis_ret_value.strip()\r
+ apis_ret_value = apis_ret_value.replace('(', ' ').replace(')', ' ').replace(';', ' ')\r
+ apis_ret_value = apis_ret_value.split()\r
+ return_type_dict[apis_ret_value[1]] = apis_ret_value[0]\r
+ return return_type_dict\r
+\r
--- /dev/null
+import re
+
+def get_build_parameters(message):
+ message = message.lower()
+ build_params = []
+ indexes_semicolon = [_.start() for _ in re.finditer(":", message)]
+ indexes_comma = [_.start() for _ in re.finditer(",", message)]
+ indexes_profile = [_.start() for _ in re.finditer("profile", message)]
+
+ if(indexes_comma):
+ build_params.append((message[indexes_semicolon[0]+1:indexes_comma[0]]).strip())
+ build_params.append((message[indexes_semicolon[1]+1:]).strip())
+ else:
+ build_params.append((message[indexes_semicolon[0]+1:indexes_profile[0]]).strip())
+ build_params.append((message[indexes_semicolon[1]+1:]).strip())
+
+ return build_params
+
+
--- /dev/null
+from validate_api import *
+from list_module_files import *
+from get_current_dir_path import *
+import re
+
+
+def check_if_tc_already_exists(MODULE_NAME, HEADER_FILE_NAME, FILE_NAME_C, API_NAME):
+ cb_declaration=""
+ CURRENT_PATH = get_current_dir_path()
+ DIR = CURRENT_PATH + "src/utc/"
+ ROOTSTRAPS_DIR = get_latest_rootstrap() + "/"
+ if MODULE_NAME == 'bluetooth':
+ MODULE_NAME = 'network'
+ MODULE_NAME = get_api_header_file_contained_folder_name(ROOTSTRAPS_DIR, HEADER_FILE_NAME)
+ with open(DIR + "/" + MODULE_NAME + "/" + FILE_NAME_C,"r") as file_one:
+ for line in file_one:
+ line = line.rstrip()
+ if re.search(r"\b{}\b".format(API_NAME),line):
+ return True
+ return False
+
+
+def check_if_tc_aleady_exists_in_all_c_files(TC_WRITE_DIR, MODULE_NAME):
+ all_c_files_list = get_all_files_of_module(TC_WRITE_DIR, MODULE_NAME)
+ # print(all_c_files_list)
+
+
+def check_if_api_exists_grep(MODULE_NAME, API_SEARCH, TC_WRITE_DIR):
+ CURRENT_PATH = get_current_dir_path()
+ command = f"grep -inr --include \*.c -R -i -w {API_SEARCH} {CURRENT_PATH}src/utc/{MODULE_NAME}/ &"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
+ proc_stdout = process.communicate()[0]
+ proc_stdout_result = proc_stdout.decode()
+ if proc_stdout_result:
+ return True
+ else:
+ return False
+
+
+
--- /dev/null
+{\r
+ "intents": [\r
+ {\r
+ "tag": "request",\r
+ "patterns": ["Hi, I have an ACR request", "I want you to add new utc"],\r
+ "responses": [\r
+ "Is that request for a new module or for additional API coverage?"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "existingmodule",\r
+ "patterns": [\r
+ "Its existing module, need to add new TCs",\r
+ "webrtc module request to add two new TCs"\r
+ ],\r
+ "responses": ["Please provide module name in the form of \nModule name: \n\n[ To navigate, please type 'Back' ]"]\r
+ },\r
+ {\r
+ "tag": "modulename",\r
+ "patterns": ["Module name:", "module name is dlog"],\r
+ "responses": [\r
+ "Please provide API information in the format of \nAPI names: API_NAME_1 API_NAME_2 \n\n[ To navigate, please type 'Back' ]"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "apiinfo",\r
+ "patterns": [\r
+ "API names are as follows",\r
+ "API pre-post conditions are as follows"\r
+ ],\r
+ "responses": ["Thankyou, found in rootstrap", "Not present in rootstrap"]\r
+ },\r
+ {\r
+ "tag": "prepostinfo",\r
+ "patterns": [\r
+ "Pre-condition API names are as follows",\r
+ "API pre-post conditions are as follows"\r
+ ],\r
+ "responses": ["Thankyou, for providing details for pre/post APIs.\nSorry, but there is some internal error, please launch tool again."]\r
+ },\r
+ {\r
+ "tag": "tcwritelocation",\r
+ "patterns": [\r
+ "FILE name: utc-media-webrtc.c",\r
+ "FILE name:"\r
+ ],\r
+ "responses": ["Thankyou, for providing input."]\r
+ },\r
+ {\r
+ "tag": "newmodule",\r
+ "patterns": [\r
+ "Its request for new module addition",\r
+ "New module utc needs to be added"\r
+ ],\r
+ "responses": [\r
+ "Please provide module name in the form of \nModule name: \n\n[ To navigate, please type 'Back' ]"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "negativetc",\r
+ "patterns": [\r
+ "Do you want to add negative TCs? \nType Yes or No",\r
+ "Add a negative TC \nType Yes or No"\r
+ ],\r
+ "responses": [\r
+ "Seems there is some wrong input. Please try again. Thanks"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "tizenversion",\r
+ "patterns": ["Tizen 6.0", "Tizen 6.5", "Tizen 7.0", "all"],\r
+ "responses": ["Please provide module name in the form of \nModule name: \n\n[ To navigate, please type 'Back' ]"]\r
+ },\r
+ {\r
+ "tag": "modulenotfound",\r
+ "patterns": ["No"],\r
+ "responses": [\r
+ "Module not found \nPlease type the module name again in the form of \nModule name:",\r
+ "Please recheck the module name. Entered module name doesn't exists. \nPlease type the module name again in the form of \nModule name: \n\n[ To navigate, please type 'Back' ]"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "buildwrittentc",\r
+ "patterns": ["No"],\r
+ "responses": [\r
+ "Thanks, Goodbye !!",\r
+ "Thank You for providing input. Goodbye !"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "installwrittentc",\r
+ "patterns": ["No"],\r
+ "responses": [\r
+ "Thanks, Goodbye !!",\r
+ "Thank You for providing input. Goodbye !"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "buildparameters",\r
+ "patterns": ["ARCH: armv7l, Profile: mobile", "ARCH: x86, Profile: wearable"],\r
+ "responses": [\r
+ "Please provide architecture and profile for which you want to build TC in the format of \nARCH: ARCHITECTURE_NAME, PROFILE: PROFILE_NAME"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "launchtctmgr",\r
+ "patterns": ["Yes, I want to execute the TCs"],\r
+ "responses": [\r
+ "Installing the tpk ..."\r
+ ]\r
+ },\r
+ {\r
+ "tag": "greetings",\r
+ "patterns": ["Hi", "Hello", "Hey"],\r
+ "responses": [\r
+ "Hello, Is this request for new module or for existing module?"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "goback",\r
+ "patterns": ["Back"],\r
+ "responses": [\r
+ "Going Back"\r
+ ]\r
+ },\r
+ {\r
+ "tag": "none",\r
+ "patterns": [\r
+ ""\r
+ ],\r
+ "responses": [\r
+ "Error!! \nInvalid Input. Please try writing again"\r
+ ]\r
+\r
+ },\r
+ {\r
+ "tag": "featureinfo",\r
+ "patterns": ["feature"],\r
+ "responses": [\r
+ "Do you want to add Pre and Post condition APIs for the above APIs?\n(Yes or No)\n\n[ To navigate, please type 'Back' ]"\r
+ ]\r
+ }\r
+ ]\r
+}\r
--- /dev/null
+from latest_rootstrap import *
+from read_csv import *
+import re
+from header_file_location import *
+from validate_api import *
+
+def check_api_header_file_location(HEADER_FILE_NAME, API_SEARCH):
+ DIR = get_latest_rootstrap()
+ with open(DIR + "//" + HEADER_FILE_NAME,"r") as file_one:
+ for line_no, line in enumerate(file_one):
+ if line.find("int" + " " + API_SEARCH + "(") != -1:
+ return True
+ return False
+
+def search_enum_from_param(enumInParam, ROOTSTRAPS_DIR, header_file):
+ enums_array = []
+ with open(ROOTSTRAPS_DIR + "//" + header_file,"r") as file_one:
+ find = False
+ inside_enum = False
+ for line_no, line in enumerate(file_one):
+ if line.find("typedef enum") != -1:
+ inside_enum = True
+ if inside_enum == True:
+ enums_array.append(line.strip())
+
+ if line.find("}") != -1 and line.find(enumInParam + ";") == -1 and len(line)<80:
+ inside_enum = False
+ enums_array = []
+
+ if line.find(enumInParam + ";") != -1 and line.find("}") != -1:
+ find = True
+ break
+
+ if find == True:
+ return enums_array
+
+ return enums_array
+
+def enum_finder(API, ROOTSTRAPS_DIR, header_files_dict, params):
+ enums = []
+ enums_param_value_dict = {}
+ header_file = ""
+ enum = ""
+ flag=False
+ for param in params:
+ enumInParam = param.split(" ")[0]
+ for header_file in header_files_dict:
+ enums = search_enum_from_param(enumInParam, ROOTSTRAPS_DIR, header_file)
+ if len(enums) != 0:
+ flag=True
+ break
+ if len(enums) != 0:
+ for ele in enums:
+ ele = ele.strip()
+ if ele[:2] == '/*' or 'typedef' in ele:
+ continue
+ else:
+ enum_value = ele.split(",")[0]
+ break
+ enums_param_value_dict[enumInParam] = enum_value
+ for key,val in enums_param_value_dict.items():
+ if "=" in val:
+ enums_param_value_dict[key]=((val.split('=')[0])).strip()
+ return enums_param_value_dict
+
--- /dev/null
+import subprocess
+import re
+from get_current_dir_path import *
+
+# Function opens tct-mgr tool for to run tc
+
+def open_tct_mgr():
+ command = f"tct-mgr"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
+
+
+def tpk_build_install(PROCESS, TYPE_OF_TCs, MODULE_NAME, DEVICE_TYPE, ARCHITECTURE_TYPE):
+ lst = []
+ CURRENT_PATH = get_current_dir_path()
+ command = f"echo 'Samsung@123' | sudo -S ./tpkbuild {PROCESS} {TYPE_OF_TCs} {MODULE_NAME} {DEVICE_TYPE} {ARCHITECTURE_TYPE} &"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True, cwd=CURRENT_PATH)
+ proc_stdout = process.communicate(input='Samsung@123')[0]
+ for line in proc_stdout.decode().split('\n'):
+ lst.append(line)
+ return "\n".join(lst)
+
+
--- /dev/null
+from validate_api import *
+import re
+
+
+def cb_function_declaration(MODULE_NAME, HEADER_FILE_NAME,CB_FUNC):
+ cb_declaration=""
+ DIR = get_latest_rootstrap()
+ if MODULE_NAME == 'bluetooth':
+ MODULE_NAME = 'network'
+
+
+ flag=False
+ flag2=False
+ with open(DIR + "/" + HEADER_FILE_NAME,"r") as file_one:
+ for line in file_one:
+ line =line.strip()
+ if line.find('typedef')!=-1 and line.find(CB_FUNC) != -1:
+ flag= True
+ if flag:
+ for word in line:
+ cb_declaration = cb_declaration + word
+ if word == '\n':
+ continue
+ if word == ";":
+ flag2 = True
+ break
+ if flag2:
+ break
+ cb_declaration=cb_declaration.replace('typedef','',1)
+ cb_declaration=cb_declaration.replace('(',' callback_',1)
+ cb_declaration=cb_declaration.replace('*','',1)
+ cb_declaration=cb_declaration.replace(')','',1)
+ cb_declaration=cb_declaration.replace(';','',1)
+ cb_declaration=cb_declaration.replace('\n','')
+
+ if flag:
+ to_remove_str = cb_declaration[cb_declaration.index(')')+1:]
+ cb_declaration = cb_declaration.replace(to_remove_str, '')
+ cb_declaration='static'+cb_declaration+'\n{ \n //Please enter your code here\n}\n'
+ return cb_declaration
--- /dev/null
+import subprocess
+import re
+
+def get_current_dir_path():
+ lst = []
+ command = f"pwd"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
+ proc_stdout = process.communicate(input='Samsung@123')[0]
+ for line in proc_stdout.decode().split('\n'):
+ lst.append(line)
+ path = "\n".join(lst)
+ pos = path.find("tool/")
+ return path[:pos]
+
+# print(get_current_dir_path())
+
+
+def get_current_dir_path_for_image():
+ lst = []
+ command = f"pwd"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
+ proc_stdout = process.communicate(input='Samsung@123')[0]
+ for line in proc_stdout.decode().split('\n'):
+ lst.append(line)
+ path = "".join(lst)
+ # pos = path.find("tool/")
+ return path
+
+# print(get_current_dir_path_for_image())
\ No newline at end of file
--- /dev/null
+from validate_api import *
+from header_file_location import *
+from api_information import *
+from header_file_parse import *
+import re
+
+
+#extract return value for API for INVALID_PARAMETERS
+def get_retval_of_invalid_params(MODULE_NAME, HEADER_FILE_NAME, API_NAME):
+ api_info=""
+ DIR = get_latest_rootstrap()
+ if MODULE_NAME == 'bluetooth':
+ MODULE_NAME = 'network'
+ line_no = 0
+ with open(DIR + "/" + HEADER_FILE_NAME,"r") as file_one:
+ for line in file_one:
+ line_no += 1
+ if line.find(API_NAME) != -1:
+ # break
+ with open(DIR + "/" + HEADER_FILE_NAME,"r") as file_one:
+ for line in file_one:
+ line_no += 1
+ if line.find("@retval") != -1 and line.find("INVALID_PARAMETER") != -1:
+ api_info=api_info+line
+ break
+ api_info=api_info.split()
+ if len(api_info)>0:
+ for st in api_info:
+ if st.find("#")!=-1:
+ st=st[1:]
+ break
+ return st
+ else:
+ return ""
+
--- /dev/null
+# this function uses grep command to get header file location among all the folders which are present in the rootsraps.
+
+import subprocess
+
+
+def get_api_header_file_location(ROOTSTRAPS_DIR, module_header_name_search):
+ lst = []
+ command = f"find {ROOTSTRAPS_DIR} | grep -w {module_header_name_search}"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
+ proc_stdout = process.communicate()[0].strip()
+ for line in proc_stdout.decode().split('\n'):
+ lst.append(line)
+ return lst[0]
+
+
+def get_api_header_file_contained_folder_name(ROOTSTRAPS_DIR, module_header_name_search):
+ res = get_api_header_file_location(ROOTSTRAPS_DIR, module_header_name_search)
+ res = res.partition(ROOTSTRAPS_DIR)[-1]
+ pos = res.rfind('/')
+ if pos == -1:
+ return ""
+ return res[:pos]
+
--- /dev/null
+from validate_api import *
+from header_file_location import *
+from api_information import *
+import re
+
+def input_output_text_extract(MODULE_NAME, HEADER_FILE_NAME, API_SEARCH):
+ inp_out_params = []
+ api_info = []
+ DIR = get_latest_rootstrap()
+ if MODULE_NAME == 'bluetooth':
+ MODULE_NAME = 'network'
+
+ line_no = 0
+ flag = False
+ with open(DIR + "/" + HEADER_FILE_NAME,"r") as file_one:
+ for line in file_one:
+ line_no += 1
+ if line.find("int" + " " + API_SEARCH) != -1:
+ api_info.append(line)
+ flag = True
+ break
+
+ file_one = open(DIR + "/" + "/" + HEADER_FILE_NAME,"r")
+ lines=file_one.readlines()
+ if flag == True:
+ for i in range(line_no-2, 0, -1):
+ inp_out_params.append(lines[i])
+ if lines[i].find("@brief") != -1:
+ break
+
+ inp_out_params.reverse()
+ return inp_out_params
+
+
+
+def input_output_params_extract(MODULE_NAME, HEADER_FILE_NAME, API_SEARCH, inp_out_params_list):
+ text = input_output_text_extract(MODULE_NAME, HEADER_FILE_NAME, API_SEARCH)
+ for ele in text:
+ if "@param[in" in ele:
+ if API_SEARCH in inp_out_params_list:
+ inp_out_params_list[API_SEARCH].append({ele.split()[2]: "in"})
+ else:
+ inp_out_params_list[API_SEARCH] = [{ele.split()[2]: "in"}]
+ elif "@param [in" in ele:
+ if API_SEARCH in inp_out_params_list:
+ inp_out_params_list[API_SEARCH].append({ele.split()[3]: "in"})
+ else:
+ inp_out_params_list[API_SEARCH] = [{ele.split()[3]: "in"}]
+ elif "@param[out]" in ele:
+ if API_SEARCH in inp_out_params_list:
+ inp_out_params_list[API_SEARCH].append({ele.split()[2]: "out"})
+ else:
+ inp_out_params_list[API_SEARCH] = [{ele.split()[2]: "out"}]
+ elif "@param [out]" in ele:
+ if API_SEARCH in inp_out_params_list:
+ inp_out_params_list[API_SEARCH].append({ele.split()[3]: "out"})
+ else:
+ inp_out_params_list[API_SEARCH] = [{ele.split()[3]: "out"}]
+
+ return inp_out_params_list
+
+def api_description_extract(MODULE_NAME, HEADER_FILE_NAME, API_SEARCH):
+ text = input_output_text_extract(MODULE_NAME, HEADER_FILE_NAME, API_SEARCH)
+ flag = False
+ desc = ""
+ for ele in text:
+ if "@brief" in ele and flag == False:
+ word = "@brief"
+ start_index = ele.find(word)
+ end_index = start_index + len(word)
+ desc = desc + ele[end_index:]
+ flag = True
+ continue
+ if flag == True:
+ if ("@since" not in ele and "@detail" not in ele and "@details" not in ele):
+ ele = ele.replace('*', '')
+ desc = desc + ele
+ if flag == True and "@since" in ele or "@detail" in ele or "@details" in ele:
+ break
+
+ desc = desc.replace('\r', '').replace('\n', '')
+
+ return desc
+
--- /dev/null
+from header_file_parse import *
+
+inp_out_params_list = {}
+
+
+def check_if_param_is_in_or_out(inp_out_params_list):
+ combined_list_params_type = []
+ for ele in inp_out_params_list:
+ for i in inp_out_params_list[ele]:
+ combined_list_params_type.append(i)
+
+ final_params_list_without_duplicates = {}
+ for ele in combined_list_params_type:
+ for dict_key in ele:
+ if dict_key in final_params_list_without_duplicates:
+ if final_params_list_without_duplicates[dict_key] == "in" and ele[dict_key] == "out":
+ final_params_list_without_duplicates[dict_key] = "out"
+ else:
+ final_params_list_without_duplicates[dict_key] = ele[dict_key]
+
+
+ return final_params_list_without_duplicates
--- /dev/null
+import os\r
+\r
+def latest_rootstrap():\r
+ rootstrap_folder_names = []\r
+ rootstrap_latest_folder_names = []\r
+ ROOTSTRAP_DIR = r"/home/sri/tizen-studio/platforms/tizen-8.0/tizeniot/rootstraps"\r
+ for entry_name in os.listdir(ROOTSTRAP_DIR):\r
+ entry_path = os.path.join(ROOTSTRAP_DIR, entry_name)\r
+ if os.path.isdir(entry_path):\r
+ rootstrap_folder_names.append(entry_name)\r
+\r
+ rootstrap_dates = []\r
+ for folder_name in rootstrap_folder_names:\r
+ if len(folder_name) < 25:\r
+ continue\r
+ else:\r
+ folder_name = folder_name.split('.',4)[4]\r
+ rootstrap_dates.append(int(folder_name[:8]))\r
+\r
+ latest_date_rootstrap = str(max(rootstrap_dates))\r
+\r
+ for find_latest in rootstrap_folder_names:\r
+ if latest_date_rootstrap in find_latest:\r
+ rootstrap_latest_folder_names.append(find_latest)\r
+ min_len = 100\r
+ for ele in rootstrap_latest_folder_names:\r
+ if len(ele) < min_len:\r
+ min_len = len(ele) \r
+ res = ele\r
+ find_latest = ROOTSTRAP_DIR + "//" + res\r
+ return find_latest\r
+\r
--- /dev/null
+from validate_api import *
+import re
+
+def extract_all_apis_text(MODULE_NAME, HEADER_FILE_NAME):
+ api_info = []
+ DIR = get_latest_rootstrap()
+ if MODULE_NAME == 'bluetooth':
+ MODULE_NAME = 'network'
+
+ with open(DIR + "/" + HEADER_FILE_NAME,"r") as file_one:
+ for line in file_one:
+ if line.find("int" + " " ) != -1:
+ if "typedef" not in line:
+ api_info.append(line)
+ return api_info
+
+
+def get_all_api_names(MODULE_NAME, HEADER_FILE_NAME):
+ all_apis_list = extract_all_apis_text(MODULE_NAME, HEADER_FILE_NAME)
+ all_apis_list_filtered = []
+ for ele in all_apis_list:
+ if(ele.find('(') > 0 and ele.startswith("int")):
+ pos_bracket = ele.index('(')
+ ele = ele[4:pos_bracket]
+ all_apis_list_filtered.append(ele)
+ return "\n".join(all_apis_list_filtered)
+
--- /dev/null
+
+
+import subprocess
+
+# Function uses ls command to list all the available files in the module and display it to the user.
+def get_all_files_of_module(TC_WRITE_DIR, module_name):
+ lst = []
+ TC_WRITE_DIR = TC_WRITE_DIR + '/' + module_name
+ command = f"ls {TC_WRITE_DIR}"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
+ proc_stdout = process.communicate()[0].strip()
+ for line in proc_stdout.decode().split('\n'):
+ if line[-2:] == ".c" and line[:3] != "tct":
+ lst.append(line)
+ return '\n'.join(lst)
+
+
+
+# Function uses ls command to list all the available header files in the module
+def get_all_header_files_of_module(TC_WRITE_DIR, module_name):
+ lst = []
+ TC_WRITE_DIR = TC_WRITE_DIR + '/' + module_name
+ command = f"ls {TC_WRITE_DIR}"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
+ proc_stdout = process.communicate()[0].strip()
+ for line in proc_stdout.decode().split('\n'):
+ if line[-2:] == ".h":
+ lst.append(line)
+
+ return lst
+
+
+# Fucntion checks whether file name already exists in module or not
+def check_if_file_name_exists(FILE_NAME, TC_WRITE_DIR ,module_name):
+ file_names_list = get_all_files_of_module(TC_WRITE_DIR, module_name)
+ if FILE_NAME in file_names_list:
+ return True
+ else:
+ return False
+
+
--- /dev/null
+import imp
+import logging
+import logging.handlers
+import datetime
+import inspect
+import traceback
+from inspect import currentframe, getframeinfo
+from logger_init import *
+import sys
+sys.path.append('/usr/local/lib/python3.6/site-packages')
+
+
+def log_create(logger, PRINT_ERR_LOG):
+ excdata = traceback.format_exc().splitlines()
+ excarray = excdata[1:-1] + [excdata[-1]]
+ logger.error(f'{PRINT_ERR_LOG}\n{excarray[0]}\n{excarray[1]}\n{excarray[-1]}')
+
+
+def log_info_save(logger, LOG_INFO_TXT, LOG_INFO_VAL):
+ logger.info(f'{getframeinfo(currentframe()).filename.split("/")[-1]}:{inspect.currentframe().f_code.co_name}({getframeinfo(currentframe()).lineno}) - {LOG_INFO_TXT}: {LOG_INFO_VAL}')
+
+def log_info_save_processing(logger, LOG_INFO_TXT):
+ logger.info(f'{getframeinfo(currentframe()).filename.split("/")[-1]}:{inspect.currentframe().f_code.co_name}({getframeinfo(currentframe()).lineno}) - {LOG_INFO_TXT}')
--- /dev/null
+import imp
+import logging
+import logging.handlers
+import datetime
+import inspect
+import traceback
+import os
+from inspect import currentframe, getframeinfo
+
+
+
+def logger_init():
+
+ dt = datetime.datetime.now()
+
+ isFolderPresent = os.path.isdir('LOG')
+
+ if not isFolderPresent:
+
+ os.makedirs('LOG')
+
+ filename = 'LOG/log_file_'+str(dt.year)+str(dt.month)+str(dt.day)+'_'+str(dt.hour)+str(dt.minute)+str(dt.second)+'.log'
+
+ logger = logging.getLogger('TCT_Assistance_tool')
+
+ logger.setLevel(logging.DEBUG)
+
+ #should_roll_over = os.path.isfile(filename)
+ handler = logging.FileHandler(filename, mode='a')
+ #if should_roll_over: # log already exists, roll over!
+ # handler.doRollover()
+
+ handler.setLevel(logging.INFO)
+
+ formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%d/%b/%Y %I:%M:%S %p')
+
+ handler.setFormatter(formatter)
+
+ logger.addHandler(handler)
+
+ logger = logging.getLogger('TCT_Assistance_tool.Chatbot')
+
+ logger.info(f'{getframeinfo(currentframe()).filename.split("/")[-1]}:{inspect.currentframe().f_code.co_name}({getframeinfo(currentframe()).lineno}) - Application started')
+
+
+ logger.info(f'{getframeinfo(currentframe()).filename.split("/")[-1]}:{inspect.currentframe().f_code.co_name}({getframeinfo(currentframe()).lineno}) - Reading dataset file...')
+ return logger
--- /dev/null
+from get_current_dir_path import *
+import subprocess
+
+def provide_permission(MODULE_NAME, CURRENT_PATH):
+ CURRENT_PATH = CURRENT_PATH + "/src/utc"
+ command = f"echo 'Samsung@123' | sudo -S chmod -R 777 {MODULE_NAME} &"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True, cwd=CURRENT_PATH)
+ process.communicate(input='Samsung@123')[0]
+
+
+
+def new_module_addition(MODULE_NAME, TYPE_OF_TCs):
+ lst = []
+ CURRENT_PATH = get_current_dir_path()
+ command = f"echo 'Samsung@123' | sudo -S ./tpkbuild addmod {TYPE_OF_TCs} {MODULE_NAME} &"
+ process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True, cwd=CURRENT_PATH)
+ proc_stdout = process.communicate(input='Samsung@123')[0]
+ for line in proc_stdout.decode().split('\n'):
+ lst.append(line)
+ provide_permission(MODULE_NAME, CURRENT_PATH)
+ return "\n".join(lst)
+
+def clean_header_file(file_path, MODULE_NAME, h_file):
+ with open(file_path + "/"+ MODULE_NAME + "/" + "tct-" + MODULE_NAME + "-core_" + h_file + ".h", 'r') as fr:
+ lines = fr.readlines()
+ ptr = 0
+ find_line = False
+ search_line_tc_array = "testcase tc_array[]"
+ search_line_extern = "extern int"
+ deleting_line_pos = 0
+
+ with open(file_path + "/" + MODULE_NAME + "/" + "tct-" + MODULE_NAME + "-core_" + h_file + ".h", 'w') as fw:
+ for line in lines:
+ if line.find(search_line_extern) != -1:
+ continue
+ if line.find(search_line_tc_array) != -1:
+ find_line = True
+ deleting_line_pos = ptr + 3
+ fw.write(line)
+ elif find_line == True and ptr < deleting_line_pos:
+ #Not including this line
+ ptr += 1
+ continue
+ else:
+ fw.write(line)
+ ptr += 1
+
+def add_header_line(file_path, MODULE_NAME, HEADER_FILE_NAMES_TO_UPDATE):
+ #for .c file
+ HEADER_FILE_DICT1=[]
+ for HEADER_FILE_NAME in HEADER_FILE_NAMES_TO_UPDATE:
+ if "/" in HEADER_FILE_NAME:
+ POS_OF_SLASH = HEADER_FILE_NAME.index("/")
+ HEADER_FILE_NAME_WITHOUT_SLASH = HEADER_FILE_NAME[POS_OF_SLASH+1:]
+ HEADER_FILE_DICT1.append(HEADER_FILE_NAME_WITHOUT_SLASH)
+ else:
+ HEADER_FILE_DICT1.append(HEADER_FILE_NAME)
+
+ tc_init2 = (
+ f'#include <{HEADER_FILE_NAME_WITHOUT_SLASH}>\n' for HEADER_FILE_NAME_WITHOUT_SLASH in HEADER_FILE_DICT1
+ )
+
+ tc_init2=''.join(tc_init2)
+
+ with open(file_path + "/" + MODULE_NAME + "/" + "utc-" + MODULE_NAME + ".c", 'r') as fr:
+ lines = fr.readlines()
+ search_line = "#include"
+ found = False
+
+ with open(file_path + "/" + MODULE_NAME + "/" + "utc-" + MODULE_NAME + ".c", 'w') as fw:
+ for line in lines:
+ if line.find(search_line) != -1 and found == False:
+ found = True
+ fw.write(line)
+ fw.write(tc_init2)
+ else:
+ fw.write(line)
+
+def clean_existing_code(file_path, MODULE_NAME):
+ #for .c file
+ with open(file_path + "/" + MODULE_NAME + "/" + "utc-" + MODULE_NAME + ".c", 'r') as fr:
+ lines = fr.readlines()
+ ptr = 0
+ find_cleanup_line = False
+ search_line = "void utc_" + MODULE_NAME + "_cleanup(void)"
+ deleting_line_pos = 0
+
+ with open(file_path + "/" + MODULE_NAME + "/" + "utc-" + MODULE_NAME + ".c", 'w') as fw:
+ for line in lines:
+ if line.find(search_line) != -1:
+ find_cleanup_line = True
+ deleting_line_pos = ptr + 3
+ fw.write(line)
+ elif find_cleanup_line == True and ptr > deleting_line_pos:
+ #Not including this line
+ ptr += 1
+ continue
+ else:
+ fw.write(line)
+ ptr += 1
+
+ #for .h file
+ header_files = ["mobile", "tizeniot", "tv", "wearable"]
+
+ for h_file in header_files:
+ clean_header_file(file_path, MODULE_NAME, h_file)
+
--- /dev/null
+,Text,label
+0,add utc for webrtc apis,existingmodule
+1,The module is already existing,existingmodule
+2,REQUEST TO CREATE UTC OF NEW MODULE,newmodule
+3,tizen version 6.5,tizenversion
+4,Request is for Tizen version 6.0,tizenversion
+5,REQUEST TO COVER NEW APIS,request
+6,MODULE NAME: BLUETOOTH,modulename
+7,MODULE NAME:,modulename
+8,request to prepare utc,request
+9,file name: utc_media_webrtc.c,tcwritelocation
+10,THIS IS REQUEST TO COVER NEW MODULE APIS,newmodule
+11,FILE NAME: UTC_MEDIA_WEBRTC.C,tcwritelocation
+12,POST:,prepostinfo
+13,HI,greetings
+14,Add utc for webrtc APIs,existingmodule
+15,file name:,tcwritelocation
+16,pre: attach_panel_create,prepostinfo
+17,"its existing module, need to add new tcs",existingmodule
+18,"Its existing module, need to add new TCs",existingmodule
+19,TIZEN VERSION 6.5,tizenversion
+20,hello,greetings
+21,Tizen 6.5,tizenversion
+22,Tizen 7.0,tizenversion
+23,Pre: attach_panel_show Post: attach_panel_destroy,prepostinfo
+24,Request to create UTC of new module,newmodule
+25,"ITS EXISTING MODULE, NEED TO ADD NEW TCS",existingmodule
+26,Tizen version 6.5,tizenversion
+27,the module is already existing,existingmodule
+28,Request is for Tizen version 7.0,tizenversion
+29,FILE NAME:,tcwritelocation
+30,request is for tizen version 6.0,tizenversion
+31,Tizen version 7.0,tizenversion
+32,PRE:,prepostinfo
+33,REQUEST IS FOR TIZEN VERSION 7.0,tizenversion
+34,API names: attach_panel_create attach_panel_destroy,apiinfo
+35,Tizen 6.0,tizenversion
+36,module name:,modulename
+37,request is for tizen version 6.5,tizenversion
+38,tizen version 6.0,tizenversion
+39,Post:,prepostinfo
+40,tizen 6.0,tizenversion
+41,module name: bluetooth,modulename
+42,api names:,apiinfo
+43,NEED TO ADD NEW APIS IN BLUETOOTH MODULE,existingmodule
+44,API names:,apiinfo
+45,Module name: bluetooth,modulename
+46,Module name:,modulename
+47,This is an ACR request,request
+48,This is request to cover new module APIs,newmodule
+49,file name: utc-messaging-email.c,tcwritelocation
+50,REQUEST TO PREPARE UTC,request
+51,pre: attach_panel_show post: attach_panel_destroy,prepostinfo
+52,TIZEN 7.0,tizenversion
+53,Tizen version 6.0,tizenversion
+54,HELLO,greetings
+55,tizen 7.0,tizenversion
+56,TIZEN VERSION 7.0,tizenversion
+57,THIS IS AN ACR REQUEST,request
+58,FILE name: utc-messaging-email.c,tcwritelocation
+59,post: attach_panel_destroy,prepostinfo
+60,Pre: attach_panel_create,prepostinfo
+61,PRE: ATTACH_PANEL_SHOW POST: ATTACH_PANEL_DESTROY,prepostinfo
+62,REQUEST IS FOR TIZEN VERSION 6.5,tizenversion
+63,API NAMES:,apiinfo
+64,REQUEST IS FOR TIZEN VERSION 6.0,tizenversion
+65,Request is for Tizen version 6.5,tizenversion
+66,request to cover new apis,request
+67,TIZEN 6.0,tizenversion
+68,FILE name:,tcwritelocation
+69,TIZEN 6.5,tizenversion
+70,API NAMES: ATTACH_PANEL_CREATE ATTACH_PANEL_DESTROY,apiinfo
+71,POST: ATTACH_PANEL_DESTROY,prepostinfo
+72,tizen version 7.0,tizenversion
+73,Request to cover new APIS,request
+74,hi,greetings
+75,hello,greetings
+76,THE MODULE IS ALREADY EXISTING,existingmodule
+77,request is for tizen version 7.0,tizenversion
+78,Need to add new APIs in bluetooth module,existingmodule
+79,post:,prepostinfo
+80,FILE name: utc_media_webrtc.c,tcwritelocation
+81,Request to prepare UTC,request
+82,FILE NAME: UTC-MESSAGING-EMAIL.C,tcwritelocation
+83,request to create utc of new module,newmodule
+84,ARCH: PROFILE: ,executetc
+85,need to add new apis in bluetooth module,existingmodule
+86,this is request to cover new module apis,newmodule
+87,Pre:,prepostinfo
+88,hi,greetings
+89,Post: attach_panel_destroy,prepostinfo
+90,PRE: ATTACH_PANEL_CREATE,prepostinfo
+91,ARCH: armv7l PROFILE: wearable,executetc
+92,this is an acr request,request
+93,pre:,prepostinfo
+94,ARCH: armv7l PROFILE: tizeniot,executetc
+95,TIZEN VERSION 6.0,tizenversion
+96,ARCH: armv7l PROFILE: mobile,executetc
+97,ADD UTC FOR WEBRTC APIS,existingmodule
+98,api names: attach_panel_create attach_panel_destroy,apiinfo
+99,ARCH: armv7l PROFILE: tv,executetc
+100,tizen 6.5,tizenversion
+101,header info:,headerinfo
+102,Do you want to add negative TCs?,negativetc
+103,Add a negative TC,negativetc
+104,negative TC,negativetc
+105,Header File:dns-sd.h,headerinfo
+106,Back,goback
+107,I want to go back,goback
+108,Feature name:,featureinfo
+109,feature:,featureinfo
+110,New module:,newmodule
+111,newmodule:,newmodule
+112,Header File:,headerinfo
+113,headerfile:,headerinfo
+114,existing,existingmodule
+115,I want to add negative tc,negativetc
+116,NEW MODULE:webrtc,newmodule
+117,pre:yaca_key_generate,prepostinfo
+118,pre:yaca,prepostinfo
+119,Pre:yaca,prepostinfo
+120,PRE:yaca,prepostinfo
+121,Module name:yaca,modulename
--- /dev/null
+from latest_rootstrap import *\r
+from read_csv import *\r
+from api_information import *\r
+from validate_api import *\r
+import re\r
+\r
+\r
+pre_post_dict = {}\r
+\r
+def get_minimum_index_in_pre_post(prestr, poststr):\r
+ if len(prestr) > 0 and len(poststr) > 0:\r
+ first = prestr[0]\r
+ second = poststr[0]\r
+ if first < second:\r
+ return 'pre_present'\r
+ else:\r
+ return 'post_present'\r
+ elif len(prestr) > 0 and len(poststr) == 0:\r
+ return 'pre_present'\r
+ elif len(poststr) > 0 and len(prestr) == 0:\r
+ return 'post_present'\r
+\r
+\r
+def get_pre_post_api_list_info(API_NAMES, MODULE_NAME, CURR_API_IND, pre_post_api_names):\r
+ pre_post_api_names = pre_post_api_names.lower()\r
+ prestr = ""\r
+ poststr = ""\r
+ preapi = []\r
+ postapi = []\r
+ indexes = [_.start() for _ in re.finditer(":", pre_post_api_names)]\r
+ indexPost = [_.start() for _ in re.finditer("post", pre_post_api_names)]\r
+ indexPre = [_.start() for _ in re.finditer("pre", pre_post_api_names)]\r
+\r
+ ret_val = get_minimum_index_in_pre_post(indexPre, indexPost)\r
+\r
+ if len(indexes) == 2:\r
+ prestr = pre_post_api_names[indexes[0]+1:(indexPost[0])]\r
+ poststr = pre_post_api_names[indexes[1]+1:]\r
+ elif len(indexes) == 1:\r
+ if len(indexPre) == 0 or ret_val == 'post_present':\r
+ poststr = pre_post_api_names[indexes[0]+1:]\r
+ elif len(indexPost) == 0 or ret_val == 'pre_present':\r
+ prestr = pre_post_api_names[indexes[0]+1:]\r
+\r
+ prestr = prestr.split()\r
+ poststr = poststr.split()\r
+\r
+ for i in prestr:\r
+ if '_' in i:\r
+ pos = i.find(":")\r
+ if pos != 0:\r
+ i = i[pos+1:]\r
+ preapi.append(i)\r
+ elif "_" and ":" not in i:\r
+ preapi.append(i)\r
+ elif "_" not in i and ":" in i:\r
+ pos = i.find(":")\r
+ i = i[pos+1:]\r
+ if len(i) > 1:\r
+ preapi.append(i)\r
+\r
+ for i in poststr:\r
+ if '_' in i:\r
+ pos = i.find(":")\r
+ if pos != 0:\r
+ i = i[pos+1:]\r
+ postapi.append(i)\r
+ elif "_" and ":" not in i:\r
+ postapi.append(i)\r
+ elif "_" not in i and ":" in i:\r
+ pos = i.find(":")\r
+ i = i[pos+1:]\r
+ if len(i) > 1:\r
+ postapi.append(i)\r
+\r
+ if 'pre' in preapi:\r
+ preapi.remove('pre')\r
+ if 'pre:' in preapi:\r
+ preapi.remove('pre:')\r
+ if 'post' in preapi:\r
+ preapi.remove('post')\r
+ if 'post:' in preapi:\r
+ preapi.remove('post:')\r
+\r
+ pre_post_dict[API_NAMES] = {}\r
+ pre_post_dict[API_NAMES]['Pre'] = preapi\r
+ pre_post_dict[API_NAMES]['Post'] = postapi \r
+\r
+ return pre_post_dict\r
+\r
--- /dev/null
+home = /usr/local/bin
+include-system-site-packages = false
+version = 3.6.8
--- /dev/null
+import csv\r
+\r
+\r
+def module_files_dict():\r
+ mydict = {}\r
+\r
+ #Open the file in read mode\r
+ with open('Module_Header_Mapping.csv', mode='r') as infile:\r
+ reader = csv.reader(infile, skipinitialspace=True)\r
+ for row in reader:\r
+ temp = row[1:]\r
+ temp1 = []\r
+ for val in temp:\r
+ if not val:\r
+ continue\r
+ temp1.append(val.lower())\r
+ # print(temp1)\r
+ mydict[row[0].lower()] = temp1\r
+ return mydict\r
+# print(module_files_dict())
\ No newline at end of file
--- /dev/null
+import warnings\r
+import sys\r
+if not sys.warnoptions:\r
+ warnings.simplefilter("ignore")\r
+\r
+sys.path.append('/usr/local/lib/python3.6/site-packages')\r
+import json\r
+from torch.optim.lr_scheduler import StepLR\r
+from sklearn.utils.class_weight import compute_class_weight\r
+from transformers import AdamW\r
+from torchinfo import summary\r
+from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\r
+from transformers import DistilBertTokenizer, DistilBertModel\r
+from sklearn.preprocessing import LabelEncoder\r
+from validate_module import *\r
+from validate_api import *\r
+from api_information import *\r
+from template_tc import *\r
+from pre_post_information import *\r
+from logger_init import *\r
+from log_create import *\r
+from list_module_files import *\r
+from update_header_files import *\r
+from execute_tc import *\r
+from build_tc_parameters import *\r
+from list_all_apis import *\r
+from check_if_tc_exists import *\r
+from template_tc_negative import *\r
+from get_current_dir_path import *\r
+from enum_finder import *\r
+from CMakeFileUpdate import *\r
+from new_module_addition import *\r
+from header_file_location import *\r
+import numpy as np\r
+import pandas as pd\r
+import re\r
+import torch\r
+import imp\r
+import random\r
+import torch.nn as nn\r
+import os, stat\r
+import subprocess\r
+import transformers\r
+import traceback\r
+import time\r
+import matplotlib.pyplot as plt\r
+device = torch.device('cpu')\r
+\r
+# logging modules\r
+import logging\r
+import logging.handlers\r
+import datetime\r
+import inspect\r
+from inspect import currentframe, getframeinfo\r
+# tkinter modules\r
+from tkinter import *\r
+from tkinter import messagebox\r
+from tkinter import ttk\r
+from PIL import Image, ImageTk\r
+import tkinter\r
+import tkinter as tk\r
+from tkinter.ttk import Progressbar\r
+from update_module_mapper_file import *\r
+base = Tk()\r
+style = ttk.Style()\r
+\r
+# initializing log file\r
+logger = logger_init()\r
+\r
+# We have prepared a dataset with 7 labels\r
+try:\r
+ df = pd.read_csv('newdata.csv', encoding='ISO-8859-1')\r
+ df.head()\r
+except:\r
+ log_create(logger, "Error occurred while reading dataset file!")\r
+\r
+df['label'].value_counts()\r
+\r
+\r
+le = LabelEncoder()\r
+df['label'] = le.fit_transform(df['label'])\r
+\r
+df['label'].value_counts(normalize=True)\r
+\r
+train_text, train_labels = df['Text'], df['label']\r
+\r
+try:\r
+ # Load the DistilBert tokenizer\r
+ tokenizer = DistilBertTokenizer.from_pretrained(r'/home/sri/distilbert-model')\r
+ # Import the DistilBert pretrained model\r
+ bert = DistilBertModel.from_pretrained(r'/home/sri/distilbert-model')\r
+\r
+except:\r
+ log_create(logger, "Error while importing tokenizer ot NLP model")\r
+\r
+text = ["this is a distil bert model.", "data is oil"]\r
+# Encode the text\r
+encoded_input = tokenizer(text, pad_to_max_length=True, return_tensors='pt')\r
+\r
+\r
+\r
+seq_len = [len(i.split()) for i in train_text]\r
+pd.Series(seq_len).hist(bins=13)\r
+\r
+global max_seq_len\r
+max_seq_len = 3\r
+\r
+tokens_train = tokenizer(\r
+ train_text.tolist(),\r
+ max_length=max_seq_len,\r
+ pad_to_max_length=True,\r
+ truncation=True,\r
+ return_token_type_ids=False\r
+)\r
+\r
+# for train set\r
+train_seq = torch.tensor(tokens_train['input_ids'])\r
+train_mask = torch.tensor(tokens_train['attention_mask'])\r
+train_y = torch.tensor(train_labels.tolist())\r
+train_mask\r
+batch_size= 6\r
+train_data = TensorDataset(train_seq, train_mask, train_y)\r
+train_sampler = RandomSampler(train_data)\r
+train_dataloader = DataLoader(\r
+ train_data, sampler=train_sampler, batch_size=batch_size)\r
+\r
+try:\r
+ class BERT_Arch(nn.Module):\r
+ def __init__(self, bert):\r
+ super(BERT_Arch, self).__init__()\r
+ self.bert = bert\r
+\r
+ self.dropout = nn.Dropout(0.1)\r
+\r
+ self.relu = nn.ReLU()\r
+ self.fc1 = nn.Linear(768, 512)\r
+ self.fc2 = nn.Linear(512, 256)\r
+ self.fc3 = nn.Linear(256, 14)\r
+ self.softmax = nn.LogSoftmax(dim=1)\r
+\r
+ def forward(self, sent_id, mask):\r
+\r
+ cls_hs = self.bert(sent_id, attention_mask=mask)[0][:, 0]\r
+\r
+ x = self.fc1(cls_hs)\r
+ x = self.relu(x)\r
+ x = self.dropout(x)\r
+\r
+ x = self.fc2(x)\r
+ x = self.relu(x)\r
+ x = self.dropout(x)\r
+ x = self.fc3(x)\r
+ x = self.softmax(x)\r
+ return x\r
+\r
+except:\r
+ log_create(logger, "Error in BERT Architecture!")\r
+\r
+style.layout("text.Horizontal.TProgressbar",[('Horizontal.Progressbar.trough',\r
+ {'children': [('Horizontal.Progressbar.pbar',\r
+ {'side': 'left', 'sticky': 'ns'})],\r
+ 'sticky': 'nswe'}),\r
+ ('Horizontal.Progressbar.label', {'sticky': ''})])\r
+progress = Progressbar(base, orient = HORIZONTAL,length = 100,style="text.Horizontal.TProgressbar", mode = 'determinate')\r
+\r
+def bar(inp_str):\r
+ import time\r
+\r
+ style.configure("text.Horizontal.TProgressbar", text=inp_str,background="royalblue",foreground="white",font=("Malgun Gothic", 10, 'bold'))\r
+ for p in range(0, 100,10):\r
+ progress['value'] =p\r
+ base.update_idletasks()\r
+ time.sleep(.5)\r
+ progress['value'] = 100\r
+\r
+# Load intents from json file\r
+log_info_save_processing(logger, "Importing data_TCT.json file")\r
+\r
+try:\r
+ f = open("data_TCT.json")\r
+ data = json.load(f)\r
+\r
+except:\r
+ log_create(logger, "Error occurred while importing the json file")\r
+\r
+\r
+\r
+probs = {}\r
+\r
+def get_prediction(str):\r
+ str = re.sub(r"[^a-zA-Z ]+", "", str)\r
+ test_text = [str]\r
+ model=torch.load("modelweight.pth")\r
+ model.eval()\r
+ tokens_test_data = tokenizer(\r
+ test_text,\r
+ max_length=max_seq_len,\r
+ pad_to_max_length=True,\r
+ truncation=True,\r
+ return_token_type_ids=False\r
+ )\r
+ test_seq = torch.tensor(tokens_test_data["input_ids"])\r
+ test_mask = torch.tensor(tokens_test_data["attention_mask"])\r
+\r
+ preds = None\r
+ with torch.no_grad():\r
+ preds = model(test_seq.to(device), test_mask.to(device))\r
+\r
+ for i in range(len(preds[0])):\r
+ probs[le.inverse_transform([i])[0]] = np.array(torch.exp(preds[0]))[i]\r
+\r
+ log_info_save(logger, "Prediction probabilitites", probs)\r
+\r
+ #for none class\r
+ if(torch.max(torch.exp(preds))<0.80):\r
+ return "none"\r
+\r
+ preds = preds.detach().cpu().numpy()\r
+ preds = np.argmax(preds, axis=1)\r
+ return le.inverse_transform(preds)[0]\r
+\r
+\r
+# global module_name\r
+CURR_API_IND = 0\r
+NO_OF_NEGATIVE_TC = 10\r
+check_if_pre_post_api_exist = True\r
+API_NAMES_LIST = []\r
+FUNC_API_ALL_ARGS = []\r
+all_combined_func_args = []\r
+build_params = []\r
+enum_dict = {}\r
+enum_dict_pre_post = {}\r
+feature_name = ""\r
+previous_intent = 'entry'\r
+execute_tc_params_text = 'ARCHITECTURE: armv7l PROFILE: mobile'\r
+RET_TYPE = "int"\r
+stage_list = ["TC Addition", "Module Name", "API Info", "Feature Info", "Pre Post Info", "Negative TC"]\r
+last_stage_index = 0\r
+new_module = False\r
+all_pre_post_api_skip = False\r
+flag_check_negative=False\r
+isExist=True\r
+callback_duplicate_check = []\r
+\r
+def get_response(message):\r
+ try:\r
+ global result\r
+ global module_name\r
+ global MODULE_NAME\r
+ global API_NAMES\r
+ global CURR_API_IND\r
+ global check_if_pre_post_api_exist\r
+ global API_NAMES_LIST\r
+ global get_api_list_info\r
+ global FUNC_ARGS\r
+ global RET_TYPE\r
+ global TC_WRITE_DIR\r
+ global FUNC_API_ALL_ARGS\r
+ global all_combined_func_args\r
+ global intent\r
+ global get_tc_template_code\r
+ global get_negative_tc_template_code\r
+ global HEADER_FILE_CONTAINED_FOLDER\r
+ global previous_intent\r
+ global execute_tc_params_text\r
+ global WRITE_NEGATIVE_TC_USER_INPUT\r
+ global NO_OF_NEGATIVE_TC\r
+ global stage_list\r
+ global last_stage_index\r
+ global api_names\r
+ global pre_post_api_names\r
+ global enum_dict\r
+ global enum_dict_pre_post\r
+ global feature_name\r
+ global new_module\r
+ global all_pre_post_api_skip\r
+ global header_files_dict\r
+ global TARGET_API_INPUT_PARAMS_LIST\r
+ global flag_check_negative\r
+ global isExist\r
+ global callback_duplicate_check\r
+\r
+ except:\r
+ log_create(logger, "Variable name error occured")\r
+\r
+ try:\r
+ if "pre:" in message.lower() and "yaca" in message.lower():\r
+ intent="prepostinfo"\r
+ else:\r
+ intent = get_prediction(message)\r
+ log_info_save(logger, "Intent", intent)\r
+ except:\r
+ log_create(logger, "Error occurred in get_prediction function")\r
+\r
+ if intent == "existingmodule" and probs[intent]<0.85:\r
+ intent = "none"\r
+ if intent == "greetings" and previous_intent != "entry" and previous_intent != 'goback' and previous_intent != 'after_launch':\r
+ result = "invalid response, please try again!!"\r
+ else:\r
+ for i in data['intents']:\r
+ if i["tag"] == intent:\r
+ result = random.choice(i["responses"])\r
+ try:\r
+ if message == '1' or message == '2' or message == '3' or message == '4' or message == '5' or message == '6' or message == "exit" or message == "EXIT" or message == "Exit":\r
+ if previous_intent == "goback":\r
+ if message == '1':\r
+ msg = "greetings"\r
+ if message == '2':\r
+ if new_module == True:\r
+ msg = "newmodule"\r
+ previous_intent = "newmodule"\r
+ else:\r
+ msg = "existingmodule"\r
+ if message == '3':\r
+ msg = "Module Name: "+ module_name\r
+ if message == '4':\r
+ msg = "API names: "+ api_names\r
+ if message == '5':\r
+ msg = "Feature name: "+ feature_name\r
+ callback_duplicate_check.clear()\r
+ if message == '6':\r
+ CURR_API_IND = len(API_NAMES) - 1\r
+ input_params.clear()\r
+ msg = pre_post_api_names\r
+ if message == 'exit' or message == 'EXIT' or message == 'Exit':\r
+ return "exit"\r
+ get_response(msg)\r
+\r
+ elif message.lower() == 'yes' or message.lower() =='no':\r
+ #in case when module name typed wrong and suggestion is provided\r
+ if previous_intent == 'modulename':\r
+ if message.lower() == 'yes':\r
+ last_stage_index = 1\r
+ intent = 'modulename'\r
+ elif message.lower() == "no":\r
+ intent = 'modulenotfound'\r
+ for i in data['intents']:\r
+ if i["tag"] == intent:\r
+ result = random.choice(i["responses"])\r
+\r
+ elif previous_intent == 'apiinfo':\r
+ if message.lower() == 'yes':\r
+ result = "Please enter supported features for the above-mentioned APIs, in the form of \nFeature name:" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+ elif message.lower() == 'no':\r
+ last_stage_index = 3\r
+ previous_intent = 'featureinfo'\r
+ feature_name = ''\r
+ result = "Feature details skipped.\n" \\r
+ + "Do you want to add Pre and Post condition APIs for the above APIs?" + "\n" \\r
+ + "(Yes or No)" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+\r
+ elif previous_intent =='featureinfo':\r
+ if message.lower() == 'yes':\r
+ all_pre_post_api_skip = False\r
+ result = "Please enter Pre and Post condition APIs for API: " + f"{API_NAMES[0]}" +" in the format of \nPre: API_NAME_1 API_NAME_2 Post: API_NAME_1 API_NAME_2 separated by space" \\r
+ +"\n\n If you don't want to write pre and post APIs for " + f"{API_NAMES[0]}" + " please write 'Pre:'" \\r
+ +"\n\n[ To navigate, please type 'Back' ]"\r
+ elif message.lower() == 'no':\r
+ all_pre_post_api_skip = True\r
+ get_response('Pre:')\r
+\r
+\r
+ #ask a question to add negative Tcs or not\r
+ elif previous_intent == 'prepostinfo':\r
+ last_stage_index = 5\r
+ if message.lower() == "yes":\r
+ if not flag_check_negative:\r
+ WRITE_NEGATIVE_TC_USER_INPUT = False\r
+ result = "Negative TCs not possible for this API, Only positive TCs will be created. \n\n"\r
+ else:\r
+ WRITE_NEGATIVE_TC_USER_INPUT = True\r
+ result = "Thank You for providing input. \n"\r
+ elif message.lower() == "no":\r
+ WRITE_NEGATIVE_TC_USER_INPUT = False\r
+ result = "Thank You for providing input. Only positive TCs will be created \n"\r
+\r
+ if new_module == False:\r
+ result = result + "All .C TC Code files in the mentioned directory are listed as below \n" \\r
+ + f"{TC_WRITE_DIR}" + "/" + f"{MODULE_NAME}" + "\n\n" \\r
+ + get_all_files_of_module(TC_WRITE_DIR, MODULE_NAME) + "\n\n" \\r
+ + "Please provide the file name in which you want to write the TC in the format of \nFILE name: NAME_OF_THE_FILE.c" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+ else:\r
+ msg = "FILE name: utc-" + MODULE_NAME + ".c"\r
+ get_response(msg)\r
+\r
+\r
+ #ask a question to build or not\r
+ elif previous_intent == 'tcwritelocation':\r
+ if message.lower() == "yes":\r
+ intent = 'buildparameters'\r
+ for i in data['intents']:\r
+ if i["tag"] == intent:\r
+ result = random.choice(i["responses"])\r
+ elif message.lower() == "no":\r
+ result = 'Do you want to continue for next module ? (Yes/No)'\r
+ previous_intent = 'after_launch'\r
+\r
+\r
+\r
+ #ask a question to execute or not\r
+ elif previous_intent == 'executetc':\r
+ if message.lower() == 'yes':\r
+ intent = 'launchtctmgr'\r
+ elif message.lower() == "no":\r
+ result = 'Do you want to continue for next module ? (Yes/No)'\r
+ previous_intent = 'after_launch'\r
+\r
+\r
+ elif previous_intent == 'after_launch':\r
+ if message.lower() == 'yes':\r
+ input_params.clear()\r
+ msg = "greetings"\r
+ get_response(msg)\r
+ elif message.lower() == "no":\r
+ return "exit"\r
+\r
+\r
+ elif intent == 'existingmodule':\r
+ new_module = False\r
+ previous_intent='existingmodule'\r
+\r
+ elif intent == 'newmodule':\r
+ new_module = True\r
+ #result will be send from dataTCT.json file\r
+\r
+ elif intent == 'modulename':\r
+ last_stage_index = 0\r
+ pos_of_semicolon = [_.start() for _ in re.finditer(":", message)]\r
+ module_name = message[pos_of_semicolon[0]+1:]\r
+ module_name = module_name.strip()\r
+ module_name = module_name.lower()\r
+ if new_module == True:\r
+ last_stage_index = 1\r
+ module_check = module_autocorrect(module_name)\r
+ if module_check == True:\r
+ result = "Module name already exists. Please write module name apart from existing one.\n" + "Please provide module name in the form of \nModule name:" + "\n\n[ To navigate, please type 'Back' ]"\r
+ previous_intent = 'modulename'\r
+ elif module_name=='':\r
+ result = "No Module name details entered!! \n\n Please provide Module name in the format of \n Module name:\n\n [ To navigate, please type 'Back' ] "\r
+ elif module_check != True and previous_intent!="goback":\r
+ result = "Please enter Header file details in the format of \nHeader File: HEADER_FILE_1 HEADER_FILE_2" + "\n\n[ To navigate, please type 'Back' ]"\r
+ previous_intent = 'modulename'\r
+ elif module_check != True and previous_intent == "goback":\r
+ result = "Please enter Header file details in the format of \nHeader File: HEADER_FILE_1 HEADER_FILE_2" + "\n\n[ To navigate, please type 'Back' ]"\r
+ previous_intent = 'modulename'\r
+ else:\r
+ previous_intent = 'modulename'\r
+ module_name_suggested = module_autocorrect(module_name)\r
+ if module_name_suggested == True:\r
+ last_stage_index = 1\r
+ result = "Module name found" + "\n" + result\r
+ elif module_name_suggested != '':\r
+ result = "Module name not found[Please check mapping file: Module_Header_Mapping.csv]" + "\n" + "\n" + "Did you mean ? " + module_name_suggested[0] + "\n" + "Type Yes to continue otherwise type No" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+ module_name = module_name_suggested[0]\r
+ else:\r
+ result = "Module name not found[Please check mapping file: Module_Header_Mapping.csv], \n\nPlease type the module name again in the form of \nModule name:" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+\r
+ elif intent == 'headerinfo':\r
+ new_module = True\r
+ HEADER_FILE_VALUE = []\r
+ pos_of_semicolon = [_.start() for _ in re.finditer(":", message)]\r
+ header_file_name = message[pos_of_semicolon[0]+1:]\r
+ header_file_name = header_file_name.strip()\r
+\r
+ HEADER_FILES_NAMES_TO_UPDATE = list(map(str, header_file_name.split()))\r
+ if HEADER_FILES_NAMES_TO_UPDATE != []:\r
+ header_file_name = HEADER_FILES_NAMES_TO_UPDATE[0]\r
+ ROOTSTRAPS_DIR = get_latest_rootstrap()\r
+ ROOTSTRAPS_DIR = ROOTSTRAPS_DIR + "//"\r
+\r
+ for header_file in HEADER_FILES_NAMES_TO_UPDATE:\r
+ HEADER_FILE_LOCATION = get_api_header_file_location(ROOTSTRAPS_DIR, header_file)\r
+ if HEADER_FILE_LOCATION == "":\r
+ break\r
+ HEADER_FILE_VALUE.append(HEADER_FILE_LOCATION.partition(ROOTSTRAPS_DIR)[-1])\r
+\r
+\r
+ if HEADER_FILE_LOCATION == "":\r
+ result = "Header file not found in rootstrap! So, Module not created.\nPlease enter the correct header file details in the form of form of \nHeader File:" + "\n\n[ To navigate, please type 'Back' ]"\r
+ else:\r
+ #add a new module\r
+ type_of_tc = "utc"\r
+ new_module_addition(module_name, type_of_tc)\r
+ CURRENT_PATH = get_current_dir_path()\r
+ TC_WRITE_DIR = CURRENT_PATH + r'src/utc'\r
+\r
+ clean_existing_code(TC_WRITE_DIR, module_name)\r
+ add_header_line(TC_WRITE_DIR, module_name, HEADER_FILES_NAMES_TO_UPDATE)\r
+ update_module_mapper_file(HEADER_FILE_VALUE, module_name)\r
+ result = "Please provide API information in the format of \nAPI names: API_NAME_1 API_NAME_2 \n\n[ To navigate, please type 'Back' ]"\r
+ else:\r
+ result= "No Header File details entered!! \n\n Please provide Header File details in the format of \n Header File :\n\n [ To navigate, please type 'Back' ] "\r
+\r
+\r
+\r
+ elif intent == 'apiinfo':\r
+ callback_duplicate_check.clear()\r
+ clear_api_list()\r
+ last_stage_index = 1\r
+ CURR_API_IND = 0\r
+ API_NAMES_LIST = []\r
+ FUNC_API_ALL_ARGS = []\r
+ enum_dict = {}\r
+ pos_of_semicolon = [_.start() for _ in re.finditer(":", message)]\r
+ api_names = message[pos_of_semicolon[0]+1:]\r
+ MODULE_NAME = module_name.lower()\r
+ API_NAMES = list(map(str, api_names.split()))\r
+ if len(API_NAMES) != 0:\r
+ for items in range(len(API_NAMES)):\r
+ API_NAMES[items] = API_NAMES[items].strip()\r
+ header_files_dict = get_header_files(MODULE_NAME)\r
+ ROOTSTRAPS_DIR = get_latest_rootstrap()\r
+ ROOTSTRAPS_DIR = ROOTSTRAPS_DIR + "//"\r
+ check_if_api_exist = validate_api(API_NAMES, MODULE_NAME)\r
+ CURRENT_PATH = get_current_dir_path()\r
+ TC_WRITE_DIR = CURRENT_PATH + r'src/utc'\r
+ if check_if_api_exist == True:\r
+ for API_SEARCH in API_NAMES:\r
+ if check_if_api_exists_grep(MODULE_NAME, API_SEARCH, TC_WRITE_DIR):\r
+ clear_api_list()\r
+ return "ThankYou for providing input." + "\n" + "TC already exists for API: " + API_SEARCH + "\n" + "Please try writing again." + "\n\n[ To navigate, please type 'Back' ]"\r
+\r
+ api_return_values = get_api_return_values()\r
+ api_params = get_api_parameters(API_NAMES)\r
+ for k, v in api_return_values.items():\r
+ for i in API_NAMES:\r
+ if i == k:\r
+ RET_TYPE = v\r
+ for k, v in api_params.items():\r
+ for i in API_NAMES:\r
+ if i == k:\r
+ FUNC_ARGS = v\r
+ FUNC_API_ALL_ARGS.append(FUNC_ARGS)\r
+\r
+ for API in API_NAMES:\r
+ enum = enum_finder(API, ROOTSTRAPS_DIR, header_files_dict, api_params[API])\r
+ if enum != {}:\r
+ enum_dict[API] = enum\r
+ else:\r
+ enum_dict[API] = {}\r
+\r
+ last_stage_index = 2\r
+ previous_intent = 'apiinfo'\r
+ result = "Thankyou, APIs found in rootstrap.\n" \\r
+ + "Do you want to add Feature for above APIs?" + "\n" \\r
+ + "(Yes or No)" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+\r
+ else:\r
+ if isExist:\r
+ top_msg_display = "APIs not present in rootstraps. Please try writing again." + "\n\n" + "All the APIs present in the header file are mentioned below for your reference:"\r
+ result = ""\r
+ for HEADER_FILE_NAME in header_files_dict:\r
+ if "/" in HEADER_FILE_NAME:\r
+ POS_OF_SLASH = HEADER_FILE_NAME.index("/")\r
+ HEADER_FILE_NAME_WITHOUT_SLASH = HEADER_FILE_NAME[POS_OF_SLASH+1:]\r
+ temp = "\n\n" + "Header File Name: " + HEADER_FILE_NAME_WITHOUT_SLASH + "\n\n" +get_all_api_names(MODULE_NAME, HEADER_FILE_NAME)\r
+ result = result + temp\r
+ else:\r
+ temp = "\n\n" + "Header File Name: " + HEADER_FILE_NAME + "\n\n" +get_all_api_names(MODULE_NAME, HEADER_FILE_NAME)\r
+ result = result + temp\r
+ result = top_msg_display + result + "\n\n\nPlease provide API information in the format of \nAPI names:" + "\n\n[ To navigate, please type 'Back' ]"\r
+ clear_api_list()\r
+ else:\r
+ result="Header File not found in rootstrap, Please check Module_Header_Mapping.csv"\r
+\r
+\r
+ else:\r
+ result = "No API details entered !!" + "\n\nPlease provide API information in the format of \nAPI names:" + "\n\n[ To navigate, please type 'Back' ]"\r
+\r
+ elif intent == 'featureinfo':\r
+ last_stage_index = 3\r
+ CURR_API_IND = 0\r
+ pos_of_semicolon = [_.start() for _ in re.finditer(":", message)]\r
+ feature_name = message[pos_of_semicolon[0]+1:]\r
+ feature_name = feature_name.strip()\r
+ if feature_name != "":\r
+ previous_intent = 'featureinfo'\r
+ first_char = feature_name[0]\r
+ last_char = feature_name[len(feature_name)-1]\r
+\r
+ if first_char == '"' or first_char =="'":\r
+ feature_name = feature_name.replace(first_char,"",1)\r
+\r
+ if last_char == '"' or last_char =="'":\r
+ feature_name = feature_name.replace(last_char,"",1)\r
+ ## print("feature name2")\r
+ feature_name = feature_name.strip()\r
+\r
+\r
+ result = "Do you want to add Pre and Post condition APIs for the above APIs?" + "\n" \\r
+ + "(Yes or No)" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+\r
+ elif feature_name == "" and previous_intent == 'goback':\r
+ previous_intent = 'featureinfo'\r
+ # print("feature_name,sfsadf",feature_name, previous_intent)\r
+ first_char = feature_name[0]\r
+ last_char = feature_name[len(feature_name)-1]\r
+\r
+ if first_char == '"' or first_char =="'":\r
+ feature_name = feature_name.replace(first_char,"",1)\r
+ ## print("feature name1", feature_name)\r
+\r
+ if last_char == '"' or last_char =="'":\r
+ feature_name = feature_name.replace(last_char,"",1)\r
+ ## print("feature name2")\r
+ feature_name = feature_name.strip()\r
+\r
+\r
+ result = "Do you want to add Pre and Post condition APIs for the above APIs?" + "\n" \\r
+ + "(Yes or No)" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+\r
+ else:\r
+ result = "No Feature details entered!!\n\nPlease enter supported features for the above-mentioned APIs, in the form of \nFeature name:" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+\r
+\r
+ elif intent == 'prepostinfo':\r
+ enum_dict_pre_post = {}\r
+ \r
+ header_files_dict = get_header_files(MODULE_NAME)\r
+ pre_post_api_names = message\r
+ ## print("pre post details---------------", pre_post_api_names)\r
+ NEGATIVE_TC_COUNT = 10\r
+ last_stage_index = 4\r
+ \r
+ # get_pre_post_api_list_info(API_NAMES, MODULE_NAME, pre_post_api_names)\r
+ #CURR_API_IND = 0\r
+ ## print("api length", API_NAMES)\r
+ ## print("curr_api_ind", CURR_API_IND)\r
+ if CURR_API_IND < len(API_NAMES):\r
+ ## print("curr_api_index", CURR_API_IND)\r
+ ### print("Current value of current index")\r
+ ### print(CURR_API_IND)\r
+ get_pre_post_api_list = get_pre_post_api_list_info(API_NAMES[CURR_API_IND], MODULE_NAME, CURR_API_IND , pre_post_api_names)\r
+ # print("looooooogsssssss",get_pre_post_api_list)\r
+ check_if_pre_post_api_exist &= (validate_api(get_pre_post_api_list[API_NAMES[CURR_API_IND]]['Pre'], MODULE_NAME) and validate_api(get_pre_post_api_list[API_NAMES[CURR_API_IND]]['Post'], MODULE_NAME))\r
+ # print("check_if_pre_post_api_exist",check_if_pre_post_api_exist)\r
+ #pre_post_enum = enum_finder_for_pre_post(get_pre_post_api_list, ROOTSTRAPS_DIR, header_files_dict, api_params)\r
+ ## print('afasdfgdsafsdaf',get_pre_post_api_list[API_NAMES[CURR_API_IND]]['Pre'])\r
+ API_NAMES_LIST += get_pre_post_api_list[API_NAMES[CURR_API_IND]]['Pre'] + get_pre_post_api_list[API_NAMES[CURR_API_IND]]['Post']\r
+ # print(API_NAMES_LIST)\r
+ ## print("CURR_API_IND",CURR_API_IND)\r
+ ## print("length",len(API_NAMES))\r
+ if CURR_API_IND < len(API_NAMES):\r
+ #for case when pre and post are not to be entered by user. User has selected no\r
+ if all_pre_post_api_skip == True:\r
+ CURR_API_IND = CURR_API_IND + 1\r
+ # print("inside CURR_API_IND + 1 < len(API_NAMES) and get_response called again",CURR_API_IND)\r
+ ## print("API_NAMES[CURR_API_IND]",API_NAMES[CURR_API_IND-1])\r
+ ## print("API_NAMES[CURR_API_IND+1]",API_NAMES[CURR_API_IND])\r
+ CURR_API_IND = len(API_NAMES)\r
+ for API_IDX in range(1, len(API_NAMES)):\r
+ get_pre_post_api_list = get_pre_post_api_list_info(API_NAMES[API_IDX], MODULE_NAME, API_IDX , pre_post_api_names)\r
+ # print("get_pre_post_api_list",get_pre_post_api_list)\r
+ API_NAMES_LIST += get_pre_post_api_list[API_NAMES[API_IDX]]['Pre'] + get_pre_post_api_list[API_NAMES[API_IDX]]['Post']\r
+ # print("API_NAMES_LIST",API_NAMES_LIST)\r
+ # get_response('Pre:')\r
+\r
+ else:\r
+ if (CURR_API_IND+1)<len(API_NAMES):\r
+ result = "Thankyou, for providing details for pre/post APIs for " + f"{API_NAMES[CURR_API_IND]}" + "\nPlease Enter pre/post APIs for API:" + f"{API_NAMES[CURR_API_IND+1]}" \\r
+ + "\n\n If you don't want to write pre and post APIs for API:" + f"{API_NAMES[CURR_API_IND+1]}" + " please write 'Pre:'"\\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+ else:\r
+ result = "Thankyou, for providing details for pre/post APIs for " + f"{API_NAMES[CURR_API_IND]}"\r
+ #if CURR_API_IND + 1 < len(API_NAMES):\r
+\r
+ if all_pre_post_api_skip == True:\r
+ CURR_API_IND = len(API_NAMES)\r
+ else:\r
+ CURR_API_IND = CURR_API_IND + 1\r
+ ## print("After_CURR_API_IND", CURR_API_IND)\r
+ appended_code = ""\r
+ appended_negative_tc_code = ""\r
+ WRITE_NEGATIVE_TC_USER_INPUT = False\r
+ if CURR_API_IND == len(API_NAMES):\r
+ ## print(check_if_pre_post_api_exist)\r
+ if check_if_pre_post_api_exist:\r
+ ## print('Pre and Post APIS are valid')\r
+ ### print("Entered Loop")\r
+ get_all_api_list = get_api_return_values()\r
+ # get_all_agrs_list = get_api_parameters(API_NAMES + get_pre_post_api_list[API_NAMES[CURR_API_IND]]['Pre'] + get_pre_post_api_list[API_NAMES[CURR_API_IND]]['Post'])\r
+ get_all_agrs_list = get_api_parameters(API_NAMES + API_NAMES_LIST)\r
+ # print("checking for ags", get_all_agrs_list)\r
+ PRE_POST_API_ARGS_LIST = get_all_agrs_list\r
+ ROOTSTRAPS_DIR = get_latest_rootstrap()\r
+ ROOTSTRAPS_DIR = ROOTSTRAPS_DIR + "//"\r
+ HEADER_FILE_NAME = header_files_dict[0]\r
+ pos = HEADER_FILE_NAME.find('/')\r
+ if pos > 0:\r
+ HEADER_FILE_NAME = HEADER_FILE_NAME[pos+1:]\r
+ for API_IDX in range(len(API_NAMES)):\r
+ # print("details of each API", API_IDX)\r
+ # print("for api ---", API_NAMES[API_IDX])\r
+ # print("looooooogsssssss",get_pre_post_api_list)\r
+ PRE_POST_API_LIST = get_pre_post_api_list[API_NAMES[API_IDX]]\r
+ # print("cjeclomg dlfm", PRE_POST_API_LIST)\r
+\r
+ pre_apis = PRE_POST_API_LIST['Pre']\r
+ ## print("pre_apis",pre_apis)\r
+ post_apis = PRE_POST_API_LIST['Post']\r
+\r
+\r
+ if len(pre_apis) != 0:\r
+ for pre_api in pre_apis:\r
+ api_params_pre = PRE_POST_API_ARGS_LIST[pre_api]\r
+ ## print("api_params",api_params_pre)\r
+ enum = enum_finder(pre_api, ROOTSTRAPS_DIR, header_files_dict, api_params_pre)\r
+ if enum != {}:\r
+ ## print("enum found")\r
+ enum_dict_pre_post[pre_api] = enum\r
+ else:\r
+ ## print("enum not found for pre API!")\r
+ enum_dict_pre_post[pre_api] = {}\r
+ if len(post_apis) != 0:\r
+ for post_api in post_apis:\r
+ api_params_post = PRE_POST_API_ARGS_LIST[post_api]\r
+ ## print("api_params_post", api_params_post)\r
+ enum = enum_finder(post_api, ROOTSTRAPS_DIR, header_files_dict, api_params_post)\r
+ ## print("post_api_detail ->", post_api)\r
+ #post_key = "Pre-" + API_NAMES[API_IDX] + "- " + post_api\r
+ if enum != {}:\r
+ # print("enum found")\r
+ enum_dict_pre_post[post_api] = enum\r
+ else:\r
+ # print("enum not found for pre API!")\r
+ enum_dict_pre_post[post_api] = {}\r
+\r
+\r
+ ## print("enum pre post dict for API - ", enum_dict_pre_post)\r
+\r
+ ## print("Header file name checking", HEADER_FILE_NAME)\r
+ HEADER_FILE_CONTAINED_FOLDER = get_api_header_file_contained_folder_name(ROOTSTRAPS_DIR, HEADER_FILE_NAME)\r
+ HEADER_FILE_CONTAINED_FOLDER = HEADER_FILE_CONTAINED_FOLDER.replace('-','_')\r
+ ## print("Header file contained folder", HEADER_FILE_CONTAINED_FOLDER)\r
+ ## print("API_NAMES[API_IDX]",API_NAMES[API_IDX])\r
+ ## print("PRE_POST_API_LIST", PRE_POST_API_LIST)\r
+ ## print("PRE_POST_API_ARGS_LIST",PRE_POST_API_ARGS_LIST)\r
+ ## print("FUNC_API_ALL_ARGS[API_IDX]",FUNC_API_ALL_ARGS[API_IDX])\r
+ ## print("HEADER_FILE_CONTAINED_FOLDER",HEADER_FILE_CONTAINED_FOLDER)\r
+ ## print("enum_dict",enum_dict)\r
+ ## print("enum_dict_pre_post",enum_dict_pre_post)\r
+ ## print("feature_name",feature_name)\r
+ get_tc_template_code = tc_code_write1(RET_TYPE, MODULE_NAME, API_NAMES[API_IDX], PRE_POST_API_LIST, PRE_POST_API_ARGS_LIST, FUNC_API_ALL_ARGS[API_IDX], HEADER_FILE_CONTAINED_FOLDER, enum_dict, enum_dict_pre_post, feature_name, callback_duplicate_check)\r
+ ## print("get_tc_template_code",get_tc_template_code)\r
+ appended_code = appended_code + "\n" + get_tc_template_code\r
+ ## print("tc_code from tct_assistance ")\r
+ # print(appended_code)\r
+ # code, NO_OF_NEGATIVE_TC = all_negative_tc_combined(RET_TYPE, MODULE_NAME, API_NAMES[API_IDX], PRE_POST_API_LIST, PRE_POST_API_ARGS_LIST, FUNC_API_ALL_ARGS[API_IDX], HEADER_FILE_CONTAINED_FOLDER, NEGATIVE_TC_COUNT)\r
+ #appended_negative_tc_code = appended_negative_tc_code + appended_code\r
+ # print("TARGET_API_INPUT_PARAMS_LIST",TARGET_API_INPUT_PARAMS_LIST)\r
+ if len(TARGET_API_INPUT_PARAMS_LIST) > 0:\r
+ appended_negative_tc_code = appended_negative_tc_code + get_tc_template_code + "\n" + all_negative_tc_combined(RET_TYPE, MODULE_NAME, API_NAMES[API_IDX], PRE_POST_API_LIST, PRE_POST_API_ARGS_LIST, FUNC_API_ALL_ARGS[API_IDX], HEADER_FILE_CONTAINED_FOLDER, 10, feature_name, enum_dict, enum_dict_pre_post) + "\n"\r
+ flag_check_negative = True\r
+ input_params.append(len(TARGET_API_INPUT_PARAMS_LIST))\r
+ TARGET_API_INPUT_PARAMS_LIST.clear()\r
+ # print("inputdsfsadfds_params",input_params)\r
+ elif len(TARGET_API_INPUT_PARAMS_LIST) == 0:\r
+ input_params.append(0)\r
+ appended_negative_tc_code = appended_negative_tc_code + get_tc_template_code\r
+\r
+ if API_IDX == len(API_NAMES):\r
+ break\r
+ get_tc_template_code = appended_code\r
+ get_negative_tc_template_code = appended_negative_tc_code\r
+\r
+ previous_intent = 'prepostinfo'\r
+ last_stage_index = 4\r
+ if all_pre_post_api_skip == True:\r
+ result = "Pre and Post condition skipped.\n\n"\r
+ else:\r
+ result = "Thank You for providing pre/post condition APIs. \n\n"\r
+ result = result + "Do you want to add negative TCs also?" + "\n" \\r
+ + "(Yes or No)" \\r
+ + "\n\n[ To navigate, please type 'Back' ]"\r
+\r
+ elif check_if_pre_post_api_exist == False:\r
+ CURR_API_IND = CURR_API_IND - 1\r
+ check_if_pre_post_api_exist = True\r
+ for i in API_NAMES_LIST:\r
+ for j in get_pre_post_api_list[API_NAMES[CURR_API_IND]]['Pre']:\r
+ if i == j:\r
+ API_NAMES_LIST.remove(i)\r
+ break\r
+ for i in API_NAMES_LIST:\r
+ for j in get_pre_post_api_list[API_NAMES[CURR_API_IND]]['Post']:\r
+ if i == j:\r
+ API_NAMES_LIST.remove(i)\r
+ break\r
+\r
+ result = "Pre/Post condition APIs provided by you does not exists." \\r
+ + "\n\n[ Please type 'Back' and provide all Pre/Post APIs data again. ]"\r
+\r
+ elif intent == 'tcwritelocation':\r
+ #write tc in the mentioned file name collected from the user\r
+\r
+ MODULE_NAME = module_name\r
+ colon_pos = message.find(':')\r
+ file_name = message[colon_pos+1:]\r
+ file_name = file_name.strip()\r
+\r
+ previous_intent = 'tcwritelocation'\r
+ # global input_params\r
+ last_stage_index = 6\r
+ # print("WRITE_NEGATIVE_TC_USER_INPUT",WRITE_NEGATIVE_TC_USER_INPUT)\r
+\r
+ if file_name != "":\r
+ if check_if_file_name_exists(file_name, TC_WRITE_DIR, MODULE_NAME):\r
+ #inp_params=ret_input_params()\r
+ with open(TC_WRITE_DIR + "/" + MODULE_NAME + "/" + f"{file_name}", "a") as myfile:\r
+ if WRITE_NEGATIVE_TC_USER_INPUT:\r
+ # print("writing neg and pos tc")\r
+ ## print("get_negative_tc_template_code",get_negative_tc_template_code)\r
+ ## print(get_negative_tc_template_code)\r
+ myfile.write(get_negative_tc_template_code)\r
+ else:\r
+ # print("printing pos tc")\r
+ ## print(get_tc_template_code)\r
+ myfile.write(get_tc_template_code)\r
+\r
+ # code for making entry of new tc in header files if a new file is created\r
+ for API_IDX in range(len(API_NAMES)):\r
+ # print("API_NAMES",API_NAMES)\r
+ # print("TC_WRITE_DIR",TC_WRITE_DIR,"MODULE_NAME",MODULE_NAME,"HEADER_FILE_CONTAINED_FOLDER",HEADER_FILE_CONTAINED_FOLDER,"filename",file_name)\r
+ update_all_header_files(TC_WRITE_DIR, MODULE_NAME, HEADER_FILE_CONTAINED_FOLDER, API_NAMES[API_IDX], file_name, True)\r
+ # if user type yes when asked for negative TCs then update negative tc in header files\r
+ if WRITE_NEGATIVE_TC_USER_INPUT:\r
+ inp_params = ret_input_params()\r
+ # print("API_IDX",API_IDX)\r
+ # print("inp_params",inp_params)\r
+ if inp_params!=[]:\r
+ for idx in range(1, inp_params[API_IDX]+1):\r
+ update_all_header_files_for_negative_tc(TC_WRITE_DIR, MODULE_NAME, HEADER_FILE_CONTAINED_FOLDER, API_NAMES[API_IDX], idx, API_IDX,file_name)\r
+\r
+ if new_module == True:\r
+ result = result + "TC is created successfully at path : " + f"{TC_WRITE_DIR}" + "/" + f"{MODULE_NAME}" + "/" + f"{file_name}" + "\n\n" + "Do you want to build ?\n(Yes or No)"\r
+ else:\r
+ result = "Thankyou, for providing file name.\n" + "TC is created successfully at path : " + f"{TC_WRITE_DIR}" + "/" + f"{MODULE_NAME}" + "/" + f"{file_name}" + "\n\n" + "Do you want to build ?\n(Yes or No)"\r
+ else:\r
+ # print("MODULE_NAME,file_name,header_files_dict",MODULE_NAME,file_name,header_files_dict)\r
+ get_tc_init_code = tc_code_init(MODULE_NAME,file_name,header_files_dict)\r
+ # print("filename----",file_name)\r
+ with open(TC_WRITE_DIR + "/" + MODULE_NAME + "/" + f"{file_name}", "a+") as myfile:\r
+ myfile.write(get_tc_init_code)\r
+ if WRITE_NEGATIVE_TC_USER_INPUT:\r
+ # print("writing neg and pos tc for new file")\r
+ # print(get_negative_tc_template_code)\r
+ myfile.write(get_negative_tc_template_code)\r
+ else:\r
+ # print("writing only pos tc for a new file")\r
+ # print(get_tc_template_code)\r
+ myfile.write(get_tc_template_code)\r
+\r
+ # code for making entry of new tc in header files if a new file is created\r
+ for API_IDX in range(len(API_NAMES)):\r
+ ### print("reprint 1")\r
+ inp_params=[]\r
+ update_all_header_files(TC_WRITE_DIR, MODULE_NAME, HEADER_FILE_CONTAINED_FOLDER, API_NAMES[API_IDX], file_name, False)\r
+ # if user type yes when asked for negative TCs then update negative tc in header files\r
+ if WRITE_NEGATIVE_TC_USER_INPUT:\r
+ ## print("API INDEX", API_IDX)\r
+ inp_params = ret_input_params()\r
+ # print("input params", inp_params)\r
+ if inp_params!=[] and API_IDX <= (len(inp_params) -1):\r
+ for idx in range(1, inp_params[API_IDX]+1):\r
+ # print("idx", idx)\r
+ # print("API NAMES", API_NAMES)\r
+ # print("\n API names of index is ", API_NAMES[API_IDX])\r
+ update_all_header_files_for_negative_tc(TC_WRITE_DIR, MODULE_NAME, HEADER_FILE_CONTAINED_FOLDER, API_NAMES[API_IDX], idx, API_IDX,file_name)\r
+ # print("updating CMakelist file for new tc file created")\r
+ # print(TC_WRITE_DIR)\r
+ # print(file_name)\r
+ updateCMakeFile(TC_WRITE_DIR, MODULE_NAME, file_name)\r
+\r
+ result = "Thankyou, for providing file name." + "A new file will be created at path : " + f"{TC_WRITE_DIR}" + "/" + f"{MODULE_NAME}" + "/" + f"{file_name}" + "\n\n" + "Do you want to build ?\n(Yes or No)"\r
+\r
+ else:\r
+ result="File name details not entered!! \n\n Please provide file name in the format of \nFile name:\n\n [ To navigate, please type 'Back' ]"\r
+\r
+\r
+ elif intent == 'executetc':\r
+ MODULE_NAME = module_name\r
+ previous_intent = "executetc"\r
+ execute_tc_params_text = message\r
+ # print("execute_tc_params_text", execute_tc_params_text)\r
+ build_params = get_build_parameters(message)\r
+ # print("params", build_params)\r
+ arch_value = build_params[0].lower()\r
+ # print(arch_value)\r
+ profile_value = build_params[1].lower()\r
+ # print(profile_value)\r
+\r
+ if (arch_value == "armv7l" or arch_value == "x86" or arch_value == "x64" or arch_value == "aarch64") and (profile_value == "tv" or profile_value == "tizeniot"):\r
+ # print("build params are correct")\r
+ bar("Build Started !! Please wait...")\r
+ output_build = tpk_build_install("build", "utc", MODULE_NAME, build_params[1], build_params[0])\r
+ # time.sleep(3)\r
+ if output_build.find("CREATION SUCCESSFUL") != -1:\r
+ if previous_intent == 'executetc':\r
+ style.configure("text.Horizontal.TProgressbar", text="",background="lightgray",foreground="lightgray", font=("Malgun Gothic", 10, 'bold'))\r
+ base.update()\r
+ result = "Build completed successfully" + "\n\n" + "Do you want to execute TCs?" + "\n" + "(Yes or No)"\r
+ else:\r
+ result = "Build Failed, Please check the TC file and try again."\r
+ print(output_build)\r
+ else:\r
+ result = "Build parameters values are not correct" + "\n" + "Please try again.."\r
+\r
+ if intent == "launchtctmgr":\r
+ # print("inside launchtctmgr intent")\r
+ bar("Installing...")\r
+ execute_params = get_build_parameters(execute_tc_params_text)\r
+ output_execute = tpk_build_install("install", "utc", MODULE_NAME, execute_params[1], execute_params[0])\r
+ style.configure("text.Horizontal.TProgressbar", text="",background="lightgray",foreground="lightgray", font=("Malgun Gothic", 10, 'bold'))\r
+ base.update()\r
+ open_tct_mgr()\r
+ previous_intent="after_launch"\r
+ result = "Installing the package..." + "Make sure the target is connected" "\n" + "Launching TCT-MGR tool" "\n\n" + "Do you want to continue for another module?"\r
+\r
+ print(output_execute)\r
+\r
+ elif intent == "goback":\r
+ # print("checking new module value from goback", new_module)\r
+ # print("Going back\n")\r
+ # print("previous stage is ", last_stage_index)\r
+ # print("previous result was: ")\r
+ # print(result)\r
+ if last_stage_index == 6:\r
+ result = "You can't go back at this stage. Please write the appropriate inputs"\r
+ else:\r
+ previous_intent = "goback"\r
+ ind = 0\r
+ result = "Please select numbers for the corresponding stage you want to go to:\n"\r
+ while ind <= last_stage_index and ind < 6:\r
+ result = result + str(ind+1) + ". " + stage_list[ind] + "\n"\r
+ ind = ind + 1\r
+ result = result + "\n\n" + "If you wish to EXIT, Please type Exit"\r
+\r
+ except:\r
+ log_create(logger, "Error occurred in get_prediction function")\r
+ return "Invalid Input. Please try writing again"\r
+\r
+\r
+\r
+ return result\r
+\r
+\r
+print("TC Assistant tool launched successfully..!!")\r
+log_info_save_processing(logger, "TC Assistant tool launched successfully..!!")\r
+\r
+# GUI with tkinter\r
+\r
+def copy_text(res):\r
+ # base.withdraw()\r
+ base.clipboard_clear()\r
+ base.clipboard_append(res)\r
+ base.update()\r
+\r
+def _on_mousewheel(event):\r
+ base.yview_scroll(int(-1*(event.delta/120)), "units")\r
+\r
+def center(win):\r
+ """\r
+ centers a tkinter window\r
+ :param win: the main window or Toplevel window to center\r
+ """\r
+ win.update_idletasks()\r
+ width = win.winfo_width()\r
+ frm_width = win.winfo_rootx() - win.winfo_x()\r
+ win_width = width + 2 * frm_width\r
+ height = win.winfo_height()\r
+ titlebar_height = win.winfo_rooty() - win.winfo_y()\r
+ win_height = height + titlebar_height + frm_width\r
+ x = win.winfo_screenwidth() // 2 - win_width // 2\r
+ y = win.winfo_screenheight() // 2 - win_height // 2\r
+ win.geometry('{}x{}+{}+{}'.format(width, height, x, y))\r
+ win.deiconify()\r
+\r
+#control + a event in entry box\r
+def select_all(event):\r
+ EntryBox.tag_add(SEL, "1.0", END)\r
+ EntryBox.mark_set(INSERT, "1.0")\r
+ EntryBox.see(INSERT)\r
+ return 'break'\r
+\r
+def send(event=None):\r
+ msg = EntryBox.get("1.0",'end-1c').strip()\r
+ EntryBox.delete("0.0",END)\r
+\r
+ if msg != '':\r
+ # print("msg ############", msg)\r
+ if '\n' in msg:\r
+ msg = msg.replace('\n','')\r
+ msg = msg.replace('\t','')\r
+ # print("msg after ############", msg)\r
+\r
+ log_info_save(logger, "YOU", msg)\r
+ ChatLog.config(state=NORMAL)\r
+\r
+ ChatLog.tag_configure('tag-left', justify='left')\r
+ ChatLog.tag_configure('tag-right', justify='right')\r
+ ChatLog.insert(END, '\n')\r
+ User = Label(ChatLog,text=f"You: "+msg,background='#d0ffff', justify='left', padx=10, pady=5,font=("Malgun Gothic", 11 ),wraplength=500, cursor="hand1")\r
+ ChatLog.insert('end', '\n ','tag-right')\r
+ ChatLog.window_create('end', window=User)\r
+ ChatLog.insert(END, '\n')\r
+ ChatLog.yview(END)\r
+ if msg.lower() == "exit":\r
+ res = "Thanks, Goodbye !!"\r
+ User = Label(ChatLog,text="Assistant: "+res,background='#ffffd0', justify='left', padx=10, pady=5,font=("Malgun Gothic", 11 ),wraplength=500, cursor="hand1")\r
+ ChatLog.insert('end', '\n') # space to move Label to the right\r
+ ChatLog.window_create('end', window=User)\r
+ ChatLog.insert(END, '\n')\r
+ ChatLog.config(state=NORMAL)\r
+ ChatLog.yview(END)\r
+ #time.sleep(2)\r
+ base.after(1000,base.quit)\r
+ else:\r
+ try:\r
+ res = get_response(msg)\r
+\r
+ except:\r
+ log_create(logger, "Error occurred while executing get_response function!")\r
+ res = get_response(msg)\r
+\r
+ ChatLog.insert(END, '\n')\r
+\r
+ log_info_save(logger, "Assitant", res)\r
+ if res == "exit":\r
+ res = "Thanks, Goodbye !!"\r
+ User = Label(ChatLog,text="Assistant: "+res,background='#ffffd0', justify='left', padx=10, pady=5,font=("Malgun Gothic", 11 ),wraplength=500, cursor="hand1")\r
+ ChatLog.insert('end', '\n') # space to move Label to the right\r
+ ChatLog.window_create('end', window=User)\r
+ ChatLog.insert(END, '\n')\r
+ ChatLog.config(state=NORMAL)\r
+ ChatLog.yview(END)\r
+ #time.sleep(2)\r
+ base.after(1000,base.quit)\r
+ elif msg.lower() != 'exit' and res != 'exit':\r
+ Bot = Label(ChatLog,text="Assistant: "+res,background='#ffffd0', justify='left', padx=10, pady=5,font=("Malgun Gothic", 11 ),wraplength=500, cursor="hand1")\r
+ ChatLog.insert('end', '\n') # space to move Label to the right\r
+ ChatLog.window_create('end', window=Bot)\r
+ ChatLog.insert(END, '\n')\r
+ ChatLog.config(state=NORMAL)\r
+ ChatLog.yview(END)\r
+ User.bind("<Button-1>", lambda e:copy_text(msg))\r
+ Bot.bind("<Button-1>", lambda e:copy_text(res))\r
+\r
+ ChatLog.config(state=DISABLED)\r
+ # ChatLog.yview(END)\r
+\r
+\r
+def helpText():\r
+ # subprocess.call([opener, '/home/sri/tctapi/7.0/api/tool/TC_Assistant/HELP_TEXT.txt'])\r
+ #Creates a Button to Open the Toplevel Window which opens a popup to display all the instructions\r
+ top= Toplevel(base)\r
+ top.geometry("750x820")\r
+ top.title("Help Guide")\r
+ with open('HELP_TEXT.txt', 'r') as file:\r
+ data = file.read()\r
+\r
+ scroll_bar_help = Scrollbar(top)\r
+ scroll_bar_help.pack( side = RIGHT, fill = Y )\r
+ mylist = Text(top, bd=0, bg="light grey", height="50", width="30", font="Arial",wrap=WORD)\r
+ mylist.insert(END, data)\r
+ mylist.pack(fill = BOTH )\r
+ mylist.config(state=DISABLED)\r
+ scroll_bar_help.config( command = mylist.yview )\r
+ mylist['yscrollcommand'] = scroll_bar_help.set\r
+\r
+\r
+def on_closing():\r
+ if messagebox.askokcancel("Quit", "Do you want to quit?"):\r
+ ## print("TC Assistant tool is closed..Goodbye..!!")\r
+ sys.exit()\r
+ base.destroy()\r
+\r
+\r
+CURRENT_PATH = get_current_dir_path()\r
+CURRENT_PATH_IMG = get_current_dir_path_for_image()\r
+base.title("TC Assistant")\r
+base.call('wm', 'iconphoto', base._w, ImageTk.PhotoImage(file=CURRENT_PATH_IMG + '/logo1.png', master = base))\r
+base.geometry("600x800")\r
+base.resizable(width=FALSE, height=FALSE)\r
+# base.eval('tk::PlaceWindow . center')\r
+center(base)\r
+\r
+ChatLog = Text(base, bd=0, bg="white", height="8", width="10", font="Arial",wrap=WORD)\r
+ChatLog.pack(fill=BOTH)\r
+\r
+welcomeText = "Hey, Welcome to TC Assistance System. Tell me how would you like to proceed? \n > You can add a new UTC in existing module [Type: 'existing']\n > You can add UTC in new module [Type: 'new']\n"\r
+\r
+log_info_save(logger, "Assitant", welcomeText)\r
+\r
+Bot = Label(ChatLog,text="Assistant: "+welcomeText,background='#ffffd0', justify='left', padx=10, pady=5,font=("Malgun Gothic", 11),wraplength=500, cursor="hand2")\r
+ChatLog.insert('end', '\n ')\r
+ChatLog.window_create('end', window=Bot)\r
+ChatLog.insert(END, '\n')\r
+\r
+ChatLog.config(state=DISABLED)\r
+\r
+scrollbar = Scrollbar(base, command=ChatLog.yview)\r
+ChatLog['yscrollcommand'] = scrollbar.set\r
+\r
+SendButton = Button(base, font=("Verdana", 11, 'bold'), text="Send", width="9", height=5,\r
+ bd=5, bg="#6495ED", activebackground="#6495ED", fg='#ffffff',\r
+ command=send, relief="raised")\r
+\r
+\r
+EntryBox = Text(base, bd=1, bg="white", width="29", height="5", font=("Malgun Gothic", 12))\r
+EntryBox.focus_set()\r
+EntryBox.pack()\r
+\r
+copyrightText = Label(base,text='Copyright (c) 2023 Samsung Electronics Co., Ltd.',justify='right',padx=4,font=("Verdana",10))\r
+\r
+helpButton = Button(base,font=("Verdana",10),text='Help',width=5,height=2,bg='black',activebackground='grey',fg='white',command= helpText)\r
+\r
+\r
+scrollbar.place(x=576, y=22, height=656)\r
+ChatLog.place(x=6, y=22, height=656, width=570)\r
+EntryBox.place(x=6, y=680, height=80, width=455)\r
+SendButton.place(x=461, y=678, height=83)\r
+copyrightText.place(x=6, y=770)\r
+helpButton.place(x=530,y=765,height=30,width=60)\r
+# progress.place(width=150)\r
+progress.pack(fill=X, ipady=2)\r
+base.bind('<Return>',send)\r
+base.protocol("WM_DELETE_WINDOW", on_closing)\r
+base.bind_all("<MouseWheel>", _on_mousewheel)\r
+EntryBox.bind("<Control-Key-a>", select_all)\r
+EntryBox.bind("<Control-Key-A>", select_all)\r
+base.mainloop()\r
--- /dev/null
+from header_file_location import *
+from header_file_parse import *
+from input_output_params import *
+from validate_api import *
+from get_callback_func import *
+
+ALL_COMBINED_FUNC_ARGS = []
+callback_duplicate_check = []
+
+# global TARGET_API_INPUT_PARAMS_LIST
+TARGET_API_INPUT_PARAMS_LIST = []
+Module_name_new =""
+
+tc_code_inti = """/**
+ * @testcase utc_bluetooth_bt_initialize_p
+ * @since_tizen 8_0
+ * @description
+ * @scenario
+ */
+int utc_bluetooth_bt_initialize_p(void)
+{
+ int ret = bt_initialize();
+ assert_eq(ret, BT_ERROR_NONE);
+
+ return 0;
+}"""
+
+
+def check_if_str_or_int(inp_string):
+ if "char" in inp_string:
+ # return "test" if string
+ return '"test"'
+ elif "int" in inp_string:
+ return "1"
+ elif "void" in inp_string:
+ return "NULL"
+ elif "_h" in inp_string:
+ return "NULL"
+ else:
+ return "None"
+
+def iniatialize_variables(inp_out_params_list_updated, all_comb_args_set, enum_dict, enum_dict_pre_post):
+ # all_comb_args_set = ["const char interface", "const char service_type", "dnssd_service_h dnssd_service", "const char service_name", "unsigned int service_int"]
+ # inp_out_params_list_updated = input_output_params_extract("nsd", "nsd/dns-sd-internal.h", "dnssd_create_remote_service", inp_out_params_list_updated)
+ # inp_out_params_list_updated = input_output_params_extract("nsd", "nsd/dns-sd-internal.h", "dnssd_destroy_remote_service", inp_out_params_list_updated)
+ ## print(inp_out_params_list_updated)
+ ## print(check_if_param_is_in_or_out(inp_out_params_list_updated))
+ #enum_dict = {'dnssd_service_set_interface': {'webrtc_state_e': 'WEBRTC_ERROR_PERMISSION_DENIED'}, 'webrtc_get_state': {'webrtc_state_e': 'WEBRTC_STATE_IDLE'}}
+ check_if_param_is_in_or_out_dict = check_if_param_is_in_or_out(inp_out_params_list_updated)
+ store_last_word_of_args = []
+ for pos, ele in enumerate(all_comb_args_set):
+ if ele.find("_cb")>0:
+ all_comb_args_set[pos] =""
+ elif ele.split()[-1] in check_if_param_is_in_or_out_dict:
+ dict_value = check_if_param_is_in_or_out_dict[ele.split()[-1]]
+ ele1 = ele
+ if dict_value == "in" and "char" in ele:
+ ele = ele.split()
+ for l in ele:
+ if l == ele[-1]:
+ ele[-1] = "*" + l
+ ele = " ".join(ele)
+ all_comb_args_set[pos] = ele + " " + "=" + " " + check_if_str_or_int(ele)
+ elif dict_value == "in" and "void" in ele:
+ ele = ele.split()
+ for l in ele:
+ if l == ele[-1]:
+ ele[-1] = "*" + l
+ ele = " ".join(ele)
+ all_comb_args_set[pos] = ele + " " + "=" + " " + check_if_str_or_int(ele)
+ elif "_h" in ele:
+ all_comb_args_set[pos] = ele + " " + "=" + " " + check_if_str_or_int(ele)
+ elif "_h" not in ele and dict_value == "out":
+ ele = ele.split()
+ for l in ele:
+ if l == ele[-1]:
+ ele[-1] = "" + l
+ ele = " ".join(ele)
+ if "void" in ele:
+ # print(ele)
+ del all_comb_args_set[pos]
+ else:
+ all_comb_args_set[pos] = ele
+ ## print("all combs args set")
+ ## print(all_comb_args_set)
+ ## print("storing", store_last_word_of_args)
+ store_last_word_of_args1 = store_last_word_of_args[0:pos+1]
+ if ele.split()[-1] in store_last_word_of_args1:
+ all_comb_args_set.remove(all_comb_args_set[pos])
+ # break
+ store_last_word_of_args.append(ele.split()[-1])
+ ## print("iniatialized variables 2")
+
+ for i in all_comb_args_set:
+ if i == 'void' or i == 'void;' or i == '' or i == ' ' or i == ';':
+ all_comb_args_set.remove(i)
+
+ for pos, i in enumerate(all_comb_args_set):
+ # print("reached till here tc_code4 part 0")
+ # print(all_comb_args_set)
+ if i != "" and i != "void":
+ variable_name = i.split(" ")[1]
+ datatype_name = i.split(" ")[0]
+ # print("var name", variable_name)
+ # print("data name", datatype_name)
+ variable_name_without_ptr = variable_name.replace("*","")
+ # print("var name without ptr", variable_name_without_ptr)
+ flag = 0
+ flag_pre_post = 0
+
+ # print("reached till here tc_code4 part 1",enum_dict)
+ for ele, val in enum_dict.items():
+ # print("entered", ele, val)
+ for ele1, val1 in val.items():
+ # print("entered1", ele1, val1)
+ if ele1 in i:
+ if variable_name_without_ptr in check_if_param_is_in_or_out_dict:
+ if check_if_param_is_in_or_out_dict[variable_name_without_ptr] == "out":
+ all_comb_args_set[pos] = datatype_name + " " + variable_name_without_ptr
+ all_comb_args_set[pos] = all_comb_args_set[pos] + " " + "=" + " " + val1
+ flag = 1
+ break
+ if flag == 1:
+ break
+ # print("reached till here tc_code4 part 2",enum_dict_pre_post)
+ if "=" not in all_comb_args_set[pos]:
+ for ele, val in enum_dict_pre_post.items():
+ # print("entered inside pre post api", ele, val)
+ for ele1, val1 in val.items():
+ # print("entered1 inside pre post api", ele1, val1)
+ if ele1 in i:
+ if variable_name_without_ptr in check_if_param_is_in_or_out_dict:
+ if check_if_param_is_in_or_out_dict[variable_name_without_ptr] == "out":
+ all_comb_args_set[pos] = datatype_name + " " + variable_name_without_ptr
+ all_comb_args_set[pos] = all_comb_args_set[pos] + " " + "=" + " " + val1
+ flag = 1
+ break
+ if flag == 1:
+ break
+ # print("reached till here tc_code4 part 3")
+ # print("all arguments sequential ", i)
+ if i == "void" or i == "void;" or i == "" or i == " ":
+ all_comb_args_set.remove(i)
+ # # print("all_comb_args_set => ", all_comb_args_set)
+ # print("alllll_comb_argsssssss",all_comb_args_set)
+ tc_code4 = (
+ f" {k};"
+ "\n"
+ for k in all_comb_args_set)
+
+ # print(tc_code4)
+ return ''.join(tc_code4)
+
+
+
+
+def tc_code_write(RET_TYPE, MODULE_NAME, API_NAMES, FUNC_ARGS):
+ tc_code = (
+ "/**\n"
+ f"* @testcase utc_{API_NAMES}_p\n"
+ "* @since_tizen 8_0\n"
+ "* @description \n"
+ "* @scenario \n"
+ "*/\n"
+ f"{RET_TYPE} utc_{API_NAMES}_p(void)\n"
+ "{\n"
+ " int ret;\n"
+
+ f" ret = {API_NAMES}({FUNC_ARGS.replace('*', '&')});\n"
+ f" assert_eq(ret, TIZEN_ERROR_NONE);\n"
+
+ " return 0;\n"
+ "}\n"
+ )
+
+ return tc_code
+
+def concat_params1(v):
+ FUNC_ARGS = ""
+ FUNC_ARGS = v[0].split()[-1]
+ for j in range(1, len(v)):
+ FUNC_ARGS += ', ' + v[j].split()[-1]
+ return FUNC_ARGS
+
+
+# calculates count of all input paramters present in the target api to find out number of null values to be passed
+# it also maintains a dict TARGET_API_INPUT_PARAMS_LIST which stores all the input parameters in target api
+
+def list_target_api_in_params(API_NAME, check_if_param_is_in_or_out_dict, inp_out_params_list_updated):
+ TARGET_API_INPUT_PARAMS_LIST.clear()
+ if API_NAME in inp_out_params_list_updated:
+ #if len(inp_out_params_list_updated)>0:
+ in_out_array = inp_out_params_list_updated[API_NAME]
+ # print("in_out_array",in_out_array)
+ ## print("inp_out_params_list_updated[API_NAME]",inp_out_params_list_updated[API_NAME])
+ for ele in in_out_array:
+ for key, val in ele.items():
+ if val == 'in' and "_cb" not in key and 'user_data' not in key:
+ TARGET_API_INPUT_PARAMS_LIST.append(key)
+ ## print("TARGET_API_INPUT_PARAMS_LIST",TARGET_API_INPUT_PARAMS_LIST)
+ return TARGET_API_INPUT_PARAMS_LIST
+
+
+def concat_params(CURR_API, v, check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB):
+ FUNC_ARGS = ""
+ # print("CURR_API", CURR_API)
+ # print("check_if_param_is_in_or_out_dict", check_if_param_is_in_or_out_dict)
+ # print("inp_out_params_list_updated[CURR_API]", inp_out_params_list_updated)
+ # print("inp_out_params_list_updated[CURR_API]", inp_out_params_list_updated[CURR_API])
+ # print("inp_out_params_list_updated", inp_out_params_list_updated)
+ COMBINED_API_ARGS_DICT_CB = PRE_POST_API_ARGS_LIST.copy()
+ # print("PRE_POST_API_ARGS_LIST", PRE_POST_API_ARGS_LIST)
+ # print("TARGET_API_ARGS", TARGET_API_ARGS)
+ # print("TARGET_API_NAME_CB", TARGET_API_NAME_CB)
+ COMBINED_API_ARGS_DICT_CB[TARGET_API_NAME_CB] = TARGET_API_ARGS
+ # print("COMBINED_API_ARGS_DICT_CB", COMBINED_API_ARGS_DICT_CB)
+
+ # print(v)
+ # print("inp_out_params_list_updated inside concat_params", inp_out_params_list_updated)
+ # print("all_callback_args inside concat_params", all_callback_args)
+ for j in range(0, len(v)):
+ # print("j",j)
+ # print("(v[j].split()[-1])", (v[j].split()[-1]))
+ # print("v[j].split()[-1]).replace('*', '')",(v[j].split()[-1]).replace('*', ''))
+ if (v[j].split()[-1]).replace('*', '') in check_if_param_is_in_or_out_dict:
+ for ij in inp_out_params_list_updated[CURR_API]:
+ # print("inp_out_params_list_updated[CURR_API]sdfsadfsda",inp_out_params_list_updated[CURR_API])
+ # print("ij # print inside concat", ij)
+ key = list(ij.keys())[0]
+ value = ij[key]
+
+ # print("key value items are", key, value)
+ if (key == (v[j].split()[-1]).replace('*', '') and value == "out") and ("_cb" not in key and "callback" not in key) and ("_cb" not in COMBINED_API_ARGS_DICT_CB[CURR_API][j]):
+ FUNC_ARGS += "&" + (v[j].split()[-1]).replace('*', '') + ', '
+ # print("Func_args in 1st if",FUNC_ARGS)
+ # break
+ elif (key == (v[j].split()[-1]).replace('*', '') and value == "in") and ("_cb" not in key and "callback" not in key) and ("_cb" not in COMBINED_API_ARGS_DICT_CB[CURR_API][j]):
+ FUNC_ARGS += "" + (v[j].split()[-1]).replace('*', '') + ', '
+ # print("Func_args in 2nd if",FUNC_ARGS)
+ # break
+ elif "_cb" in key or "callback" in key or "_cb" in COMBINED_API_ARGS_DICT_CB[CURR_API][j]:
+ if IDX_CALLBACK < len(all_callback_args):
+ for curr_ele in COMBINED_API_ARGS_DICT_CB[CURR_API]:
+ splited_key = curr_ele.split()[0]
+ if splited_key in all_callback_args[IDX_CALLBACK]:
+ FUNC_ARGS += "callback_" + all_callback_args[IDX_CALLBACK] + ', '
+ # print("FUNC_ARGS inside callback")
+ # print(FUNC_ARGS)
+ IDX_CALLBACK = IDX_CALLBACK + 1
+ # break
+ # print("FUNC_ARGS at the end")
+ # print(FUNC_ARGS)
+ # flag = flag + 1
+ # print("final func args")
+ # print(FUNC_ARGS)
+
+ else:
+ # print("Func_args in else",FUNC_ARGS)
+ FUNC_ARGS += "" + (v[j].split()[-1]) + ', '
+
+ FUNC_ARGS = FUNC_ARGS.strip()
+ # print("fuinc args", FUNC_ARGS)
+ FUNC_ARGS = FUNC_ARGS.rstrip(FUNC_ARGS[-1])
+ if "void" in FUNC_ARGS:
+ return ""
+ else:
+ return FUNC_ARGS
+
+def combined_func_args(lst):
+ return set(lst)
+
+
+def init_params_in_out_dict(inp_out_params_list_updated):
+ # print("inp_out_params_list_updated",inp_out_params_list_updated)
+ check_if_param_is_in_or_out_dict = check_if_param_is_in_or_out(inp_out_params_list_updated)
+ # print("checking if_param is in or out", check_if_param_is_in_or_out_dict)
+ return check_if_param_is_in_or_out_dict
+
+
+def tc_code_write1(RET_TYPE, MODULE_NAME, API_NAME, PRE_POST_API_LIST, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, HEADER_FILE_CONTAINED_FOLDER, enum_dict, enum_dict_pre_post, feature_name, callback_duplicate_check):
+ # PRE_POST_API_LIST = PRE_POST_API_LIST['badge_create']
+ ## print("checking")
+ ## print("enum_dict", enum_dict)
+ ## print("enum_pre_post", enum_dict_pre_post)
+ IDX_CALLBACK = 0
+ inp_out_params_list_updated = {}
+ check_if_param_is_in_or_out_dict = {}
+ ALL_COMBINED_FUNC_ARGS = []
+ # api_desc_list = {}
+ pre_apis = PRE_POST_API_LIST['Pre']
+ ## print("pre",pre_apis)
+ post_apis = PRE_POST_API_LIST['Post']
+ ## print("post",post_apis)
+ if HEADER_FILE_CONTAINED_FOLDER == "":
+ HEADER_FILE_CONTAINED_FOLDER = MODULE_NAME
+ for ele in pre_apis:
+ for ele_arg in PRE_POST_API_ARGS_LIST[ele]:
+ if "**" in ele_arg:
+ ALL_COMBINED_FUNC_ARGS.append(ele_arg.replace('*', '',1))
+ else:
+ ALL_COMBINED_FUNC_ARGS.append(ele_arg.replace('*', ''))
+ # print("ALL_COMBINED",ALL_COMBINED_FUNC_ARGS)
+ for ele in post_apis:
+ for ele_arg in PRE_POST_API_ARGS_LIST[ele]:
+ if "**" in ele_arg:
+ ALL_COMBINED_FUNC_ARGS.append(ele_arg.replace('*', '',1))
+ else:
+ ALL_COMBINED_FUNC_ARGS.append(ele_arg.replace('*', ''))
+
+ for ele in TARGET_API_ARGS:
+ if "**" in ele:
+ ALL_COMBINED_FUNC_ARGS.append(ele.replace('*', '',1))
+ else:
+ ALL_COMBINED_FUNC_ARGS.append(ele.replace('*', ''))
+
+ # print("all_combined_func_args",ALL_COMBINED_FUNC_ARGS)
+ combined_func_args(ALL_COMBINED_FUNC_ARGS)
+ all_callback_args = []
+ all_comb_args_set = []
+ all_comb_args_set = list(combined_func_args(ALL_COMBINED_FUNC_ARGS))
+ # print("all_comb_args_set",all_comb_args_set)
+ for ele in all_comb_args_set:
+ if "_cb" in ele:
+ all_callback_args.append(ele.split(" ")[0])
+
+
+
+
+ header_files_dict = get_header_files(MODULE_NAME)
+ ## print("##############")
+ ## print("header_files_dict",header_files_dict)
+ # for ever file in the dictionary we have to check if all the api names provided by the user exists or not
+ # we will take api names one by one and check in all the files if it exists or not
+ for API_SEARCH in pre_apis:
+ ## print("API_SEARCH",API_SEARCH)
+ for HEADER_FILE_NAME in header_files_dict:
+ ## print("HEADER_FILE_NAME",HEADER_FILE_NAME)
+ inp_out_params_list_updated = input_output_params_extract(MODULE_NAME, HEADER_FILE_NAME, API_SEARCH, inp_out_params_list_updated)
+ # print("inp_out_params_list_updated in pre api",inp_out_params_list_updated)
+ # print("post_apis",post_apis)
+ for API_SEARCH in post_apis:
+ ## print("hi")
+ for HEADER_FILE_NAME in header_files_dict:
+ ## print("hi1")
+ inp_out_params_list_updated = input_output_params_extract(MODULE_NAME, HEADER_FILE_NAME, API_SEARCH, inp_out_params_list_updated)
+ # print("inp_out_params_list_updated in post api",inp_out_params_list_updated)
+ ## print("hi in post")
+ for HEADER_FILE_NAME in header_files_dict:
+ ## print("hi")
+ ## print("HEADER_FILE_NAME",HEADER_FILE_NAME)
+ inp_out_params_list_updated = input_output_params_extract(MODULE_NAME, HEADER_FILE_NAME, API_NAME, inp_out_params_list_updated)
+ # print("inp_out_params_list_updated in header file",inp_out_params_list_updated)
+ for HEADER_FILE_NAME in header_files_dict:
+ api_desc = api_description_extract(MODULE_NAME, HEADER_FILE_NAME, API_NAME)
+ # print("api_desc",api_desc)
+ if api_desc != "":
+ break
+ ## print("###### inp_out_params_list_updated")
+ ## print(inp_out_params_list_updated)
+ # global callback_duplicate_check
+
+ TARGET_API_NAME_CB = API_NAME
+ callback_func_combined = ""
+ # print("aaaaaaaaaaaaca",all_callback_args)
+ for cb_name in all_callback_args:
+ for header_file in header_files_dict:
+ #print("header_files_dict",header_files_dict)
+ #print(header_file)
+ if cb_name not in callback_duplicate_check:
+ callback_func_combined = callback_func_combined + cb_function_declaration(MODULE_NAME,header_file,cb_name)
+ #print('cb_function_declaration(MODULE_NAME,header_file,cb_name', cb_function_declaration(MODULE_NAME,header_file,cb_name))
+ if cb_function_declaration(MODULE_NAME,header_file,cb_name) != '':
+ callback_duplicate_check.append(cb_name)
+ # break
+ else:
+ callback_func_combined = callback_func_combined + ''
+
+ # callback_duplicate_check = callback_duplicate_check + all_callback_args
+ # print("callback_func_combined")
+ tc_code0 = (
+ "/**\n"
+ f"* @testcase utc_{API_NAME}_p\n"
+ "* @since_tizen 8_0\n"
+ "* @type Positive\n"
+ f"* @description {api_desc}\n"
+ "* @scenario \n"
+ "*/\n")
+ tc_code = (
+ f"{RET_TYPE} utc_{API_NAME}_p(void)\n"
+ "{\n"
+ " int ret;\n")
+ # tc_code4 = (
+ # f" {k};"
+ # "\n"
+ # for k in all_comb_args_set)
+ # ## print("#########")
+ # ## print(inp_out_params_list_updated)
+ ## print("all_comb_args_set from tc_code")
+ # print("inp_out_params_list_updated final",inp_out_params_list_updated)
+ tc_code4 = iniatialize_variables(inp_out_params_list_updated, all_comb_args_set, enum_dict, enum_dict_pre_post)
+ # print("tc_code_4", tc_code4)
+
+ tc_code6 = callback_func_combined
+ # f" {i}" for i in pre_apis
+ # f"{PRE_POST_API_ARGS_LIST[i]}"
+ check_if_param_is_in_or_out_dict = init_params_in_out_dict(inp_out_params_list_updated)
+ # function call to iniatialize
+ # print("inp_out_params_list_updated",inp_out_params_list_updated)
+ list_target_api_in_params(API_NAME, check_if_param_is_in_or_out_dict, inp_out_params_list_updated)
+
+ if MODULE_NAME == "nsd":
+ MODULE_NAME = "dnssd"
+ if MODULE_NAME == "email":
+ MODULE_NAME = "emails"
+
+ tc_code1 = (f" ret = {i}({concat_params(i, PRE_POST_API_ARGS_LIST[i], check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB)});\n assert_eq(ret, TIZEN_ERROR_NONE);\n\n" for i in pre_apis)
+ # print("tc_code1",tc_code1)
+ tc_code_feature = ""
+ if feature_name != "":
+ x = feature_name.split('/')
+ length = len(x)
+ key_word = x[length - 1]
+ key_word=key_word.replace('.','_')
+
+ tc_code_feature = (f" bool {key_word}_supported = false; \n\n"
+ f" ret = system_info_get_platform_bool(\"{feature_name}\", &{key_word}_supported);\n"
+ f" if({key_word}_supported == false)" + "{\n"
+ f" ret = {API_NAME}({concat_params(API_NAME, TARGET_API_ARGS, check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB)});\n"
+ f" assert_eq(ret, TIZEN_ERROR_NOT_SUPPORTED);\n"
+ f" return 0;\n"
+ " }\n\n")
+
+ ## print("tc_code_feature",tc_code_feature)
+ # print("lAPI_NAME",API_NAME, "TARGET_API_ARGS",TARGET_API_ARGS, "check_if_param_is_in_or_out_dict",check_if_param_is_in_or_out_dict, "inp_out_params_list_updated",inp_out_params_list_updated, "all_callback_args",all_callback_args, "IDX_CALLBACK",IDX_CALLBACK)
+ tc_code2 = (f" ret = {API_NAME}({concat_params(API_NAME, TARGET_API_ARGS, check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB)});\n"
+ f" assert_eq(ret, TIZEN_ERROR_NONE);\n\n")
+ tc_code3 = (f" ret = {j}({concat_params(j, PRE_POST_API_ARGS_LIST[j], check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB)});\n assert_eq(ret, TIZEN_ERROR_NONE);\n\n"
+ # f" return 0;\n"
+ # "}\n"
+ for j in post_apis)
+ ## print("tc code 3", ''.join(tc_code3))
+ tc_code5 = (f" return 0;\n"
+ "}\n")
+ ## print("tc code 5", tc_code5)
+ ## print("tc_code_6", tc_code6)
+ ## print("checking tccode1")
+ ## print(''.join(tc_code1))
+ ## print("\n" + ''.join(tc_code1))
+ ## print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^66")
+ ## print("checking tc")
+ ## print(tc_code6 + "\n\n" + tc_code0 + tc_code + tc_code4 + "\n" + ''.join(tc_code1) + tc_code_feature + tc_code2 + ''.join(tc_code3) + tc_code5)
+ return "\n" + tc_code6 + "\n\n" + tc_code0 + tc_code + tc_code4 + "\n" + ''.join(tc_code1) + tc_code_feature + tc_code2 + ''.join(tc_code3) + tc_code5
+
+
+def tc_code_init(MODULE_NAME, file_name,header_files_dict):
+
+ tc_init0 = (
+ "/**\n"
+ "* Copyright (c) 2023 Samsung Electronics Co., Ltd All Rights Reserved\n"
+ "*\n"
+ '* Licensed under the Apache License, Version 2.0 (the "License");\n'
+ "* you may not use this file except in compliance with the License.\n"
+ "* You may obtain a copy of the License at\n"
+ "*\n"
+ "* http://www.apache.org/licenses/LICENSE-2.0\n"
+ "*\n"
+ "* Unless required by applicable law or agreed to in writing, software\n"
+ '* distributed under the License is distributed on an "AS IS" BASIS,\n'
+ "* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
+ "* See the License for the specific language governing permissions and\n"
+ "* limitations under the License.\n"
+ "*/\n\n"
+ )
+
+ HEADER_FILE_DICT1=[]
+ for HEADER_FILE_NAME in header_files_dict:
+ #error occurence
+ if "/" in HEADER_FILE_NAME:
+ POS_OF_SLASH = HEADER_FILE_NAME.index("/")
+ # print("POS_OF_SLASH",POS_OF_SLASH)
+ HEADER_FILE_NAME_WITHOUT_SLASH = HEADER_FILE_NAME[POS_OF_SLASH+1:]
+ # print(HEADER_FILE_NAME_WITHOUT_SLASH)
+ HEADER_FILE_DICT1.append(HEADER_FILE_NAME_WITHOUT_SLASH)
+ else:
+ HEADER_FILE_DICT1.append(HEADER_FILE_NAME)
+ tc_init1 = (
+ '#include "assert.h"\n'
+ "#include <glib.h>\n"
+ )
+
+ tc_init2 = (
+ f"#include <{HEADER_FILE_NAME_WITHOUT_SLASH}>\n" for HEADER_FILE_NAME_WITHOUT_SLASH in HEADER_FILE_DICT1
+ )
+
+ tc_init3 = (
+ "#include <dlog.h>\n"
+ "#include <Elementary.h>\n\n\n"
+ )
+
+ file_name_split = os.path.splitext(file_name)[0]
+
+ # print("file_name_after_split",file_name_split)
+ file_name_split = file_name_split.replace('-','_')
+ if 'utc' in file_name_split:
+ word_list=file_name_split.split('_')
+ word_list.remove('utc')
+ file_name_split='_'.join(word_list)
+ tc_init4 = (
+ "/**\n"
+ f"* @function utc_{file_name_split}_startup\n"
+ "* @description Called before each test\n"
+ "* @parameter NA\n"
+ "* @return NA\n"
+ "*/\n"
+ f"void utc_{file_name_split}_startup(void)\n"
+ "{\n"
+ "}\n\n"
+ )
+
+ tc_init5 = (
+ "/**\n"
+ f"* @function utc_{file_name_split}_cleanup\n"
+ "* @description Called after each test\n"
+ "* @parameter NA\n"
+ "* @return NA\n"
+ "*/\n"
+ f"void utc_{file_name_split}_cleanup(void)\n"
+ "{\n"
+ "}\n\n"
+ )
+
+ return tc_init0 + tc_init1 + ''.join(tc_init2) + tc_init3 + tc_init4 + tc_init5
--- /dev/null
+from header_file_location import *
+from header_file_parse import *
+from input_output_params import *
+from validate_api import *
+from get_callback_func import *
+from template_tc import *
+from get_return_val_of_api import *
+import numpy as np
+
+ALL_COMBINED_FUNC_ARGS = []
+input_params = []
+flag = 0
+flag_in_params = 0
+
+
+
+def check_if_str_or_int(inp_string):
+ if "char" in inp_string:
+ # return "test" if string
+ return '"test"'
+ elif "int" in inp_string:
+ return "1"
+ elif "void" in inp_string:
+ return "NULL"
+ elif "_h" in inp_string:
+ return "NULL"
+ else:
+ return "None"
+
+#NULL in case of handle, -1 for int or float or double
+def check_if_str_or_int_neg(list_of_all_params_with_retval, inp_string):
+ for val in list_of_all_params_with_retval:
+ val_temp = val.split()[1]
+ if inp_string in val_temp:
+ if "float" in val or "int" in val or "double" in val or "unsigned" in val or "unsigned int" in val:
+ return "-1"
+ if ("_e" in val and "_h" not in val):
+ return "-1"
+ else:
+ return "NULL"
+ return "NULL"
+
+def iniatialize_variables(inp_out_params_list_updated, all_comb_args_set, enum_dict, enum_dict_pre_post):
+ #enum_dict = {'dnssd_service_set_interface': {'webrtc_state_e': 'WEBRTC_ERROR_PERMISSION_DENIED'}, 'webrtc_get_state': {'webrtc_state_e': 'WEBRTC_STATE_IDLE'}}
+ check_if_param_is_in_or_out_dict = check_if_param_is_in_or_out(inp_out_params_list_updated)
+ store_last_word_of_args = []
+ for pos, ele in enumerate(all_comb_args_set):
+ if ele.find("_cb")>0:
+ all_comb_args_set[pos] =""
+ elif ele.split()[-1] in check_if_param_is_in_or_out_dict:
+ dict_value = check_if_param_is_in_or_out_dict[ele.split()[-1]]
+ ele1 = ele
+ if dict_value == "in" and "char" in ele:
+ ele = ele.split()
+ for l in ele:
+ if l == ele[-1]:
+ ele[-1] = "*" + l
+ ele = " ".join(ele)
+ all_comb_args_set[pos] = ele + " " + "=" + " " + check_if_str_or_int(ele)
+ elif dict_value == "in" and "void" in ele:
+ ele = ele.split()
+ for l in ele:
+ if l == ele[-1]:
+ ele[-1] = "*" + l
+ ele = " ".join(ele)
+ all_comb_args_set[pos] = ele + " " + "=" + " " + check_if_str_or_int(ele)
+ elif "_h" in ele:
+ all_comb_args_set[pos] = ele + " " + "=" + " " + check_if_str_or_int(ele)
+ elif "_h" not in ele and dict_value == "out":
+ ele = ele.split()
+ for l in ele:
+ if l == ele[-1]:
+ ele[-1] = "" + l
+ ele = " ".join(ele)
+ if "void" in ele:
+ # print(ele)
+ del all_comb_args_set[pos]
+ else:
+ all_comb_args_set[pos] = ele
+ ## print("all combs args set")
+ ## print(all_comb_args_set)
+ ## print("storing", store_last_word_of_args)
+ store_last_word_of_args1 = store_last_word_of_args[0:pos+1]
+ if ele.split()[-1] in store_last_word_of_args1:
+ all_comb_args_set.remove(all_comb_args_set[pos])
+ # break
+ store_last_word_of_args.append(ele.split()[-1])
+ ## print("iniatialized variables 2")
+
+ for i in all_comb_args_set:
+ if i == 'void' or i == 'void;' or i == '' or i == ' ' or i == ';':
+ all_comb_args_set.remove(i)
+
+ for pos, i in enumerate(all_comb_args_set):
+ # print("reached till here tc_code4 part 0")
+ # print(all_comb_args_set)
+ if i != "" and i != "void":
+ variable_name = i.split(" ")[1]
+ datatype_name = i.split(" ")[0]
+ # print("var name", variable_name)
+ # print("data name", datatype_name)
+ variable_name_without_ptr = variable_name.replace("*","")
+ # print("var name without ptr", variable_name_without_ptr)
+ flag = 0
+ flag_pre_post = 0
+
+ # print("reached till here tc_code4 part 1",enum_dict)
+ for ele, val in enum_dict.items():
+ # print("entered", ele, val)
+ for ele1, val1 in val.items():
+ # print("entered1", ele1, val1)
+ if ele1 in i:
+ if variable_name_without_ptr in check_if_param_is_in_or_out_dict:
+ if check_if_param_is_in_or_out_dict[variable_name_without_ptr] == "out":
+ all_comb_args_set[pos] = datatype_name + " " + variable_name_without_ptr
+ all_comb_args_set[pos] = all_comb_args_set[pos] + " " + "=" + " " + val1
+ flag = 1
+ break
+ if flag == 1:
+ break
+ # print("reached till here tc_code4 part 2",enum_dict_pre_post)
+ if "=" not in all_comb_args_set[pos]:
+ for ele, val in enum_dict_pre_post.items():
+ # print("entered inside pre post api", ele, val)
+ for ele1, val1 in val.items():
+ # print("entered1 inside pre post api", ele1, val1)
+ if ele1 in i:
+ if variable_name_without_ptr in check_if_param_is_in_or_out_dict:
+ if check_if_param_is_in_or_out_dict[variable_name_without_ptr] == "out":
+ all_comb_args_set[pos] = datatype_name + " " + variable_name_without_ptr
+ all_comb_args_set[pos] = all_comb_args_set[pos] + " " + "=" + " " + val1
+ flag = 1
+ break
+ if flag == 1:
+ break
+ # print("reached till here tc_code4 part 3")
+ # print("all arguments sequential ", i)
+ if i == "void" or i == "void;" or i == "" or i == " ":
+ all_comb_args_set.remove(i)
+ # # print("all_comb_args_set => ", all_comb_args_set)
+ # print("alllll_comb_argsssssss",all_comb_args_set)
+ tc_code4 = (
+ f" {k};"
+ "\n"
+ for k in all_comb_args_set)
+
+ # print(tc_code4)
+ return ''.join(tc_code4)
+
+
+
+def concat_params1(v):
+ FUNC_ARGS = ""
+ FUNC_ARGS = v[0].split()[-1]
+ for j in range(1, len(v)):
+ FUNC_ARGS += ', ' + v[j].split()[-1]
+ return FUNC_ARGS
+
+def concat_params(CURR_API, v, check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB):
+ FUNC_ARGS = ""
+ COMBINED_API_ARGS_DICT_CB = PRE_POST_API_ARGS_LIST.copy()
+ COMBINED_API_ARGS_DICT_CB[TARGET_API_NAME_CB] = TARGET_API_ARGS
+ # print("COMBINED_API_ARGS_DICT_CB", COMBINED_API_ARGS_DICT_CB)
+ for j in range(0, len(v)):
+ if (v[j].split()[-1]).replace('*', '') in check_if_param_is_in_or_out_dict:
+
+ for ij in inp_out_params_list_updated[CURR_API]:
+ key = list(ij.keys())[0]
+ value = ij[key]
+
+ # print("key items are", key)
+ if (key == (v[j].split()[-1]).replace('*', '') and value == "out") and ("_cb" not in key and "callback" not in key) and ("_cb" not in COMBINED_API_ARGS_DICT_CB[CURR_API][j]):
+ FUNC_ARGS += "&" + (v[j].split()[-1]).replace('*', '') + ', '
+ # print("Func_args in 1st if",FUNC_ARGS)
+ # break
+ elif (key == (v[j].split()[-1]).replace('*', '') and value == "in") and ("_cb" not in key and "callback" not in key) and ("_cb" not in COMBINED_API_ARGS_DICT_CB[CURR_API][j]):
+ FUNC_ARGS += "" + (v[j].split()[-1]).replace('*', '') + ', '
+ # print("Func_args in 2nd if",FUNC_ARGS)
+ # break
+ elif "_cb" in key or "callback" in key or "_cb" in COMBINED_API_ARGS_DICT_CB[CURR_API][j]:
+ if IDX_CALLBACK < len(all_callback_args):
+ for curr_ele in COMBINED_API_ARGS_DICT_CB[CURR_API]:
+ splited_key = curr_ele.split()[0]
+ if splited_key in all_callback_args[IDX_CALLBACK]:
+ FUNC_ARGS += "callback_" + all_callback_args[IDX_CALLBACK] + ', '
+ # print("FUNC_ARGS inside callback")
+ # print(FUNC_ARGS)
+ IDX_CALLBACK = IDX_CALLBACK + 1
+ # break
+ # print("FUNC_ARGS at the end")
+ # print(FUNC_ARGS)
+ # flag = flag + 1
+ # print("final func args")
+ # print(FUNC_ARGS)
+
+ else:
+ # print("Func_args in else",FUNC_ARGS)
+ FUNC_ARGS += "" + (v[j].split()[-1]) + ', '
+
+ FUNC_ARGS = FUNC_ARGS.strip()
+ # print("fuinc args", FUNC_ARGS)
+ FUNC_ARGS = FUNC_ARGS.rstrip(FUNC_ARGS[-1])
+ if "void" in FUNC_ARGS:
+ return ""
+ else:
+ return FUNC_ARGS
+
+def concat_params_target(CURR_API, v, check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, INPUT_PARAMETER_MARKED_NULL, all_comb_args_set, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB):
+ FUNC_ARGS = ""
+ COMBINED_API_ARGS_DICT_CB = PRE_POST_API_ARGS_LIST.copy()
+ COMBINED_API_ARGS_DICT_CB[TARGET_API_NAME_CB] = TARGET_API_ARGS
+ for j in range(0, len(v)):
+ if (v[j].split()[-1]).replace('*', '') in check_if_param_is_in_or_out_dict:
+ for ij in inp_out_params_list_updated[CURR_API]:
+ # for key, value in ij.items():
+ key = list(ij.keys())[0]
+ value = ij[key]
+ if (key == (v[j].split()[-1]).replace('*', '') and value == "out") and ("_cb" not in key and "callback" not in key) and ("_cb" not in COMBINED_API_ARGS_DICT_CB[CURR_API][j]):
+ FUNC_ARGS += "&" + (v[j].split()[-1]).replace('*', '') + ', '
+ # break
+ elif (key == (v[j].split()[-1]).replace('*', '') and value == "in"):
+ if key == INPUT_PARAMETER_MARKED_NULL:
+ # FUNC_ARGS += "NULL" + ", "
+ FUNC_ARGS += check_if_str_or_int_neg(all_comb_args_set, key) + ", "
+ # break
+ elif (key!=INPUT_PARAMETER_MARKED_NULL) and ("_cb" not in key and "callback" not in key) and ("_cb" not in COMBINED_API_ARGS_DICT_CB[CURR_API][j]):
+ FUNC_ARGS += "" + (v[j].split()[-1]).replace('*', '') + ', '
+ # break
+ elif (key!=INPUT_PARAMETER_MARKED_NULL) and ("_cb" in key or "callback" in key or "_cb" in COMBINED_API_ARGS_DICT_CB[CURR_API][j]):
+ if IDX_CALLBACK < len(all_callback_args):
+ for curr_ele in COMBINED_API_ARGS_DICT_CB[CURR_API]:
+ splited_key = curr_ele.split()[0]
+ if splited_key in all_callback_args[IDX_CALLBACK]:
+ FUNC_ARGS += "callback_" + all_callback_args[IDX_CALLBACK] + ', '
+ # print("FUNC_ARGS inside callback")
+ # print(FUNC_ARGS)
+ IDX_CALLBACK = IDX_CALLBACK + 1
+ # break
+
+ else:
+ FUNC_ARGS += "" + (v[j].split()[-1]) + ', '
+
+ FUNC_ARGS = FUNC_ARGS.strip()
+ FUNC_ARGS = FUNC_ARGS.rstrip(FUNC_ARGS[-1])
+ if "void" in FUNC_ARGS:
+ return ""
+ else:
+ return FUNC_ARGS
+
+def combined_func_args(lst):
+ return set(lst)
+
+def init_params_in_out_dict(inp_out_params_list_updated):
+ check_if_param_is_in_or_out_dict = check_if_param_is_in_or_out(inp_out_params_list_updated)
+ return check_if_param_is_in_or_out_dict
+
+# calculates count of all input paramters present in the target api to find out number of null values to be passed
+# it also maintains a dict TARGET_API_INPUT_PARAMS_LIST which stores all the input parameters in target api
+
+def calc_count_of_in_params(API_NAME, inp_out_params_list_updated):
+ global flag
+ # print("inp_out_params_list_updated hergrvb",inp_out_params_list_updated)
+ # print(inp_out_params_list_updated)
+ cnt = 0
+ if API_NAME in inp_out_params_list_updated:
+ in_out_array = inp_out_params_list_updated[API_NAME]
+ else:
+ in_out_array = []
+
+ for ele in in_out_array:
+ key = list(ele.keys())[0]
+ val = ele[key]
+ if val == 'in' and "_cb" not in key and 'user_data' not in key:
+ cnt = cnt + 1
+
+ global input_params
+ if flag == 0:
+ # input_params.append(cnt)
+ # print("appended input_params when not zero", input_params, flag, cnt)
+ flag = 1
+ # print("###########calc_count_of_in_params")
+ # print(API_NAME)
+ # print(inp_out_params_list_updated)
+ # print(in_out_array)
+ # print(input_params)
+ return cnt
+
+def ret_input_params():
+ return input_params
+# main negative tc template which gets formed, later appended in .c file of the module
+
+def tc_code_write_negative(RET_TYPE, MODULE_NAME, API_NAME, PRE_POST_API_LIST, PRE_POST_API_ARGS_LIST, FUNC_ARGS, HEADER_FILE_CONTAINED_FOLDER, NEGATIVE_TC_COUNT, INPUT_PARAMETER_MARKED_NULL, feature_name, enum_dict, enum_dict_pre_post):
+ # print("PRE_POST_API_LIST")
+ # print(PRE_POST_API_LIST)
+ # print("PRE_POST_API_ARGS_LIST")
+ # print(PRE_POST_API_ARGS_LIST)
+ IDX_CALLBACK = 0
+ inp_out_params_list_updated = {}
+ check_if_param_is_in_or_out_dict = {}
+ ALL_COMBINED_FUNC_ARGS = []
+ # api_desc_list = {}
+ pre_apis = PRE_POST_API_LIST['Pre']
+ post_apis = PRE_POST_API_LIST['Post']
+ if HEADER_FILE_CONTAINED_FOLDER == "":
+ HEADER_FILE_CONTAINED_FOLDER = MODULE_NAME
+ for ele in pre_apis:
+ for ele_arg in PRE_POST_API_ARGS_LIST[ele]:
+ if "**" in ele_arg:
+ ALL_COMBINED_FUNC_ARGS.append(ele_arg.replace('*', '',1))
+ else:
+ ALL_COMBINED_FUNC_ARGS.append(ele_arg.replace('*', ''))
+ for ele in post_apis:
+ for ele_arg in PRE_POST_API_ARGS_LIST[ele]:
+ if "**" in ele_arg:
+ ALL_COMBINED_FUNC_ARGS.append(ele_arg.replace('*', '',1))
+ else:
+ ALL_COMBINED_FUNC_ARGS.append(ele_arg.replace('*', ''))
+ for ele in FUNC_ARGS:
+ if "**" in ele:
+ ALL_COMBINED_FUNC_ARGS.append(ele.replace('*', '',1))
+ else:
+ ALL_COMBINED_FUNC_ARGS.append(ele.replace('*', ''))
+ ## print(type(ALL_COMBINED_FUNC_ARGS))
+ combined_func_args(ALL_COMBINED_FUNC_ARGS)
+ all_callback_args = []
+ all_comb_args_set = []
+ all_comb_args_set = list(combined_func_args(ALL_COMBINED_FUNC_ARGS))
+ for ele in all_comb_args_set:
+ if "_cb" in ele:
+ all_callback_args.append(ele.split(" ")[0])
+
+
+ header_files_dict = get_header_files(MODULE_NAME)
+ # for ever file in the dictionary we have to check if all the api names provided by the user exists or not
+ # we will take api names one by one and check in all the files if it exists or not
+ for API_SEARCH in pre_apis:
+ for HEADER_FILE_NAME in header_files_dict:
+ inp_out_params_list_updated = input_output_params_extract(MODULE_NAME, HEADER_FILE_NAME, API_SEARCH, inp_out_params_list_updated)
+ for API_SEARCH in post_apis:
+ for HEADER_FILE_NAME in header_files_dict:
+ inp_out_params_list_updated = input_output_params_extract(MODULE_NAME, HEADER_FILE_NAME, API_SEARCH, inp_out_params_list_updated)
+ for HEADER_FILE_NAME in header_files_dict:
+ inp_out_params_list_updated = input_output_params_extract(MODULE_NAME, HEADER_FILE_NAME, API_NAME, inp_out_params_list_updated)
+ api_desc = api_description_extract(MODULE_NAME, HEADER_FILE_NAME, API_NAME)
+
+ callback_func_combined = ""
+ for cb_name in all_callback_args:
+ for header_file in header_files_dict:
+ callback_func_combined = callback_func_combined + cb_function_declaration(MODULE_NAME,header_file,cb_name)
+
+ global INPUT_PARAMETERS_COUNT
+ check_if_param_is_in_or_out_dict = init_params_in_out_dict(inp_out_params_list_updated)
+ INPUT_PARAMETERS_COUNT = calc_count_of_in_params(API_NAME, inp_out_params_list_updated)
+ TARGET_API_NAME_CB = API_NAME
+ TARGET_API_ARGS = FUNC_ARGS
+
+
+ if INPUT_PARAMETERS_COUNT > 1:
+ tc_code0 = (
+ "/**\n"
+ f"* @testcase utc_{API_NAME}_n{NEGATIVE_TC_COUNT}\n"
+ "* @since_tizen 8_0\n"
+ "* @type Negative\n"
+ f"* @description {api_desc} Invalid parameters passed and check API's return value with error code.\n"
+ "* @scenario \n"
+ "*/\n")
+ else:
+ tc_code0 = (
+ "/**\n"
+ f"* @testcase utc_{API_NAME}_n\n"
+ "* @since_tizen 8_0\n"
+ "* @type Negative\n"
+ f"* @description {api_desc} Invalid parameters passed and check API's return value with error code.\n"
+ "* @scenario \n"
+ "*/\n")
+
+ if INPUT_PARAMETERS_COUNT > 1:
+ tc_code = (
+ f"{RET_TYPE} utc_{API_NAME}_n{NEGATIVE_TC_COUNT}(void)\n"
+ "{\n"
+ " int ret;\n")
+ else:
+ tc_code = (
+ f"{RET_TYPE} utc_{API_NAME}_n(void)\n"
+ "{\n"
+ " int ret;\n")
+
+ tc_code4 = iniatialize_variables(inp_out_params_list_updated, all_comb_args_set, enum_dict, enum_dict_pre_post)
+
+
+ if MODULE_NAME == "nsd":
+ MODULE_NAME = "dnssd"
+ if MODULE_NAME == "email":
+ MODULE_NAME = "emails"
+
+ tc_code1 = (f" ret = {i}({concat_params(i, PRE_POST_API_ARGS_LIST[i], check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB)});\n assert_eq(ret, TIZEN_ERROR_NONE);\n\n" for i in pre_apis)
+
+ # add invalid parameters to negative tc target api
+ for HEADER_FILE_NAME in header_files_dict:
+ RETVAL_INVALID_PARAMETERS = get_retval_of_invalid_params(MODULE_NAME, HEADER_FILE_NAME, API_NAME)
+ if len(RETVAL_INVALID_PARAMETERS) > 0:
+ break
+
+ tc_code_feature = ""
+ if feature_name != "":
+ x = feature_name.split('/')
+ length = len(x)
+ key_word = x[length - 1]
+ key_word=key_word.replace('.','_')
+
+ tc_code_feature = (f" bool {key_word}_supported = false; \n\n"
+ f" ret = system_info_get_platform_bool(\"{feature_name}\", &{key_word}_supported);\n"
+ f" if({key_word}_supported == false)" + "{\n"
+ f" ret = {API_NAME}({concat_params_target(API_NAME, FUNC_ARGS, check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, INPUT_PARAMETER_MARKED_NULL, all_comb_args_set, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB)});\n"
+ f" assert_eq(ret, TIZEN_ERROR_NOT_SUPPORTED);\n"
+ f" return 0;\n"
+ " }\n\n")
+ tc_code2 = (f" ret = {API_NAME}({concat_params_target(API_NAME, FUNC_ARGS, check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, INPUT_PARAMETER_MARKED_NULL, all_comb_args_set, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB)});\n"
+ f" assert_eq(ret, {RETVAL_INVALID_PARAMETERS});\n\n")
+
+ tc_code3 = (f" ret = {j}({concat_params(j, PRE_POST_API_ARGS_LIST[j], check_if_param_is_in_or_out_dict, inp_out_params_list_updated, all_callback_args, IDX_CALLBACK, PRE_POST_API_ARGS_LIST, TARGET_API_ARGS, TARGET_API_NAME_CB)});\n assert_eq(ret, TIZEN_ERROR_NONE);\n\n"
+
+ for j in post_apis)
+
+ tc_code5 = (f" return 0;\n"
+ "}\n")
+
+ return tc_code0 + tc_code + tc_code4 + "\n" + ''.join(tc_code1) + tc_code_feature + tc_code2 + ''.join(tc_code3) + tc_code5
+
+def get_no_of_negative_tc_count(var_no_of_neg_tc_count):
+ return var_no_of_neg_tc_count
+
+
+# this function combines all the negative tc such as n1, n2, n3 ... according to the number of input parameters calculated in calc_count_of_in_params()
+
+def all_negative_tc_combined(RET_TYPE, MODULE_NAME, API_NAME, PRE_POST_API_LIST, PRE_POST_API_ARGS_LIST, FUNC_ARGS, HEADER_FILE_CONTAINED_FOLDER, NEGATIVE_TC_COUNT, feature_name, enum_dict, enum_dict_pre_post):
+ negative_tc_code = ""
+ #find count of input parameters in TARGET API
+ global var_no_of_neg_tc_count
+ for num in range(1, NEGATIVE_TC_COUNT+1):
+ negative_tc_code = negative_tc_code + tc_code_write_negative(RET_TYPE, MODULE_NAME, API_NAME, PRE_POST_API_LIST, PRE_POST_API_ARGS_LIST, FUNC_ARGS, HEADER_FILE_CONTAINED_FOLDER, num, TARGET_API_INPUT_PARAMS_LIST[num-1], feature_name, enum_dict, enum_dict_pre_post)
+ if num >= INPUT_PARAMETERS_COUNT:
+ NEGATIVE_TC_COUNT = INPUT_PARAMETERS_COUNT
+ get_no_of_negative_tc_count(INPUT_PARAMETERS_COUNT)
+ break
+ flag = 0
+
+ return negative_tc_code
+
+
--- /dev/null
+import sys
+sys.path.append('/usr/local/lib/python3.6/site-packages')
+import json
+from torch.optim.lr_scheduler import StepLR
+from sklearn.utils.class_weight import compute_class_weight
+from transformers import AdamW
+from torchinfo import summary
+from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
+from transformers import DistilBertTokenizer, DistilBertModel
+from sklearn.preprocessing import LabelEncoder
+from validate_module import *
+from validate_api import *
+from api_information import *
+from template_tc import *
+from pre_post_information import *
+from logger_init import *
+from log_create import *
+from list_module_files import *
+from update_header_files import *
+from execute_tc import *
+from build_tc_parameters import *
+import numpy as np
+import pandas as pd
+import re
+import torch
+import imp
+import random
+import torch.nn as nn
+import os, stat
+import subprocess
+import transformers
+import traceback
+import time
+import matplotlib.pyplot as plt
+device = torch.device('cpu')
+
+# logging modules
+import logging
+import logging.handlers
+import datetime
+import inspect
+from inspect import currentframe, getframeinfo
+
+
+# initializing log file
+logger = logger_init()
+
+# We have prepared a dataset with 7 labels
+try:
+ df = pd.read_csv('newdata.csv', encoding='ISO-8859-1')
+ df.head()
+except:
+ log_create(logger, "Error occurred while reading dataset file!")
+
+df['label'].value_counts()
+
+
+le = LabelEncoder()
+df['label'] = le.fit_transform(df['label'])
+
+df['label'].value_counts(normalize=True)
+
+train_text, train_labels = df['Text'], df['label']
+
+try:
+ # Load the DistilBert tokenizer
+ tokenizer = DistilBertTokenizer.from_pretrained(r'/home/sri/distilbert-model')
+ # Import the DistilBert pretrained model
+ bert = DistilBertModel.from_pretrained(r'/home/sri/distilbert-model')
+
+except:
+ log_create(logger, "Error while importing tokenizer ot NLP model")
+
+text = ["this is a distil bert model.", "data is oil"]
+# Encode the text
+encoded_input = tokenizer(text, padding=True, truncation=True, return_tensors='pt')
+
+
+seq_len = [len(i.split()) for i in train_text]
+pd.Series(seq_len).hist(bins=13)
+
+max_seq_len = 3
+
+tokens_train = tokenizer(
+ train_text.tolist(),
+ max_length=max_seq_len,
+ pad_to_max_length=True,
+ truncation=True,
+ return_token_type_ids=False
+)
+
+# for train set
+train_seq = torch.tensor(tokens_train['input_ids'])
+train_mask = torch.tensor(tokens_train['attention_mask'])
+train_y = torch.tensor(train_labels.tolist())
+train_mask
+batch_size= 6
+train_data = TensorDataset(train_seq, train_mask, train_y)
+train_sampler = RandomSampler(train_data)
+train_dataloader = DataLoader(
+ train_data, sampler=train_sampler, batch_size=batch_size)
+
+try:
+ class BERT_Arch(nn.Module):
+ def __init__(self, bert):
+ super(BERT_Arch, self).__init__()
+ self.bert = bert
+
+ self.dropout = nn.Dropout(0.1)
+
+ self.relu = nn.ReLU()
+ self.fc1 = nn.Linear(768, 512)
+ self.fc2 = nn.Linear(512, 256)
+ self.fc3 = nn.Linear(256, 15)
+ self.softmax = nn.LogSoftmax(dim=1)
+
+ def forward(self, sent_id, mask):
+
+ cls_hs = self.bert(sent_id, attention_mask=mask)[0][:, 0]
+
+ x = self.fc1(cls_hs)
+ x = self.relu(x)
+ x = self.dropout(x)
+
+ x = self.fc2(x)
+ x = self.relu(x)
+ x = self.dropout(x)
+ x = self.fc3(x)
+ x = self.softmax(x)
+ return x
+
+except:
+ log_create(logger, "Error in BERT Architecture!")
+
+for param in bert.parameters():
+ param.requires_grad = False
+
+try:
+ model = BERT_Arch(bert)
+
+except:
+ log_create(logger, "Error occurred while building model!")
+
+# push the model to CPU
+model = model.to(device)
+# summary(model)
+
+# define the optimizer
+optimizer = AdamW(model.parameters(), lr=1e-3)
+log_info_save(logger, "optimizer", optimizer)
+
+class_wts = compute_class_weight(
+ class_weight="balanced", classes=np.unique(train_labels), y=train_labels)
+# print(class_wts)
+log_info_save(logger, "Class weights", class_wts)
+
+# convert class weights to tensor
+weights = torch.tensor(class_wts, dtype=torch.float)
+weights = weights.to(device)
+# loss function
+cross_entropy = nn.NLLLoss(weight=weights)
+log_info_save(logger, "Loss function", cross_entropy)
+
+train_losses = []
+# number of training epochs
+epochs = 150
+lr_sch = torch.optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1)
+log_info_save(logger, "Epochs", epochs)
+log_info_save(logger, "Scheduler", lr_sch)
+
+
+# function to train the model
+
+try:
+ def train():
+
+ model.train()
+ total_loss = 0
+
+ total_preds = []
+ for step, batch in enumerate(train_dataloader):
+
+ if step % 50 == 0 and not step == 0:
+ print(' Batch {:>5,} of {:>5,}.'.format(step, len(train_dataloader)))
+ batch = [r.to(device) for r in batch]
+ sent_id, mask, labels = batch
+
+ preds = model(sent_id, mask)
+ loss = cross_entropy(preds, labels)
+ total_loss = total_loss + loss.item()
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
+ optimizer.step()
+ optimizer.zero_grad()
+ preds = preds.detach().cpu().numpy()
+ total_preds.append(preds)
+ avg_loss = total_loss / len(train_dataloader)
+
+ total_preds = np.concatenate(total_preds, axis=0)
+ # returns the loss and predictions
+ # print(total_preds)
+ return avg_loss, total_preds
+except:
+ log_create(logger, "Error occurred while training!")
+
+log_info_save_processing(logger, "Training...")
+
+
+try:
+ for epoch in range(epochs):
+ # print('\n Epoch {:} / {:}'.format(epoch + 1, epochs))
+ # train model
+ train_loss, _ = train()
+ train_losses.append(train_loss)
+ torch.backends.cudnn.deterministic = True
+ torch.backends.cudnn.benchmark = False
+except:
+ log_create(logger, "Error occurred while training file!")
+
+
+log_info_save_processing(logger, "Training completed successfully")
+
+print(f'\nTraining Loss: {train_loss:.3f}')
+
+output_model = 'mymodel.pth'
+
+# Load intents from json file
+log_info_save_processing(logger, "Importing data_TCT.json file")
+
+try:
+ f = open("data_TCT.json")
+ data = json.load(f)
+
+except:
+ log_create(logger, "Error occurred while importing the json file")
+
+# print(data)
+torch.save(model,'modelweight.pth')
+# print("model saved")
\ No newline at end of file
--- /dev/null
+import subprocess
+import re
+from list_module_files import *
+from template_tc_negative import *
+
+global found_text
+dict_of_file_and_position = {}
+
+global startup_and_cleanup_data
+global startup_line
+global cleanup_line
+startup_line=''
+cleanup_line= ''
+
+def get_text_to_update(TC_WRITE_DIR, module_name, file_name, API_NAME):
+ with open(TC_WRITE_DIR + "/" + module_name + "/" + file_name,"r") as file_one:
+ flag1 = False
+ flag2 = False
+ for line in file_one:
+ if line.find('startup(void)')!=-1:
+ global startup_line
+ startup_line = line.split(' ', 1)[1]
+ flag1 = True
+ if line.find('cleanup(void)')!=-1:
+ global cleanup_line
+ cleanup_line = line.split(' ', 1)[1]
+ flag2 = True
+ if flag1 == True and flag2 == True:
+ break
+ return [startup_line, cleanup_line]
+
+# list newly added apis in the the header file i.e mobile.h, tizeniot.h, wearable.h, tv.h
+
+def find_text_position_in_header_files(TC_WRITE_DIR, module_name, file_name, TEXT_TO_SEARCH):
+ found_text = False
+ cnt = 0
+ with open(TC_WRITE_DIR + '/' + module_name + '/' + file_name,"r") as file_one:
+ for line in file_one:
+ cnt += 1
+ if re.search(TEXT_TO_SEARCH, line):
+ found_text = True
+ dict_of_file_and_position[file_name] = cnt
+
+
+
+def get_dict_of_position_in_header_files(TC_WRITE_DIR, module_name, TEXT_TO_SEARCH):
+ files_list = get_all_header_files_of_module(TC_WRITE_DIR, module_name)
+ for file_name in files_list:
+ find_text_position_in_header_files(TC_WRITE_DIR, module_name, file_name, TEXT_TO_SEARCH)
+
+ return dict_of_file_and_position
+
+
+# Function for writing text at specific line
+def writetoendofline(lines, line_no, append_txt):
+ lines[line_no] = lines[line_no].replace('\n', '') + '\n' + append_txt + '\n'
+
+
+def update_header_file(TC_WRITE_DIR, module_name, POSITION_DICT, TEXT_TO_UPDATE, INDEX_SHIFT):
+ # open the file in read mode to read the current input to memory
+ for i in POSITION_DICT.keys():
+ ## print("\n\n i value", i)
+ with open(TC_WRITE_DIR + "/" + module_name + "/" + f"{i}", 'r') as txtfile:
+ lines = txtfile.readlines()
+ #check if tc entry is already present in all header files
+ IS_PRESENT = False
+ with open(TC_WRITE_DIR + "/" + module_name + "/" + f"{i}", 'w') as txtfile:
+ for CURR_LINE in lines:
+ if TEXT_TO_UPDATE in CURR_LINE:
+ IS_PRESENT = True
+ break
+ if IS_PRESENT == False:
+ writetoendofline(lines, POSITION_DICT[i] - INDEX_SHIFT, TEXT_TO_UPDATE)
+
+ # write the edited content back to the file
+ with open(TC_WRITE_DIR + "/" + module_name + "/" + f"{i}", 'w') as txtfile:
+ txtfile.writelines(lines)
+
+ txtfile.close()
+
+def update_all_header_files(TC_WRITE_DIR, module_name, folder_name, API_NAME, file_name, existing_code):
+ startup_and_cleanup_data = get_text_to_update(TC_WRITE_DIR, module_name, file_name, API_NAME)
+ startup_line = startup_and_cleanup_data[0].replace('\n', '')
+ cleanup_line = startup_and_cleanup_data[1].replace('\n', '')
+ startup_line_in_tc_array = startup_line.split('(void)')[0]
+ cleanup_line_in_tc_array = cleanup_line.split('(void)')[0]
+ if existing_code == True:
+ INDEX_SHIFT = [3, 2]
+ TEXT_TO_SEARCH = ["testcase tc_array\[]", "{NULL, NULL}"]
+ TEXT_TO_UPDATE = [f"extern int utc_{API_NAME}_p(void);",
+ f'{{"utc_{API_NAME}_p",utc_{API_NAME}_p, {startup_line_in_tc_array}, {cleanup_line_in_tc_array}}},']
+ else:
+ INDEX_SHIFT = [1, 3, 2]
+ TEXT_TO_SEARCH = ["cleanup\(void\)", "testcase tc_array\[]", "{NULL, NULL}"]
+ TEXT_TO_UPDATE = [f"extern void {startup_line};\nextern void {cleanup_line};",
+ f"extern int utc_{API_NAME}_p(void);",
+ f'{{"utc_{API_NAME}_p",utc_{API_NAME}_p, {startup_line_in_tc_array}, {cleanup_line_in_tc_array}}},']
+
+ TEXT_TO_UPDATE[len(TEXT_TO_UPDATE)-1] = " " + TEXT_TO_UPDATE[len(TEXT_TO_UPDATE)-1]
+ dict_of_file_and_position.clear()
+ for idx in range(len(TEXT_TO_UPDATE)):
+ POSITION_DICT = get_dict_of_position_in_header_files(TC_WRITE_DIR, module_name, TEXT_TO_SEARCH[idx])
+
+ update_header_file(TC_WRITE_DIR, module_name, POSITION_DICT, TEXT_TO_UPDATE[idx], INDEX_SHIFT[idx])
+
+# function to make entry of negative tc in header files
+def update_all_header_files_for_negative_tc(TC_WRITE_DIR, module_name, folder_name, API_NAME, IDX_NEGATIVE_TC, API_IDX, file_name):
+ startup_and_cleanup_data = get_text_to_update(TC_WRITE_DIR, module_name, file_name, API_NAME)
+ startup_line = startup_and_cleanup_data[0].replace('\n', '')
+ cleanup_line = startup_and_cleanup_data[1].replace('\n', '')
+ startup_line_in_tc_array = startup_line.split('(void)')[0]
+ cleanup_line_in_tc_array = cleanup_line.split('(void)')[0]
+ inp_params = ret_input_params()
+ INDEX_SHIFT = [3, 2]
+ TEXT_TO_SEARCH = ["testcase tc_array\[]", "{NULL, NULL}"]
+ if inp_params[API_IDX] > 1:
+ TEXT_TO_UPDATE = [f"extern int utc_{API_NAME}_n{IDX_NEGATIVE_TC}(void);",
+ f'{{"utc_{API_NAME}_n{IDX_NEGATIVE_TC}",utc_{API_NAME}_n{IDX_NEGATIVE_TC},{startup_line_in_tc_array}, {cleanup_line_in_tc_array}}},']
+ else:
+ TEXT_TO_UPDATE = [f"extern int utc_{API_NAME}_n(void);",
+ f'{{"utc_{API_NAME}_n",utc_{API_NAME}_n,{startup_line_in_tc_array}, {cleanup_line_in_tc_array}}},']
+
+ TEXT_TO_UPDATE[len(TEXT_TO_UPDATE)-1] = " " + TEXT_TO_UPDATE[len(TEXT_TO_UPDATE)-1]
+ dict_of_file_and_position.clear()
+ for idx in range(len(TEXT_TO_UPDATE)):
+ POSITION_DICT = get_dict_of_position_in_header_files(TC_WRITE_DIR, module_name, TEXT_TO_SEARCH[idx])
+ update_header_file(TC_WRITE_DIR, module_name, POSITION_DICT, TEXT_TO_UPDATE[idx], INDEX_SHIFT[idx])
+
--- /dev/null
+import csv
+from csv import writer
+import pandas as pd
+
+def update_module_mapper_file(HEADER_FILE_VALUE, module_name):
+ try:
+ List = [module_name]
+ for header_file in HEADER_FILE_VALUE:
+ List.append(header_file)
+ with open('Module_Header_Mapping.csv', 'a') as f_object:
+ # Pass this file object to csv.writer()
+ # and get a writer object
+ writer_object = writer(f_object)
+ # Pass the list as an argument into
+ # the writerow()
+ writer_object.writerow(List)
+ # Close the file object
+ f_object.close()
+ except:
+ print("some error occurred while updating csv file")
\ No newline at end of file
--- /dev/null
+from latest_rootstrap import *\r
+from read_csv import *\r
+import re\r
+import os\r
+from header_file_location import *\r
+\r
+global found_api\r
+api_info = []\r
+def get_latest_rootstrap():\r
+ latest_rootstrap_dir = latest_rootstrap()\r
+ DIR = latest_rootstrap_dir + "//" + "usr/include"\r
+ return DIR\r
+\r
+\r
+def get_header_files(MODULE_NAME):\r
+ module_files_map = module_files_dict()\r
+ # extract header files from the above dictionary and return them in a list\r
+ return module_files_map[MODULE_NAME]\r
+\r
+\r
+def check_api_in_module(HEADER_FILE_NAME, API_SEARCH):\r
+ found_api = False\r
+ flag_new=False\r
+ multiple_line_apis = False\r
+ DIR = get_latest_rootstrap()\r
+ path=DIR + "//" + HEADER_FILE_NAME\r
+ isExist = os.path.exists(path)\r
+ if isExist == False:\r
+ return False\r
+ with open(DIR + "//" + HEADER_FILE_NAME,"r") as file_one:\r
+ updated_line_multiple=''\r
+ for line_no, line in enumerate(file_one):\r
+ if line.find("int" + " " + API_SEARCH + "(") != -1:\r
+ found_api = True\r
+ updated_line = line.strip()\r
+\r
+ updated_line_multiple = updated_line_multiple+updated_line\r
+ if ";" not in updated_line:\r
+ for line_no, line in enumerate(file_one):\r
+ if ";" in line:\r
+ updated_line = line.strip()\r
+ updated_line_multiple = updated_line_multiple+updated_line\r
+ flag_new=True\r
+ break\r
+ else:\r
+ updated_line = line.strip()\r
+ updated_line_multiple = updated_line_multiple+updated_line\r
+ if flag_new:\r
+ break\r
+\r
+\r
+ if updated_line_multiple != '':\r
+ api_info.append(updated_line_multiple)\r
+ if not found_api:\r
+ return False\r
+ else:\r
+ return True\r
+\r
+\r
+def list_apis():\r
+ return api_info\r
+\r
+def clear_api_list():\r
+ api_info.clear()\r
+\r
+global found\r
+\r
+def validate_api(API_NAMES, MODULE_NAME):\r
+ found = False\r
+ # we get the directory of the latest rootstrap\r
+ DIR = get_latest_rootstrap()\r
+ # based on module name we get from the arguments we have to get header files in the form of dictionary\r
+ header_files_dict = get_header_files(MODULE_NAME)\r
+ if(len(API_NAMES) == 0):\r
+ return True\r
+ # for ever file in the dictionary we have to check if all the api names provided by the user exists or not\r
+ # we will take api names one by one and check in all the files if it exists or not\r
+ for API_SEARCH in API_NAMES:\r
+ found = False\r
+ for HEADER_FILE_NAME in header_files_dict:\r
+ api_exists_or_not = check_api_in_module(HEADER_FILE_NAME, API_SEARCH)\r
+ if api_exists_or_not == True:\r
+ found = True\r
+ break\r
+ if found == False:\r
+ return found\r
+ return found\r
--- /dev/null
+import pandas as pd\r
+import numpy as np\r
+import textdistance\r
+import re\r
+import csv\r
+from collections import Counter\r
+\r
+filename = open('Module_Header_Mapping.csv', 'r')\r
+filedata = csv.DictReader(filename)\r
+words = []\r
+\r
+\r
+for value in filedata:\r
+ words.append(value['Key'])\r
+\r
+words=[i.lower() for i in words]\r
+V = set(words)\r
+word_freq = {}\r
+probs = {}\r
+\r
+# build frequency of words\r
+word_freq = Counter(words)\r
+\r
+# calculate relative frequency of words\r
+def relative_freq_words(word_freq):\r
+ Total = sum(word_freq.values())\r
+ for k in word_freq.keys():\r
+ probs[k] = word_freq[k]/Total\r
+ return probs\r
+\r
+\r
+def module_autocorrect(input_word):\r
+ # print(input_word)\r
+ input_word = input_word.strip()\r
+ probs = relative_freq_words(word_freq)\r
+ input_word = input_word.lower()\r
+ if input_word in V:\r
+ return True\r
+ else:\r
+ # sort similar words acc to jaccard distance\r
+ sim = [1-(textdistance.Jaccard(qval=2).distance(v, input_word))for v in word_freq.keys()]\r
+ df = pd.DataFrame.from_dict(probs, orient='index').reset_index()\r
+ df = df.rename(columns={'index': 'Word', 0: 'Prob'})\r
+ df['Similarity'] = sim\r
+ output = df.sort_values(['Similarity', 'Prob'],ascending=False).head(1)\r
+ df_output = output['Word'].tolist()\r
+ df_similarity = output['Similarity'].tolist()\r
+ # for i in df_output:\r
+ # # print(i)\r
+ ret_statement = ''\r
+ if df_similarity[0] <= 0.1:\r
+ ret_statement = ''\r
+ else:\r
+ ret_statement = df_output\r
+ return ret_statement\r
+\r
+\r
+# print(module_autocorrect('capi-system-sys-settgs'))\r