SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler offline
Testing Magento with
            Selenium IDE

Dmitriy Romanov
Professional Service QA Engineer
dmitriy.romanov@varien.com
Contents
                                Why Automate Testing ?

                                       Why Selenium ?

                 “Create Simple Product with Related” Example :

 Recording macro
 Analyzing and fixing script source
 Featuring script
                        Selenium Best Practices for Magento:

 Using meaningful locators                        Using *waitfor for dynamical changes
 Script parameterization with Variables           Break out link between TestLogic and
 XPath functions and expressions in Selenium      How to add Assert* and Verify*
 Working with Non-Visible Page Elements           Using Comments
Why Automate Testing ?

 Fast Execution and Feedback
 Reliable
 Repeatable
 Comprehensive
 Reusable parts
 Better Software Quality
 Overall QA Cost Reduction
Selenium usage example
Why Selenium ?
Why Selenium ?
Why Selenium ?
Selenium IDE
• Begin: write and run tests in Firefox.
• Selenium IDE is a Firefox add-on that records clicks, typing, and
  other actions to make a test, which you can play back in the
  browser.

Selenium Remote Control (RC)
• Customize: your language, your browser.
• l (RC) runs your tests in multiple browsers and platforms. Tweak
  your tests in your preferred language.


Selenium Grid
• Deploy: scale out, speed up.
• Selenium Grid extends Selenium RC to distribute your tests across multiple
  servers, saving you time by running tests in parallel.
Selenium Advantages
   Run directly in Browser
   Support AJAX testing

   Multibrowser
   Multiplatform
   Extendable
   Multilanguage
   Free and Open Source
Input Parameters:
Product Name:              Simple Product
SKU                        sp-01
Price                      12
WebSite                    Selenium
Category                   SeL
Related products SKU1      ssp-RA
Related products SKU2      ssp-RB


                Condition to check:
Successful message:      “Product was successfully saved.”
Для примера построения такого теста возьмем такую
часть функционала Админ части, как создание
простого (Simple) продукта.

В тесте заполним все необходимые поля для
отображения на фронте. Из необязательных –
добавим два related продукта.

Демонстрационное видео создания продукта
можно посмотреть отдельно.
Finding solid start point:

click   //ul[@id='nav']/li[3]/ul/li[1]/a/span
…
Using meaningful locators:

        click   //ul[@id='nav']/li[3]/ul/li[1]/a/span




click   //div[@class="nav-bar"]//li [a/span="Manage Products"]/a
Avoid autogenerated IDs:

 click         id_8ad1a1cebaeae9432f842806bb7bf99a

 сlick         id_481d270db32669b7f9f7092eedc00242




clickAndWait       //button[span="Add Product"]

clickAndWait       //button[span="Continue"]
Script parameterization with Variables

            Recorded script:
                                   label=Simple
select        product_type
                                   Product

              id_481d270db32669
click
              b7f9f7092eedc00242

type          name                 Simple Product

type          description          Simple Product
type          short_description    Simple Product
type          sku                  ssp-01
type          weight               10
select        status               label=Enabled
Script parameterization with Variables


         Introducing variables:
store   Simple Product               Name
store   ssp-01                       SKU
store   Selenium                    Website
store   SeL                         Category
store   ssp-RA                    RelProdSKU1
store   ssp-RB                    RelProdSKU2
Script parameterization with Variables


                  Using variables:
type     name                          ${Name}
type     description                   ${Name}
type     short_description             ${Name}
type     sku                           ${SKU }
type     weight                           10
select   status                      label=Enabled
Improve script readability
click       //a[@id='product_info_tabs_group_5']/span
type        Price                                              12
select      tax_class_id                                       label=Taxable Goods
click       //a[@id='product_info_tabs_inventory']/span
type        inventory_qty                                      1000
select      inventory_stock_availability                       label=In Stock




click     //ul[@id='product_info_tabs']//a[span='Prices']
 type                          Price                                   12
select                      tax_class_id                      label=Taxable Goods

click    //ul[@id='product_info_tabs']//a[span='Inventory']
 type                      inventory_qty                             1000
select              inventory_stock_availability                label=In Stock
Using XPath functions:

                 Website selection:
click   //a[@id='product_info_tabs_websites']/span

click   product_website_44




                   Updated version:
click   //ul[@id='product_info_tabs']//a[span='Websites’]

click                         ???
Using XPath functions:




… div[@id='grop_fields']/div[12]/div[1]/big/strong/label
Using XPath functions:
 <label for="product_website_44" class=" ">Selenium
                  Website</label>

