1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+ """Network connectivity test script to simulate connection issues.
4+
5+ This script helps understand how the current VK bot handles network disconnections
6+ and connection failures.
7+ """
8+ import sys
9+ import os
10+ import time
11+ import signal
12+ import threading
13+ from unittest .mock import patch , MagicMock
14+
15+ # Add python module path to import Bot
16+ sys .path .insert (0 , os .path .join (os .path .dirname (__file__ ), '..' , 'python' ))
17+
18+ try :
19+ import requests
20+ from saya import Vk
21+ from python .__main__ import Bot
22+ from python .tokens import BOT_TOKEN
23+ import python .config as config
24+ except ImportError as e :
25+ print (f"Import error: { e } " )
26+ print ("This is expected in the isolated test environment" )
27+ sys .exit (1 )
28+
29+
30+ class NetworkTestBot (Bot ):
31+ """Test bot with network failure simulation."""
32+
33+ def __init__ (self , * args , ** kwargs ):
34+ self .connection_lost_count = 0
35+ self .reconnection_attempts = 0
36+ self .max_reconnection_attempts = 5
37+ self .reconnection_delay = 2 # seconds
38+ super ().__init__ (* args , ** kwargs )
39+
40+ def call_method (self , method , params = None ):
41+ """Override call_method to simulate network failures."""
42+ try :
43+ return super ().call_method (method , params )
44+ except (requests .exceptions .ConnectionError ,
45+ requests .exceptions .Timeout ,
46+ requests .exceptions .HTTPError ) as e :
47+ print (f"Network error detected: { type (e ).__name__ } : { e } " )
48+ self .connection_lost_count += 1
49+ return self ._handle_network_error (method , params , e )
50+
51+ def _handle_network_error (self , method , params , error ):
52+ """Handle network errors with reconnection logic."""
53+ if self .reconnection_attempts >= self .max_reconnection_attempts :
54+ print (f"Max reconnection attempts ({ self .max_reconnection_attempts } ) reached. Giving up." )
55+ raise error
56+
57+ self .reconnection_attempts += 1
58+ print (f"Attempting reconnection { self .reconnection_attempts } /{ self .max_reconnection_attempts } " )
59+
60+ # Exponential backoff
61+ delay = self .reconnection_delay * (2 ** (self .reconnection_attempts - 1 ))
62+ print (f"Waiting { delay } seconds before retry..." )
63+ time .sleep (delay )
64+
65+ try :
66+ result = super ().call_method (method , params )
67+ print (f"Reconnection successful on attempt { self .reconnection_attempts } " )
68+ self .reconnection_attempts = 0 # Reset on success
69+ return result
70+ except Exception as e :
71+ print (f"Reconnection attempt { self .reconnection_attempts } failed: { e } " )
72+ return self ._handle_network_error (method , params , e )
73+
74+
75+ def simulate_network_failure ():
76+ """Simulate network failures by patching requests."""
77+
78+ def failing_request (* args , ** kwargs ):
79+ """Mock function that always raises connection error."""
80+ raise requests .exceptions .ConnectionError ("Simulated network failure" )
81+
82+ # Patch requests to simulate network failure
83+ with patch .object (requests .Session , 'post' , side_effect = failing_request ):
84+ with patch .object (requests .Session , 'get' , side_effect = failing_request ):
85+ print ("Network failure simulation active" )
86+
87+ try :
88+ # Create test bot instance
89+ bot = NetworkTestBot (token = BOT_TOKEN , group_id = config .BOT_GROUP_ID , debug = True )
90+
91+ # Test method call that should fail
92+ print ("Testing API call with simulated network failure..." )
93+ result = bot .call_method ('users.get' , {'user_ids' : 1 })
94+ print (f"Unexpected success: { result } " )
95+
96+ except Exception as e :
97+ print (f"Final error after all retry attempts: { type (e ).__name__ } : { e } " )
98+
99+
100+ def test_current_bot_resilience ():
101+ """Test how the current bot handles network issues."""
102+ print ("Testing current bot network resilience..." )
103+
104+ # Mock network issues
105+ def intermittent_failure (* args , ** kwargs ):
106+ """Randomly fail some requests."""
107+ import random
108+ if random .random () < 0.7 : # 70% failure rate
109+ raise requests .exceptions .ConnectionError ("Intermittent network failure" )
110+ return MagicMock ()
111+
112+ with patch .object (requests .Session , 'post' , side_effect = intermittent_failure ):
113+ try :
114+ bot = Bot (token = BOT_TOKEN , group_id = config .BOT_GROUP_ID , debug = True )
115+
116+ # Test multiple calls
117+ for i in range (5 ):
118+ try :
119+ print (f"Attempt { i + 1 } : Making API call..." )
120+ result = bot .call_method ('users.get' , {'user_ids' : 1 })
121+ print (f"Success: { result } " )
122+ except Exception as e :
123+ print (f"Failed: { type (e ).__name__ } : { e } " )
124+ time .sleep (1 )
125+
126+ except Exception as e :
127+ print (f"Bot initialization failed: { e } " )
128+
129+
130+ if __name__ == '__main__' :
131+ print ("=== VK Bot Network Resilience Test ===" )
132+ print ("This script tests how the bot handles network disconnections and failures." )
133+ print ()
134+
135+ print ("1. Testing with simulated complete network failure:" )
136+ simulate_network_failure ()
137+ print ()
138+
139+ print ("2. Testing with intermittent network failures:" )
140+ test_current_bot_resilience ()
141+ print ()
142+
143+ print ("Test completed." )
0 commit comments