U
    h@                  	   @   s  d dl mZmZmZmZ d dlmZmZ d dlm	Z	 d dl
mZ d dlmZ d dlZd dlZd dlmZmZmZmZ ejejdd	 eeZed
dZedd Zedd Zeddeeeef  eeef ee dddZeedddZ edeeee eeee dddZ!dS )    )capture_exceptioncapture_messageset_tagset_context)monitor_openai_apimonitor_critical_system)
ChatOpenAI)LangChainTracer)OpenAIN)OptionalListDictAnyz4%(asctime)s - %(name)s - %(levelname)s - %(message)s)levelformatzopenai-cost-tracking)project_namec               
   C   s^   zddl m}  | W S  tk
rX } z(td|  t|ddi W Y dS d}~X Y nX dS )z Get OpenAI API key from settingsr   )OPENAI_API_KEYzError loading OpenAI API key: functionget_openai_api_keyN)config.settingsr   	Exceptionloggererrorr   )r   e r   9/var/www/html/testcasegenerator.evdpl.com/ai/generator.pyr      s    r   c               
   C   sn   z"ddl m} m}m} | ||dW S  tk
rh } z(td|  t|ddi W Y dS d}~X Y nX dS )z*Get OpenRouter configuration from settingsr   )OPENROUTER_API_KEYOPENROUTER_SITE_URLOPENROUTER_SITE_NAME)api_keysite_url	site_namez(Error loading OpenRouter configuration: r   get_openrouter_configN)r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r"      s    r"   Tcritical)messagesconfigreturnc              
   C   s   zb|r| ds td W dS td|d d}|jjj|d |d di d	| d
}|jd jj	W S  t
k
r } z(td|  t|ddi W Y dS d}~X Y nX dS )z'Make API call to OpenRouter as fallbackr   z OpenRouter API key not availableNzhttps://openrouter.ai/api/v1)base_urlr   r    r!   )zHTTP-RefererzX-Titlez deepseek/deepseek-chat-v3.1:free)Zextra_headersZ
extra_bodymodelr%   r   z"Error making OpenRouter API call: r   make_openrouter_call)getr   r   r
   ZchatZcompletionscreatechoicesmessagecontentr   r   )r%   r&   clientZ
completionr   r   r   r   r*   -   s*    

r*   )	test_typer'   c              	   C   sN   ddddddddddd	dd
dd	dddd	dddd	dd}| | i S )z.Get the configuration for a specific test typeZTC_FUNCzEfunctional test cases focusing on valid inputs and expected behaviors   )prefixdescription	max_countZTC_NEGzNnegative test cases focusing on invalid inputs, error handling, and edge casesZTC_UIz4UI test cases focusing on visual elements and layout   ZTC_UXzDuser experience test cases focusing on user interaction and workflowZ	TC_COMPATz@compatibility test cases across different browsers and platformsZTC_PERFz@performance test cases focusing on load times and responsiveness)dashboard_functionalZdashboard_negativeZdashboard_uiZdashboard_uxZdashboard_compatibilityZdashboard_performance)r+   )r1   Zbase_configsr   r   r   get_test_type_configK   s4     r8    )r4   summaryselected_typessource_typeurlr'   c                    s  | st d dS |r"t|dkr0t d dS t d|  t d|  t dt|  d g }|D ](t d	  t  st d
  qnd d  d}|dkrd| d|  d d  d d  d d  d d| dn<d| d|  d d  d d  d d  d d| dzt }|rV|dksV|dkrld}t | t|td d!d"|t	gd#t d$ d% t
