使用Mocked REST API测试环境

Baz*_*Baz 8 python rest

假设我有一个非常简单的网络应用程序,如果现任总统是民主党人,则呈现为蓝色,如果他们是共和党人,则呈现红色.REST API用于通过端点获取当前的总裁:

/presidents/current
Run Code Online (Sandbox Code Playgroud)

它当前返回json对象:

{name: "Donald Trump", party: "Republican"}
Run Code Online (Sandbox Code Playgroud)

因此,当我的页面加载时,我会调用端点,并根据返回的人显示红色或蓝色.

我希望测试这个HTML/javascript页面,我希望模拟后端,以便我可以在测试环境中控制API响应.例如:

def test_republican():
    # configure the response for this test that the web app will receive when it connects to this endpoint
    configure_endpoint(
        "/presidents/current", 
        jsonify(
            name="Donald Trump",
            party="Republican"
        )
    )  

    # start the web app in the browser using selenium 
    load_web_app(driver, "http://localhost:8080")  

    e = driver.find_element_by_name("background")
    assert(e.getCssValue("background-color") == "red")


def test_democrat():
    # configure the response for this test that the web app will receive when it connects to this endpoint
    configure_endpoint(
        "/presidents/current", 
        jsonify(
            name="Barack Obama",
            party="Democrat"
        )
    )    

    # start the web app in the browser using selenium 
    load_web_app(driver, "http://localhost:8080")  

    e = driver.find_element_by_name("background")
    assert(e.getCssValue("background-color") == "blue")
Run Code Online (Sandbox Code Playgroud)

所以问题是我应该如何实现函数configure_endpoint()以及你能推荐我的库?

das*_*s-g 1

如果您的load_web_app函数使用该requests访问 REST API,则使用requests-mock是一种伪造该库的功能以进行测试的便捷方法。