mimicker
v1.0.0
Mimicker是受Wiremock啟發的Python本地HTTP模擬服務器,旨在簡化用於測試目的的HTTP端點的過程。 Mimicker不需要第三方圖書館,而且輕量級,因此非常適合集成測試,本地開發和CI環境。
模仿者可以使用PIP或POTRY直接從PYPI中安裝:
pip install mimickerpoetry 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方法和路徑定義多個路由。這是GET和POST路線的一個示例:
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 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 get(path) :定義一個GET端點。post(path) :定義一個POST端點。put(path) :定義一個PUT 。delete(path) :定義DELETE端點。.body(content) :定義響應body 。.status(code) :定義響應status code 。.headers(headers) headers Mimicker支持Python 3.7及以上。
Mimicker根據MIT許可發布。有關更多信息,請參見許可證。