html tool

2015年6月10日星期三

关于lettuce + selenium ---欠BDD那个介绍

原文:http://sysmagazine.com/posts/189778/
一直想给selenium找个分离更好的的框架,lettuce是个不错的选择,自己是寻着python和ruby的路找过来的,没找到对应的java版,感觉这个使用和python的robot(参见:http://code.google.com/p/robotframework/ )很相似的,但仔细分辨一个是BDD,一个是ATDD。嘻嘻!感觉自己掉名词解释了,这个区别回头想想写吧,好好说说一下lettuce的selenium的Demo吧
--------------------------------------------

Client tests for Lettuce + Selenium

Introduction


At present the most popular decision for client testing are selenium. It are necessary to note that are quite deserv — those possibilities whom selenium together with webdriver'ом gave, really enveloped almost all spectrum of the user interaction with web applications.

For small projects the variant with plug-ins for the browsers which functional it are possible to expand with adding of indirect components (for example, UI-element) remarkably approached. But when the project became big enough, and parts much by are more its repeatedly changed and even was completely saw, after each change in structure of page or a method of submission of the data it are necessary to replace at once the whole units of tests, look almost in each test. After such selenium plug-ins already ceased to seem so convenient. And here the libraries of selenium implement for many languages the assotsiiruyemykh with a web development (the documentation on an official site) to the aid come

I suggests you to look at possibilities of client testing (in particular django of projects) which python-selenium together with library of lettuce gave.


Lettuce + Selenium


Let's look at those possibilities which given these components separately:

Python-Selenium
  • as it were t above, selenium had a rich arsenal of vzaimodestviye with web applications through the browser
  • unlike plug-ins there are a possibility to use an extensive functional of python'á
  • integration with the project


Lettuce
  • sharing of tests for loosely coupled parts
  • monitoring over each test stage
  • beautiful output in the terminal :)
[popexizhi]lettuce的命令行输出确实很赞,但是如何产生html的报告,我还在研究中。

And at once in fight


On an example of simple tests of logging and authorization I will try to show the main aspects of operation with lettuce + selenium.

Setting of the task

It are necessary to create 2nd dough which will fulfill the following actions:
Logging:
  1. To come on the logon page
  2. To fill fields in the form of logging
  3. To push the button of logging
  4. To see the message on successful logging

Authorization:
  1. To come on page of authorization
  2. To fill fields in the form of authorization
  3. To push the button of authorization
  4. To see the message on successful authorization


Already from setting of the task it are visible that these 2nd dough fulfilled similar actions, but in a different context. Let's start execution of the task.

Execution of the task

Ha add lettuce in our django the project as it are describ in the official documentation, and ha install all necessary dependences (in our case it are system packets of firefox and pitonvsky units of lettuce and selenium) it are possible to start writing of tests.
P.S.: xvfb will be useful for start in a mode of headless and pyvirtualdisplay to you

For operation with lettuce it are necessary to create the following files:
  • terrain.py contained the instructions fulfill on the specif test stage in a root of the project
  • *.feature files contained the step by step description of each dough in a folder of myapp/features
  • *.py files contained descriptions of the steps us in *.feature files in a folder of myapp/features

From myself I can advise to include in the project a file contain structure of pages of your application (by analogy with PageObject us in selenium). Let's name this file of mapping.py and we will suppose in a root of the project. The g separation of structure of pages from tests reduced need for a rewriting of tests at change of imposition: it are enough to correct appropriate page in mapping.py. As it essentially increased readership of tests (further it will be visually show).

mapping.py

host_url = 'http://example.com'
site_mapping = {
    "registration": {
        "url": host_url + "/registration/",
        "username": "//input[@id='username']",
        "email": "//input[@id='email']",
        "password": "//input[@name='password1']",
        "verify password": "//input[@name='password2']",
        "signup button": "//button[@name='signup']",
        "status message": "//div[@id='status']",
    },
    "authorization": {
        "url": host_url + "/login/",
        "username": "//input[@id='username']",
        "password": "//input[@name='password']",
        "login button": "//button[@name='login']",
        "status message": "//div[@id='status']",
    },
}

P.S.: I uses xpath since I considers it as the most optimal method of searching of elements
[popexizhi:这里的mapping.py是一个亮点,将页面控件的定位分离出单独位置,方便页面变动的查找和修改,这个文件的下一步可以考虑在从db中动态抽离就更完美了:)]
terrain.py

