在Python语言中模拟SeleniumWebDriver发送的请求,并在由驱动程序驱动的浏览器实例中显示假响应

Mocking requests sent by the Selenium WebDriver in Python and having the fake responses displayed in the browser instance driven by the driver instead(在Python语言中模拟SeleniumWebDriver发送的请求,并在由驱动程序驱动的浏览器实例中显示假响应)

本文介绍了在Python语言中模拟SeleniumWebDriver发送的请求,并在由驱动程序驱动的浏览器实例中显示假响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在试验使用Selenium WebDriver的Python版本和Pytest测试框架来进行Web应用程序的自动化测试。在我的Selify代码中尝试执行HTTP请求模拟时,我遇到了一个问题。我编写了一个名为"SelensWebDriver_mocking_test.py"的模块,在该模块中导航到Python官方网站,在页面顶部的搜索框中填写搜索词,然后按Enter键转到结果页面。当我不试图嘲弄任何东西时,代码就能完美地工作。假设您已经安装了Selify和Pytest,您可以通过键入以下命令从命令行界面运行它:
py.test full/path/to/module/Selenium_WebDriver_Mocking_test.py

或键入以下内容:

python -m pytest full/path/to/module/Selenium_WebDriver_Mocking_test.py

代码如下所示。

# contents of Selenium_WebDriver_Mocking_test.py

import selenium.webdriver
import selenium.webdriver.common.keys as common
import selenium.webdriver.support.ui as user_interface
import selenium.webdriver.support.expected_conditions as expected_conditions
import selenium.webdriver.common.by as locate
import re
import pytest


browsers = {
    "firefox_driver": selenium.webdriver.Firefox(),
    "chrome_driver": selenium.webdriver.Chrome()
}

website_homepage_url = "http://www.python.org"
title_1 = "Welcome to Python.org"


# Test set-up and tear down functions
@pytest.fixture(scope = 'session', params = browsers.keys())
def browser(request):
    driver = browsers[request.param]
    driver.maximize_window()
    def close_browser():
        driver.quit()
    request.addfinalizer(close_browser)
    return driver


@pytest.mark.parametrize(
    "search_term",
    [
        ("pycon"),
        ("tkinter"),
        ("django"),
    ]
)
def test_mocking_get_request_works_properly(search_term, browser):
    browser.get(website_homepage_url)
    assert title_1 in browser.title                 # Check you are on the right page
    search_text_box = browser.find_element_by_css_selector("#id-search-field")
    search_text_box.send_keys(search_term)
    search_text_box.send_keys(common.Keys.RETURN)
    search_page_title = user_interface.WebDriverWait(browser, 10).until(
            expected_conditions.visibility_of_element_located(
                (locate.By.XPATH, "//h2[contains(., 'Search')]")))
    assert search_page_title.is_displayed()         # Check you are on the right page
然后,我为一个虚假的结果页面编写了一些HTML,并尝试使用由Gabriel Falcao编写的HTTPretty工具将该页面作为响应返回,该响应将出现在浏览器中,而不是真正的Python.org结果页面。修改后的代码如下所示。

# contents of Selenium_WebDriver_Mocking_test.py

import selenium.webdriver
import selenium.webdriver.common.keys as common
import selenium.webdriver.support.ui as user_interface
import selenium.webdriver.support.expected_conditions as expected_conditions
import selenium.webdriver.common.by as locate
import time
import httpretty
import re
import pytest


browsers = {
    "firefox_driver": selenium.webdriver.Firefox(),
    "chrome_driver": selenium.webdriver.Chrome()
}

website_homepage_url = "http://www.python.org"
title_1 = "Welcome to Python.org"

request_url_pattern = re.compile('https://www.python.org/search/.*')
response_html_lines = ["<!DOCTYPE html>",
                       "<html>",
                       "<head>",
                       "<title>Welcome to my fun page</title>",
                       "<meta charset="UTF-8">"
                       "</head>",
                       "<body>",
                       "<h2>Search Python.org</h2>",
                       "<h2>So far so good (^_^)</h2>",
                       "<img src = "http://i.imgur.com/EjcKmEj.gif">",
                       "</body>",
                       "</html>"]
