
    h@                        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	            ej        e          Z ed
          Zed             Zed             Z ed          deeeef                  deeef         dee         fd            ZdedefdZ eddededee         dededee         f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                      	 ddl m}  | S # t          $ r:}t                              d|            t          |ddi           Y d}~dS d}~ww xY w)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   es     9/var/www/html/testcasegenerator.evdpl.com/ai/generator.pyr   r      s|    222222   9a99:::!j*>?@@@ttttts   
 
A/A		Ac                      	 ddl m} m}m} | ||dS # t          $ r:}t
                              d|            t          |ddi           Y d}~dS d}~ww xY w)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   s       r   r$   r$      s    
aaaaaaaaaa)+-
 
 	

    CCCDDD!j*ABCCCttttts    
A/AATcriticalmessagesconfigreturnc                    	 |r|                     d          st                              d           dS t          d|d                   }|j        j                            |d         |d         di d	| 
          }|j        d         j        j	        S # t          $ r:}t                              d|            t          |ddi           Y d}~dS d}~ww xY w)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)extra_headers
extra_bodymodelr'   r   z"Error making OpenRouter API call: r   make_openrouter_call)getr   r   r   chatcompletionscreatechoicesmessagecontentr   r   )r'   r(   client
completionr   s        r   r/   r/   -   s    	VZZ	22 	LL;<<<439%
 
 

 [,33 &z 2!+.  4 4 
 

 !!$,44   =!==>>>!j*@ABBBttttts   1B AB 
C/CC	test_typec           	      p    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 typeTC_FUNCzEfunctional test cases focusing on valid inputs and expected behaviors   )prefixdescription	max_countTC_NEGzNnegative test cases focusing on invalid inputs, error handling, and edge casesTC_UIz4UI test cases focusing on visual elements and layout   TC_UXzDuser experience test cases focusing on user interaction and workflow	TC_COMPATz@compatibility test cases across different browsers and platformsTC_PERFz@performance test cases focusing on load times and responsiveness)dashboard_functionaldashboard_negativedashboard_uidashboard_uxdashboard_compatibilitydashboard_performance)r0   )r9   base_configss     r   get_test_type_configrM   K   s      b!
 !
 k
 
 Q
 
 a
 
 "]$
 $
  ]"
 "
5 L@ Ir***     r>   summaryselected_typessource_typeurlc                 	   | st                               d           dS |rt          |          dk    rt                               d           dS t                               d|            t                               d|            t                               dt          |            d           g }|D ]t                               d	            t	                    st                               d
            Odd          d}|dk    r+d| d|  dd          dd          dd          d d| dn*d| d|  dd          dd          dd          d d| d	 t                      }|r|dk    s|dk    r+d}t                               |           t          |          t          d d!d"|t          g#          t                               d$ d%           t          d&'          fd(            }	 |	            }
|
j                                        }|r<t                               d) d*           d+ d,| }|                    |           nt                               d- d%           n# t          $ r}t                               d. d/t          |                      t                               d0 d%           	 t!                      }|r|                    d1          s)t                               d2           t          d3          d4d5 d6d          d7d          d8d9d:d9g}t%          ||          }|r<t                               d) d;           d+ d<| }|                    |           n-t                               d= d%           t          d>          n}# t          $ rp}t                               d? d/t          |                      t'          ||| rt          |           ndt          |          d@           Y d}~Y d}~d}~ww xY wY d}~nd}~ww xY wt                               dA            |st                               dB           dS t                               dCt          |           dD           d,d,                    |          z   S )Ez0Generate 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: r=   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.
        rS   z
            Website URL: z"
            Content Description: z

            Generate **up to r?   z test cases** for r>   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.   temperature
max_tokensopenai_api_key	callbackszSending request to OpenAI for z test casesTr%   c            
      j                         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 r?   [ maximum) by analyzing the content complexity and generating only what's truly needed. Use r=   = as the prefix. Focus on quality and relevance over quantity.roler6   user)invoke)r(   current_llmpromptr9   s   r   make_openai_callz,generate_test_case.<locals>.make_openai_call2  s    ")) ( $Egp  $E  $E  FL  MX  FY  $E  $E  v|  }E  vF  $E  $E  $E  $77+   rN   z
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 availabler\   r]   r^   r_   r`   ra   rc   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 )r9   r(   rP   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inforM   warningr   
ValueErrorr	   tracerr   r6   stripappendr   strr$   r0   r/   r   join)r>   rP   rQ   rR   rS   all_test_casesbase_promptr!   	error_msgrg   response
test_casestest_cases_with_headerr   openrouter_configr'   ri   r(   re   rf   r9   s                    @@@@r   generate_test_caserz   o   s     GHHHt S00A55FGGGt
KKDNDDEEE
KK%G%%&&&
KKDs;'7'7DDDEEEN# pH pH	E)EEFFF%i00 	NNE)EEFFFV
 x   4 % "-  %[1	  FLMEZ	  281A  #, , -  FF2  *  %[1	  FLMEZ	  281A  #, , -  F4P	(**G ,g)CCCwRcGcGc_	Y''' +++ %# &!(  K KKOOOOPPP  ...       /. ('))H!)//11J VYYYYZZZ)Ry)R)Rj)R)R&%%&<====TiTTTUUU (	 (	 (	LLR)RR#a&&RRSSSKKWWWWXXX#$9$;$;!( B0A0E0Ei0P0P BLL!VWWW$%@AAA
 !) $Egp  $E  $E  FL  MX  FY  $E  $E  v|  }E  vF  $E  $E  $E  $77 2(<MNN
 JKK jY j j jkkk-q9-q-qeo-q-q*"))*@AAAALL!^	!^!^!^___$%HIII B
  
 
 
tytt_bcq_r_rttuuu!!!*$&>I*P#k*:*:*:q&).&9&9& &    
 BAAAA3(	T 	F9FFGGGG 8999t
KKY^9L9LYYYZZZFKK////sF   4DJQAQ)C)OQ
QA!Q>QQQQ)rO   NNN)"utils.error_loggerr   r   r   r   utils.error_monitorr   r   langchain_openair	   %langchain.callbacks.tracers.langchainr
   openair   osloggingtypingr   r   r   r   basicConfigINFO	getLogger__name__r   rn   r   r$   rq   r/   dictrM   rz    rN   r   <module>r      s+   W W W W W W W W W W W W K K K K K K K K ' ' ' ' ' ' A A A A A A       				  , , , , , , , , , , , ,  ',/e f f f f		8	$	$ 
&<	=	=	=      T"""4S#X#7 c3h T\]`Ta    #":"+C "+D "+ "+ "+ "+H G0 G0C G0# G0DQTI G0kn G0| G0  LT  UX  LY G0 G0 G0 G0 G0 G0rN   