d&d' fd(d)}	|	 }
|
j }|rt d* d+ d, d-| }|| nt d. d% W n~ tk
r } z\t d/ d0t|  t d1 d% zt }|rd|d2svt d3 td4d5d6 d7 d  d8 d  d9d:d;d:g}t||}|rt d* d< d, d=| }|| nt d> d% td?W nt tk
rt } zTt d@ d0t|  t| || rFt| ndt|dA W Y W Y qnW 5 d}~X Y nX W 5 d}~X Y nX t dB  qn|st dC dS t dDt| dE d-d-| S )Fz0Generate test cases based on user-selected typesz0No description provided for test case generationNr   z/No test types selected for test case generationz!Generating test cases for types: z	Summary: zDescription length: z charactersz#Starting generation for test type: zSkipping unknown test type: u   
        You are an expert QA engineer. Your task is to create **clear, detailed, and professional test cases**.

        ✅ STRICT FORMAT for each test case:

        Title: r3   u  _[SequentialNumber]_[Meaningful_Brief_Title]
        Scenario: [One or two lines describing the intent of the test]
        Preconditions: [State assumptions, setup, or required data before execution]
        Steps to Reproduce:
        1. [Step 1 in action-oriented language]
        2. [Step 2]
        ...
        Expected Result: [Clear, testable outcome of the steps]
        Actual Result: [Leave as 'To be filled during execution']
        Priority: [High / Medium / Low]
        Test Data: [If applicable – specify input values, files, or environment details]

        ⚡ RULES:
        - Each test case must cover a **unique and valuable scenario**.
        - Steps must be **clear, actionable, and written like instructions to a QA engineer**.
        - Expected Results must be **specific and measurable** (not vague like “It should work”).
        - Do NOT duplicate scenarios.
        - Do NOT mix with other test types.
        - Use professional QA terminology.
        r=   z
            Website URL: z"
            Content Description: z

            Generate **up to r5   z test cases** for r4   u  .

            ⚡ ANALYSIS REQUIREMENTS:
            - Carefully review the website’s structure and functionality
            - Think about real-world user workflows and how they may fail
            - Consider UI, UX, and interaction edge cases
            - Include cross-browser compatibility (Chrome, Firefox, Safari, Edge)
            - Consider mobile responsiveness (desktop vs. mobile behavior)

            ⚡ TEST CASE REQUIREMENTS:
            1. Prefix all test case titles with z"
            2. Focus **only** on a   test scenarios for web testing
            3. Write **detailed, step-by-step instructions** that can be executed by QA
            4. Specify **exact expected results** for every step or final outcome
            5. Ensure scenarios are **unique and non-overlapping**
            6. Include both **happy paths and edge cases**
            7. Add **test data** where necessary

            z
            z
            Task Title: z
            Task Description: u  .

            ⚡ ANALYSIS REQUIREMENTS:
            - Carefully analyze the task description
            - Identify **all functional components and user actions**
            - Think about positive, negative, and edge case scenarios
            - Consider different **user roles, permissions, and data inputs**
            - Anticipate possible **failure points** or boundary conditions

            ⚡ TEST CASE REQUIREMENTS:
            1. Prefix all test case titles with aQ   scenarios
            3. Write **step-by-step reproducible instructions**
            4. Provide **clear and measurable expected results**
            5. Ensure each case is **unique and does not overlap**
            6. Include **test data** where relevant
            7. Include **priority level** for execution planning

            your_openai_api_key_heremissing_api_keyuA   ⚠️ Invalid or missing OPENAI_API_KEY in environment variableszgpt-4o-minig333333?i.  )r)   Ztemperature
max_tokensZopenai_api_key	callbackszSending request to OpenAI for z test casesTr#   c                
      s6    dd d d  d d  ddd	dgS )
NsystemAYou are a senior QA engineer. Generate the appropriate number of  test cases (up to r5   [ maximum) by analyzing the content complexity and generating only what's truly needed. Use r3   = as the prefix. Focus on quality and relevance over quantity.roler/   user)invoker   r&   Zcurrent_llmpromptr1   r   r   make_openai_call2  s    z,generate_test_case.<locals>.make_openai_callz
Generated z% test cases successfully using OpenAIzTEST TYPE: z

zReceived empty response for zOpenAI API failed for z test cases: z&Attempting fallback to OpenRouter for r   z3OpenRouter configuration not available for fallbackzNo fallback API availablerB   rC   rD   rE   rF   rG   rI   z2 test cases successfully using OpenRouter fallbackz (Generated via OpenRouter)

z$OpenRouter fallback also failed for z!Both OpenAI and OpenRouter failedz'Fallback to OpenRouter also failed for )r1   r&   r:   Zdescription_lengthfallback_errorz$Completed generation for test type: z!Failed to generate any test casesz&Successfully generated test cases for z test types)r   r   leninfor8   warningr   
ValueErrorr   tracerr   r/   stripappendr   strr"   r+   r*   r   join)r4   r:   r;   r<   r=   all_test_casesZbase_promptr   	error_msgrM   response
test_casesZtest_cases_with_headerr   Zopenrouter_configr%   rN   r   rK   r   generate_test_caseo   s    


K

	


2
r\   )r9   NNN)"utils.error_loggerr   r   r   r   utils.error_monitorr   r   Zlangchain_openair   Z%langchain.callbacks.tracers.langchainr	   openair
   osloggingtypingr   r   r   r   basicConfigINFO	getLogger__name__r   rS   r   r"   rV   r*   dictr8   r\   r   r   r   r   <module>   s&   




,$