fake_response_html = "
".join(response_html_lines)


# Test set-up and tear down functions
@pytest.fixture(scope = 'session', params = browsers.keys())
def browser(request):
    driver = browsers[request.param]
    driver.maximize_window()
    def close_browser():
        driver.quit()
    request.addfinalizer(close_browser)
    return driver


@pytest.mark.parametrize(
    "search_term",
    [
        ("pycon"),
        ("tkinter"),
        ("django"),
    ]
)
def test_mocking_get_request_works_properly(search_term, browser):
    httpretty.enable()
    httpretty.register_uri(httpretty.GET,
                           request_url_pattern,
                           body = fake_response_html)
    browser.get(website_homepage_url)
    assert title_1 in browser.title                 # Check you are on the right page
    search_text_box = browser.find_element_by_css_selector("#id-search-field")
    search_text_box.send_keys(search_term)
    search_text_box.send_keys(common.Keys.RETURN)
    search_page_title = user_interface.WebDriverWait(browser, 10).until(
            expected_conditions.visibility_of_element_located(
                (locate.By.XPATH, "//h2[contains(., 'Search')]")))
    assert search_page_title.is_displayed()         # Check you are on the right page
    time.sleep(10)
    httpretty.disable()
    httpretty.reset()

该方法不起作用,我在其中一个测试迭代的日志中得到以下消息:

C:Python27python.exe "C:Program Files (x86)JetBrainsPyCharm 

Community Edition 4.0.4helperspycharmpytestrunner.py" -p pytest_teamcity C:/Users/johnsmith/Computer_Code/Python/Automation_Testing/Selenium_WebDriver_Mocking_test.py
Testing started at 10:10 ...
============================= test session starts =============================
platform win32 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.6.4
plugins: xdist
collected 6 items

../../../../../../Users/johnsmith/Computer_Code/Python/Automation_Testing/Selenium_WebDriver_Mocking_test.py F
search_term = 'pycon'
browser = <selenium.webdriver.firefox.webdriver.WebDriver object at 0x0000000002E67EB8>

    @pytest.mark.parametrize(
        "search_term",
        [
            ("pycon"),
            ("tkinter"),
            ("django"),
        ]
    )
    def test_mocking_get_request_works_properly(search_term, browser):
        httpretty.enable()
        httpretty.register_uri(httpretty.GET,
                               request_url_pattern,
                               body = fake_response_html)      
>       browser.get(website_homepage_url)

C:UsersjohnsmithComputer_CodePythonAutomation_TestingSelenium_WebDriver_Mocking_test.py:70: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
C:Python27libsite-packagesseleniumwebdriver
emotewebdriver.py:187: in get
    self.execute(Command.GET, {'url': url})
C:Python27libsite-packagesseleniumwebdriver
emotewebdriver.py:173: in execute
    response = self.command_executor.execute(driver_command, params)
C:Python27libsite-packagesseleniumwebdriver
emote
emote_connection.py:349: in execute
    return self._request(command_info[0], url, body=data)
C:Python27libsite-packagesseleniumwebdriver
emote
emote_connection.py:379: in _request
    self._conn.request(method, parsed_url.path, body, headers)
C:Python27libhttplib.py:973: in request
    self._send_request(method, url, body, headers)
C:Python27libhttplib.py:1007: in _send_request
    self.endheaders(body)
C:Python27libhttplib.py:969: in endheaders
    self._send_output(message_body)
C:Python27libhttplib.py:829: in _send_output
    self.send(msg)
C:Python27libhttplib.py:791: in send
    self.connect()
C:Python27libhttplib.py:772: in connect
    self.timeout, self.source_address)
C:Python27libsite-packageshttprettycore.py:477: in create_fake_connection
    s.connect(address)
