繁体   English   中英

无法运行 selenium pytest 测试与 webdriver-manager 使用 docker 容器与 Z23EEEB37947BDD25BDDZ6:

[英]Unable to run the selenium pytest tests with webdriver-manager using the docker container with python:3.9-alpine image

I'm trying to run the test_home_page_title.py selenium pytest test on the docker container created with the python:3.9-alpine image. 我使用webdriver-manager来获取所需的驱动程序。 但我收到以下错误。

你能帮忙吗?

(venv) C:\PycharmProjects\pomproject>docker run -ti pomproject:1.0 /bin/sh
/pomproject # py.test -s -v --capture=tee-sys tests/test_home_page_title.py
=================================================================== test session starts ===================================================================
platform linux -- Python 3.9.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- /usr/local/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.9.5', 'Platform': 'Linux-4.19.128-microsoft-standard-x86_64-with', 'Packages': {'pytest': '6.2.4', 'py': '1.10.0', 'pluggy': '0.13.
1'}, 'Plugins': {'forked': '1.3.0', 'metadata': '1.11.0', 'allure-pytest': '2.9.43', 'xdist': '2.2.1', 'order': '1.0.0', 'rerunfailures': '10.0', 'Faker':
'8.7.0', 'html': '3.1.1', 'failed-screenshot': '1.0.2', 'instafail': '0.4.2'}}
rootdir: /pomproject
plugins: forked-1.3.0, metadata-1.11.0, allure-pytest-2.9.43, xdist-2.2.1, order-1.0.0, rerunfailures-10.0, Faker-8.7.0, html-3.1.1, failed-screenshot-1.0.
2, instafail-0.4.2
collected 1 item

tests/test_home_page_title.py::TestHomePageTitle::test_login_page_title ----------Driver - Setup----------


====== WebDriver manager ======
/bin/sh: google-chrome: not found
/bin/sh: google-chrome-stable: not found
ERROR                                                                       [100%]----------Write output data sheet.----------


========================================================================= ERRORS ==========================================================================
________________________________________________ ERROR at setup of TestHomePageTitle.test_login_page_title ________________________________________________

request = <SubRequest 'driver_setup' for <Function test_login_page_title>>

    @pytest.fixture(scope="module")
    def driver_setup(request):
        global driver
        print('-' * 10 + 'Driver - Setup' + '-' * 10)
        browser_name = request.config.getoption("browser_name")
        browser_name = browser_name.upper()
        if browser_name == "CHROME":
>           driver = webdriver.Chrome(ChromeDriverManager().install())

