Skip to content

Commit d53dc25

Browse files
committed
format.sh
1 parent 5c5c0aa commit d53dc25

File tree

4 files changed

+93
-97
lines changed

4 files changed

+93
-97
lines changed

py/selenium/webdriver/common/bidi/network.py

Lines changed: 81 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -16,35 +16,35 @@
1616
# under the License.
1717

1818
import uuid
19+
1920
from .session import session_subscribe
2021
from .session import session_unsubscribe
2122

2223

2324
class Network:
2425
EVENTS = {
25-
'before_request': 'network.beforeRequestSent',
26-
'response_started': 'network.responseStarted',
27-
'response_completed': 'network.responseCompleted',
28-
'auth_required': 'network.authRequired',
29-
'fetch_error': 'network.fetchError'
26+
"before_request": "network.beforeRequestSent",
27+
"response_started": "network.responseStarted",
28+
"response_completed": "network.responseCompleted",
29+
"auth_required": "network.authRequired",
30+
"fetch_error": "network.fetchError",
3031
}
3132

3233
PHASES = {
33-
'before_request': 'beforeRequestSent',
34-
'response_started': 'responseStarted',
35-
'auth_required': 'authRequired'
34+
"before_request": "beforeRequestSent",
35+
"response_started": "responseStarted",
36+
"auth_required": "authRequired",
3637
}
3738

3839
def __init__(self, conn):
3940
self.conn = conn
4041
self.callbacks = {}
4142
self.subscriptions = {
42-
'network.responseStarted': [],
43-
'network.beforeRequestSent': [],
44-
'network.authRequired': []
43+
"network.responseStarted": [],
44+
"network.beforeRequestSent": [],
45+
"network.authRequired": [],
4546
}
4647

47-
4848
def command_iterator(self, command):
4949
"""Generator to yield command."""
5050
yield command.to_json()
@@ -59,50 +59,37 @@ def __add_intercept(self, phases=None, contexts=None, url_patterns=None):
5959
phases = []
6060
if contexts is None and url_patterns is None:
6161
params = {
62-
'phases': phases,
62+
"phases": phases,
6363
}
6464
elif contexts is None:
65-
params = {
66-
'phases': phases,
67-
'urlPatterns': url_patterns
68-
}
65+
params = {"phases": phases, "urlPatterns": url_patterns}
6966
elif url_patterns is None:
70-
params = {
71-
'phases': phases,
72-
'contexts': contexts
73-
}
67+
params = {"phases": phases, "contexts": contexts}
7468
else:
75-
params = {
76-
'phases': phases,
77-
'contexts': contexts,
78-
'urlPatterns': url_patterns
79-
}
80-
command = {'method': 'network.addIntercept', 'params': params}
69+
params = {"phases": phases, "contexts": contexts, "urlPatterns": url_patterns}
70+
command = {"method": "network.addIntercept", "params": params}
8171
self.conn.execute(self.command_iterator(command))
8272

8373
def __remove_intercept(self, intercept=None, request_id=None):
8474
"""Remove an intercept from the network."""
8575
if request_id is not None:
86-
command = {'method': 'network.removeIntercept', 'requestId': request_id}
76+
command = {"method": "network.removeIntercept", "requestId": request_id}
8777
self.conn.execute(self.command_iterator(command))
8878
elif intercept is not None:
89-
command = {'method': 'network.removeIntercept', 'intercept': intercept}
79+
command = {"method": "network.removeIntercept", "intercept": intercept}
9080
self.conn.execute(self.command_iterator(command))
9181
else:
92-
raise ValueError('Either requestId or intercept must be specified')
82+
raise ValueError("Either requestId or intercept must be specified")
9383

