Skip to content

Commit

Permalink
improve pytests
Browse files Browse the repository at this point in the history
  • Loading branch information
Svinokur committed Aug 13, 2024
1 parent be40c03 commit 38fc49a
Show file tree
Hide file tree
Showing 19 changed files with 100 additions and 218 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
[![Downloads](https://static.pepy.tech/badge/selenium-driver-updater)](https://pepy.tech/project/selenium-driver-updater)
[![Downloads](https://static.pepy.tech/badge/selenium-driver-updater/month)](https://pepy.tech/project/selenium-driver-updater)
[![Downloads](https://static.pepy.tech/badge/selenium-driver-updater/week)](https://pepy.tech/project/selenium-driver-updater)
[![Donate with Bitcoin](https://en.cryptobadges.io/badge/micro/32GJnnDrPkSKVzrRho84KwD5RsMW4ywMiW)](https://en.cryptobadges.io/donate/32GJnnDrPkSKVzrRho84KwD5RsMW4ywMiW)
[![Donate with Ethereum](https://en.cryptobadges.io/badge/micro/0xf2691CC12a70B4589edf081E059fD4A1c457417D)](https://en.cryptobadges.io/donate/0xf2691CC12a70B4589edf081E059fD4A1c457417D)

[![Windows](https://github.com/Svinokur/selenium_driver_updater/actions/workflows/windows-tests.yml/badge.svg)](https://github.com/Svinokur/selenium_driver_updater/actions/workflows/windows-tests.yml)
[![macOS](https://github.com/Svinokur/selenium_driver_updater/actions/workflows/macOS-tests.yml/badge.svg)](https://github.com/Svinokur/selenium_driver_updater/actions/workflows/macOS-tests.yml)
Expand Down
2 changes: 1 addition & 1 deletion selenium_driver_updater/_setting.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
'opera': r'reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall" /f Opera',
},
'Linux': {
'chrome': 'google-chrome-stable',
'chrome': ['google-chrome-stable'],
'firefox': 'firefox',
'opera': 'opera',
}
Expand Down
115 changes: 59 additions & 56 deletions selenium_driver_updater/browsers/_chromeBrowser.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,7 @@ def main(self) -> None:
self._compare_chrome_browser_versions()

def _compare_chrome_browser_versions(self):
"""Compares current version of chrome browser to latest version
Returns:
Tuple of bool, str and str
is_browser_up_to_date (bool) : It true the browser is up to date. Defaults to False.
current_version (str) : Current version of the browser.
latest_version (str) : Latest version of the browser.
"""
"""Compares current version of chrome browser to latest version"""
current_version : str = ''
latest_version : str = ''

Expand Down Expand Up @@ -108,55 +99,67 @@ def _get_current_version_chrome_browser_selenium(self) -> str:

return browser_version

def _get_current_version_chrome_browser_selenium_via_terminal(self) -> str:
"""Gets current chrome browser version via command in terminal
Returns:
str
browser_version (str) : Current chrome browser version.
"""
def _get_current_version_chrome_browser_selenium(self) -> str:
"""Gets current chrome browser version"""
browser_version = ''
try:
browser_version = self._get_current_version_chrome_browser_selenium_via_terminal()
if not browser_version:
logger.info('Trying to get current version of chrome browser via chromedriver')
if Path(self.chromedriver_path).exists() and not browser_version:
browser_version = self._get_version_via_chromedriver()
logger.info(f'Current version of chrome browser: {browser_version}')
except (WebDriverException, SessionNotCreatedException, OSError):
pass # [Errno 86] Bad CPU type in executable:
return browser_version

browser_version : str = ''
browser_version_terminal : str = ''
def _get_version_via_chromedriver(self) -> str:
"""Get Chrome version via chromedriver"""
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
with webdriver.Chrome(executable_path=self.chromedriver_path, options=chrome_options) as driver:
return str(driver.capabilities['browserVersion'])

def _get_current_version_chrome_browser_selenium_via_terminal(self) -> str:
"""Gets current chrome browser version via command in terminal"""
chromebrowser_path = self.setting["ChromeBrowser"]["Path"]
if chromebrowser_path:

logger.info('Trying to get current version of chrome browser via terminal')

if platform.system() == 'Windows':

for command in chromebrowser_path:

with subprocess.Popen(command, stdout=subprocess.PIPE) as process:
browser_version_terminal = process.communicate()[0].decode('UTF-8')

if 'invalid' not in browser_version_terminal.lower():
break

elif platform.system() == 'Linux':

with subprocess.Popen([chromebrowser_path, '--version'], stdout=subprocess.PIPE) as process:
browser_version_terminal = process.communicate()[0].decode('UTF-8')

elif platform.system() == 'Darwin':

for path in chromebrowser_path:

with subprocess.Popen([path, '--version'], stdout=subprocess.PIPE) as process:
browser_version_terminal = process.communicate()[0].decode('UTF-8')

if 'no such file or directory' not in browser_version_terminal.lower():
break


find_string = re.findall(self.setting["Program"]["wedriverVersionPattern"], browser_version_terminal)
browser_version = find_string[0] if len(find_string) > 0 else ''

return browser_version
if not chromebrowser_path:
return ''

logger.info('Trying to get current version of chrome browser via terminal')
browser_version_terminal = self._run_version_command(chromebrowser_path)

return self._extract_browser_version(browser_version_terminal)

def _run_version_command(self, chromebrowser_path: str) -> str:
"""Runs the command to get the browser version"""
if platform.system() == 'Windows':
return self._run_command_on_windows(chromebrowser_path)
elif platform.system() == 'Linux':
return self._run_command_on_unix(chromebrowser_path)
elif platform.system() == 'Darwin':
return self._run_command_on_unix(chromebrowser_path)
return ''

def _run_command_on_windows(self, chromebrowser_path: str) -> str:
"""Runs the command on Windows"""
for command in chromebrowser_path:
with subprocess.Popen(command, stdout=subprocess.PIPE) as process:
output = process.communicate()[0].decode('UTF-8')
if 'invalid' not in output.lower():
return output
return ''

def _run_command_on_unix(self, chromebrowser_path: str) -> str:
"""Runs the command on Unix-based systems"""
for path in chromebrowser_path:
with subprocess.Popen([path, '--version'], stdout=subprocess.PIPE) as process:
return process.communicate()[0].decode('UTF-8')

def _extract_browser_version(self, browser_version_terminal: str) -> str:
"""Extracts the browser version from terminal output"""
find_string = re.findall(self.setting["Program"]["wedriverVersionPattern"], browser_version_terminal)
return find_string[0] if find_string else ''

def _get_latest_version_chrome_browser(self, no_messages : bool = False) -> str:
"""Gets latest chrome browser version
Expand Down
11 changes: 1 addition & 10 deletions selenium_driver_updater/browsers/_edgeBrowser.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,7 @@ def _get_latest_version_edge_browser(self) -> str:
return latest_version

def _compare_edge_browser_versions(self):
"""Compares current version of edge browser to latest version
Returns:
Tuple of bool, str and str
is_browser_up_to_date (bool) : It true the browser is up to date. Defaults to False.
current_version (str) : Current version of the browser.
latest_version (str) : Latest version of the browser.
"""
"""Compares current version of edge browser to latest version"""

current_version : str = ''
latest_version : str = ''
Expand Down
14 changes: 1 addition & 13 deletions selenium_driver_updater/browsers/_firefoxBrowser.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,19 +112,7 @@ def _get_latest_version_firefox_browser(self) -> str:


def _compare_firefox_browser_versions(self):
"""Compares current version of firefox browser to latest version
Returns:
Tuple of bool, str and str
is_browser_up_to_date (bool) : It true the browser is up to date. Defaults to False.
current_version (str) : Current version of the browser.
latest_version (str) : Latest version of the browser.
Raises:
Except: If unexpected error raised.
"""
"""Compares current version of firefox browser to latest version"""
current_version : str = ''
latest_version : str = ''

Expand Down
14 changes: 1 addition & 13 deletions selenium_driver_updater/browsers/_operaBrowser.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,19 +127,7 @@ def _get_latest_version_opera_browser(self) -> str:
return latest_version

def _compare_opera_browser_versions(self):
"""Compares current version of opera browser to latest version
Returns:
Tuple of bool, str and str
is_browser_up_to_date (bool) : It true the browser is up to date. Defaults to False.
current_version (str) : Current version of the browser.
latest_version (str) : Latest version of the browser.
Raises:
Except: If unexpected error raised.
"""
"""Compares current version of opera browser to latest version"""

current_version : str = ''
latest_version : str = ''
Expand Down
Binary file not shown.
4 changes: 2 additions & 2 deletions selenium_driver_updater/test/chrome_browser_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ def test_get_latest_version_chrome_browser(chrome_browser_setup, ):
assert latest_version is not None
assert len(latest_version) > 0

def test_compare_current_version_and_latest_version_chrome_browser(chrome_browser_setup, ):
def test_compare_chrome_browser_versions(chrome_browser_setup, ):
"""Test to compare the current version and latest version of Chrome browser."""
chrome_browser_setup._compare_current_version_and_latest_version_chrome_browser()
chrome_browser_setup._compare_chrome_browser_versions()

def test_chromedriver_is_up_to_date(chrome_browser_setup, ):
"""Test to check if ChromeDriver is up to date."""
Expand Down
8 changes: 3 additions & 5 deletions selenium_driver_updater/test/chrome_driver_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,7 @@ def test_download_driver_failure(chrome_driver_setup):
"""Test downloading driver with failure."""
_, chrome_driver_failure = chrome_driver_setup
with pytest.raises(DriverVersionInvalidException):
file_name = chrome_driver_failure._download_driver(version='blablablanotversion')
assert len(file_name) == 0
chrome_driver_failure._download_driver(version='blablablanotversion')

def test_compare_current_version_and_latest_version_failure(chrome_driver_setup):
"""Test comparing current and latest versions with failure."""
Expand All @@ -74,8 +73,7 @@ def test_chromedriver_is_up_to_date_failure(chrome_driver_setup):
"""Test if ChromeDriver is up to date with failure."""
_, chrome_driver_failure = chrome_driver_setup
with pytest.raises(DriverVersionInvalidException):
filename = chrome_driver_failure.main()
assert len(filename) == 0
chrome_driver_failure.main()

def test_if_version_is_valid_failure(chrome_driver_setup):
"""Test if a specific version is valid with failure."""
Expand All @@ -85,7 +83,7 @@ def test_if_version_is_valid_failure(chrome_driver_setup):

def test_get_result_by_request(chrome_driver_setup):
"""Test getting the result by request."""
chrome_driver, _ = chrome_driver_setup
_, _ = chrome_driver_setup
url = str(setting["ChromeDriver"]["LinkLastRelease"])
json_data = RequestsGetter.get_result_by_request(url=url)
assert len(json_data) > 0
Expand Down
4 changes: 2 additions & 2 deletions selenium_driver_updater/test/edge_browser_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ def test_get_latest_version_edge_browser(edge_browser_setup, ):
assert latest_version is not None
assert len(latest_version) > 0

def test_compare_current_version_and_latest_version_edge_browser(edge_browser_setup, ):
def test_compare_edge_browser_versions(edge_browser_setup, ):
"""Test to compare the current version and latest version of Edge browser."""
edge_browser_setup._compare_current_version_and_latest_version_edge_browser()
edge_browser_setup._compare_edge_browser_versions()

def test_if_edgebrowser_is_up_to_date(edge_browser_setup, ):
"""Test to check if Edge browser is up to date."""
Expand Down
10 changes: 3 additions & 7 deletions selenium_driver_updater/test/edge_driver_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,13 @@ def test_check_download_driver_failure(setup_edgedriver):
def test_compare_current_version_and_latest_version_failure(setup_edgedriver):
_, edgedriver_failure, _ = setup_edgedriver
with pytest.raises(DriverVersionInvalidException):
is_driver_up_to_date, current_version, latest_version = edgedriver_failure._compare_current_version_and_latest_version()
assert not is_driver_is_up_to_date
assert len(current_version) == 0
assert len(latest_version) == 0
edgedriver_failure._compare_current_version_and_latest_version()


def test_check_if_edgedriver_is_up_to_date_failure(setup_edgedriver):
_, edgedriver_failure, _ = setup_edgedriver
with pytest.raises(DriverVersionInvalidException):
filename = edgedriver_failure.main()
assert len(filename) == 0
edgedriver_failure.main()


def test_check_if_version_is_valid_failure(setup_edgedriver):
Expand All @@ -79,7 +75,7 @@ def test_check_get_result_by_request(setup_edgedriver):
_, _, setting_local = setup_edgedriver
url = str(setting_local["EdgeDriver"]["LinkLastRelease"])
json_data = RequestsGetter.get_result_by_request(url=url)
assert len(json_data) >= 0
assert len(json_data) > 0


def test_check_download_driver_specific_version(setup_edgedriver):
Expand Down
40 changes: 7 additions & 33 deletions selenium_driver_updater/test/extractor_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@
import pytest
import time
from pathlib import Path
import shutil
import zipfile
import tarfile
from selenium_driver_updater.util.extractor import Extractor

base_dir = os.path.dirname(os.path.abspath(__file__))

GECKODRIVER_EXE = 'geckodriver.exe'

@pytest.fixture(scope="module")
def setup_paths():
out_path = os.path.join(base_dir, 'archive')
out_path = os.path.join(base_dir, 'archive') + os.path.sep
zip_archive_path = os.path.join(out_path, 'geckodriver-v0.29.0-win64.zip')
tar_archive_path = os.path.join(out_path, 'geckodriver-v0.29.1-macos-aarch64.tar.gz')
tar_xz_archive_path = os.path.join(out_path, 'Opera_78.0.4093.112_Autoupdate_arm64.tar.xz')
Expand Down Expand Up @@ -44,7 +43,7 @@ def test_extract_all_zip_archive_with_specific_name_failure(setup_paths):
archive_path="invalid_path.zip",
out_path=setup_paths["out_path"],
delete_archive=False,
filename='geckodriver.exe',
filename=GECKODRIVER_EXE,
filename_replace='geckodriverzip'
)

Expand All @@ -58,21 +57,14 @@ def test_extract_all_tar_archive_with_specific_name_failure(setup_paths):
filename_replace='geckodrivertar'
)

def test_extract_all_tar_xz_archive_failure(setup_paths):
with pytest.raises(FileNotFoundError):
Extractor.extract_all_tar_xz_archive(
archive_path="invalid_path.tar.xz",
out_path=setup_paths["out_path"]
)

def test_extract_all_zip_archive(setup_paths):
Extractor.extract_all_zip_archive(
archive_path=setup_paths["zip_archive_path"],
out_path=setup_paths["out_path"],
delete_archive=False
)

geckodriver_path = os.path.join(setup_paths["out_path"], 'geckodriver.exe')
geckodriver_path = os.path.join(setup_paths["out_path"], GECKODRIVER_EXE)
assert Path(geckodriver_path).exists()
Path(geckodriver_path).unlink()
assert not Path(geckodriver_path).exists()
Expand All @@ -90,15 +82,12 @@ def test_extract_all_tar_gz_archive(setup_paths):
assert not Path(geckodriver_path).exists()

def test_extract_all_zip_archive_with_specific_name(setup_paths):
# Проверка содержимого архива перед извлечением
with zipfile.ZipFile(setup_paths["zip_archive_path"], 'r') as zip_ref:
print("Contents of the zip archive:", zip_ref.namelist())

Extractor.extract_all_zip_archive_with_specific_name(
archive_path=setup_paths["zip_archive_path"],
out_path=setup_paths["out_path"],
delete_archive=False,
filename='geckodriver.exe',
filename=GECKODRIVER_EXE,
filename_replace='geckodriverzip'
)

Expand All @@ -109,9 +98,6 @@ def test_extract_all_zip_archive_with_specific_name(setup_paths):
assert not Path(geckodriver_path).exists()

def test_extract_all_tar_archive_with_specific_name(setup_paths):
# Проверка содержимого архива перед извлечением
with tarfile.open(setup_paths["tar_archive_path"], 'r') as tar_ref:
print("Contents of the tar archive:", tar_ref.getnames())

Extractor.extract_all_zip_archive_with_specific_name(
archive_path=setup_paths["tar_archive_path"],
Expand All @@ -125,16 +111,4 @@ def test_extract_all_tar_archive_with_specific_name(setup_paths):
print(f"Checking existence of {geckodriver_path}")
assert Path(geckodriver_path).exists(), f"Expected file not found: {geckodriver_path}"
Path(geckodriver_path).unlink()
assert not Path(geckodriver_path).exists()

def test_extract_all_tar_xz_archive(setup_paths):
Extractor.extract_all_tar_xz_archive(
archive_path=setup_paths["tar_xz_archive_path"],
out_path=setup_paths["out_path"],
delete_archive=False
)

opera_path = os.path.join(setup_paths["out_path"], 'Opera.app')
assert Path(opera_path).exists()
shutil.rmtree(opera_path)
assert not Path(opera_path).exists()
assert not Path(geckodriver_path).exists()
Loading

0 comments on commit 38fc49a

Please sign in to comment.