
    	]jG                        d Z ddlZddlmZmZ ddlmZ ddlZddlmZ ddl	m
Z
 ddlmZ ddlmZmZmZ dd	lmZmZ dd
lmZmZmZ ddlmZmZmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z#m$Z$ ddl%m&Z&  e
       Z' ejP                  e)      Z*ejV                  jX                   G d d             Z-ejV                  jX                   G d d             Z.y)z
Label Studio Open Source FSM Integration Tests.

Tests the core FSM functionality with real Django models in LSO,
focusing on coverage of state_manager.py and utils modules.
    N)datetimetimezone)patchCurrentContext)get_user_model)cache)AnnotationStateChoicesProjectStateChoicesTaskStateChoices)StateManagerStateManagerError)AnnotationStateProjectState	TaskState)get_current_state_safeis_fsm_enabledresolve_organization_id)OrganizationFactory)ProjectFactory)
Annotation)AnnotationFactoryTaskFactory)UserFactoryc                       e Zd ZdZ ej
                  d      d        Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zy)TestLSOFSMIntegrationz
    Test LSO FSM integration with real models.

    Focuses on improving coverage of state_manager.py and utils.py
    by testing error paths, cache behavior, and bulk operations.
    Tautousec              #   X  K   t        j                          t               | _        t	               | _        t        j                  | j
                         t        j                  | j                  j                         d t        j                          t        j                          ywzSet up test data.N
r	   clearr   orgr   userr   set_userset_organization_ididselfs    U/root/env/lib/python3.12/site-packages/label_studio/fsm/tests/test_lso_integration.pysetup_test_dataz%TestLSOFSMIntegration.setup_test_data'   d      	&(M			***488;;7   B(B*c                    t        | j                        }t        j                  |      }|t        j
                  k(  s
J d|        t        t        j                  j                  |      j                  d            }t        |      dk(  sJ |d   j                  t        j
                  k(  sJ |d   j                  dk(  sJ y)	z
        Test that creating a project automatically generates a state record.

        Validates:
        - Project model extends FsmHistoryStateModel
        - Automatic state transition on creation
        - State is CREATED for new projects
        organizationExpected CREATED, got project
created_at   r   project_createdN)r   r#   r   get_current_state_valuer   CREATEDlistr   objectsfilterorder_bylenstatetransition_name)r)   r3   r>   historys       r*   %test_project_creation_generates_statez;TestLSOFSMIntegration.test_project_creation_generates_state3   s     !dhh7 44W=+333U7MeW5UU3 |++2272CLL\Z[7|q   qz#6#>#>>>>qz))->>>>    c                    t        | j                        }t        |      }t        j                  |      }|t
        j                  k(  s
J d|        t        t        j                  j                  |      j                  d            }t        |      dk(  sJ |d   j                  t
        j                  k(  sJ y)	z
        Test that creating a task automatically generates a state record.

        Validates:
        - Task model extends FsmHistoryStateModel
        - Automatic state transition on creation
        - State is CREATED for new tasks
        r/   r2   r1   )taskr4   r5   r   N)r   r#   r   r   r7   r   r8   r9   r   r:   r;   r<   r=   r>   )r)   r3   rD   r>   r@   s        r*   "test_task_creation_generates_statez8TestLSOFSMIntegration.test_task_creation_generates_stateH   s     !dhh77+ 44T:(000R4J5'2RR0 y((//T/:CCLQR7|q   qz#3#;#;;;;rB   c                    t        | j                        }t        |      }t        || j                        }t        j                  |      }|t        j                  k(  s
J d|        t        t        j                  j                  |      j                  d            }t        |      dk\  sJ |d   j                  t        j                  k(  sJ y	)
a  
        Test that creating an annotation automatically generates a state record.

        Validates:
        - Annotation model extends FsmHistoryStateModel
        - Automatic state transition on creation
        - State is CREATED for new annotations in LSO
        r/   r2   )rD   completed_byr1   )
annotationr4   r5   r   N)r   r#   r   r   r$   r   r7   r
   r8   r9   r   r:   r;   r<   r=   r>   )r)   r3   rD   rH   r>   r@   s         r*   (test_annotation_creation_generates_statez>TestLSOFSMIntegration.test_annotation_creation_generates_state]   s     !dhh77+&DtyyI
 44Z@.666X:PQVPW8XX6 ..555LUUVbcd7|q   qz#9#A#AAAArB   c                    t        | j                        }t        j                          t	        j
                  |      }|t        j                  k(  sJ t	        j
                  |      }|t        j                  k(  sJ ||k(  sJ y)z
        Test that StateManager caching works correctly.

        Validates:
        - State retrieval works consistently
        - Cache doesn't cause incorrect state returns
        - Multiple accesses return same state
        r/   N)r   r#   r	   r"   r   r7   r   r8   )r)   r3   state1state2s       r*   test_cache_functionalityz.TestLSOFSMIntegration.test_cache_functionalitys   sy     !dhh7 	55g>,44444 55g>,44444 rB   c                     t        | j                        }t        j                  j	                  |      j                          t        j                          t        |      }|J y)z
        Test get_current_state_safe returns None for entities without states.

        Validates:
        - Utility function handles entities with no state records
        - No exceptions raised
        - Returns None gracefully
        r/   r2   N)	r   r#   r   r:   r;   deleter	   r"   r   )r)   r3   r>   s      r*   )test_get_current_state_safe_with_no_statez?TestLSOFSMIntegration.test_get_current_state_safe_with_no_state   sQ     !dhh7##G#4;;= 'w/}}rB   c                     t        | j                        }t        |      }t        |      }|| j                  j                  k(  sJ t        |      }|| j                  j                  k(  sJ y)a  
        Test resolve_organization_id utility function.

        Validates:
        - Extracts organization_id from entity with direct attribute
        - Extracts organization_id from entity with project relation
        - Falls back to CurrentContext
        r/   r2   N)r   r#   r   r   r'   )r)   r3   rD   org_ids       r*   (test_resolve_organization_id_from_entityz>TestLSOFSMIntegration.test_resolve_organization_id_from_entity   s`     !dhh77+ )1$$$ ).$$$rB   c                 <    t        | j                        }|du sJ y)z
        Test is_fsm_enabled checks feature flag correctly.

        Validates:
        - Feature flag check works
        - Returns True when enabled
        r$   TN)r   r$   )r)   results     r*   test_is_fsm_enabled_in_lsoz0TestLSOFSMIntegration.test_is_fsm_enabled_in_lso   s      TYY/~~rB   c                 @   ddl m}  |       } |       |_        d|j                  _        d|j                  _        d|_        t        j                  t              5 }t        j                  |       ddd       dt        j                        v sJ y# 1 sw Y   #xY w)z
        Test StateManager error handling for invalid entities.

        Validates:
        - Proper error raised for entities without state model
        - Error includes helpful message
        r   Mocknonexistent_modelztest.nonexistentr5   NzNo state model found)unittest.mockrZ   _meta
model_namelabel_lowerpkpytestraisesr   r   r7   strvalue)r)   rZ   mock_entityexc_infos       r*   !test_state_manager_error_handlingz7TestLSOFSMIntegration.test_state_manager_error_handling   s     	'f F':$(:% ]],- 	>00=	> &X^^)<<<<	> 	>s   BBc                 2   t        | j                        }t        d      D cg c]  }t        |       }}t	        j
                          t        j                  |       |D ],  }t        j                  |      }|t        j                  k(  r,J  yc c}w )z
        Test bulk cache warming for multiple entities.

        Validates:
        - Warm cache operation works for multiple entities
        - Subsequent state retrievals are faster (cached)
        - Correct states for all entities
        r/      r2   N)r   r#   ranger   r	   r"   r   
warm_cacher7   r   r8   )r)   r3   _tasksrD   r>   s         r*   test_warm_cache_bulk_operationz4TestLSOFSMIntegration.test_warm_cache_bulk_operation   s     !dhh77<Qx@!W-@@ 	&  	5D 88>E,44444	5 As   Bc                     t        | j                        }t        j                  |      }t	        |      dk\  sJ |d   j
                  t        j                  k(  sJ |d   j                  dk(  sJ y)z
        Test retrieving state history for an entity.

        Validates:
        - History retrieval works
        - States are in chronological order
        - All transition metadata captured
        r/   r5   r   r6   N)	r   r#   r   get_state_historyr=   r>   r   r8   r?   r)   r3   r@   s      r*   test_get_state_historyz,TestLSOFSMIntegration.test_get_state_history   sp     !dhh7 009 7|q   qz#6#>#>>>>qz))->>>>rB   c                     t        | j                        }t        j                  |      }t	        |      dk\  sJ |D cg c]  }|j
                   }}|t        |      k(  sJ yc c}w )z
        Test that state history is returned in chronological order.

        Validates:
        - History is ordered by creation time
        - Oldest states appear first
        - All state records are included
        r/   r5   N)r   r#   r   rp   r=   r4   sorted)r)   r3   r@   h
timestampss        r*   test_get_state_history_orderingz5TestLSOFSMIntegration.test_get_state_history_ordering   si     !dhh7 009 7|q    -44qall4
4VJ//// 5s    A&c                     t        | j                        }t        |      }t        || j                  ddigd      }|j                          t        j                  |      }|t        j                  k(  sJ y)z
        Test annotation created from draft has correct state.

        Validates:
        - Draft-based annotation workflow
        - Correct transition triggered
        - State is CREATED in LSO
        r/   r2   testdataF)rD   rG   rV   was_cancelledN)
