Selenium ��� mac os

Selenium: для любителей яблок

Привет! Это моя новая статья, посвященная Selenium. Ранее я уже подробно рассказал об организации масштабируемого кластера Selenium (часть I, часть II). Затем мы рассмотрели вопрос использования Selenium в качестве инструмента отладки автотестов (раз, два), Наконец, нам удалось создать порядок из хаоса на Windows (ссылка). Сегодня мы будем иметь дело с яблоками, точнее с одним большим Яблоком (т.е. с Apple).

Хотя Selenium является относительно простым инструментом, жизнь усложняется, когда мы пытаемся запускать автоматические тесты в браузерах из Купертино: Safari под MacOS и мобильный Safari под iOS. Чтобы полностью разобраться с браузерами для настольных операционных систем, давайте сегодня поговорим о Safari под MacOS. Сегодня свежие версии Safari разрабатываются только под MacOS. Исторически работа с Safari была реализована в Selenium при помощи браузерного расширения, которое транслировало команды Selenium во внутренние команды браузера. Изначально расширение загружалось в Safari автоматически. Позже из-за изменения правил безопасности в Safari нужно было установить расширение один раз вручную. Наконец, с выходом Safari X все значительно поменялось. Теперь Safari использует отдельно стоящий процесс веб-драйвера — safaridriver , аналогично chromedriver у Chrome и geckodriver у Firefox. Чтобы запустить тесты в Safari нужно:

Запустить safaridriver (обычно устанавливаемый вместе с Safari и расположенный в /usr/bin/safaridriver ) на свободном порту, например, 4444. Команда для запуска будет такая:

