首页>编程相关>其他源码

Mimicker是受Wiremock启发的Python本地HTTP模拟服务器,旨在简化用于测试目的的HTTP端点的过程。 Mimicker不需要第三方图书馆,而且轻量级,因此非常适合集成测试,本地开发和CI环境。

特征

安装

模仿者可以使用PIP或POTRY直接从PYPI中安装:

使用PIP:

pip install mimicker

使用诗歌:

poetry add mimicker

用法

要启动具有简单端点的特定端口模拟器,您可以使用以下代码段:

 from mimicker . mimicker import mimicker , get

mimicker ( 8080 ). routes (
    get ( "/hello" ).
    body ({ "message" : "Hello, World!" }).
    status ( 200 )
)

例子

使用路径参数

模拟器可以动态处理路径参数。这是您可以用路径中的变量模拟端点的方法:

 from mimicker . mimicker import mimicker , get

mimicker ( 8080 ). routes (
    get ( "/hello/{name}" )
    . body ({ "message" : "Hello, {name}!" })
    . status ( 200 )
)

# When the client sends a request to /hello/world, the response will be:
# {"message": "Hello, world!"} 

使用标题

您也可以使用自定义标头模拟响应:

 from mimicker . mimicker import mimicker , get

mimicker ( 8080 ). routes (
    get ( "/hello" )
    . body ( "Hello with headers" )
    . headers ([( "Content-Type" , "text/plain" ), ( "Custom-Header" , "Value" )])
    . status ( 200 )
)

# The response will include custom headers 

多个路线

Mimicker允许您为不同的HTTP方法和路径定义多个路由。这是GETPOST路线的一个示例:

 from mimicker . mimicker import mimicker , get , post

mimicker ( 8080 ). routes (
    get ( "/greet" )
    . body ({ "message" : "Hello, world!" })
    . status ( 200 ),

    post ( "/submit" )
    . body ({ "result" : "Submission received" })
    . status ( 201 )
)

# Now the server responds to:
# GET /greet -> {"message": "Hello, world!"}
# POST /submit -> {"result": "Submission received"} 

处理不同的状态代码

您也可以为同一端点模拟不同的HTTP状态代码:

 from mimicker . mimicker import mimicker , get

mimicker ( 8080 ). routes (
    get ( "/status" )
    . body ({ "message" : "Success" })
    . status ( 200 ),

    get ( "/error" )
    . body ({ "message" : "Not Found" })
    . status ( 404 )
)

# GET /status -> {"message": "Success"} with status 200
# GET /error -> {"message": "Not Found"} with status 404 

与JSON身体嘲笑反应

Mimicker支持JSON机构,使其非常适合API测试:

 from mimicker . mimicker import mimicker , get

mimicker ( 8080 ). routes (
    get ( "/json" )
    . body ({ "message" : "Hello, JSON!" })
    . status ( 200 )
)

# The response will be: {"message": "Hello, JSON!"} 

支持其他身体类型(文本,文件等)

除JSON身体外,Mimicker还支持响应体的其他类型的内容。这是您可以返回文本或文件内容的方式:

文本响应:
 from mimicker . mimicker import mimicker , get

mimicker ( 8080 ). routes (
    get ( "/text" )
    . body ( "This is a plain text response" )
    . status ( 200 )
)

# The response will be plain text: "This is a plain text response" 

文件响应:

您还可以从模拟端点返回文件:

 from mimicker . mimicker import mimicker , get

mimicker ( 8080 ). routes (
    get ( "/file" )
    . body ( open ( "example.txt" , "rb" ). read ())  # Mock a file response
    . status ( 200 )
)

# The response will be the content of the "example.txt" file 

可用功能:

要求

Mimicker支持Python 3.7及以上。

执照

Mimicker根据MIT许可发布。有关更多信息,请参见许可证。

展开
附加信息