tests/conftest.py:24:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/local/lib/python3.9/site-packages/webdriver_manager/chrome.py:25: in __init__
    self.driver = ChromeDriver(name=name,
/usr/local/lib/python3.9/site-packages/webdriver_manager/driver.py:57: in __init__
    self.browser_version = chrome_version(chrome_type)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

browser_type = 'google-chrome'

    def chrome_version(browser_type=ChromeType.GOOGLE):
        pattern = r'\d+\.\d+\.\d+'

        cmd_mapping = {
            ChromeType.GOOGLE: {
                OSType.LINUX: linux_browser_apps_to_cmd('google-chrome', 'google-chrome-stable'),
                OSType.MAC: r'/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version',
                OSType.WIN: r'reg query "HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon" /v version'
            },
            ChromeType.CHROMIUM: {
                OSType.LINUX: linux_browser_apps_to_cmd('chromium', 'chromium-browser'),
                OSType.MAC: r'/Applications/Chromium.app/Contents/MacOS/Chromium --version',
                OSType.WIN: r'reg query "HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome" /v version'
            },
            ChromeType.MSEDGE: {
                OSType.MAC: r'/Applications/Microsoft\ Edge.app/Contents/MacOS/Microsoft\ Edge --version',
                OSType.WIN: r'reg query "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Edge\BLBeacon" /v version',
            }
        }

        cmd = cmd_mapping[browser_type][os_name()]
        version = None
        with os.popen(cmd) as stream:
            stdout = stream.read()
            version = re.search(pattern, stdout)

        if not version:
>           raise ValueError(f'Could not get version for Chrome with this command: {cmd}')
E           ValueError: Could not get version for Chrome with this command: google-chrome --version || google-chrome-stable --version

/usr/local/lib/python3.9/site-packages/webdriver_manager/utils.py:155: ValueError
------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------
----------Driver - Setup----------
------------------------------------------------------------------ Captured stderr setup ------------------------------------------------------------------


====== WebDriver manager ======
------------------------------------------------------------------- Captured log setup --------------------------------------------------------------------
INFO     WDM:logger.py:22

INFO     WDM:logger.py:12 ====== WebDriver manager ======
================================================================= short test summary info =================================================================
ERROR tests/test_home_page_title.py::TestHomePageTitle::test_login_page_title - ValueError: Could not get version for Chrome with this command: google-c...
==================================================================== 1 error in 0.50s =====================================================================

Dockerfile:

FROM python:3.9-alpine
RUN mkdir /pomproject/
ADD . /pomproject/
WORKDIR /pomproject/
RUN pip install --upgrade pip
RUN pip install -r requirements.txt

要求.txt

selenium
python-dotenv
pytest
pytest-html
pytest-xdist
openpyxl
webdriver-manager
xlrd
pytest-rerunfailures
pytest-instafail
pytest-failed-screenshot
PyYAML
xlsxwriter
Faker
pytest-order

test_home_page_title.py

from pages.login_page import LoginPage
from lib.commonfunctions import CommonFunctions
import settings as s
from utilities.custom_logger import Logger
from utilities.loaders import load_xlsx


class TestHomePageTitle(Logger):

    def test_login_page_title(self, driver_setup, tests_setup):
        log = self.get_logger()
        self.data = tests_setup
        test_data = [x for x in self.data['test_home_page_title'] if x['Run?'] == 'Y']

        for i in range(len(test_data)):

            self.driver = driver_setup

            # Libraries needed
            commonfunctions = CommonFunctions(self.driver, test_data, i)

            # Pages needed
            loginpage = LoginPage(self.driver)

            log.info("Launching application url.")
            self.driver.get(s.qa_baseurl)
            log.info("Launching of application url successful.")

            actual_title = self.driver.title
            expected_title = 'Your store. Login'

            if actual_title == expected_title:
                log.info("'Home Page Title' test passed.")
                assert True
            else:
                log.info("'Home Page Title' failed.")
                assert False

conftest.py

from selenium import webdriver
import pytest
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from utilities.loaders import load_xlsx, write_data_dic_to_file


# This section of coded is added to provide browser name from command line as parameter
# while executing the pytest tests
def pytest_addoption(parser):
    parser.addoption(
        "--browser_name", action="store", default="chrome"
    )


@pytest.fixture(scope="module")
def driver_setup(request):
    global driver
    print('-' * 10 + 'Driver - Setup' + '-' * 10)
    browser_name = request.config.getoption("browser_name")
    browser_name = browser_name.upper()
    if browser_name == "CHROME":
        driver = webdriver.Chrome(ChromeDriverManager().install())
    elif browser_name == "FIREFOX":
        driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
    elif browser_name == "EDGE":
        driver = webdriver.Edge(EdgeChromiumDriverManager().install())
    driver.maximize_window()
    yield driver
    print('-' * 10 + 'Driver - Tear Down' + '-' * 10)
    driver.close()
    driver.quit()


@pytest.fixture(scope="class")
def setup_demo():
    print("I will be executing first.")
    yield
    print("I will be executed last")


@pytest.fixture()
def data_load():
    print("User profile data being created.")
    return ["Vishva", "Thimmeogwda", "vishruth.cse@gmail.com"]


@pytest.fixture(params=[("Chrome", "Vishva", "Thimmegowda"), ("Firefox", "Vishva"), ("Edge", "JT")])
def crossbrowser(request):
    return request.param


# This section of the code runs after all the tests run
@pytest.fixture(scope='session', autouse=True)
def tests_setup():
    driver = None
    data = load_xlsx("./data/nopcommerce_test_data.xlsx")
    yield data
    print('-' * 10 + "Write output data sheet." + '-' * 10)
    write_data_dic_to_file(data)
    # To make sure all the opened web browser instances are closed properly
    if driver is not None:
        driver.quit()

您已经在 python 中安装了所需的一切,但您的 Docker 映像上仍然没有 chrome。 您需要在系统上安装 chrome + chrome-driver。

也许这个问题可以帮助你在 alpine https://stackoverflow.com/a/59814060/13441649上安装 chrome + chrome-driver

您的错误准确地显示了它:

/bin/sh: google-chrome: not found
/bin/sh: google-chrome-stable: not found

它表明在 PATH 中找不到两个可执行文件

我认为使用 webdriver-manager 意味着我不再需要安装驱动程序,但情况似乎并非如此,至少在 docker 容器上运行 Selenium 时。 我设法通过将此行添加到我的 Dockerfile 来修复此错误(我使用的是官方 python 基本映像):

RUN apt-get update && apt-get install firefox-esr -y

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM