@@ -511,9 +511,7 @@ async def authenticate(self, reauthenticate: bool = False) -> None:
511511 await auth .authenticate (creds , self , reauthenticate = reauthenticate )
512512 self .ready = True
513513 duration = time .monotonic () - self .creation_time
514- if self .enabled_for_cmap :
515- assert self .listeners is not None
516- self .listeners .publish_connection_ready (self .address , self .id , duration )
514+ # Log before publishing event to prevent potential listener preemption in tests
517515 if self .enabled_for_logging and _CONNECTION_LOGGER .isEnabledFor (logging .DEBUG ):
518516 _debug_log (
519517 _CONNECTION_LOGGER ,
@@ -524,6 +522,9 @@ async def authenticate(self, reauthenticate: bool = False) -> None:
524522 driverConnectionId = self .id ,
525523 durationMS = duration ,
526524 )
525+ if self .enabled_for_cmap :
526+ assert self .listeners is not None
527+ self .listeners .publish_connection_ready (self .address , self .id , duration )
527528
528529 def validate_session (
529530 self , client : Optional [AsyncMongoClient [Any ]], session : Optional [AsyncClientSession ]
@@ -1028,9 +1029,7 @@ async def connect(self, handler: Optional[_MongoClientErrorHandler] = None) -> A
10281029 self .active_contexts .add (tmp_context )
10291030
10301031 listeners = self .opts ._event_listeners
1031- if self .enabled_for_cmap :
1032- assert listeners is not None
1033- listeners .publish_connection_created (self .address , conn_id )
1032+ # Log before publishing event to prevent potential listener preemption in tests
10341033 if self .enabled_for_logging and _CONNECTION_LOGGER .isEnabledFor (logging .DEBUG ):
10351034 _debug_log (
10361035 _CONNECTION_LOGGER ,
@@ -1040,6 +1039,9 @@ async def connect(self, handler: Optional[_MongoClientErrorHandler] = None) -> A
10401039 serverPort = self .address [1 ],
10411040 driverConnectionId = conn_id ,
10421041 )
1042+ if self .enabled_for_cmap :
1043+ assert listeners is not None
1044+ listeners .publish_connection_created (self .address , conn_id )
10431045
10441046 try :
10451047 networking_interface = await _configured_protocol_interface (self .address , self .opts )
0 commit comments