//div[@id=’product_info_tabs_websites_content’]//label
   //div[@id='product_info_tabs_websites_content']
          //label[text()='Selenium Website']
          label[text()=${Website}+' Website']
   //div[@id='product_info_tabs_websites_content']
      //label[text()=concat(${Website},' Website')]
   //div[@id='product_info_tabs_websites_content']
          //label[contains(text(),${Website})]
Using XPath functions:
Using XPath functions:

                 Website selection:
click   product_website_44




                   Updated version:
        //div[@id='product_info_tabs_websites_content']
click
               //label[contains(text(),${Website})]
Working with AJAX:
                Category selection:

click      //a[@id='product_info_tabs_categories']/span

click      ext-gen485




                 Updated version:
   click   //a[@id='product_info_tabs_categories']/span
                  //div[@id='product-categories']
   click
                 //a[contains(span,${Category})]
Причина в том, что сразу после перехода на закладку
категорий дерево категорий еще не отрисовано и нет
еще элемента с именем нашей категории.

Замена click на clickandwait здесь не поможет, т.к.,
фактически, страница не перегружается, а заново
отрисовывается только ее часть. Так работает AJAX-
технология, которая с помощью AJAX запросов/ответов
меняет содержимое страницы без полной перезагрузки.

Для того, чтобы найти решение, нужно ответить на
вопрос:

          Что поменялось на странице ?
Working with AJAX:
Working with AJAX. Main Question


What’s up, Doc ?
Working with AJAX:


Awaiting AJAX Response Solutions:


     Use Pause(waitTime)

              OR


  Get Answer for the Question:
“What’s changed on Page ?”
Working with AJAX:
Working with AJAX:
Working with AJAX:
Working with AJAX:
                               Category selection:

   click                 //a[@id='product_info_tabs_categories']/span

   click                 ext-gen485




       click                  //a[@id='product_info_tabs_categories']/span
waitForElementNotPre
        sent
                     //div[@id='loading-mask' and contains(@style,'display: none')]

waitForElemenPresent //div[@id='loading-mask' and contains(@style,'display: none')]

       Click         //div[@id='product-categories']//a[contains(span,${Category})]
Dynamical changes:


              Related products additions:
click   //a[@id='product_info_tabs_related']/span
type    filter_sku                                  ssp-RA
click   id_39e3a2128d47dfd177243389483acede
click   //input[@name='' and @value='240']
type    filter_sku                                  ssp-RB
click   id_39e3a2128d47dfd177243389483acede
click   //input[@name='' and @value='241']
Dynamical changes:
                                     Corrected version:
    click         //ul[@id='product_info_tabs']//a[span='Related Products']
                                                                                   ${RelProdSK
    type                                  filter_sku
                                                                                       U1}
    click      //*[@id='related_product_grid']//button[contains(span,'Search')]
waitForEleme
                //div[@id='loading-mask' and contains(@style,'display: none')]
ntNotPresent
waitForEleme
                //div[@id='loading-mask' and contains(@style,'display: none')]
  nPresent
waitForEleme //table[@id='related_product_grid_table']//td[contains(text(),${Rel
  ntPresent                            ProdSKU1})]
             //table[@id='related_product_grid_table']//td[contains(text(),${Rel
    click
                                       ProdSKU1})]
                                                                                   ${RelProdSK
    type                                  filter_sku
                                                                                       U2}
    click      //*[@id='related_product_grid']//button[contains(span,'Search')]
waitForEleme //table[@id='related_product_grid_table']//td[contains(text(),${Rel
  ntPresent                            ProdSKU1})]
             //table[@id='related_product_grid_table']//td[contains(text(),${Rel
    сlick
                                       ProdSKU1})]
Using User Interface Map



Original Selenese:
   click           id_1b1bca379a27ffade3083654c82ac9d9
Magento EE 1.6.x - 1.7.x:
 ClickAndWait   //button[span='Save And Continue Edit']
Magento EE 1.8.x:
 ClickAndWait   //button[span='Save and Continue Edit']
Using User Interface Map:
             Dealing With Changed Design:
       //button[contains(span,'Save’) and contains(span,'Edit’)']
                                  OR
     //button[upper-case(span)='SAVE AND CONTINUE EDIT']
                                  OR
//button[translate(span,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKL
       MNOPQRSTUVWXYZ')='SAVE AND CONTINUE EDIT']
                                  OR

                        Using UI-Map
Using User Interface Map:

