[py]: Open chromium extension files inside context managers for auto closing
import base64
import os
import warnings
-from typing import List, Union
+from typing import List, Union, BinaryIO
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.options import ArgOptions
@@ -74,15 +74,17 @@ class ChromiumOptions(ArgOptions):
"""
:Returns: A list of encoded extensions that will be loaded
"""
- encoded_extensions = []
- for ext in self._extension_files:
- file_ = open(ext, 'rb')
+ def _decode(file_data: BinaryIO) -> str:
# Should not use base64.encodestring() which inserts newlines every
# 76 characters (per RFC 1521). Chromedriver has to remove those
# unnecessary newlines before decoding, causing performance hit.
- encoded_extensions.append(base64.b64encode(file_.read()).decode('UTF-8'))
+ return base64.b64encode(file_data.read()).decode("utf-8")
+
+ encoded_extensions = []
+ for extension in self._extension_files:
+ with open(extension, "rb") as f:
+ encoded_extensions.append(_decode(f))
- file_.close()
return encoded_extensions + self._extensions
def add_extension(self, extension: str) -> None:
