Skip to content

Commit 386a0dc

Browse files
committed
move command_builder to common.py to avoid function duplication
1 parent f37a13e commit 386a0dc

File tree

3 files changed

+55
-52
lines changed

3 files changed

+55
-52
lines changed

py/selenium/webdriver/common/bidi/browser.py

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
from typing import Dict
1919
from typing import List
2020

21+
from selenium.webdriver.common.bidi.common import command_builder
22+
2123

2224
class ClientWindowState:
2325
"""Represents a window state."""
@@ -143,29 +145,14 @@ class Browser:
143145
def __init__(self, conn):
144146
self.conn = conn
145147

146-
def command_builder(self, method: str, params: Dict = None) -> Dict:
147-
"""Build a command iterator to send to the browser.
148-
149-
Parameters:
150-
-----------
151-
method: The method to execute.
152-
params: The parameters to pass to the method. Default is None.
153-
"""
154-
if params is None:
155-
params = {}
156-
157-
command = {"method": method, "params": params}
158-
cmd = yield command
159-
return cmd
160-
161148
def create_user_context(self) -> str:
162149
"""Creates a new user context.
163150
164151
Returns:
165152
-------
166153
str: The ID of the created user context.
167154
"""
168-
result = self.conn.execute(self.command_builder("browser.createUserContext", {}))
155+
result = self.conn.execute(command_builder("browser.createUserContext", {}))
169156
return result["userContext"]
170157

171158
def get_user_contexts(self) -> List[str]:
@@ -175,7 +162,7 @@ def get_user_contexts(self) -> List[str]:
175162
-------
176163
List[str]: A list of user context IDs.
177164
"""
178-
result = self.conn.execute(self.command_builder("browser.getUserContexts", {}))
165+
result = self.conn.execute(command_builder("browser.getUserContexts", {}))
179166
return [context_info["userContext"] for context_info in result["userContexts"]]
180167

181168
def remove_user_context(self, user_context_id: str) -> None:
@@ -190,7 +177,7 @@ def remove_user_context(self, user_context_id: str) -> None:
190177
Exception: If the user context ID is "default" or does not exist.
191178
"""
192179
params = {"userContext": user_context_id}
193-
self.conn.execute(self.command_builder("browser.removeUserContext", params))
180+
self.conn.execute(command_builder("browser.removeUserContext", params))
194181

195182
def get_client_windows(self) -> List[ClientWindowInfo]:
196183
"""Gets all client windows.
@@ -199,5 +186,5 @@ def get_client_windows(self) -> List[ClientWindowInfo]:
199186
-------
200187
List[ClientWindowInfo]: A list of client window information.
201188
"""
202-
result = self.conn.execute(self.command_builder("browser.getClientWindows", {}))
189+
result = self.conn.execute(command_builder("browser.getClientWindows", {}))
203190
return [ClientWindowInfo.from_dict(window) for window in result["clientWindows"]]
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Licensed to the Software Freedom Conservancy (SFC) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The SFC licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
18+
from typing import Dict
19+
20+
21+
def command_builder(method: str, params: Dict = None) -> Dict:
22+
"""Build a command iterator to send to the BiDi protocol.
23+
24+
Parameters:
25+
-----------
26+
method: The method to execute.
27+
params: The parameters to pass to the method. Default is None.
28+
29+
Returns:
30+
--------
31+
The response from the command execution.
32+
"""
33+
if params is None:
34+
params = {}
35+
36+
command = {"method": method, "params": params}
37+
cmd = yield command
38+
return cmd

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

Lines changed: 11 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
# specific language governing permissions and limitations
1616
# under the License.
1717

18+
from selenium.webdriver.common.bidi.common import command_builder
19+
1820

1921
class NetworkEvent:
2022
"""Represents a network event."""
@@ -51,18 +53,6 @@ def __init__(self, conn):
5153
self.callbacks = {}
5254
self.subscriptions = {}
5355