UI-Map Example for 1.6.x and 1.7.x :
     var uiMap = new UIMap();

    uiMap.addPageset({
        name: 'Dashboard',
        description: 'Main page with operations menu',
        paths: ['index.php/control/index']
    });

    uiMap.addElement('Dashboard', {
        name: 'saveandcontinue_button',
        description: 'Save and Continue button',
        locator: "xpath=//button[span='Save And Continue
    Edit']"
    });
Using UI-Map

UI-Map Example for 1.8.x :
     ...
         locator: "xpath=//button[span='Save And Continue
     Edit']"
     ...
Adding UI-Map extension to IDE:
Adding Assertion to Script:


 assertTextPresent      Product was successfully saved.


 assertTextPresent      Product has been successfully saved.




assertTextPresent    ui=Dashboard::product_saved_message()
Review and Comment Source:
1    Input parameters
2    Store                  Simple Product                               Name
3    Store                  ssp-01                                       SKU
4    Store                  'Selenium'                                   Website
5    Store                  'SeL-Category'                               Category
6    Store                  ssp-RA                                       RelProdSKU1
7    Store                  ssp-RB                                       RelProdSKU2
8    Open manage products, click "Add Product"
                            //div[@class="nav-bar"]//li[a/span="Manage
9    clickAndWait
                            Products"]/a


10   clickAndWait           //button[span="Add Product"]



11   clickAndWait           //button[span="Continue"]

12   Fill General Tab
13   type                   name                                         ${Name}
14   type                   description                                  ${Name}
15   type                   short_description                            ${Name}
16   type                   sku                                          ${SKU}
17   type                   weight                                       10
18   Select                 status                                       label=Enabled
Review and Comment Source:
19   Fill Price Tab

20   click                       //ul[@id='product_info_tabs']//a[span='Prices']

21   type                        price                                                        12
22   select                      tax_class_id                                                 label=Taxable Goods
23   Fill Inventory Tab

24   click                       //ul[@id='product_info_tabs']//a[span='Inventory']

25   type                        inventory_qty                                                     100
26   select                      inventory_stock_availability                                      label=In Stock
27   Fill Websites Tab

28   click                       //ul[@id='product_info_tabs']//a[span='Websites']

                                 //div[@id='product_info_tabs_websites_content']//label[contains(text(),$
29   click
                                 {Website})]
30   Fill Category Tab

31   click                       //ul[@id='product_info_tabs']//a[span='Categories']

32   waitForElementNotPresent    //div[@id='loading-mask' and contains(@style,'display: none')]

33   waitForElementPresent       //div[@id='loading-mask' and contains(@style,'display: none')]

34   click                       //div[@id='product-categories']//a[contains(span,${Category})]

35   Fill Related Products Tab

36   click                       //ul[@id='product_info_tabs']//a[span='Related Products']

37   waitForElementPresent       filter_sku
Review and Comment Source:
38   type                       filter_sku                                                                       ${RelProdSKU1}
39   click                      //*[@id='related_product_grid']//button[contains(span,'Search')]
40   waitForElementNotPresent   //div[@id='loading-mask' and contains(@style,'display: none')]
41   waitForElementPresent      //div[@id='loading-mask' and contains(@style,'display: none')]
                                //table[@id='related_product_grid_table']//td[contains(text(),${RelProdSKU1
42   waitForElementPresent
                                })]
                                //table[@id='related_product_grid_table']//td[contains(text(),${RelProdSKU1
43   click
                                })]
44   type                       filter_sku                                                                  ${RelProdSKU2}

45   click                      //*[@id='related_product_grid']//button[contains(span,'Search')]


46   waitForElementNotPresent   //div[@id='loading-mask' and contains(@style,'display: none')]

47   waitForElementPresent      //div[@id='loading-mask' and contains(@style,'display: none')]
                                //table[@id='related_product_grid_table']/tbody/tr/td[contains(text(),${RelPro
48   waitForElementPresent
                                dSKU2})]
                                //table[@id='related_product_grid_table']/tbody/tr/td[contains(text(),${RelPro
49   click
                                dSKU2})]
50   Save And Continue
51   click                      ui=Dashboard::saveandcontinue_button()
52   Product saved assertion

53   assertElementPresent       ui=Dashboard::product_saved_message()
Script Changes Statistic and Conclusions:


Recorder Script Lines Count:
                                 27
Final Script Lines Count:
                                 56
Unchanged Lines:                 7
Conclusions:


      Selenium Best Practices for Magento:

                                    Using *waitfor for dynamical
 Using meaningful locators
                                   changes
 Script parameterization with      Break out link between
Variables                          TestLogic and Design
 Xpath and JavaScript functions
                                      When Assert* and Verify*