r   r#   r   r   r$   saver   r7   r
   r8   )r)   r3   rD   rH   r>   s        r*   #test_annotation_from_draft_workflowz9TestLSOFSMIntegration.test_annotation_from_draft_workflow  ss     !dhh77+  V$%	

 	 44Z@.66666rB   c                 \   t        | j                        }t        j                  |       d|_        |j                          t        t        j                  j                  |      j                  d            }t        |      dk(  sJ |d   j                  t        j                  k(  sJ y)z
        Test that multiple state transitions are recorded correctly.

        Validates:
        - Multiple transitions create multiple records
        - History ordering is correct
        - Each transition has correct metadata
        r/   ri   r2   r4   r5   r   N)r   r#   r   r7   maximum_annotationsr|   r9   r   r:   r;   r<   r=   r>   r   r8   rq   s      r*   ,test_state_manager_with_multiple_transitionszBTestLSOFSMIntegration.test_state_manager_with_multiple_transitions(  s     !dhh7 	,,W5 '(# |++2272CLL\Z[ 7|q   qz#6#>#>>>>rB   N)__name__
__module____qualname____doc__ra   fixturer+   rA   rE   rI   rM   rP   rS   rW   rg   rn   rr   rw   r}   r    rB   r*   r   r      sh     V^^D!	 "	?*<*B, .$%(	=.5*?&0*72?rB   r   c                       e Zd ZdZ ej
                  d      d        Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zy)TestLSOFSMUtilitiesz`
    Test LSO FSM utility functions.

    Focuses on improving coverage of utils.py module.
    Tr   c              #   X  K   t        j                          t               | _        t	               | _        t        j                  | j
                         t        j                  | j                  j                         d t        j                          t        j                          ywr    r!   r(   s    r*   r+   z#TestLSOFSMUtilities.setup_test_dataK  r,   r-   c                 f    t        | j                        }t        || j                        }|J y)z
        Test resolve_organization_id with user parameter.

        Validates:
        - User parameter takes precedence
        - Correct organization extracted
        r/   rU   N)r   r#   r   r$   )r)   r3   rR   s      r*   &test_resolve_organization_id_with_userz:TestLSOFSMUtilities.test_resolve_organization_id_with_userW  s.     !dhh7(tyyA!!!rB   c                     t        j                  | j                  j                         ddlm}  |g       }t        |      }|| j                  j                  k(  sJ y)z
        Test resolve_organization_id falls back to CurrentContext.

        Validates:
        - CurrentContext used when no other source available
        - Correct ID returned
        r   rY   )specN)r   r&   r#   r'   r\   rZ   r   )r)   rZ   re   rR   s       r*   0test_resolve_organization_id_fallback_to_contextzDTestLSOFSMUtilities.test_resolve_organization_id_fallback_to_contextd  sH     	**488;;7 	'm(5$$$rB   c                     t        | j                        }t        j                          t	        |      }|J |t
        j                  k(  sJ y)z
        Test get_current_state_safe returns correct state value.

        Validates:
        - Function returns state string (not None)
        - State value is correct
        - Works correctly with database query
        r/   N)r   r#   r	   r"   r   r   r8   )r)   r3   state_values      r*   &test_get_current_state_safe_with_statez:TestLSOFSMUtilities.test_get_current_state_safe_with_statev  sH     !dhh7 -W5&&&199999rB   c                     t        | j                        }t        d      D cg c]  }t        j                  |       }}t        d |D              sJ yc c}w )z
        Test StateManager handles concurrent access correctly.

        Validates:
        - No race conditions in state retrieval
        - Cache consistency
        - Multiple simultaneous requests work correctly
        r/   
   c              3   B   K   | ]  }|t         j                  k(    y w)N)r   r8   ).0ss     r*   	<genexpr>zSTestLSOFSMUtilities.test_state_manager_handles_concurrent_access.<locals>.<genexpr>  s     D1+333Ds   N)r   r#   rj   r   r7   all)r)   r3   rl   statess       r*   ,test_state_manager_handles_concurrent_accessz@TestLSOFSMUtilities.test_state_manager_handles_concurrent_access  sT     !dhh7 JOrSA,66w?SS DVDDDD Ts   Ac                     t        | j                        }t        j                  t        dd      5  t	        j
                  |      }|J 	 ddd       y# 1 sw Y   yxY w)z
        Test get_current_state_value returns None when FSM is disabled.

        Validates:
        - Returns None instead of raising when feature flag is off
        - Handles disabled state gracefully
        r/   _is_fsm_enabledFreturn_valueN)r   r#   r   objectr   r7   r)   r3   rV   s      r*   .test_get_current_state_value_when_fsm_disabledzBTestLSOFSMUtilities.test_get_current_state_value_when_fsm_disabled  sR     !dhh7\\,(9N 	"!99'BF>!>	" 	" 	"s   AA c                 *   ddl m} t        | j                        }t        j                  t
        j                         |d      z
  }t        j                  t
        j                        }t        j                  |||      }t        |      dk\  sJ y)z
        Test get_states_in_time_range for time-based queries.

        Validates:
        - UUID7-based time range queries work
        - Returns states within specified time range
        r   )	timedeltar/   r5   )daysN)
r   r   r   r#   nowr   utcr   get_states_in_time_ranger=   )r)   r   r3   
start_timeend_timer   s         r*   test_get_states_in_time_rangez1TestLSOFSMUtilities.test_get_states_in_time_range  sm     	' dhh7 \\(,,/)2CC
<<-66w
HU 6{arB   c                    t        | j                        }t        j                  |      }|t        j
                  k(  sJ t        j                  |       t        j                  |      }|t        j
                  k(  sJ y)z
        Test cache invalidation for entity state.

        Validates:
        - Cache is cleared for specific entity
        - Subsequent lookups hit database
        r/   N)r   r#   r   r7   r   r8   invalidate_cache)r)   r3   r>   state_afters       r*   test_invalidate_cachez)TestLSOFSMUtilities.test_invalidate_cache  sp     !dhh7 44W=+33333 	%%g. #::7C199999rB   c                     t        | j                        }t        j                  |      }|J |j                  t
        j                  k(  sJ t        |d      sJ t        |d      sJ y)z
        Test get_current_state_object returns full state record.

        Validates:
        - Returns BaseState instance with full audit information
        - Contains all expected fields
        r/   Ntriggered_byr?   )r   r#   r   get_current_state_objectr>   r   r8   hasattr)r)   r3   state_objects      r*   test_get_current_state_objectz1TestLSOFSMUtilities.test_get_current_state_object  sl     !dhh7 $<<WE'''!!%8%@%@@@@|^444|%6777rB   c                     t        | j                        }t        j                  t        dd      5  t	        j
                  |dd| j                        }|du sJ 	 d	d	d	       y	# 1 sw Y   y	xY w)
z
        Test transition_state returns True when FSM is disabled.

        Validates:
        - Returns True without creating state record
        - Handles disabled state gracefully
        r/   r   Fr   	NEW_STATEry   )entity	new_stater?   r$   TN)r   r#   r   r   r   transition_stater$   r   s      r*   "test_transition_state_fsm_disabledz6TestLSOFSMUtilities.test_transition_state_fsm_disabled  sf     !dhh7\\,(9N 	"!22+vTXT]T]F T>!>		" 	" 	"s   *A''A0c                     t        d      D cg c]  }t        | j                         }}t        j                  |       |D ],  }t        j
                  |      }|t        j                  k(  r,J  yc c}w )z
        Test warm_cache with multiple entities for bulk operations.

        Validates:
        - Cache is populated for all entities
        - Subsequent get_current_state_value calls are fast (from cache)
           r/   N)rj   r   r#   r   rk   r7   r   r8   )r)   rl   projectsr3   r>   s        r*   !test_warm_cache_multiple_entitiesz5TestLSOFSMUtilities.test_warm_cache_multiple_entities  sr     DI8LaN9LL 	)   	8G 88AE/77777	8 Ms   A4c                     ddl m} t               du sJ  |j                  d       t               du sJ  |j                         du sJ  |j                  d       t               du sJ  |j                         du sJ y)z
        Test CurrentContext.set_fsm_disabled() directly.

        Validates:
        - Can disable FSM via CurrentContext
        - is_fsm_enabled() respects the flag
        - State is properly restored
        r   r   TFN)core.current_requestr   r   set_fsm_disabledis_fsm_disabled)r)   r   s     r*   %test_fsm_disabled_via_current_contextz9TestLSOFSMUtilities.test_fsm_disabled_via_current_context  s     	8 4''' 	(''-5(((-~--/4777 	(''.4'''-~--/5888rB   N)r   r   r   r   ra   r   r+   r   r   r   r   r   r   r   r   r   r   r   r   rB   r*   r   r   C  s^     V^^D!	 "	"%$:"E"" *:*8$" 8$9rB   r   )/r   loggingr   r   r\   r   ra   r   r   django.contrib.authr   django.core.cacher	   fsm.state_choicesr
   r   r   fsm.state_managerr   r   fsm.state_modelsr   r   r   	fsm.utilsr   r   r   organizations.tests.factoriesr   projects.tests.factoriesr   tasks.modelsr   tasks.tests.factoriesr   r   users.tests.factoriesr   User	getLoggerr   loggermark	django_dbr   r   r   rB   r*   <module>r      s     '   / . # [ [ = E E U U = 3 # @ -			8	$ a? a? a?H	 V9 V9 V9rB   