9484
def __continue_with_auth(self, request_id, username, password):
9585
"""Continue with authentication."""
96-
command = {'method': 'network.continueWithAuth', 'params':
97-
{
98-
'request': request_id,
99-
'action': 'provideCredentials',
100-
'credentials': {
101-
'type': 'password',
102-
'username': username,
103-
'password': password
104-
}
105-
}
86+
command = {
87+
"method": "network.continueWithAuth",
88+
"params": {
89+
"request": request_id,
90+
"action": "provideCredentials",
91+
"credentials": {"type": "password", "username": username, "password": password},
92+
},
10693
}
10794
self.conn.execute(self.command_iterator(command))
10895

@@ -122,17 +109,19 @@ def __handle_event(self, event, data):
122109

123110
def add_authentication_handler(self, username, password):
124111
"""Adds an authentication handler."""
125-
self.__add_intercept(phases=[self.PHASES['auth_required']])
126-
self.__on('auth_required', lambda data: self.__continue_with_auth(data['request']['request'], username, password))
127-
self.subscriptions['auth_required'] = [username, password]
112+
self.__add_intercept(phases=[self.PHASES["auth_required"]])
113+
self.__on(
114+
"auth_required", lambda data: self.__continue_with_auth(data["request"]["request"], username, password)
115+
)
116+
self.subscriptions["auth_required"] = [username, password]
128117

129118
def remove_authentication_handler(self):
130119
"""Removes an authentication handler."""
131-
self.__remove_intercept(intercept='auth_required')
132-
del self.subscriptions['auth_required']
133-
session_unsubscribe(self.conn, self.EVENTS['auth_required'])
120+
self.__remove_intercept(intercept="auth_required")
121+
del self.subscriptions["auth_required"]
122+
session_unsubscribe(self.conn, self.EVENTS["auth_required"])
134123

135-
def add_request_handler(self, callback, url_pattern=''):
124+
def add_request_handler(self, callback, url_pattern=""):
136125
"""Adds a request handler that executes a callback function when a
137126
request matches the given URL pattern.
138127
@@ -145,34 +134,36 @@ def add_request_handler(self, callback, url_pattern=''):
145134
Returns:
146135
str: The request ID of the intercepted response.
147136
"""
148-
self.__add_intercept(phases=[self.PHASES['before_request']])
137+
self.__add_intercept(phases=[self.PHASES["before_request"]])
138+
149139
def callback_on_url_match(data):
150-
if url_pattern in data['request']['url']:
140+
if url_pattern in data["request"]["url"]:
151141
# create request object to pass to callback
152-
request_id = data['request'].get('requestId', uuid.uuid4())
153-
url = data['request'].get('url')
154-
method = data['request'].get('method')
155-
headers = data['request'].get('headers', {})
156-
body = data['request'].get('body', None)
142+
request_id = data["request"].get("requestId", uuid.uuid4())
143+
url = data["request"].get("url")
144+
method = data["request"].get("method")
145+
headers = data["request"].get("headers", {})
146+
body = data["request"].get("body", None)
157147
request = Request(request_id, url, method, headers, body, self)
158148
callback(request)
159-
request_id = self.__on('before_request', callback_on_url_match)
149+
150+
request_id = self.__on("before_request", callback_on_url_match)
160151
self.callbacks[request_id] = callback
161-
if 'before_request' not in self.subscriptions or not self.subscriptions.get('before_request'):
162-
self.subscriptions['before_request'] = [request_id]
152+
if "before_request" not in self.subscriptions or not self.subscriptions.get("before_request"):
153+
self.subscriptions["before_request"] = [request_id]
163154
else:
164-
self.subscriptions['before_request'].append(request_id)
155+
self.subscriptions["before_request"].append(request_id)
165156
return request_id
166157

167158
def remove_request_handler(self, request_id):
168159
"""Removes a request handler."""
169160
self.__remove_intercept(request_id=request_id)
170-
self.subscriptions['before_request'].remove(request_id)
161+
self.subscriptions["before_request"].remove(request_id)
171162
del self.callbacks[request_id]
172-
if len(self.subscriptions['before_request']) == 0:
173-
session_unsubscribe(self.conn, self.EVENTS['before_request'])
163+
if len(self.subscriptions["before_request"]) == 0:
164+
session_unsubscribe(self.conn, self.EVENTS["before_request"])
174165

175-
def add_response_handler(self, callback, url_pattern=''):
166+
def add_response_handler(self, callback, url_pattern=""):
176167
"""Adds a response handler that executes a callback function when a
177168
response matches the given URL pattern.
178169
@@ -185,32 +176,35 @@ def add_response_handler(self, callback, url_pattern=''):
185176
Returns:
186177
str: The request ID of the intercepted response.
187178
"""
188-
self.__add_intercept(phases=[self.PHASES['response_started']])
179+
self.__add_intercept(phases=[self.PHASES["response_started"]])
180+
189181
def callback_on_url_match(data):
190182
# create response object to pass to callback
191-
if url_pattern in data['response']['url']:
192-
request_id = data['request'].get('requestId', uuid.uuid4())
193-
url = data['response'].get('url')
194-
status_code = data['response'].get('status')
195-
body = data['response'].get('body', None)
196-
headers = data['response'].get('headers', {})
183+
if url_pattern in data["response"]["url"]:
184+
request_id = data["request"].get("requestId", uuid.uuid4())
185+
url = data["response"].get("url")
186+
status_code = data["response"].get("status")
187+
body = data["response"].get("body", None)
188+
headers = data["response"].get("headers", {})
197189
response = Response(request_id, url, status_code, headers, body, self)
198190
callback(response)
199-
request_id = self.__on('response_started', callback_on_url_match)
191+
192+
request_id = self.__on("response_started", callback_on_url_match)
200193
self.callbacks[request_id] = callback
201-
if 'response_started' not in self.subscriptions or not self.subscriptions.get('response_started'):
202-
self.subscriptions['response_started'] = [request_id]
194+
if "response_started" not in self.subscriptions or not self.subscriptions.get("response_started"):
195+
self.subscriptions["response_started"] = [request_id]
203196
else:
204-
self.subscriptions['response_started'].append(request_id)
197+
self.subscriptions["response_started"].append(request_id)
205198
return request_id
206199

207200
def remove_response_handler(self, response_id):
208201
"""Removes a response handler."""
209202
self.__remove_intercept(request_id=response_id)
210-
self.subscriptions['response_started'].remove(response_id)
203+
self.subscriptions["response_started"].remove(response_id)
211204
del self.callbacks[response_id]
212-
if len(self.subscriptions['response_started']) == 0:
213-
session_unsubscribe(self.conn, self.EVENTS['response_started'])
205+
if len(self.subscriptions["response_started"]) == 0:
206+
session_unsubscribe(self.conn, self.EVENTS["response_started"])
207+
214208

215209
class Request:
216210
def __init__(self, request_id, url, method, headers, body, network: Network):
@@ -223,24 +217,23 @@ def __init__(self, request_id, url, method, headers, body, network: Network):
223217

224218
def continue_request(self):
225219
"""Continue after sending a request."""
226-
params = {
227-
'requestId': self.request_id
228-
}
220+
params = {"requestId": self.request_id}
229221
if self.url is not None:
230-
params['url'] = self.url
222+
params["url"] = self.url
231223
if self.method is not None:
232-
params['method'] = self.method
224+
params["method"] = self.method
233225
if self.headers is not None:
234-
params['headers'] = self.headers
226+
params["headers"] = self.headers
235227
if self.body is not None:
236-
params['body'] = self.body
237-
command = {'method': 'network.continueRequest', 'params': params}
228+
params["body"] = self.body
229+
command = {"method": "network.continueRequest", "params": params}
238230
self.network.conn.execute(self.command_iterator(command))
239231

240232
def command_iterator(self, command):
241233
"""Generator to yield command."""
242234
yield command.to_json()
243235

236+
244237
class Response:
245238
def __init__(self, request_id, url, status_code, headers, body, network: Network):
246239
self.request_id = request_id
@@ -252,15 +245,12 @@ def __init__(self, request_id, url, status_code, headers, body, network: Network
252245

253246
def continue_response(self):
254247
"""Continue after receiving a response."""
255-
params = {
256-
'requestId': self.request_id,
257-
'status': self.status_code
258-
}
248+
params = {"requestId": self.request_id, "status": self.status_code}
259249
if self.headers is not None:
260-
params['headers'] = self.headers
250+
params["headers"] = self.headers
261251
if self.body is not None:
262-
params['body'] = self.body
263-
command = {'method': 'network.continueResponse', 'params': params}
252+
params["body"] = self.body
253+
command = {"method": "network.continueResponse", "params": params}
264254
self.network.conn.execute(self.command_iterator(command))
265255

266256
def command_iterator(self, command):

py/selenium/webdriver/remote/webdriver.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1252,7 +1252,7 @@ def network(self):
12521252
if not self._websocket_connection:
12531253
self._start_bidi()
12541254

1255-
if not hasattr(self, '_network') or self._network is None:
1255+
if not hasattr(self, "_network") or self._network is None:
12561256
self._network = Network(self._websocket_connection)
12571257

12581258
return self._network

py/selenium/webdriver/remote/websocket_connection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def execute(self, command):
7070
return self._deserialize_result(result, command)
7171

7272
def add_callback(self, event, callback):
73-
event_name = event.event_class if hasattr(event, 'event_class') else event
73+
event_name = event.event_class if hasattr(event, "event_class") else event
7474
if event_name not in self.callbacks:
7575
self.callbacks[event_name] = []
7676

py/test/selenium/webdriver/common/bidi_network_tests.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
def test_network_initialized(driver):
2525
assert driver.network is not None
2626

27+
2728
@pytest.mark.xfail_safari
2829
def test_add_response_handler(driver, pages):
2930
passed = [False]
@@ -36,6 +37,7 @@ def callback(response):
3637
pages.load("basicAuth")
3738
assert passed[0], "Callback was NOT successful"
3839

40+
3941
@pytest.mark.xfail_safari
4042
def test_remove_response_handler(driver, pages):
4143
passed = [False]
@@ -49,6 +51,7 @@ def callback(response):
4951
pages.load("basicAuth")
5052
assert not passed[0], "Callback should NOT be successful"
5153

54+
5255
@pytest.mark.xfail_safari
5356
def test_add_request_handler(driver, pages):
5457
passed = [False]
@@ -61,6 +64,7 @@ def callback(request):
6164
pages.load("basicAuth")
6265
assert passed[0], "Callback was NOT successful"
6366

67+
6468
@pytest.mark.xfail_safari
6569
def test_remove_request_handler(driver, pages):
6670
passed = [False]
@@ -74,15 +78,17 @@ def callback(request):
7478
pages.load("basicAuth")
7579
assert not passed[0], "Callback should NOT be successful"
7680

81+
7782
@pytest.mark.xfail_safari
7883
def test_add_authentication_handler(driver, pages):
79-
driver.network.add_authentication_handler('test','test')
84+
driver.network.add_authentication_handler("test", "test")
8085
pages.load("basicAuth")
81-
assert driver.find_element(By.TAG_NAME, 'h1').text == 'authorized', "Authentication was NOT successful"
86+
assert driver.find_element(By.TAG_NAME, "h1").text == "authorized", "Authentication was NOT successful"
87+
8288

8389
@pytest.mark.xfail_safari
8490
def test_remove_authentication_handler(driver, pages):
85-
driver.network.add_authentication_handler('test', 'test')
91+
driver.network.add_authentication_handler("test", "test")
8692
driver.network.remove_authentication_handler()
8793
pages.load("basicAuth")
88-
assert driver.find_element(By.TAG_NAME, 'h1').text != 'authorized', "Authentication was successful"
94+
assert driver.find_element(By.TAG_NAME, "h1").text != "authorized", "Authentication was successful"

0 commit comments

Comments
 (0)