C:Python27libsite-packageshttprettycore.py:311: in connect
    self.truesock.connect(self._address)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

name = 'connect', self = <socket._socketobject object at 0x000000000385F9A0>
args = (('127.0.0.1', '49952'),)

    def meth(name,self,*args):
>       return getattr(self._sock,name)(*args)
E       TypeError: an integer is required

C:Python27libsocket.py:224: TypeError

我还尝试使用David Cramer编写的响应工具。虽然这没有返回任何错误,但它也没有做任何事情,测试继续进行,就像没有发生任何嘲弄一样。我的问题是:在Python中,有没有一种方法可以模拟Selify WebDriver发送的请求,并在驱动程序驱动的浏览器实例中显示假的响应体? 如有任何帮助,我们不胜感激。

推荐答案

对于您的情况,您不能使用‘标准’模拟方法,因为您明显干扰了Web驱动程序的通信。 相反,我建议您使用https://pypi.python.org/pypi/pytest-localserver 因此,您实际上在某个随机端口上运行本地服务器,并为您所需的服务器提供服务。 我使用这种技术来测试最小分裂(我也建议您在测试中使用它) 在这里您可以看到它是如何工作的:https://github.com/pytest-dev/pytest-splinter/blob/master/tests/test_plugin.py

如果您将使用最小拆分,您的代码将如下所示:

   """Testing fake html page with pytest-splinter."""
import pytest
from pytest_localserver.http import WSGIServer
import urlparse

browsers = [
    "firefox",
    "chrome"
]

title_1 = "Welcome to my fun page"

response_html = """
    <!DOCTYPE html>
    <html>
    <head>
    <title>Welcome to my fun page</title>
    <meta charset="UTF-8">
    </head>
    <body>
    <h2>Search Python.org</h2>
    <form action="/">
        <input id="id-search-field" name="search" />
    </form>
    </body>
    </html>
    """


def simple_app(environ, start_response):
    """Simplest possible WSGI application."""
    status = '200 OK'
    response_headers = [('Content-type', 'text/html')]
    start_response(status, response_headers)
    query = urlparse.parse_qs(environ['QUERY_STRING'])
    if 'search' in query:
        search_term = query['search'][0]
        return ["""
        <!DOCTYPE html>
        <html>
        <body>
        <h2>So far so good (^_^)</h2>
        <p>You searched for: "{search_term}"</p>
        <img src="http://i.imgur.com/EjcKmEj.gif">
        </body>
        </html>
        """.format(search_term=search_term)]
    else:
        return [response_html]


@pytest.yield_fixture
def testserver():
    """Define the testserver."""
    server = WSGIServer(application=simple_app)
    server.start()
    yield server
    server.stop()


@pytest.fixture(params=browsers)
def splinter_webdriver(request):
    return request.param


@pytest.mark.parametrize(
    "search_term",
    [
        ("pycon"),
        ("tkinter"),
        ("django"),
    ]
)
def test_get_request_works_properly(search_term, browser, testserver):
    browser.visit(testserver.url)
    assert title_1 in browser.title                 # Check you are on the right page
    assert browser.find_by_xpath("//h2[contains(., 'Search')]").visible  # Check you are on the right page
    browser.find_by_css("#id-search-field").fill(search_term + '
')
    assert browser.find_by_xpath(
        """//p[contains(., 'You searched for: "{search_term}"')]""".format(search_term=search_term)).visible
    assert browser.find_by_xpath(
        "//img[contains(@src, 'i.imgur.com/EjcKmEj.gif')]").visible  # Check you get results

我为此使用的要求是:

最热 最火爆的碎片 最热-本地服务器

(全部为最新版本)

这篇关于在Python语言中模拟SeleniumWebDriver发送的请求,并在由驱动程序驱动的浏览器实例中显示假响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在Python语言中模拟SeleniumWebDriver发送的请求,并在由驱动程序驱动的浏览器实例中显示假响应

基础教程推荐