and expressions in Selenium
 Working with Non-Visible Page
                                      Using Comments
Elements

Mais conteúdo relacionado

Mais procurados

Mais procurados (11)

Mastering Oracle ADF Bindings
Mastering Oracle ADF BindingsMastering Oracle ADF Bindings
Mastering Oracle ADF Bindings
 
Spring batch
Spring batchSpring batch
Spring batch
 
소프트웨어 정의 방식 애플리케이션 플랫폼, agados 기반 애플리케이션 정의(디자인) 데모
소프트웨어 정의 방식 애플리케이션 플랫폼, agados 기반 애플리케이션 정의(디자인) 데모소프트웨어 정의 방식 애플리케이션 플랫폼, agados 기반 애플리케이션 정의(디자인) 데모
소프트웨어 정의 방식 애플리케이션 플랫폼, agados 기반 애플리케이션 정의(디자인) 데모
 
Jsf
JsfJsf
Jsf
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-Programming
 
Hvs
HvsHvs
Hvs
 
Test-driven Development with AEM
Test-driven Development with AEMTest-driven Development with AEM
Test-driven Development with AEM
 
Angular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of StatesAngular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of States
 
Day 5
Day 5Day 5
Day 5
 
Unit Testing at Scale
Unit Testing at ScaleUnit Testing at Scale
Unit Testing at Scale
 
Actionview
ActionviewActionview
Actionview
 

Semelhante a Тестирование Magento с использованием Selenium

TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
Alessandro Molina
 
Writing Gadgets with the WSO2 Gadget Server
Writing Gadgets with the WSO2 Gadget ServerWriting Gadgets with the WSO2 Gadget Server
Writing Gadgets with the WSO2 Gadget Server
WSO2
 
Introduction To Work Item Customisation
Introduction To Work Item CustomisationIntroduction To Work Item Customisation
Introduction To Work Item Customisation
wbarthol
 

Semelhante a Тестирование Magento с использованием Selenium (20)

How to convert custom plsql to web services-Soap OR Rest
How to convert custom plsql to web services-Soap OR RestHow to convert custom plsql to web services-Soap OR Rest
How to convert custom plsql to web services-Soap OR Rest
 
How to Mess Up Your Angular UI Components
How to Mess Up Your Angular UI ComponentsHow to Mess Up Your Angular UI Components
How to Mess Up Your Angular UI Components
 
Get AngularJS Started!
Get AngularJS Started!Get AngularJS Started!
Get AngularJS Started!
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
 
Introduction to Vue.js
Introduction to Vue.jsIntroduction to Vue.js
Introduction to Vue.js
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
The Rails Way
The Rails WayThe Rails Way
The Rails Way
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
 
Let's react - Meetup
Let's react - MeetupLet's react - Meetup
Let's react - Meetup
 
Writing Gadgets with the WSO2 Gadget Server
Writing Gadgets with the WSO2 Gadget ServerWriting Gadgets with the WSO2 Gadget Server
Writing Gadgets with the WSO2 Gadget Server
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
 
Testing C# and ASP.net using Ruby
Testing C# and ASP.net using RubyTesting C# and ASP.net using Ruby
Testing C# and ASP.net using Ruby
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0
 
Hidden Docs in Angular
Hidden Docs in AngularHidden Docs in Angular
Hidden Docs in Angular
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Introduction To Work Item Customisation
Introduction To Work Item CustomisationIntroduction To Work Item Customisation
Introduction To Work Item Customisation
 
Django
DjangoDjango
Django
 
Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2
 
Wave Workshop
Wave WorkshopWave Workshop
Wave Workshop
 
Creating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-htmlCreating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-html
 

Mais de Magecom Ukraine

Применение TDD при разработке веб-сервисов
Применение TDD при разработке веб-сервисовПрименение TDD при разработке веб-сервисов
Применение TDD при разработке веб-сервисов
Magecom Ukraine
 
Управление продуктом в стиле Magento Unified Process
Управление продуктом в стиле Magento Unified ProcessУправление продуктом в стиле Magento Unified Process
Управление продуктом в стиле Magento Unified Process
Magecom Ukraine
 
Ключ успеха – процесс или продукт?
Ключ успеха – процесс или продукт?Ключ успеха – процесс или продукт?
Ключ успеха – процесс или продукт?
Magecom Ukraine
 
10 000 вёдер или в погоне за Ключом от всех дверей
10 000 вёдер или в погоне за Ключом от всех дверей10 000 вёдер или в погоне за Ключом от всех дверей
10 000 вёдер или в погоне за Ключом от всех дверей
Magecom Ukraine
 
