Прочитайте оригинальную статью на ГКДВ
Для моих пользовательских потребностей я искал функциональный набор тестирования Щелки. В качестве разработчика PHP я обыменно использую в жизни, чтобы написать и играть в мои функциональные тесты. Но проект, который я хочу проверить, это написано Python, и я не хочу устанавливать и настроить PHP только для запуска тестов. А как насчет тьма и хромированного бегового двигателя? Эй, у меня была идея: внедрить прохладную синтаксис гаерокина с кукловом в Python.
О джеркине
Gherkin – это синтаксис, который выглядит:
Feature: Use the rest test suite Scenario: We can fetch data from an api Given I add these headers: | accept | application/json | Given I prepare a "GET" request to "/todos/1" When I send the request Then print the last json response And the json node "anythng" should not exist And the json node "userId" should exist And the json node "id" should be equal to "1"
Это читается человеком, (я имею в виду, не разработчика человека:)) И это действительно легко написать.
Окор
Кукла это библиотека узла, которая обеспечивает API высокого уровня для управления Chrome или Chromium по протоколу Devtools и позволяет выполнять действия в безголовом (без видимой UI) версии Chrome. В Nodejs эти тесты выглядят как:
const puppeteer = require('puppeteer'); (async() => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setRequestInterception(true); page.on('request', request => { if (request.resourceType() === 'image') request.abort(); else request.continue(); }); await page.goto('https://news.google.com/news/'); await page.screenshot({path: 'news.png', fullPage: true}); await browser.close(); })();
Понятно разработчиками, но немного уродливым (и скучно писать) … Однако, используя реальный браузер, так как Chrome для воспроизведения функциональных тестов имеет много преимуществ:
- Тестирование JavaScript
- скорость
- легко использовать
Давайте играть с PypPetTheater
PypPetTheateater – одна из моих мысль на Amaziiing (и это то, о чем эта статья). В Python механизм Щенок может быть использован благодаря Pyppeteer. . И разбирать файлы Hherkin функций, мы будем использовать габеррин-парсер.
Установите pyppetheater
Во-первых, вы должны установить хромированную безголовую двигатель (под Ubuntu):
$ wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - $ sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' $ apt-get -y update $ apt-get install -yqq unzip sudo python3-pip mysql-client google-chrome-stable $ wget -O /tmp/chromedriver.zip http://chromedriver.storage.googleapis.com/`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE`/chromedriver_linux64.zip $ unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/ $ pyppeteer-install
И установить PypPetTheater:
$ pip3 install Pyppetheater
Теперь вы можете запустить pyppet_theater
бинарный:
$ pyppet_theater /path/to/your/yml/or/feature/file
Какой-то пример теста
Каждый тестовый люкс представляет собой файл YML, который содержит некоторые параметры (при необходимости):
parameters: rest: base_endpoint: https://jsonplaceholder.typicode.com scenarios: 0: rest/rest-suite.feature
Для отдыха API:
Например, в остальном/REST-SUITE.Feature:
Feature: Use the rest test suite Scenario: We can fetch data from an api Given I add these headers: | accept | application/json | Given I prepare a "GET" request to "/todos/1" When I send the request Then print the last json response And the json node "anythng" should not exist And the json node "userId" should exist And the json node "id" should be equal to "1"
$ pyppet_theater rest.yml
Для теста на интерфейс:
Например, в игре/оформлении. Файл заражения:
Feature: Create an account on a website Scenario: As a visitor, I register on the website Given I go on "http://my-website.com" And I click on "\#signup-link" And I type "player6" in field "\#id_username" And I type "somepassword" in field "\#id_password1" And I type "somepassword" in field "\#id_password2" When I click on "\#register" Then I should be on "http://my-website.com"
И запустить:
$ pyppet_theater game/registration.feature
Для Tests MySQL:
С mysql.yml
файл
parameters: mysql: db_host: 127.0.0.1 db_user: root db_password: root db_name: test scenarios: 0: "mysql/mysql-suite.feature"
И, в MySQL/MySQL-Suite.
Feature: Use the mysql test suite Scenario: We can select, update and check existence Given the row with "id" equal to "1" in table "some_table" should exist And the row with "id" equal to "1" in table "some_table" has "some_key" equal to "some_value" Then the row with "id" equal to "1" in table "some_table" should have "some_key" equal to "some_value" And the row with "some_key" equal to "some_value" in table "some_table" should exist Scenario: We can delete and check existence Given the row with "id" equal to "1" in table "some_table" does not exist Then the row with "id" equal to "1" in table "some_table" should not exist
И запустить:
$ pyppet_theater mysql.yml
Вы также можете использовать Docker Image Отказ
Чтобы узнать больше о PypPetTheater, Перейти к репо!
Оригинал: “https://dev.to/gpenverne/functional-tests-with-puppeteer-and-gherkin-scenarios-2ha6”