54-
def command_builder(self, method, params):
55-
"""Build a command iterator to send to the network.
56-
57-
Parameters:
58-
----------
59-
method (str): The method to execute.
60-
params (dict): The parameters to pass to the method.
61-
"""
62-
command = {"method": method, "params": params}
63-
cmd = yield command
64-
return cmd
65-
6656
def _add_intercept(self, phases=[], contexts=None, url_patterns=None):
6757
"""Add an intercept to the network.
6858
@@ -88,7 +78,7 @@ def _add_intercept(self, phases=[], contexts=None, url_patterns=None):
8878
params["phases"] = phases
8979
else:
9080
params["phases"] = ["beforeRequestSent"]
91-
cmd = self.command_builder("network.addIntercept", params)
81+
cmd = command_builder("network.addIntercept", params)
9282

9383
result = self.conn.execute(cmd)
9484
self.intercepts.append(result["intercept"])
@@ -113,11 +103,11 @@ def _remove_intercept(self, intercept=None):
113103
if intercept is None:
114104
intercepts_to_remove = self.intercepts.copy() # create a copy before iterating
115105
for intercept_id in intercepts_to_remove: # remove all intercepts
116-
self.conn.execute(self.command_builder("network.removeIntercept", {"intercept": intercept_id}))
106+
self.conn.execute(command_builder("network.removeIntercept", {"intercept": intercept_id}))
117107
self.intercepts.remove(intercept_id)
118108
else:
119109
try:
120-
self.conn.execute(self.command_builder("network.removeIntercept", {"intercept": intercept}))
110+
self.conn.execute(command_builder("network.removeIntercept", {"intercept": intercept}))
121111
self.intercepts.remove(intercept)
122112
except Exception as e:
123113
raise Exception(f"Exception: {e}")
@@ -192,7 +182,7 @@ def add_request_handler(self, event, callback, url_patterns=None, contexts=None)
192182
else:
193183
params = {}
194184
params["events"] = [event_name]
195-
self.conn.execute(self.command_builder("session.subscribe", params))
185+
self.conn.execute(command_builder("session.subscribe", params))
196186
self.subscriptions[event_name] = [callback_id]
197187

198188
self.callbacks[callback_id] = result["intercept"]
@@ -220,7 +210,7 @@ def remove_request_handler(self, event, callback_id):
220210
if len(self.subscriptions[event_name]) == 0:
221211
params = {}
222212
params["events"] = [event_name]
223-
self.conn.execute(self.command_builder("session.unsubscribe", params))
213+
self.conn.execute(command_builder("session.unsubscribe", params))
224214
del self.subscriptions[event_name]
225215

226216
def clear_request_handlers(self):
@@ -234,7 +224,7 @@ def clear_request_handlers(self):
234224
del self.callbacks[callback_id]
235225
params = {}
236226
params["events"] = [event_name]
237-
self.conn.execute(self.command_builder("session.unsubscribe", params))
227+
self.conn.execute(command_builder("session.unsubscribe", params))
238228
self.subscriptions = {}
239229

240230
def add_auth_handler(self, username, password):
@@ -294,26 +284,14 @@ def __init__(
294284
self.timings = timings
295285
self.url = url
296286

297-
def command_builder(self, method, params):
298-
"""Build a command iterator to send to the network.
299-
300-
Parameters:
301-
----------
302-
method (str): The method to execute.
303-
params (dict): The parameters to pass to the method.
304-
"""
305-
command = {"method": method, "params": params}
306-
cmd = yield command
307-
return cmd
308-
309287
def fail_request(self):
310288
"""Fail this request."""
311289

312290
if not self.request_id:
313291
raise ValueError("Request not found.")
314292

315293
params = {"request": self.request_id}
316-
self.network.conn.execute(self.command_builder("network.failRequest", params))
294+
self.network.conn.execute(command_builder("network.failRequest", params))
317295

318296
def continue_request(self, body=None, method=None, headers=None, cookies=None, url=None):
319297
"""Continue after intercepting this request."""
@@ -333,7 +311,7 @@ def continue_request(self, body=None, method=None, headers=None, cookies=None, u
333311
if url is not None:
334312
params["url"] = url
335313

336-
self.network.conn.execute(self.command_builder("network.continueRequest", params))
314+
self.network.conn.execute(command_builder("network.continueRequest", params))
337315

338316
def _continue_with_auth(self, username=None, password=None):
339317
"""Continue with authentication.
@@ -358,4 +336,4 @@ def _continue_with_auth(self, username=None, password=None):
358336
params["action"] = "provideCredentials"
359337
params["credentials"] = {"type": "password", "username": username, "password": password}
360338

361-
self.network.conn.execute(self.command_builder("network.continueWithAuth", params))
339+
self.network.conn.execute(command_builder("network.continueWithAuth", params))

0 commit comments

Comments
 (0)