Best Python code snippet using localstack_python
profile_commands.py
Source:profile_commands.py  
1import logging2import tarfile3from pathlib import Path4from selenium.webdriver import Firefox5from openwpm.config import BrowserParamsInternal, ManagerParamsInternal6from ..errors import ProfileLoadError7from ..socket_interface import ClientSocket8from .types import BaseCommand9from .utils.firefox_profile import sleep_until_sqlite_checkpoint10logger = logging.getLogger("openwpm")11def dump_profile(12    browser_profile_path: Path,13    tar_path: Path,14    compress: bool,15    browser_params: BrowserParamsInternal,16) -> None:17    """Dumps a browser profile to a tar file.18    Should only be called when the browser is closed, to prevent19    database corruption in the archived profile (see section 1.220    of https://www.sqlite.org/howtocorrupt.html).21    """22    assert browser_params.browser_id is not None23    # Creating the folders if need be24    tar_path.parent.mkdir(exist_ok=True, parents=True)25    # see if this file exists first26    # if it does, delete it before we try to save the current session27    if tar_path.exists():28        tar_path.unlink()29    # backup and tar profile30    if compress:31        tar = tarfile.open(tar_path, "w:gz", errorlevel=1)32    else:33        tar = tarfile.open(tar_path, "w", errorlevel=1)34    logger.debug(35        "BROWSER %i: Backing up full profile from %s to %s"36        % (browser_params.browser_id, browser_profile_path, tar_path)37    )38    tar.add(browser_profile_path, arcname="")39    archived_items = tar.getnames()40    tar.close()41    required_items = [42        "cookies.sqlite",  # cookies43        "places.sqlite",  # history44        "webappsstore.sqlite",  # localStorage45    ]46    for item in required_items:47        if item not in archived_items:48            logger.critical(49                "BROWSER %i: %s NOT FOUND IN profile folder"50                % (browser_params.browser_id, item)51            )52            raise RuntimeError("Profile dump not successful")53class DumpProfileCommand(BaseCommand):54    """55    Dumps a browser profile currently stored in <browser_params.profile_path> to56    <tar_path>.57    """58    def __init__(59        self, tar_path: Path, close_webdriver: bool, compress: bool = True60    ) -> None:61        self.tar_path = tar_path62        self.close_webdriver = close_webdriver63        self.compress = compress64    def __repr__(self) -> str:65        return "DumpProfileCommand({},{},{})".format(66            self.tar_path, self.close_webdriver, self.compress67        )68    def execute(69        self,70        webdriver: Firefox,71        browser_params: BrowserParamsInternal,72        manager_params: ManagerParamsInternal,73        extension_socket: ClientSocket,74    ) -> None:75        # if this is a dump on close, close the webdriver and wait for checkpoint76        if self.close_webdriver:77            webdriver.close()78            sleep_until_sqlite_checkpoint(browser_params.profile_path)79        assert browser_params.profile_path is not None80        dump_profile(81            browser_params.profile_path,82            self.tar_path,83            self.compress,84            browser_params,85        )86def load_profile(87    browser_profile_path: Path,88    browser_params: BrowserParamsInternal,89    tar_path: Path,90) -> None:91    """92    Loads a zipped cookie-based profile stored at <tar_path> and unzips93    it to <browser_profile_path>. The tar will remain unmodified.94    """95    assert browser_params.browser_id is not None96    try:97        assert tar_path.is_file()98        # Untar the loaded profile99        if tar_path.name.endswith("tar.gz"):100            f = tarfile.open(tar_path, "r:gz", errorlevel=1)101        else:102            f = tarfile.open(tar_path, "r", errorlevel=1)103        f.extractall(browser_profile_path)104        f.close()105        logger.debug("BROWSER %i: Tarfile extracted" % browser_params.browser_id)106    except Exception as ex:107        logger.critical(108            "BROWSER %i: Error: %s while attempting to load profile"109            % (browser_params.browser_id, str(ex))110        )...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
