import xml.etree.ElementTree as ET import os import sys def parse_test_scenario(xml_file_path): """ Parses a test scenario XML file and extracts the configuration and all test case IDs mapped to their execution commands. Args: xml_file_path (str): The path to the XML file to parse. Returns: dict: A dictionary in the format: { 'config': , 'test_cases': { : , ... } } Returns an empty dictionary on error. """ if not os.path.exists(xml_file_path): print(f"Error: File not found at '{xml_file_path}'") return {} try: # 1. Parse the XML file tree = ET.parse(xml_file_path) root = tree.getroot() except ET.ParseError as e: print(f"Error: Failed to parse XML file. Details: {e}") return {} except Exception as e: print(f"An unexpected error occurred during file parsing: {e}") return {} # Initialize the final structured output parsed_data = { 'config': '', 'test_cases': {} } # 2. Extract the mandatory value config_element = root.find('config') if config_element is not None and config_element.text: parsed_data['config'] = config_element.text.strip() # 3. Iterate over all elements and extract ID and Exec for tc in root.findall('test_case'): tc_id_element = tc.find('test_case_id') tc_exec_element = tc.find('test_exec') # Use strip() and check against None for safety, even if validation passed tc_id = tc_id_element.text.strip() if tc_id_element is not None and tc_id_element.text else "UNKNOWN_ID" tc_exec = tc_exec_element.text.strip() if tc_exec_element is not None and tc_exec_element.text else "UNKNOWN_EXEC" # Add to the test_cases dictionary parsed_data['test_cases'][tc_id] = tc_exec return parsed_data if __name__ == "__main__": # Define a default path to test against default_test_file = 'sample_scenario.xml' # Allow passing the file path as a command-line argument for flexibility file_to_check = sys.argv[1] if len(sys.argv) > 1 else default_test_file print(f"--- XML Test Scenario Parser ---") print(f"Parsing file: {file_to_check}\n") # Run the parser scenario_data = parse_test_scenario(file_to_check) # Print results if scenario_data: print("✅ Parsing Successful. Extracted Data Structure:") print(f"CONFIG: {scenario_data['config']}") print("\nTEST CASES:") for test_id, command in scenario_data['test_cases'].items(): print(f" - {test_id}:\n '{command}'") else: print("❌ Parsing Failed or returned empty data.")