Применение компонент-ориентированной архитектуры для написания Magento Extens...
Применение компонент-ориентированной архитектуры для написания Magento Extens...Применение компонент-ориентированной архитектуры для написания Magento Extens...
Применение компонент-ориентированной архитектуры для написания Magento Extens...
Magecom Ukraine
 
Преимущества использования полнотекстового поиска в интернет-магазинах
Преимущества использования полнотекстового поиска в интернет-магазинахПреимущества использования полнотекстового поиска в интернет-магазинах
Преимущества использования полнотекстового поиска в интернет-магазинах
Magecom Ukraine
 
Все дороги ведут в Checkout
Все дороги ведут в CheckoutВсе дороги ведут в Checkout
Все дороги ведут в Checkout
Magecom Ukraine
 
Мобильные клиенты интернет-магазинов
Мобильные клиенты интернет-магазиновМобильные клиенты интернет-магазинов
Мобильные клиенты интернет-магазинов
Magecom Ukraine
 
Индексирование в Magento
Индексирование в MagentoИндексирование в Magento
Индексирование в Magento
Magecom Ukraine
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
Реализация шаблонов корпоративных приложений в Magento
Реализация шаблонов корпоративных приложений в MagentoРеализация шаблонов корпоративных приложений в Magento
Реализация шаблонов корпоративных приложений в Magento
Magecom Ukraine
 
1000 миллисекунд из жизни Magento
1000 миллисекунд из жизни Magento1000 миллисекунд из жизни Magento
1000 миллисекунд из жизни Magento
Magecom Ukraine
 
Современные платформы (фреймворки) разработки веб- приложений на PHP
Современные платформы (фреймворки) разработки веб- приложений на PHP Современные платформы (фреймворки) разработки веб- приложений на PHP
Современные платформы (фреймворки) разработки веб- приложений на PHP
Magecom Ukraine
 

Mais de Magecom Ukraine (19)

Применение TDD при разработке веб-сервисов
Применение TDD при разработке веб-сервисовПрименение TDD при разработке веб-сервисов
Применение TDD при разработке веб-сервисов
 
Управление продуктом в стиле Magento Unified Process
Управление продуктом в стиле Magento Unified ProcessУправление продуктом в стиле Magento Unified Process
Управление продуктом в стиле Magento Unified Process
 
Ключ успеха – процесс или продукт?
Ключ успеха – процесс или продукт?Ключ успеха – процесс или продукт?
Ключ успеха – процесс или продукт?
 
10 000 вёдер или в погоне за Ключом от всех дверей
10 000 вёдер или в погоне за Ключом от всех дверей10 000 вёдер или в погоне за Ключом от всех дверей
10 000 вёдер или в погоне за Ключом от всех дверей
 
Применение компонент-ориентированной архитектуры для написания Magento Extens...
Применение компонент-ориентированной архитектуры для написания Magento Extens...Применение компонент-ориентированной архитектуры для написания Magento Extens...
Применение компонент-ориентированной архитектуры для написания Magento Extens...
 
Преимущества использования полнотекстового поиска в интернет-магазинах
Преимущества использования полнотекстового поиска в интернет-магазинахПреимущества использования полнотекстового поиска в интернет-магазинах
Преимущества использования полнотекстового поиска в интернет-магазинах
 
Все дороги ведут в Checkout
Все дороги ведут в CheckoutВсе дороги ведут в Checkout
Все дороги ведут в Checkout
 
Мобильные клиенты интернет-магазинов
Мобильные клиенты интернет-магазиновМобильные клиенты интернет-магазинов
Мобильные клиенты интернет-магазинов
 
Индексирование в Magento
Индексирование в MagentoИндексирование в Magento
Индексирование в Magento
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Реализация шаблонов корпоративных приложений в Magento
Реализация шаблонов корпоративных приложений в MagentoРеализация шаблонов корпоративных приложений в Magento
Реализация шаблонов корпоративных приложений в Magento
 
1000 миллисекунд из жизни Magento
1000 миллисекунд из жизни Magento1000 миллисекунд из жизни Magento
1000 миллисекунд из жизни Magento
 
Flexibility vs Conformity - lessons learned in Open Source
Flexibility vs Conformity - lessons learned in Open SourceFlexibility vs Conformity - lessons learned in Open Source
Flexibility vs Conformity - lessons learned in Open Source
 