Запустить тесты, используя следующий Selenium URL:

  • Остановить запущенный процесс драйвера.
  • Звучит легко, не правда ли? И так оно и есть! Тем не менее есть проблема — safaridriver умеет работать только с одной копией Safari параллельно. Как преодолеть это ограничение? — Запустить драйвер несколько раз на разных портах и запустить тесты на разных URL с этими портами. Просто, но требует много ручной работы. Давайте автоматизируем этот процесс! Как это могло бы работать? А вот как:

    1. Вы запускаете сервер, предоставляющий Selenium API и указываете ему при старте, где расположен safaridriver .
    2. Когда приходит запрос на новую сессию — запущенный сервер ищет свободный порт и занимает его. Затем он запускает процесс safaridriver на этом порту и проксирует все последующие запросы туда же.
    3. Когда поступает запрос на закрытие сессии — процесс safaridriver также останавливается.

    Описанный алгоритм очень прост, поэтому он не должен требовать разработки сложного сервера, не так ли? Если вы возьмете в качестве сервера сегодняший стандарт — Selenium сервер, то будете использовать чересчур сложный инструмент для такой просто задачи. Почему это так:

    1. Selenium server — огромный как слон! Размер дистрибутива начинается от 20 Мб.
    2. Он требует установки Java — еще одного гигантского существа в ваш зоопарк. Со всякими всплывающими окнами об обновлении и графическим интерфейсом из 90-х.
    3. Он всегда голоден и ест память без причины.
    4. Он довольно плохо документирован и не работает из коробки. Нужно быть волшебником, чтобы заставить его заработать.

    Короче говоря, позвольте мне показать вам более подходящий инструмент — Selenoid. Selenoid — это легковесный демон, созданный полностью заменить тучный Selenium сервер. Завести Selenoid с Safari очень просто:

    Читайте также:  Thief ��� mac os

    Скопировать кусочек JSON, приведенный ниже, в файл (например, в

    Запустить и скачать исполняемый файл Selenoid:

    Запустить тесты, используя URL:

    Больше не нужно устанавливать Java и компанию! Но если вы, как я, не хотите делать руками и это, то можете получить аналогичный результат, используя однострочный скрипт:

    При желании вы также можете скачать и запустить легковесный UI для Selenoid. Подробнее об этом можно почитать в документации.

    Простое Selenium тестирование в Safari никогда не было так близко. Хорошего дня!

    Источник

    How To Run Test On macOS Using Selenium Safari Driver

    108568 Views | 12 Min Read

    We all know that Google Chrome is the most popular browser in the world. But do you know, with 17.24% of the overall browser market share, Safari is the second most popular one?

    The reason behind Safari’s strong presence is that it is the default web browser for all Apple devices. And we know how much developers and coders love macOS, making it absolutely necessary to ensure that our websites’ are tested and optimized for all Safari versions.

    The latest versions of Safari (10 and above) come with safaridriver, an in-built option to carry out websites’ debugging. However, the earlier versions of Safari required you to install the Safari WebDriver extension, which is no longer supported in the latest versions. Safari browser instead uses the safaridriver to implement WebDriver protocol.

    In this blog, we will see how to use Selenium safaridriver to perform testing on the Safari browser.

    Note: You need to have Safari on the Mac machine, as Apple has withdrawn the support of SafariDriver from Safari browsers on Windows.

    TABLE OF CONTENT

    Selenium Safari Driver For Automation Testing

    To use the Selenium framework for automation testing, you should have a corresponding Selenium WebDriver (e.g., Chrome WebDriver for Chrome, Geckodriver for Firefox, etc.) installed on the machine. However, in Selenium automation testing with Safari on macOS, there is no need to download Safari driver for Selenium WebDriver separately.

    Starting from Safari 10 on OS X El Capitan and macOS Sierra, the browser provides native support for the Selenium WebDriver API. As Selenium Safari driver for mac is preloaded on the OS, you need not mention the executable path for creating the Selenium WebDriver object.

    Download Safari Driver for Selenium WebDriver

    As already discussed, we don’t have to download Safari’s driver for Selenium WebDriver. Instead, Safari’s in-built driver called safaridriver is presently available in most Selenium client libraries. The safaridriver is maintained by the web developer experience team at Apple. Apple’s safaridriver executable path is /usr/bin/safaridriver. As Safari Technology Preview also provides its own executable safaridriver, it is a path of the application’s bundled contents.

    The safaridriver from Safari and safaridriver from Safari Technology Preview can run simultaneously, as each safaridriver only launches the Safari browser it is associated with.

    The legacy SafariDriver which was maintained by the Selenium project, is deprecated and should not be used. In any case, Safari throws the error ‘Safari no longer supports unsafe extensions’ if you even attempt to install the deprecated Selenium WebDriver for Safari.

    For using the Selenium safaridriver for automation testing, you only require Safari 10 (or later) installed on the machine since there is native support for Selenium WebDriver API in those Safari versions.

    Starting from Selenium 3.0.0 release, Python and Java Client libraries offer support for native driver implementation of Safari.

    Читайте также:  Служба hamachi не удалось запустить дочернюю службу windows

    Configure Safari for enabling WebDriver Support

    Even though native support for the Selenium WebDriver API is available in Safari 10 (and above), the WebDriver support is turned off by default. Follow the below-mentioned steps for enabling WebDriver support in Safari:

    macOS High Sierra (and later)

    Step 1: Run the following command on the terminal:

    Note: You may need to do so in case you are upgrading from a previous macOS release.

    macOS Sierra (and earlier)

    Step 1: Enable the ‘Show Developer’ menu in Safari through Safari ?Preferences ? Advanced ? Select ‘Show Develop menu in menu bar’ (if it is not checked).

    Step 2: Choose Develop > Allow Remote Automation.

    Step 3: Now, authorize safaridriver to launch the XPC service that hosts the local webserver. For this, run /usr/bin/safaridriver once and follow the authentication prompt.

    As we would be using Apple’s safaridriver for Selenium test automation on macOS Catalina, we would be only executing /usr/bin/safaridriver –enable (or safaridriver –enable) once on the terminal.

    Salient Features Of Selenium Safari Driver On macOS

    For supporting WebDriver without sacrificing user’s privacy and security, there are additional safeguards that ensure that Selenium test execution is completely isolated from normal browsing data and other test runs.

    Here are some of the salient features of Selenium Safari driver on macOS:

    Feature #1: Isolated Automation Windows

    The safaridriver developed by Apple’s web developer experienced team ensures that the test execution and Selenium test automation scenarios are confined to special automation windows. This means that the tests being executed using the safari driver will be isolated from normal browsing windows, user settings, and preferences.

    Like automation testing performed using geckodriver (for Firefox), Safari windows on which tests are being executed can be identified by their orange Smart Search field.

    Like a private browsing session in Safari, automation tests using Apple’s safaridriver start afresh so that the previous test session’s persistent state does not have any implications on the newly fired Selenium test automation scenario.

    Feature #2: Web Inspector

    Web Inspector (or Inspect) tool can be used during and after the Selenium WebDriver test’s execution. Features such as locating details about web elements, monitoring network performance, recording performance, etc., in Web Inspector are completely functional when Selenium test automation scenarios are being executed.

    The option Develop > Show Web Inspector menu item launches the inspection tool when the Selenium WebDriver tests are running.

    Feature #3: Selenium WebDriver commands for debugging

    Selenium Safari driver on macOS lets you specify WebDriver capabilities in a New Session for debugging.

    The safaridriver preloads Web Inspector and JavaScript debugger in the background when the Safari:automaticInspection capability is passed in a New Session request. Like the Inspect tool, you also have the option to pause the test execution for checking the execution details in the Debugger tab of Web Inspector.

    The safaridriver preloads Web Inspector and starts timeline recording in the background when the Safari:automaticProfiling capability is passed in a New Session request. The details can be viewed in the Timeline tab of the Web Inspector.

    Feature #4: Glass Pane

    A Glass Pane is installed over the Safari window, where the execution of the automation test is in progress. The glass pane intends to block any interactions such as a mouse, keyboard, resizing, closing, minimizing, etc., that can be performed manually and can hinder the test being performed in the Automation Window.

    Читайте также:  Metro exodus linux vulkan

    However, there is a way to break the glass pane if the test in progress is stuck (or failed) or you want to check something in the automation window manually. Once the glass pane is broken, the Selenium test automation session is interrupted, and the automation window continues to remain open for further inspection until it is closed manually.

    Shown below is the popup window which comes up when we try to break the WebDriver Session:

    • Turn off All Automation – This option will disable ‘Develop > Allow Remote Automation,’ enabled for using Selenium Safari driver in macOS for running automation tests.
      The command safaridriver –enable has to be rerun on the terminal if you want to run tests in the Safari browser.
    • Stop Session – This option stops the current WebDriver session, and you can continue to interact with the browser.
    • Continue Session – This option continues the session, i.e., the test is run from the point where it was paused. Once this option is selected, you would not be able to interact with the browser.

    Feature #5: Only one session at a time

    At a time, you can only attach one WebDriver session to the instance of the Safari browser. Hence, only one Safari instance and WebDriver session attached to it can be active during automation testing.

    As per Apple’s official blog, these constraints prevent the tests from internally competing with each other for resources like window focus, keyboard events, keyboard focus, and more. It also reflects what you can do in a macOS, windowing environment.

    RUN YOUR TEST ON macOS USING SELENIUM

    2000+ Browsers AND OS

    Testing With Selenium Safari Driver On macOS

    Now that we have set up Apple’s Safari driver, we look at the process of setting up Selenium WebDriver on macOS and running a test in Python. Selenium locators should be used to locate the element on which you intend to perform the required operation. When a test scenario calls a Selenium command , the command is executed in the following manner:

    1. Every Selenium command is translated into a REST API command by the client library.
    2. The REST API command sends the HTTP request to the local web server that is hosted by Apple’s safaridriver.
    3. The safaridriver validates the HTTP request contents, and the command is forwarded to the browser instance.
    4. Once the command execution is complete, the safaridriver sends an HTTP response, which the client library interprets. The corresponding result is returned to the test code.

    Let’s look at a cross browser testing scenario that showcases Selenium Safari’s driver on macOS demonstration. Here is the test scenario:

    • Go to the URL https://lambdatest.github.io/sample-todo-app/.
    • Select the first two options.
    • Send ‘Happy Testing at LambdaTest’ to the textbox with the ‘Add Button’ and verify the added text.

    We would be using the PyTest framework for the demonstration. For a quick recap about PyTest, you can refer to this detailed Selenium WebDriver tutorial. You can install PyTest on macOS by triggering the command pip install pytest on the terminal.

    Implementation

    Code WalkThrough

    A new browser instance has to be loaded for each test. Hence, the scope of the fixture is set to class instead of the session.

    Источник

    Оцените статью