code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_index(self) -> int | None:
"""Get the index of the action"""
# {'clicked_element': {'index':5}}
params = self.model_dump(exclude_unset=True).values()
if not params:
return None
for param in params:
if param is not None and 'index' in param:
return param['index']
return None | Get the index of the action | get_index | python | browser-use/browser-use | browser_use/controller/registry/views.py | https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/views.py | MIT |
def set_index(self, index: int):
"""Overwrite the index of the action"""
# Get the action name and params
action_data = self.model_dump(exclude_unset=True)
action_name = next(iter(action_data.keys()))
action_params = getattr(self, action_name)
# Update the index directly on the model
if hasattr(action_pa... | Overwrite the index of the action | set_index | python | browser-use/browser-use | browser_use/controller/registry/views.py | https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/views.py | MIT |
def _match_domains(domains: list[str] | None, url: str) -> bool:
"""
Match a list of domain glob patterns against a URL.
Args:
domains: A list of domain patterns that can include glob patterns (* wildcard)
url: The URL to match against
Returns:
True if the URL's domain matches the pattern, False othe... |
Match a list of domain glob patterns against a URL.
Args:
domains: A list of domain patterns that can include glob patterns (* wildcard)
url: The URL to match against
Returns:
True if the URL's domain matches the pattern, False otherwise
| _match_domains | python | browser-use/browser-use | browser_use/controller/registry/views.py | https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/views.py | MIT |
def get_prompt_description(self, page: Page | None = None) -> str:
"""Get a description of all actions for the prompt
Args:
page: If provided, filter actions by page using page_filter and domains.
Returns:
A string description of available actions.
- If page is None: return only actions with no page_fi... | Get a description of all actions for the prompt
Args:
page: If provided, filter actions by page using page_filter and domains.
Returns:
A string description of available actions.
- If page is None: return only actions with no page_filter and no domains (for system prompt)
- If page is provided: return... | get_prompt_description | python | browser-use/browser-use | browser_use/controller/registry/views.py | https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/views.py | MIT |
def clickable_elements_to_string(self, include_attributes: list[str] | None = None) -> str:
"""Convert the processed DOM content to HTML."""
formatted_text = []
def process_node(node: DOMBaseNode, depth: int) -> None:
next_depth = int(depth)
depth_str = depth * '\t'
if isinstance(node, DOMElementNode):... | Convert the processed DOM content to HTML. | clickable_elements_to_string | python | browser-use/browser-use | browser_use/dom/views.py | https://github.com/browser-use/browser-use/blob/master/browser_use/dom/views.py | MIT |
def get_clickable_elements_hashes(dom_element: DOMElementNode) -> set[str]:
"""Get all clickable elements in the DOM tree"""
clickable_elements = ClickableElementProcessor.get_clickable_elements(dom_element)
return {ClickableElementProcessor.hash_dom_element(element) for element in clickable_elements} | Get all clickable elements in the DOM tree | get_clickable_elements_hashes | python | browser-use/browser-use | browser_use/dom/clickable_element_processor/service.py | https://github.com/browser-use/browser-use/blob/master/browser_use/dom/clickable_element_processor/service.py | MIT |
def _direct_capture(self, event: BaseTelemetryEvent) -> None:
"""
Should not be thread blocking because posthog magically handles it
"""
if self._posthog_client is None:
return
try:
self._posthog_client.capture(
self.user_id,
event.name,
{**event.properties, **POSTHOG_EVENT_SETTINGS},
)
... |
Should not be thread blocking because posthog magically handles it
| _direct_capture | python | browser-use/browser-use | browser_use/telemetry/service.py | https://github.com/browser-use/browser-use/blob/master/browser_use/telemetry/service.py | MIT |
async def Online_Mind2Web_eval_with_retry(task, last_actions, images_path, model, score_threshold, max_retries=3):
"""
Wrapper for Online_Mind2Web_eval with retry logic.
Args:
task: The task description
last_actions: list of actions taken
images_path: list of image paths
model: The model to use ... |
Wrapper for Online_Mind2Web_eval with retry logic.
Args:
task: The task description
last_actions: list of actions taken
images_path: list of image paths
model: The model to use for evaluation
score_threshold: Score threshold for image filtering
max_retries: Maximum number of retry atte... | Online_Mind2Web_eval_with_retry | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def create_controller_with_serp_search():
"""Create a controller with SERP search instead of Google search"""
controller = Controller(exclude_actions=['search_google'])
@controller.registry.action('Search the web for a specific query')
async def search_web(query: str):
"""Search the web using Serper API"""
if ... | Create a controller with SERP search instead of Google search | create_controller_with_serp_search | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
async def search_web(query: str):
"""Search the web using Serper API"""
if not SERPER_API_KEY:
return ActionResult(extracted_content='Search unavailable: SERPER_API_KEY not configured', include_in_memory=False)
try:
# Make request to Serper API
conn = http.client.HTTPSConnection('google.serper.dev')
... | Search the web using Serper API | search_web | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def create_controller(use_serp: bool = False):
"""Create a controller, optionally with SERP search"""
if use_serp:
return create_controller_with_serp_search()
else:
return Controller() | Create a controller, optionally with SERP search | create_controller | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def get_llm(model_name: str):
"""Instantiates the correct LangChain ChatModel based on the model name."""
if model_name not in SUPPORTED_MODELS:
raise ValueError(f'Unsupported model: {model_name}. Supported models are: {list(SUPPORTED_MODELS.keys())}')
config = SUPPORTED_MODELS[model_name]
provider = config['pro... | Instantiates the correct LangChain ChatModel based on the model name. | get_llm | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
async def judge_task_result(model, task_folder: Path, score_threshold: float = 3) -> dict:
"""
Judge a single task result based on the success value of the final action.
Args:
task_folder: Path to the task result folder
Returns:
Dictionary containing judgment results
"""
result_file = task_folder / 'r... |
Judge a single task result based on the success value of the final action.
Args:
task_folder: Path to the task result folder
Returns:
Dictionary containing judgment results
| judge_task_result | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def calculate_local_summary(results_dir: str | None = None) -> dict:
"""
Calculates a summary of task results by reading the saved result.json files.
Does not make any network requests.
"""
if results_dir is None:
results_dir = 'saved_trajectories'
path = Path(results_dir)
if not path.is_dir():
logger.warni... |
Calculates a summary of task results by reading the saved result.json files.
Does not make any network requests.
| calculate_local_summary | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def stage_completed(self, stage: Stage, data: Any = None):
"""Mark stage as completed and update server payload"""
self.completed_stages.add(stage)
if data is not None:
self.stage_data[stage] = data
self._auto_update_payload() | Mark stage as completed and update server payload | stage_completed | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def _has_execution_failures(self) -> bool:
"""Check if any execution-related stages failed"""
execution_stages = {Stage.SETUP_BROWSER, Stage.RUN_AGENT, Stage.FORMAT_HISTORY}
return any(stage in self.failed_stages for stage in execution_stages) | Check if any execution-related stages failed | _has_execution_failures | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def _auto_update_payload(self):
"""Automatically update server_payload based on current state"""
# Update execution data if available
if Stage.LOAD_EXISTING in self.completed_stages:
existing_data = self.stage_data[Stage.LOAD_EXISTING]
self.server_payload.update(
{
'actionHistory': existing_data.ge... | Automatically update server_payload based on current state | _auto_update_payload | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def _update_failure_states(self):
"""Update server payload based on failed stages"""
# Check for browser/execution failures
for stage, error in self.failed_stages.items():
if stage in {Stage.SETUP_BROWSER, Stage.RUN_AGENT}:
self.server_payload['browserCrash'] = True
if error.error_type == 'timeout':
... | Update server payload based on failed stages | _update_failure_states | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def mark_critical_error(self, error_msg: str):
"""Mark task as having critical error"""
self.server_payload.update(
{
'finalResultResponse': f'Critical Error: {error_msg}',
'onlineMind2WebEvaluationJudgement': 'Critical System Error',
'onlineMind2WebEvaluationError': f'Critical flow error: {error_msg... | Mark task as having critical error | mark_critical_error | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
async def setup_browser_session(task: Task, headless: bool) -> BrowserSession:
"""Setup browser session for the task"""
logger.debug(f'Browser setup: Creating unique user data directory for task {task.task_id}')
# Create unique user data directory
base_user_data_dir = Path(BrowserProfile().user_data_dir).parent
un... | Setup browser session for the task | setup_browser_session | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
async def run_agent_with_browser(
browser_session: BrowserSession,
task: Task,
llm: BaseChatModel,
max_steps: int,
use_vision: bool,
use_serp: bool = False,
enable_memory: bool = False,
memory_interval: int = 10,
max_actions_per_step: int = 10,
validate_output: bool = False,
planner_llm: BaseChatModel | None... | Run agent with the browser session | run_agent_with_browser | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def determine_current_stage(completed_stages: set) -> Stage:
"""Determine current stage based on completed stages"""
if Stage.SAVE_SERVER in completed_stages:
return Stage.SAVE_SERVER
elif Stage.EVALUATE in completed_stages:
return Stage.EVALUATE
elif Stage.FORMAT_HISTORY in completed_stages:
return Stage.FOR... | Determine current stage based on completed stages | determine_current_stage | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
async def run_task_with_semaphore(
task: Task,
run_id: str,
convex_url: str,
secret_key: str,
eval_model: BaseChatModel,
llm: BaseChatModel,
max_steps_per_task: int,
headless: bool,
use_vision: bool,
semaphore_runs: asyncio.Semaphore, # Pass semaphore as argument
fresh_start: bool = True,
use_serp: bool = ... | Clean pipeline approach for running tasks | run_task_with_semaphore | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
async def run_multiple_tasks(
tasks: list[Task],
llm: BaseChatModel,
run_id: str,
convex_url: str,
secret_key: str,
eval_model: BaseChatModel,
max_parallel_runs: int = 3,
max_steps_per_task: int = 25,
start_index: int = 0,
end_index: int | None = None,
headless: bool = False,
use_vision: bool = True,
fresh... |
Run multiple tasks in parallel and evaluate results.
| run_multiple_tasks | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def fetch_tasks_from_server(convex_url: str, secret_key: str, test_case_name: str):
"""Fetches the specified test case file from the Convex HTTP endpoint."""
if not convex_url:
logger.error('Error: EVALUATION_TOOL_URL environment variable not set.')
return None
if not secret_key:
logger.error('Error: EVALUAT... | Fetches the specified test case file from the Convex HTTP endpoint. | fetch_tasks_from_server | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def start_new_run(convex_url: str, secret_key: str, run_details: dict, existing_run_id: str = None):
"""Sends a request to start a new evaluation run and returns the run ID."""
if not convex_url or not secret_key:
logger.error('Error: Convex URL or Secret Key not provided for starting run.')
return None
endpoin... | Sends a request to start a new evaluation run and returns the run ID. | start_new_run | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
def save_task_result_to_server(convex_url: str, secret_key: str, result_details: dict):
"""Sends a request to save a single task result to the Convex backend."""
if not convex_url:
logger.error('Error: EVALUATION_TOOL_URL environment variable not set for saving task result.')
return False
if not secret_key:
... | Sends a request to save a single task result to the Convex backend. | save_task_result_to_server | python | browser-use/browser-use | eval/service.py | https://github.com/browser-use/browser-use/blob/master/eval/service.py | MIT |
async def example_custom_window_size():
"""Example 1: Setting a custom browser window size"""
print('\n=== Example 1: Custom Window Size ===')
# Create a browser profile with a specific window size
profile = BrowserProfile(
window_size={'width': 800, 'height': 600}, # Small size for demonstration
# **playwrig... | Example 1: Setting a custom browser window size | example_custom_window_size | python | browser-use/browser-use | examples/browser/window_sizing.py | https://github.com/browser-use/browser-use/blob/master/examples/browser/window_sizing.py | MIT |
async def example_no_viewport_option():
"""Example 2: Testing browser window sizing with no_viewport option"""
print('\n=== Example 2: Window Sizing with no_viewport=False ===')
profile = BrowserProfile(window_size={'width': 1440, 'height': 900}, no_viewport=False, headless=False)
browser_session = None
try:
... | Example 2: Testing browser window sizing with no_viewport option | example_no_viewport_option | python | browser-use/browser-use | examples/browser/window_sizing.py | https://github.com/browser-use/browser-use/blob/master/examples/browser/window_sizing.py | MIT |
async def get_otp_2fa() -> ActionResult:
"""
Custom action to retrieve 2FA/MFA code from OTP secret key using pyotp.
The OTP secret key should be set in the environment variable OTP_SECRET_KEY.
"""
secret_key = os.environ.get('OTP_SECRET_KEY')
if not secret_key:
raise ValueError('OTP_SECRET_KEY environment vari... |
Custom action to retrieve 2FA/MFA code from OTP secret key using pyotp.
The OTP secret key should be set in the environment variable OTP_SECRET_KEY.
| get_otp_2fa | python | browser-use/browser-use | examples/custom-functions/2fa.py | https://github.com/browser-use/browser-use/blob/master/examples/custom-functions/2fa.py | MIT |
async def main():
"""Main function to run the example"""
browser_session = BrowserSession()
await browser_session.start()
llm = ChatOpenAI(model='gpt-4o')
# Create the agent
agent = Agent( # disco mode will not be triggered on apple.com because the LLM won't be able to see that action available, it should work ... | Main function to run the example | main | python | browser-use/browser-use | examples/custom-functions/action_filters.py | https://github.com/browser-use/browser-use/blob/master/examples/custom-functions/action_filters.py | MIT |
async def get_1password_2fa() -> ActionResult:
"""
Custom action to retrieve 2FA/MFA code from 1Password using onepassword.client SDK.
"""
client = await Client.authenticate(
# setup instructions: https://github.com/1Password/onepassword-sdk-python/#-get-started
auth=OP_SERVICE_ACCOUNT_TOKEN,
integration_name... |
Custom action to retrieve 2FA/MFA code from 1Password using onepassword.client SDK.
| get_1password_2fa | python | browser-use/browser-use | examples/custom-functions/onepassword_2fa.py | https://github.com/browser-use/browser-use/blob/master/examples/custom-functions/onepassword_2fa.py | MIT |
async def main():
"""Main function to run the agent with different memory configurations."""
common_task = 'Find the current CEO of OpenAI and then search for news about their latest projects. Summarize your findings.'
shared_agent_id = 'persistent_browser_agent_001' # Use the same ID to test persistence with Qdran... | Main function to run the agent with different memory configurations. | main | python | browser-use/browser-use | examples/features/custom_vector_store.py | https://github.com/browser-use/browser-use/blob/master/examples/features/custom_vector_store.py | MIT |
async def on_ready(self):
"""Called when the bot is ready."""
try:
print(f'We have logged in as {self.user}')
cmds = await self.tree.sync() # Sync the command tree with discord
except Exception as e:
print(f'Error during bot startup: {e}') | Called when the bot is ready. | on_ready | python | browser-use/browser-use | examples/integrations/discord/discord_api.py | https://github.com/browser-use/browser-use/blob/master/examples/integrations/discord/discord_api.py | MIT |
def initialize_agent(query: str, provider: str):
"""Initialize the browser agent with the given query and provider."""
llm = get_llm(provider)
controller = Controller()
browser_session = BrowserSession()
return Agent(
task=query,
llm=llm,
controller=controller,
browser_session=browser_session,
use_visio... | Initialize the browser agent with the given query and provider. | initialize_agent | python | browser-use/browser-use | examples/ui/command_line.py | https://github.com/browser-use/browser-use/blob/master/examples/ui/command_line.py | MIT |
async def main():
"""Main async function to run the agent."""
args = parse_arguments()
agent, browser_session = initialize_agent(args.query, args.provider)
await agent.run(max_steps=25)
input('Press Enter to close the browser...')
await browser_session.close() | Main async function to run the agent. | main | python | browser-use/browser-use | examples/ui/command_line.py | https://github.com/browser-use/browser-use/blob/master/examples/ui/command_line.py | MIT |
async def main():
"""Main function to execute the agent task."""
task = (
'Go to the Greece MFA webpage via the link I provided you.'
'Check the visa appointment dates. If there is no available date in this month, check the next month.'
'If there is no available date in both months, tell me there is no availabl... | Main function to execute the agent task. | main | python | browser-use/browser-use | examples/use-cases/check_appointment.py | https://github.com/browser-use/browser-use/blob/master/examples/use-cases/check_appointment.py | MIT |
def parse_transform(style: str) -> tuple[float, float] | None:
"""Extracts x and y pixel coordinates from a CSS transform string."""
try:
parts = style.split('(')[1].split(')')[0].split(',')
x_px_str = float(parts[0].strip().replace('px', ''))
y_px_str = float(parts[1].strip().replace('px', ''))
return x_px_s... | Extracts x and y pixel coordinates from a CSS transform string. | parse_transform | python | browser-use/browser-use | examples/use-cases/play_chess.py | https://github.com/browser-use/browser-use/blob/master/examples/use-cases/play_chess.py | MIT |
def algebraic_to_pixels(square: str, square_size: float) -> tuple[str, str]:
"""Converts algebraic notation to Lichess pixel coordinates using dynamic size."""
file_char = square[0].lower()
rank_char = square[1]
if file_char not in FILES or rank_char not in RANKS:
raise ValueError(f'Invalid square: {square}')
... | Converts algebraic notation to Lichess pixel coordinates using dynamic size. | algebraic_to_pixels | python | browser-use/browser-use | examples/use-cases/play_chess.py | https://github.com/browser-use/browser-use/blob/master/examples/use-cases/play_chess.py | MIT |
def pixels_to_algebraic(x_px: float, y_px: float, square_size: float) -> str:
"""Converts Lichess pixel coordinates to algebraic notation using dynamic size."""
if not square_size:
raise ValueError('Square size cannot be zero or None.')
x_index = int(round(x_px / square_size))
y_index = int(round(y_px / square_s... | Converts Lichess pixel coordinates to algebraic notation using dynamic size. | pixels_to_algebraic | python | browser-use/browser-use | examples/use-cases/play_chess.py | https://github.com/browser-use/browser-use/blob/master/examples/use-cases/play_chess.py | MIT |
async def calculate_square_size(page) -> float | None:
"""Dynamically calculates the size of a chess square in pixels."""
try:
board_html = await page.locator('cg-board').inner_html(timeout=3000)
soup = BeautifulSoup(board_html, 'html.parser')
pieces = soup.find_all('piece')
if not pieces:
raise ValueError... | Dynamically calculates the size of a chess square in pixels. | calculate_square_size | python | browser-use/browser-use | examples/use-cases/play_chess.py | https://github.com/browser-use/browser-use/blob/master/examples/use-cases/play_chess.py | MIT |
async def get_current_board_info(page) -> tuple[str | None, float]:
"""Reads the current board HTML and returns FEN string and square size."""
board_state = {}
board_html = ''
square_size = None
try:
board_locator = page.locator('cg-board')
await board_locator.wait_for(state='visible', timeout=3000)
board_h... | Reads the current board HTML and returns FEN string and square size. | get_current_board_info | python | browser-use/browser-use | examples/use-cases/play_chess.py | https://github.com/browser-use/browser-use/blob/master/examples/use-cases/play_chess.py | MIT |
async def read_board(browser: BrowserContext):
"""Reads the board, returns FEN and legal moves in SAN (+/#), and the last move by opponent if possible."""
page = await browser.get_current_page()
full_fen, _ = await get_current_board_info(page)
if not full_fen:
return ActionResult(extracted_content='Could not rea... | Reads the board, returns FEN and legal moves in SAN (+/#), and the last move by opponent if possible. | read_board | python | browser-use/browser-use | examples/use-cases/play_chess.py | https://github.com/browser-use/browser-use/blob/master/examples/use-cases/play_chess.py | MIT |
async def play_move(params: PlayMoveParams, browser: BrowserContext):
"""Plays a chess move given in SAN by converting it to UCI and clicking."""
san_move = params.move.strip()
page = await browser.get_current_page()
uci_move = ''
try:
current_fen, square_size = await get_current_board_info(page)
if not curre... | Plays a chess move given in SAN by converting it to UCI and clicking. | play_move | python | browser-use/browser-use | examples/use-cases/play_chess.py | https://github.com/browser-use/browser-use/blob/master/examples/use-cases/play_chess.py | MIT |
async def analyze_page_structure(url: str):
"""Analyze and print the structure of a webpage with enhanced debugging"""
browser = Browser(
config=BrowserConfig(
headless=False, # Set to True if you don't need to see the browser
),
user_data_dir=None,
)
context = BrowserContext(browser=browser)
try:
as... | Analyze and print the structure of a webpage with enhanced debugging | analyze_page_structure | python | browser-use/browser-use | tests/debug_page_structure.py | https://github.com/browser-use/browser-use/blob/master/tests/debug_page_structure.py | MIT |
def count_string_tokens(string: str, model: str) -> tuple[int, float]:
"""Count the number of tokens in a string using a specified model."""
def get_price_per_token(model: str) -> float:
"""Get the price per token for a specified model.
@todo: move to utils, use a package or sth
"""
prices = {
'gpt-4o': ... | Count the number of tokens in a string using a specified model. | count_string_tokens | python | browser-use/browser-use | tests/extraction_test.py | https://github.com/browser-use/browser-use/blob/master/tests/extraction_test.py | MIT |
def get_price_per_token(model: str) -> float:
"""Get the price per token for a specified model.
@todo: move to utils, use a package or sth
"""
prices = {
'gpt-4o': 2.5 / 1e6,
'gpt-4o-mini': 0.15 / 1e6,
}
return prices[model] | Get the price per token for a specified model.
@todo: move to utils, use a package or sth
| get_price_per_token | python | browser-use/browser-use | tests/extraction_test.py | https://github.com/browser-use/browser-use/blob/master/tests/extraction_test.py | MIT |
async def test_browser_close_doesnt_affect_external_httpx_clients():
"""
Test that Browser.close() doesn't close HTTPX clients created outside the Browser instance.
This test demonstrates the issue where Browser.close() is closing all HTTPX clients.
"""
# Create an external HTTPX client that should remain open
ex... |
Test that Browser.close() doesn't close HTTPX clients created outside the Browser instance.
This test demonstrates the issue where Browser.close() is closing all HTTPX clients.
| test_browser_close_doesnt_affect_external_httpx_clients | python | browser-use/browser-use | tests/httpx_client_test.py | https://github.com/browser-use/browser-use/blob/master/tests/httpx_client_test.py | MIT |
def test_get_prompt_description_no_filters(self):
"""Test that system prompt only includes actions with no filters"""
registry = ActionRegistry()
# Add actions with and without filters
no_filter_action = RegisteredAction(
name='no_filter_action',
description='Action with no filters',
function=lambda: ... | Test that system prompt only includes actions with no filters | test_get_prompt_description_no_filters | python | browser-use/browser-use | tests/test_action_filters.py | https://github.com/browser-use/browser-use/blob/master/tests/test_action_filters.py | MIT |
def test_page_filter_matching(self):
"""Test that page filters work correctly"""
registry = ActionRegistry()
# Create a mock page
mock_page = MagicMock(spec=Page)
mock_page.url = 'https://example.com/page'
# Create actions with different page filters
matching_action = RegisteredAction(
name='matching... | Test that page filters work correctly | test_page_filter_matching | python | browser-use/browser-use | tests/test_action_filters.py | https://github.com/browser-use/browser-use/blob/master/tests/test_action_filters.py | MIT |
def test_domain_filter_matching(self):
"""Test that domain filters work correctly with glob patterns"""
registry = ActionRegistry()
# Create actions with different domain patterns
actions = {
'exact_match': RegisteredAction(
name='exact_match',
description='Exact domain match',
function=lambda: ... | Test that domain filters work correctly with glob patterns | test_domain_filter_matching | python | browser-use/browser-use | tests/test_action_filters.py | https://github.com/browser-use/browser-use/blob/master/tests/test_action_filters.py | MIT |
def test_domain_and_page_filter_together(self):
"""Test that actions can be filtered by both domain and page filter"""
registry = ActionRegistry()
# Create a mock page
mock_page = MagicMock(spec=Page)
mock_page.url = 'https://example.com/admin'
# Actions with different combinations of filters
actions = ... | Test that actions can be filtered by both domain and page filter | test_domain_and_page_filter_together | python | browser-use/browser-use | tests/test_action_filters.py | https://github.com/browser-use/browser-use/blob/master/tests/test_action_filters.py | MIT |
async def test_registry_action_decorator(self):
"""Test the action decorator with filters"""
registry = Registry()
# Define actions with different filters
@registry.action(
description='No filter action',
)
def no_filter_action():
pass
@registry.action(description='Domain filter action', domains=[... | Test the action decorator with filters | test_registry_action_decorator | python | browser-use/browser-use | tests/test_action_filters.py | https://github.com/browser-use/browser-use/blob/master/tests/test_action_filters.py | MIT |
async def test_action_model_creation(self):
"""Test that action models are created correctly with filters"""
registry = Registry()
# Define actions with different filters
@registry.action(
description='No filter action',
)
def no_filter_action():
pass
@registry.action(description='Domain filter ac... | Test that action models are created correctly with filters | test_action_model_creation | python | browser-use/browser-use | tests/test_action_filters.py | https://github.com/browser-use/browser-use/blob/master/tests/test_action_filters.py | MIT |
async def test_registry_param_handling():
"""Test how Registry handles parameter passing for different function signatures."""
# Create a Registry instance
registry = Registry[TestContext]()
# Create test functions with different signatures
# 1. Function with browser_session as a positional parameter
@registry.... | Test how Registry handles parameter passing for different function signatures. | test_registry_param_handling | python | browser-use/browser-use | tests/test_action_params.py | https://github.com/browser-use/browser-use/blob/master/tests/test_action_params.py | MIT |
async def test_error_recovery(llm, browser_session):
"""Test agent's ability to recover from errors"""
agent = Agent(
task='Navigate to nonexistent-site.com and then recover by going to google.com ',
llm=llm,
browser_session=browser_session,
)
history: AgentHistoryList = await agent.run(max_steps=10)
actio... | Test agent's ability to recover from errors | test_error_recovery | python | browser-use/browser-use | tests/test_agent_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_agent_actions.py | MIT |
async def test_find_contact_email(llm, browser_session):
"""Test agent's ability to find contact email on a website"""
agent = Agent(
task='Go to https://browser-use.com/ and find out the contact email',
llm=llm,
browser_session=browser_session,
)
history: AgentHistoryList = await agent.run(max_steps=10)
#... | Test agent's ability to find contact email on a website | test_find_contact_email | python | browser-use/browser-use | tests/test_agent_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_agent_actions.py | MIT |
async def test_agent_finds_installation_command(llm, browser_session):
"""Test agent's ability to find the pip installation command for browser-use on the web"""
agent = Agent(
task='Find the pip installation command for the browser-use repo',
llm=llm,
browser_session=browser_session,
)
history: AgentHistory... | Test agent's ability to find the pip installation command for browser-use on the web | test_agent_finds_installation_command | python | browser-use/browser-use | tests/test_agent_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_agent_actions.py | MIT |
async def test_captcha_solver(llm, browser_session, captcha: CaptchaTest):
"""Test agent's ability to solve different types of captchas"""
agent = Agent(
task=f'Go to {captcha.url} and solve the captcha. {captcha.additional_text}',
llm=llm,
browser_session=browser_session,
)
from browser_use.agent.views impor... | Test agent's ability to solve different types of captchas | test_captcha_solver | python | browser-use/browser-use | tests/test_agent_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_agent_actions.py | MIT |
def http_server(self):
"""Create and provide a test HTTP server that serves static content."""
server = HTTPServer()
server.start()
# Add routes for common test pages
server.expect_request('/').respond_with_data(
'<html><head><title>Test Home Page</title></head><body><h1>Test Home Page</h1><p>Welcome to t... | Create and provide a test HTTP server that serves static content. | http_server | python | browser-use/browser-use | tests/test_core_functionality.py | https://github.com/browser-use/browser-use/blob/master/tests/test_core_functionality.py | MIT |
async def browser_session(self):
"""Create and provide a BrowserSession instance with security disabled."""
browser_session = BrowserSession(headless=True, user_data_dir=None)
yield browser_session
await browser_session.kill() | Create and provide a BrowserSession instance with security disabled. | browser_session | python | browser-use/browser-use | tests/test_core_functionality.py | https://github.com/browser-use/browser-use/blob/master/tests/test_core_functionality.py | MIT |
def llm(self):
"""Initialize language model for testing with minimal settings."""
return ChatOpenAI(
model='gpt-4o',
temperature=0.0,
) | Initialize language model for testing with minimal settings. | llm | python | browser-use/browser-use | tests/test_core_functionality.py | https://github.com/browser-use/browser-use/blob/master/tests/test_core_functionality.py | MIT |
async def test_search_google(self, llm, browser_session, base_url):
"""Test 'Search Google' action using a mock search page."""
agent = Agent(
task=f"Go to '{base_url}/search' and search for 'OpenAI'.",
llm=llm,
browser_session=browser_session,
)
history: AgentHistoryList = await agent.run(max_steps=3)... | Test 'Search Google' action using a mock search page. | test_search_google | python | browser-use/browser-use | tests/test_core_functionality.py | https://github.com/browser-use/browser-use/blob/master/tests/test_core_functionality.py | MIT |
async def test_scroll_down(self, llm, browser_session, base_url, http_server):
"""Test 'Scroll down' action and validate that the page actually scrolled."""
# Create a test page with scrollable content
http_server.expect_request('/scroll-test').respond_with_data(
"""
<html>
<head><title... | Test 'Scroll down' action and validate that the page actually scrolled. | test_scroll_down | python | browser-use/browser-use | tests/test_core_functionality.py | https://github.com/browser-use/browser-use/blob/master/tests/test_core_functionality.py | MIT |
async def test_dropdown(llm, browser_session):
"""Test selecting an option from a dropdown menu."""
agent = Agent(
task=(
'go to https://codepen.io/geheimschriftstift/pen/mPLvQz and first get all options for the dropdown and then select the 5th option'
),
llm=llm,
browser_session=browser_session,
)
try:... | Test selecting an option from a dropdown menu. | test_dropdown | python | browser-use/browser-use | tests/test_dropdown.py | https://github.com/browser-use/browser-use/blob/master/tests/test_dropdown.py | MIT |
async def test_dropdown_complex(llm, browser_session):
"""Test selecting an option from a complex dropdown menu."""
agent = Agent(
task=(
'go to https://codepen.io/shyam-king/pen/pvzpByJ and first get all options for the dropdown and then select the json option'
),
llm=llm,
browser_session=browser_session,... | Test selecting an option from a complex dropdown menu. | test_dropdown_complex | python | browser-use/browser-use | tests/test_dropdown_complex.py | https://github.com/browser-use/browser-use/blob/master/tests/test_dropdown_complex.py | MIT |
async def test_only_open_tab_allowed(llm, browser_session):
"""Test that only open_tab action is available while others are excluded"""
# Create list of all default actions except open_tab
excluded_actions = [
'search_google',
'go_to_url',
'go_back',
'click_element',
'input_text',
'switch_tab',
'extra... | Test that only open_tab action is available while others are excluded | test_only_open_tab_allowed | python | browser-use/browser-use | tests/test_excluded_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_excluded_actions.py | MIT |
async def browser_session():
"""Create a real browser session for testing."""
session = BrowserSession(
browser_profile=BrowserProfile(
executable_path=os.getenv('BROWSER_PATH'),
user_data_dir=None, # Use temporary profile
headless=True,
)
)
async with session:
yield session | Create a real browser session for testing. | browser_session | python | browser-use/browser-use | tests/test_google_sheets_real.py | https://github.com/browser-use/browser-use/blob/master/tests/test_google_sheets_real.py | MIT |
async def test_selector_map_basic(browser_session, controller):
"""Test that the selector map gets populated on a basic page."""
# Go to a simple page first
page = await browser_session.get_current_page()
await page.goto('https://www.google.com')
await page.wait_for_load_state()
# Update browser state to populat... | Test that the selector map gets populated on a basic page. | test_selector_map_basic | python | browser-use/browser-use | tests/test_google_sheets_real.py | https://github.com/browser-use/browser-use/blob/master/tests/test_google_sheets_real.py | MIT |
async def test_click_element_basic(browser_session, controller):
"""Test basic click element action to verify registry works."""
# Go to a simple page
page = await browser_session.get_current_page()
await page.goto('https://www.google.com')
await page.wait_for_load_state()
# Update browser state to populate sele... | Test basic click element action to verify registry works. | test_click_element_basic | python | browser-use/browser-use | tests/test_google_sheets_real.py | https://github.com/browser-use/browser-use/blob/master/tests/test_google_sheets_real.py | MIT |
async def test_google_sheets_open(browser_session, controller):
"""Test opening a Google Sheet using the existing action."""
# First check what actions are available
available_actions = list(controller.registry.registry.actions.keys())
# Google Sheets actions are registered with specific names
sheet_actions = [
... | Test opening a Google Sheet using the existing action. | test_google_sheets_open | python | browser-use/browser-use | tests/test_google_sheets_real.py | https://github.com/browser-use/browser-use/blob/master/tests/test_google_sheets_real.py | MIT |
async def test_list_all_actions(browser_session, controller):
"""Debug test to list all available actions."""
available_actions = list(controller.registry.registry.actions.keys())
print('All available actions:')
for action in sorted(available_actions):
print(f' - {action}')
# Just verify the controller has som... | Debug test to list all available actions. | test_list_all_actions | python | browser-use/browser-use | tests/test_google_sheets_real.py | https://github.com/browser-use/browser-use/blob/master/tests/test_google_sheets_real.py | MIT |
async def test_random_samples(test_cases: list[dict[str, Any]], llm, browser_session):
"""Test a random sampling of tasks across different websites"""
import random
logger.info('=== Testing Random Samples ===')
# Take random samples
samples = random.sample(test_cases, 1)
for i, case in enumerate(samples, 1):
... | Test a random sampling of tasks across different websites | test_random_samples | python | browser-use/browser-use | tests/test_mind2web.py | https://github.com/browser-use/browser-use/blob/master/tests/test_mind2web.py | MIT |
async def controller():
"""Initialize the controller with self-registered actions"""
controller = Controller()
# Define custom actions without Pydantic models
@controller.action('Print a message')
def print_message(message: str):
print(f'Message: {message}')
return f'Printed message: {message}'
@controller.... | Initialize the controller with self-registered actions | controller | python | browser-use/browser-use | tests/test_self_registered_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_self_registered_actions.py | MIT |
async def test_self_registered_actions_no_pydantic(llm, controller):
"""Test self-registered actions with individual arguments"""
agent = Agent(
task="First, print the message 'Hello, World!'. Then, add 10 and 20. Next, concatenate 'foo' and 'bar'.",
llm=llm,
controller=controller,
)
history: AgentHistoryList... | Test self-registered actions with individual arguments | test_self_registered_actions_no_pydantic | python | browser-use/browser-use | tests/test_self_registered_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_self_registered_actions.py | MIT |
async def test_mixed_arguments_actions(llm, controller):
"""Test actions with mixed argument types"""
# Define another action during the test
# Test for async actions
@controller.action('Calculate the area of a rectangle')
async def calculate_area(length: float, width: float):
area = length * width
return f'T... | Test actions with mixed argument types | test_mixed_arguments_actions | python | browser-use/browser-use | tests/test_self_registered_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_self_registered_actions.py | MIT |
async def test_pydantic_simple_model(llm, controller):
"""Test action with a simple Pydantic model argument"""
agent = Agent(
task="Process a simple model with name 'Alice' and age 30.",
llm=llm,
controller=controller,
)
history = await agent.run(max_steps=5)
# Check that the action was executed
action_nam... | Test action with a simple Pydantic model argument | test_pydantic_simple_model | python | browser-use/browser-use | tests/test_self_registered_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_self_registered_actions.py | MIT |
async def test_pydantic_nested_model(llm, controller):
"""Test action with a nested Pydantic model argument"""
agent = Agent(
task="Process a nested model with user name 'Bob', age 25, living at '123 Maple St', 'Springfield'.",
llm=llm,
controller=controller,
)
history = await agent.run(max_steps=5)
# Check... | Test action with a nested Pydantic model argument | test_pydantic_nested_model | python | browser-use/browser-use | tests/test_self_registered_actions.py | https://github.com/browser-use/browser-use/blob/master/tests/test_self_registered_actions.py | MIT |
def test_convert_initial_actions(self, mock_controller, mock_llm, mock_browser_session): # type: ignore
"""
Test that the _convert_initial_actions method correctly converts
dictionary-based actions to ActionModel instances.
This test ensures that:
1. The method processes the initial actions correctly.
2. ... |
Test that the _convert_initial_actions method correctly converts
dictionary-based actions to ActionModel instances.
This test ensures that:
1. The method processes the initial actions correctly.
2. The correct param_model is called with the right parameters.
3. The ActionModel is created with the validate... | test_convert_initial_actions | python | browser-use/browser-use | tests/test_service.py | https://github.com/browser-use/browser-use/blob/master/tests/test_service.py | MIT |
async def test_step_error_handling(self):
"""
Test the error handling in the step method of the Agent class.
This test simulates a failure in the get_next_action method and
checks if the error is properly handled and recorded.
"""
# Mock the LLM
mock_llm = MagicMock(spec=BaseChatModel)
# Mock the Messa... |
Test the error handling in the step method of the Agent class.
This test simulates a failure in the get_next_action method and
checks if the error is properly handled and recorded.
| test_step_error_handling | python | browser-use/browser-use | tests/test_service.py | https://github.com/browser-use/browser-use/blob/master/tests/test_service.py | MIT |
def test_action_decorator_with_excluded_action(self, registry_with_excludes):
"""
Test that the action decorator does not register an action
if it's in the exclude_actions list.
"""
# Define a function to be decorated
def excluded_action():
pass
# Apply the action decorator
decorated_func = registr... |
Test that the action decorator does not register an action
if it's in the exclude_actions list.
| test_action_decorator_with_excluded_action | python | browser-use/browser-use | tests/test_service.py | https://github.com/browser-use/browser-use/blob/master/tests/test_service.py | MIT |
async def test_execute_action_with_and_without_browser_context(self):
"""
Test that the execute_action method correctly handles actions with and without a browser context.
This test ensures that:
1. An action requiring a browser context is executed correctly.
2. An action not requiring a browser context is ex... |
Test that the execute_action method correctly handles actions with and without a browser context.
This test ensures that:
1. An action requiring a browser context is executed correctly.
2. An action not requiring a browser context is executed correctly.
3. The browser context is passed to the action function... | test_execute_action_with_and_without_browser_context | python | browser-use/browser-use | tests/test_service.py | https://github.com/browser-use/browser-use/blob/master/tests/test_service.py | MIT |
async def test_step_empty_action_retry(self, mock_llm, mock_controller, mock_browser_session, mock_action_model):
"""
Test that the step method retries and handles empty actions correctly.
"""
# Arrange
agent = Agent(
task='Test task',
llm=mock_llm,
controller=mock_controller,
browser_session=mock... |
Test that the step method retries and handles empty actions correctly.
| test_step_empty_action_retry | python | browser-use/browser-use | tests/test_service.py | https://github.com/browser-use/browser-use/blob/master/tests/test_service.py | MIT |
async def test_step_empty_action_retry_and_fail(self, mock_llm, mock_controller, mock_browser_session, mock_action_model):
"""
Test that the step method handles the case where get_next_action returns
empty actions twice, and inserts a safe noop action.
"""
# Arrange
agent = Agent(
task='Test task',
ll... |
Test that the step method handles the case where get_next_action returns
empty actions twice, and inserts a safe noop action.
| test_step_empty_action_retry_and_fail | python | browser-use/browser-use | tests/test_service.py | https://github.com/browser-use/browser-use/blob/master/tests/test_service.py | MIT |
async def test_token_limit_with_multiple_extractions(llm, controller, browser_session):
"""Test handling of multiple smaller extractions accumulating tokens"""
agent = Agent(
task='Call the magical function to get very special text 5 times',
llm=llm,
controller=controller,
browser_session=browser_session,
m... | Test handling of multiple smaller extractions accumulating tokens | test_token_limit_with_multiple_extractions | python | browser-use/browser-use | tests/test_stress.py | https://github.com/browser-use/browser-use/blob/master/tests/test_stress.py | MIT |
async def test_open_3_tabs_and_extract_content(llm, controller, browser_session, max_tokens):
"""Stress test: Open 3 tabs with urls and extract content"""
agent = Agent(
task='Open 3 tabs with https://en.wikipedia.org/wiki/Internet and extract the content from each.',
llm=llm,
controller=controller,
browser_s... | Stress test: Open 3 tabs with urls and extract content | test_open_3_tabs_and_extract_content | python | browser-use/browser-use | tests/test_stress.py | https://github.com/browser-use/browser-use/blob/master/tests/test_stress.py | MIT |
async def run_single_task(task_file):
"""Run a single task in the current process (called by subprocess)"""
try:
print(f'[DEBUG] Starting task: {os.path.basename(task_file)}', file=sys.stderr)
# Suppress all logging in subprocess to avoid interfering with JSON output
logging.getLogger().setLevel(logging.CRITIC... | Run a single task in the current process (called by subprocess) | run_single_task | python | browser-use/browser-use | tests/ci/evaluate_tasks.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/evaluate_tasks.py | MIT |
def create_mock_llm():
"""Create a mock LLM that returns a done action"""
mock = AsyncMock(spec=BaseChatModel)
mock._verified_api_keys = True
mock._verified_tool_calling_method = 'raw'
# Add model_name attribute for logging
mock.model_name = 'mock-llm'
# Create the response
response_content = """
{
"curren... | Create a mock LLM that returns a done action | create_mock_llm | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
def create_mock_llm_with_actions(action_sequence):
"""Factory to create mock LLMs with specific action sequences"""
mock = AsyncMock(spec=BaseChatModel)
mock._verified_api_keys = True
mock._verified_tool_calling_method = 'raw'
# Add model_name attribute for logging
mock.model_name = 'mock-llm'
action_index = 0... | Factory to create mock LLMs with specific action sequences | create_mock_llm_with_actions | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
def run_agent_in_subprocess_module(task_description):
"""Module-level function to run an agent in a subprocess"""
import asyncio
from unittest.mock import AsyncMock
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage
from browser_use import Agent
... | Module-level function to run an agent in a subprocess | run_agent_in_subprocess_module | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
async def test_one_event_loop_with_asyncio_run_and_one_task(self):
"""Test one event loop with asyncio.run and one task"""
logger.info('Testing one event loop with asyncio.run and one task')
# Create mock LLM
mock_llm = create_mock_llm()
# Just run directly in the current event loop
agent = Agent(
task... | Test one event loop with asyncio.run and one task | test_one_event_loop_with_asyncio_run_and_one_task | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
async def test_one_event_loop_two_parallel_agents(self):
"""Test one event loop with two different parallel agents"""
logger.info('Testing one event loop with two parallel agents')
# Create mock LLM
mock_llm = create_mock_llm()
# Create a shared browser session
browser_session = BrowserSession(
headles... | Test one event loop with two different parallel agents | test_one_event_loop_two_parallel_agents | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
async def test_one_event_loop_two_sequential_agents(self):
"""Test one event loop with two different sequential agents"""
logger.info('Testing one event loop with two sequential agents')
# Create mock LLM
mock_llm = create_mock_llm()
# Create a shared browser session
browser_session = BrowserSession(
h... | Test one event loop with two different sequential agents | test_one_event_loop_two_sequential_agents | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
async def test_two_event_loops_sequential(self):
"""Test two event loops, with one agent per loop sequential"""
logger.info('Testing two event loops with one agent per loop sequential')
# Create mock LLM
mock_llm = create_mock_llm()
# Just run agents sequentially in the same event loop
# This still tests ... | Test two event loops, with one agent per loop sequential | test_two_event_loops_sequential | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
async def test_two_event_loops_one_per_thread(self):
"""Test two event loops, one per thread, with one agent in each loop"""
logger.info('Testing two event loops, one per thread')
# Create mock LLM
mock_llm = create_mock_llm()
results = {}
errors = {}
def run_agent_in_thread(thread_name, task_descripti... | Test two event loops, one per thread, with one agent in each loop | test_two_event_loops_one_per_thread | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
def run_agent_in_thread(thread_name, task_description):
"""Run an agent in a new thread with its own event loop"""
try:
# Create new event loop for this thread
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def run_agent():
agent = Agent(
task=task_description,
... | Run an agent in a new thread with its own event loop | run_agent_in_thread | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
def test_two_subprocesses_one_agent_per_subprocess(self):
"""Test two subprocesses, with one agent per subprocess"""
logger.info('Testing two subprocesses with one agent per subprocess')
# Use multiprocessing to run agents in separate processes
with multiprocessing.Pool(processes=2) as pool:
tasks = ['Subpr... | Test two subprocesses, with one agent per subprocess | test_two_subprocesses_one_agent_per_subprocess | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
async def test_shared_browser_session_multiple_tabs(self):
"""Test multiple agents sharing same browser session with different tabs"""
logger.info('Testing shared browser session with multiple tabs')
# Create action sequences - each agent creates a new tab
tab_action = """
{
"current_state": {
"evalua... | Test multiple agents sharing same browser session with different tabs | test_shared_browser_session_multiple_tabs | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
async def test_reuse_browser_session_sequentially(self):
"""Test reusing a browser session sequentially with keep_alive"""
logger.info('Testing sequential browser session reuse')
# Create mock LLM
mock_llm = create_mock_llm()
# Create a session with keep_alive
session = BrowserSession(
headless=True,
... | Test reusing a browser session sequentially with keep_alive | test_reuse_browser_session_sequentially | python | browser-use/browser-use | tests/ci/test_agent_multiprocessing.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_multiprocessing.py | MIT |
def test_replace_sensitive_data_with_missing_keys(registry, caplog):
"""Test that _replace_sensitive_data handles missing keys gracefully"""
# Set log level to capture warnings
import logging
caplog.set_level(logging.WARNING)
# Create a simple Pydantic model with sensitive data placeholders
params = SensitivePa... | Test that _replace_sensitive_data handles missing keys gracefully | test_replace_sensitive_data_with_missing_keys | python | browser-use/browser-use | tests/ci/test_agent_sensitive_data.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_agent_sensitive_data.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.