Современные платформы (фреймворки) разработки веб- приложений на PHP
Современные платформы (фреймворки) разработки веб- приложений на PHP Современные платформы (фреймворки) разработки веб- приложений на PHP
Современные платформы (фреймворки) разработки веб- приложений на PHP
 
Деплоймент и распространение обновлений для веб-приложений
Деплоймент и распространение обновлений для веб-приложенийДеплоймент и распространение обновлений для веб-приложений
Деплоймент и распространение обновлений для веб-приложений
 
Расширение функциональности модульного MVC приложения
Расширение функциональности модульного MVC приложенияРасширение функциональности модульного MVC приложения
Расширение функциональности модульного MVC приложения
 
Архитектура веб-приложений на примере Zend Framework и Magento
Архитектура веб-приложений  на примере Zend Framework и MagentoАрхитектура веб-приложений  на примере Zend Framework и Magento
Архитектура веб-приложений на примере Zend Framework и Magento
 
Extension Marketplace. Площадки для распространения ПО
Extension Marketplace. Площадки для распространения ПОExtension Marketplace. Площадки для распространения ПО
Extension Marketplace. Площадки для распространения ПО
 
Стандарты и соглашения в сложных ООП-приложениях
Стандарты и соглашения в сложных ООП-приложенияхСтандарты и соглашения в сложных ООП-приложениях
Стандарты и соглашения в сложных ООП-приложениях
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Тестирование Magento с использованием Selenium

  • 1.
  • 2. Testing Magento with Selenium IDE Dmitriy Romanov Professional Service QA Engineer dmitriy.romanov@varien.com
  • 3. Contents Why Automate Testing ? Why Selenium ? “Create Simple Product with Related” Example :  Recording macro  Analyzing and fixing script source  Featuring script Selenium Best Practices for Magento:  Using meaningful locators  Using *waitfor for dynamical changes  Script parameterization with Variables  Break out link between TestLogic and  XPath functions and expressions in Selenium  How to add Assert* and Verify*  Working with Non-Visible Page Elements  Using Comments
  • 4. Why Automate Testing ?  Fast Execution and Feedback  Reliable  Repeatable  Comprehensive  Reusable parts  Better Software Quality  Overall QA Cost Reduction
  • 8. Why Selenium ? Selenium IDE • Begin: write and run tests in Firefox. • Selenium IDE is a Firefox add-on that records clicks, typing, and other actions to make a test, which you can play back in the browser. Selenium Remote Control (RC) • Customize: your language, your browser. • l (RC) runs your tests in multiple browsers and platforms. Tweak your tests in your preferred language. Selenium Grid • Deploy: scale out, speed up. • Selenium Grid extends Selenium RC to distribute your tests across multiple servers, saving you time by running tests in parallel.
  • 9.
  • 10. Selenium Advantages  Run directly in Browser  Support AJAX testing  Multibrowser  Multiplatform  Extendable  Multilanguage  Free and Open Source
  • 11. Input Parameters: Product Name: Simple Product SKU sp-01 Price 12 WebSite Selenium Category SeL Related products SKU1 ssp-RA Related products SKU2 ssp-RB Condition to check: Successful message: “Product was successfully saved.”
  • 12. Для примера построения такого теста возьмем такую часть функционала Админ части, как создание простого (Simple) продукта. В тесте заполним все необходимые поля для отображения на фронте. Из необязательных – добавим два related продукта. Демонстрационное видео создания продукта можно посмотреть отдельно.
  • 13.
  • 14. Finding solid start point: click //ul[@id='nav']/li[3]/ul/li[1]/a/span …
  • 15. Using meaningful locators: click //ul[@id='nav']/li[3]/ul/li[1]/a/span click //div[@class="nav-bar"]//li [a/span="Manage Products"]/a
  • 16. Avoid autogenerated IDs: click id_8ad1a1cebaeae9432f842806bb7bf99a сlick id_481d270db32669b7f9f7092eedc00242 clickAndWait //button[span="Add Product"] clickAndWait //button[span="Continue"]
  • 17. Script parameterization with Variables Recorded script: label=Simple select product_type Product id_481d270db32669 click b7f9f7092eedc00242 type name Simple Product type description Simple Product type short_description Simple Product type sku ssp-01 type weight 10 select status label=Enabled
  • 18. Script parameterization with Variables Introducing variables: store Simple Product Name store ssp-01 SKU store Selenium Website store SeL Category store ssp-RA RelProdSKU1 store ssp-RB RelProdSKU2
  • 19. Script parameterization with Variables Using variables: type name ${Name} type description ${Name} type short_description ${Name} type sku ${SKU } type weight 10 select status label=Enabled
  • 20. Improve script readability click //a[@id='product_info_tabs_group_5']/span type Price 12 select tax_class_id label=Taxable Goods click //a[@id='product_info_tabs_inventory']/span type inventory_qty 1000 select inventory_stock_availability label=In Stock click //ul[@id='product_info_tabs']//a[span='Prices'] type Price 12 select tax_class_id label=Taxable Goods click //ul[@id='product_info_tabs']//a[span='Inventory'] type inventory_qty 1000 select inventory_stock_availability label=In Stock
  • 21. Using XPath functions: Website selection: click //a[@id='product_info_tabs_websites']/span click product_website_44 Updated version: click //ul[@id='product_info_tabs']//a[span='Websites’] click ???
  • 22. Using XPath functions: … div[@id='grop_fields']/div[12]/div[1]/big/strong/label
  • 23. Using XPath functions: <label for="product_website_44" class=" ">Selenium Website</label> //div[@id=’product_info_tabs_websites_content’]//label //div[@id='product_info_tabs_websites_content'] //label[text()='Selenium Website'] label[text()=${Website}+' Website'] //div[@id='product_info_tabs_websites_content'] //label[text()=concat(${Website},' Website')] //div[@id='product_info_tabs_websites_content'] //label[contains(text(),${Website})]
  • 25. Using XPath functions: Website selection: click product_website_44 Updated version: //div[@id='product_info_tabs_websites_content'] click //label[contains(text(),${Website})]
  • 26. Working with AJAX: Category selection: click //a[@id='product_info_tabs_categories']/span click ext-gen485 Updated version: click //a[@id='product_info_tabs_categories']/span //div[@id='product-categories'] click //a[contains(span,${Category})]
  • 27. Причина в том, что сразу после перехода на закладку категорий дерево категорий еще не отрисовано и нет еще элемента с именем нашей категории. Замена click на clickandwait здесь не поможет, т.к., фактически, страница не перегружается, а заново отрисовывается только ее часть. Так работает AJAX- технология, которая с помощью AJAX запросов/ответов меняет содержимое страницы без полной перезагрузки. Для того, чтобы найти решение, нужно ответить на вопрос: Что поменялось на странице ?
  • 29. Working with AJAX. Main Question What’s up, Doc ?
  • 30. Working with AJAX: Awaiting AJAX Response Solutions: Use Pause(waitTime) OR Get Answer for the Question: “What’s changed on Page ?”
  • 34. Working with AJAX: Category selection: click //a[@id='product_info_tabs_categories']/span click ext-gen485 click //a[@id='product_info_tabs_categories']/span waitForElementNotPre sent //div[@id='loading-mask' and contains(@style,'display: none')] waitForElemenPresent //div[@id='loading-mask' and contains(@style,'display: none')] Click //div[@id='product-categories']//a[contains(span,${Category})]
  • 35. Dynamical changes: Related products additions: click //a[@id='product_info_tabs_related']/span type filter_sku ssp-RA click id_39e3a2128d47dfd177243389483acede click //input[@name='' and @value='240'] type filter_sku ssp-RB click id_39e3a2128d47dfd177243389483acede click //input[@name='' and @value='241']
  • 36. Dynamical changes: Corrected version: click //ul[@id='product_info_tabs']//a[span='Related Products'] ${RelProdSK type filter_sku U1} click //*[@id='related_product_grid']//button[contains(span,'Search')] waitForEleme //div[@id='loading-mask' and contains(@style,'display: none')] ntNotPresent waitForEleme //div[@id='loading-mask' and contains(@style,'display: none')] nPresent waitForEleme //table[@id='related_product_grid_table']//td[contains(text(),${Rel ntPresent ProdSKU1})] //table[@id='related_product_grid_table']//td[contains(text(),${Rel click ProdSKU1})] ${RelProdSK type filter_sku U2} click //*[@id='related_product_grid']//button[contains(span,'Search')] waitForEleme //table[@id='related_product_grid_table']//td[contains(text(),${Rel ntPresent ProdSKU1})] //table[@id='related_product_grid_table']//td[contains(text(),${Rel сlick ProdSKU1})]
  • 37. Using User Interface Map Original Selenese: click id_1b1bca379a27ffade3083654c82ac9d9 Magento EE 1.6.x - 1.7.x: ClickAndWait //button[span='Save And Continue Edit'] Magento EE 1.8.x: ClickAndWait //button[span='Save and Continue Edit']
  • 38. Using User Interface Map: Dealing With Changed Design: //button[contains(span,'Save’) and contains(span,'Edit’)'] OR //button[upper-case(span)='SAVE AND CONTINUE EDIT'] OR //button[translate(span,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKL MNOPQRSTUVWXYZ')='SAVE AND CONTINUE EDIT'] OR Using UI-Map
  • 39. Using User Interface Map: UI-Map Example for 1.6.x and 1.7.x : var uiMap = new UIMap(); uiMap.addPageset({ name: 'Dashboard', description: 'Main page with operations menu', paths: ['index.php/control/index'] }); uiMap.addElement('Dashboard', { name: 'saveandcontinue_button', description: 'Save and Continue button', locator: "xpath=//button[span='Save And Continue Edit']" });
  • 40. Using UI-Map UI-Map Example for 1.8.x : ... locator: "xpath=//button[span='Save And Continue Edit']" ...
  • 42. Adding Assertion to Script: assertTextPresent Product was successfully saved. assertTextPresent Product has been successfully saved. assertTextPresent ui=Dashboard::product_saved_message()
  • 43. Review and Comment Source: 1 Input parameters 2 Store Simple Product Name 3 Store ssp-01 SKU 4 Store 'Selenium' Website 5 Store 'SeL-Category' Category 6 Store ssp-RA RelProdSKU1 7 Store ssp-RB RelProdSKU2 8 Open manage products, click "Add Product" //div[@class="nav-bar"]//li[a/span="Manage 9 clickAndWait Products"]/a 10 clickAndWait //button[span="Add Product"] 11 clickAndWait //button[span="Continue"] 12 Fill General Tab 13 type name ${Name} 14 type description ${Name} 15 type short_description ${Name} 16 type sku ${SKU} 17 type weight 10 18 Select status label=Enabled
  • 44. Review and Comment Source: 19 Fill Price Tab 20 click //ul[@id='product_info_tabs']//a[span='Prices'] 21 type price 12 22 select tax_class_id label=Taxable Goods 23 Fill Inventory Tab 24 click //ul[@id='product_info_tabs']//a[span='Inventory'] 25 type inventory_qty 100 26 select inventory_stock_availability label=In Stock 27 Fill Websites Tab 28 click //ul[@id='product_info_tabs']//a[span='Websites'] //div[@id='product_info_tabs_websites_content']//label[contains(text(),$ 29 click {Website})] 30 Fill Category Tab 31 click //ul[@id='product_info_tabs']//a[span='Categories'] 32 waitForElementNotPresent //div[@id='loading-mask' and contains(@style,'display: none')] 33 waitForElementPresent //div[@id='loading-mask' and contains(@style,'display: none')] 34 click //div[@id='product-categories']//a[contains(span,${Category})] 35 Fill Related Products Tab 36 click //ul[@id='product_info_tabs']//a[span='Related Products'] 37 waitForElementPresent filter_sku
  • 45. Review and Comment Source: 38 type filter_sku ${RelProdSKU1} 39 click //*[@id='related_product_grid']//button[contains(span,'Search')] 40 waitForElementNotPresent //div[@id='loading-mask' and contains(@style,'display: none')] 41 waitForElementPresent //div[@id='loading-mask' and contains(@style,'display: none')] //table[@id='related_product_grid_table']//td[contains(text(),${RelProdSKU1 42 waitForElementPresent })] //table[@id='related_product_grid_table']//td[contains(text(),${RelProdSKU1 43 click })] 44 type filter_sku ${RelProdSKU2} 45 click //*[@id='related_product_grid']//button[contains(span,'Search')] 46 waitForElementNotPresent //div[@id='loading-mask' and contains(@style,'display: none')] 47 waitForElementPresent //div[@id='loading-mask' and contains(@style,'display: none')] //table[@id='related_product_grid_table']/tbody/tr/td[contains(text(),${RelPro 48 waitForElementPresent dSKU2})] //table[@id='related_product_grid_table']/tbody/tr/td[contains(text(),${RelPro 49 click dSKU2})] 50 Save And Continue 51 click ui=Dashboard::saveandcontinue_button() 52 Product saved assertion 53 assertElementPresent ui=Dashboard::product_saved_message()
  • 46. Script Changes Statistic and Conclusions: Recorder Script Lines Count: 27 Final Script Lines Count: 56 Unchanged Lines: 7
  • 47. Conclusions: Selenium Best Practices for Magento:  Using *waitfor for dynamical  Using meaningful locators changes  Script parameterization with  Break out link between Variables TestLogic and Design  Xpath and JavaScript functions  When Assert* and Verify* and expressions in Selenium  Working with Non-Visible Page  Using Comments Elements