
    $hM@                        S SK JrJrJrJr  S SKJrJr  S SKJ	r	  S SK
Jr  S SKJr  S SKrS SKrS SKJrJrJrJr  \R*                  " \R,                  SS	9  \R.                  " \5      r\" S
S9r\S 5       r\S 5       r\" SS9S\\\\4      S\\\4   S\\   4S j5       rS\S\4S jr \SS\S\S\\   S\S\S\\   4S jj5       r!g)    )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                       SSK Jn   U $ ! [         a0  n[        R	                  SU 35        [        USS05         SnAgSnAff = f)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     0D:\Projects\AI-TestCaseGenerator\ai\generator.pyr   r      sG    2 5aS9:!j*>?@s   
 
A&?Ac                       SSK Jn JnJn  U UUS.$ ! [         a0  n[
        R                  SU 35        [        USS05         SnAgSnAff = f)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$      sY    
aa)+-
 	

  ?sCD!j*ABCs    
A&AATcriticalmessagesconfigreturnc                     U(       a  UR                  S5      (       d  [        R                  S5        g[        SUS   S9nUR                  R
                  R                  US   US   S.0 S	U S
9nUR                  S   R                  R                  $ ! [         a0  n[        R                  SU 35        [        USS05         SnAgSnAff = f)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;<39%

 [[,,33 &z 2!+. 4 4 

 !!!$,,444 9!=>!j*@ABs   2B AB 
C&C		C	test_typec           	      h    SSSS.SSSS.SSS	S.S
SS	S.SSS	S.SSS	S.S.nUR                  U 0 5      $ )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                 `  ^^^^ U (       d  [         R                  S5        gU(       a  [        U5      S:X  a  [         R                  S5        g[         R                  SU 35        [         R                  SU 35        [         R                  S[        U 5       S35        / nU GH  m[         R                  S	T 35        [	        T5      mT(       d  [         R                  S
T 35        MH  STS    S3nUS:X  a"  SU SU  STS    STS    STS    ST SU S3mO!SU SU  STS    STS    STS    ST SU S3m [        5       nU(       a  US:X  d  US:X  a"  Sn[         R                  U5        [        U5      e[        S S!U[        /S"9m[         R                  S#T S$35        [        S%S&9UUUU4S' j5       n	U	" 5       n
U
R                  R                  5       nU(       a3  [         R                  S(T S)35        S*T S+U 3nUR                  U5        O[         R                  S,T S$35         [         R                  S@T 35        GM     U(       d  [         R                  SA5        g[         R                  SB[        U5       SC35        S+S+R)                  U5      -   $ ! [         Ga  n[         R                  S-T S.[        U5       35        [         R                  S/T S$35         [!        5       nU(       a  UR#                  S05      (       d   [         R                  S15        [        S25      eS3S4T S5TS    S6TS    S73S8.S9TS8./n[%        X5      nU(       a8  [         R                  S(T S:35        S*T S;U 3nUR                  U5         SnAGNd[         R                  S<T S$35        [        S=5      e! [         aa  n[         R                  S>T S.[        U5       35        ['        UTTUU (       a  [        U 5      OS[        U5      S?.5         SnA SnAGM|  SnAff = fSnAff = f)Dz0Generate 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.
        rR   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-3.5-turbogffffff?)r.   temperatureopenai_api_key	callbackszSending request to OpenAI for z test casesTr%   c            
      V   > TR                  SST ST S    ST S    S3S.S	TS./5      $ )
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_call,generate_test_case.<locals>.make_openai_call1  s    ")) (%fgpfq  rE  FL  MX  FY  EZ  Zu  v|  }E  vF  uG  GD  $E $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 availablerZ   r[   r\   r]   r^   r_   ra   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(   rO   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>   rO   rP   rQ   rR   all_test_casesbase_promptr!   	error_msgre   response
test_casestest_cases_with_headerr   openrouter_configr'   rh   r(   rc   rd   r9   s                    @@@@r   generate_test_casery   o   s    GHS0A5FG
KK3N3CDE
KK)G9%&
KK&s;'7&8DEN#	9)EF%i0NN9)EFV
 x ! "	4 % ""- /$[122DVMEZD[ 
\1 281A0B C""+ - M -F2 	 "*m ,$[122DVMEZD[ 
\1 281A0B C""+ - M -F4O	(*Gg)CCwRcGc_	Y' ++ %%&!(	K KK8;OP  . / ()H!))//1Jj3XYZ+6ykj\)R&%%&<=!=i[TUX 	:9+FG_ $b 89
KK8^9L8M[YZFKK///c  (	LL1)M#a&RSKK@;WX#$9$;!(0A0E0Ei0P0PLL!VW$%@AA
 !)%fgpfq  rE  FL  MX  FY  EZ  Zu  v|  }E  vF  uG  GD  $E $7 2(N
KK*YK7i jk/:9+Edeodp-q*"))*@AALL#G	{R]!^_$%HII 
FykQ^_bcq_r^stu!!!*$&>I#k*:q&).&9&  
=(	sK   ?CJ"J""P--=P(+B%N:$N::
P%AP P( P%%P((P-) 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   rm   r   r$   rp   r/   dictrM   ry    rN   r   <module>r      s;   W W K ' A  	  , ,   ',,/e f			8	$ 
&<	=    T"4S#X#7 c3h T\]`Ta  #:"+C "+D "+H F0C F0# F0DQTI F0kn F0| F0  LT  UX  LY F0 F0rN   