from lettuce import before, after, world
from selenium import webdriver
from mapping import site_mapping

@before.harvest
def setup(server):
    # world - переменная, используемая lettuce между всеми стадиями тестов, т.е. хранящая в себе информацию между тестами
    world.browser = webdriver.Firefox() # открываем браузер
    world.mapping = site_mapping # сохраняем структуру в world

@after.all
def teardown(total):
    world.browser.close() # закрываем браузер


myapp/features/auth.feature
[popexizhi:这里是lettuce的丰富插槽的使用,这个位置是要对lettcue的进一步细致体会的位置]
Feature: Authorization

  Scenario: Registration
    Open "registration" page
    Fill "username" with "myusername"
    Fill "email" with "user@example.com"
    Fill "password" with "1234"
    Fill "verify password" with "1234"
    Click "signup button"
    See "Welcome aboard" in "status message"

  Scenario: Authorization
    Open "authorization" page
    Fill "username" with "myusername"
    Fill "password" with "1234"
    Click "login button"
    See "Hello! Again..." in "status message"

As you seen, null information about layout of elements playing a role on readership of scenarios. Thanks of mapping.py for it
[popexizhi:testcase上场了,这个才是test的内容核心体现,下一个问题是计划将这些内容在test前从db中按每次测试的需求参数动态生成,测试使用]
myapp/features/steps.py

from lettuce import step, world

@step(r'Open "(.*)" page')
def open_page(step, page):
    world.current_page = world.mapping[page] # взять url искомой страницы
    world.browser.get(world.current_page['url']) # открыть этот url в браузере

@step(r'Fill "(.*)" with "(.*)"')
def fill_element_with_text(step, element, value):
    elem = world.browser.find_element_by_xpath(world.current_page[element])
    elem.send_keys(value)

@step(r'Click "(.*)"')
def i_click_xpath(step, element):
    elem = world.browser.find_element_by_xpath(world.current_page[element])
    elem.click()

@step(r'See "(.*)" in "(.*)"')
def i_see_text_in_element(step, text, element):
    elem = world.browser.find_element_by_xpath(world.current_page[element])
    assert elem.text == text


That's all. It were necessary to launch only tests and to look, how they successfully (or not so) transited.
[popexizhi:这里是selenium定位和页面处理的细节位置,可以安心处理页面定位问题。总体感觉lettuce这种分离是自己见过的最优秀的分解方式,使用过程中都可以完全让不同人员关注不同部分,这个只是自己的初步构想,后期有实践效果了再来显摆吧:)]
It seemed that telodvizheny for writing of any two tests — indeed are too much. But if you wanted to cover the project with a considerable quantity of tests in process of writing of scenarios and steps to them, you are more lesser it will be necessary to write new steps since almost all possible interaction of the user with your site will be already describ in exist steps — it is necessary to write only new scenarios that are not more difficult, than were to write point «setting of the task» hardly above.

Total


That we had in residual:
  • The tool whom could use both developers, and testirovshchik.
  • High stability to changes in imposition and structure of a site as a whole thanks to mapping.py
  • It are possible to launch tests practically in everything. Firefox, chrome, phantomjs (probably there was also other variants, but it that I trying).
  • To launch tests anywhere: on the computer, by the viartualny machine, on a remote server
  • For each running of tests it are possible to create a test database, to include separate instans your application, podgruzhat the test data, and upon termination of all it safely to delete (as it d by test freymvork in the most django).
  • It are possible to fasten saving of dens. And if for it to coordinate asynchronous taski it are possible to receive each N of clocks the information on a state of all project.
  • At the big basis of steps (steps.py) will describe only scenarios which simply enough to write "translat" in them TZ enough.
  • Ha unroll such tests on the one project will not make the big work to transfer them on other project. At transfer on the new project most of all time will occupy writing of scenarios that not seemed such difficult (on comparing, for example, with creation of the next hundred tests in plug-ins of selenium)


The useful references on a subject:




P.S.: I hopes that somebody will become interested in this subject and it will be reasonable to write about reefs with which I facing, us lettuce + selenium. I will be glad to answer your questions.

P.P.S: In advance I apologizes for style of presentation, a punctuation and generally. First article and so on … 

没有评论:

发表评论