Pytest Http functions

huangapple go评论53阅读模式
英文:

Pytest Http functions

问题

I can help you with the Chinese translation, but it seems like you also want assistance with unit testing your Python code using pytest. Here's the translation of your code:

我想为这段代码编写单元测试使用 pytest你可以帮助我吗

import logging
import json
import azure.functions as func
from azure.cosmos import CosmosClient
import fastapi
import os

app = fastapi.FastAPI()
client = CosmosClient.from_connection_string(os.environ["CosmosDBConnStr"])

database_name = "dmdb"
container_name = "DataContract"

database = client.get_database_client(database_name)
container = database.get_container_client(container_name)


@app.get("/marketplace/{V}")
async def get_data_by_version(V: str):
    logging.info("all data contracts are coming....")
    query = f''' SELECT c.name,c.version, c.Theme, c.title, c.description, udf.tsToDate(c._ts) as updated_at
                FROM c 
                WHERE c.version = '{V}'
                ORDER BY c._ts DESC
                OFFSET 0 LIMIT 20
               '''

    items = list(container.query_items(query, enable_cross_partition_query=True))
    logging.info(f"items: {items}")
    response_body = json.dumps(items)
    return func.HttpResponse(body=response_body, mimetype="application/json")


@app.get("/marketplace/{V}/themes")
async def get_existing_themes_by_version(V: str):
    query = f"SELECT c.Theme FROM c WHERE c.version = '{V}'"
    items = list(container.query_items(query, enable_cross_partition_query=True))
    unique_themes = list(set(item["Theme"] for item in items))
    response_body = json.dumps(unique_themes)
    return func.HttpResponse(body=response_body, mimetype="application/json")


@app.get("/marketplace/{V}/{id}")
async def get_data_by_version_and_id(V: str, id: str):

    query = f"SELECT * FROM c WHERE c.version = '{V}' AND c.id = '{id}'"
    items = list(container.query_items(query, enable_cross_partition_query=True))

    if not items:
        return func.HttpResponse(
            f"No item with version '{V}' and id '{id}' was found",
            status_code=404
        )

    response_body = json.dumps(items[0])
    return func.HttpResponse(body=response_body, mimetype="application/json")


async def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    return await func.AsgiMiddleware(app).handle_async(req, context)

If you have questions about unit testing with pytest or need further assistance with that part, please feel free to ask.

英文:

I would like to make unit test for this code via pytest. could you help me about it.

import logging
import json
import azure.functions as func
from azure.cosmos import CosmosClient
import fastapi
import os
app = fastapi.FastAPI()
client = CosmosClient.from_connection_string(os.environ["CosmosDBConnStr"])
database_name = "dmdb"
container_name = "DataContract"
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)
@app.get("/marketplace/{V}")
async def get_data_by_version(V: str):
logging.info("all data contracts are coming....")
query = f''' SELECT c.name,c.version, c.Theme, c.title, c.description, udf.tsToDate(c._ts) as updated_at
FROM c 
WHERE c.version = '{V}'
ORDER BY c._ts DESC
OFFSET 0 LIMIT 20
'''
items = list(container.query_items(query, enable_cross_partition_query=True))
logging.info(f"items: {items}")
response_body = json.dumps(items)
return func.HttpResponse(body=response_body, mimetype="application/json")
@app.get("/marketplace/{V}/themes")
async def get_existing_themes_by_version(V: str):
query = f"SELECT c.Theme FROM c WHERE c.version = '{V}'"
items = list(container.query_items(query, enable_cross_partition_query=True))
unique_themes = list(set(item["Theme"] for item in items))
response_body = json.dumps(unique_themes)
return func.HttpResponse(body=response_body, mimetype="application/json")
@app.get("/marketplace/{V}/{id}")
async def get_data_by_version_and_id(V: str, id: str):
query = f"SELECT * FROM c WHERE c.version = '{V}' AND c.id = '{id}'"
items = list(container.query_items(query, enable_cross_partition_query=True))
if not items:
return func.HttpResponse(
f"No item with version '{V}' and id '{id}' was found",
status_code=404
)
response_body = json.dumps(items[0])
return func.HttpResponse(body=response_body, mimetype="application/json")
async def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
return await func.AsgiMiddleware(app).handle_async(req, context)

this is my code. how can I make a test with py test. i am getting this answers from the urls:

this is for all summmarize data:

http://localhost:7071/marketplace/V1
{"_HttpResponse__status_code":200,"_HttpResponse__mimetype":"application/json","_HttpResponse__charset":"utf-8","_HttpResponse__headers":{},"_HttpResponse__body":"[{\"name\": \"demo_contrac1\", \"version\": \"V1\", \"Theme\": \"Theme1\", \"title\": \"title1\", \"description\": \"test data contract management2\", \"updated_at\": \"2023-06-02T17:06:44.000Z\"}]"}

this is for themes:

http://localhost:7071/marketplace/V1/themes:
{"_HttpResponse__status_code":200,"_HttpResponse__mimetype":"application/json","_HttpResponse__charset":"utf-8","_HttpResponse__headers":{},"_HttpResponse__body":"[\"Theme1\"]"}

this is for get by id:

http://localhost:7071/marketplace/V1/123:
{"_HttpResponse__status_code":200,"_HttpResponse__mimetype":"application/json","_HttpResponse__charset":"utf-8","_HttpResponse__headers":{},"_HttpResponse__body":"{\"version\": \"V1\", \"name\": \"demo_contrac1\", \"title\": \"title1\", \"Theme\": \"Theme1\", \"description\": \"test data contract management2\", \"data owner\": \"j.jansen@amsterdam.nl\", \"confidentiality\": \"open\", \"table1\": {\"description:\": \"testen\", \"attribute_1\": {\"type\": \"int\", \"description:\": \"testen\", \"identifiability\": \"identifiable\"}}, \"id\": \"f895357f-efe0-4e64-a3b4-868f54e266c1\", \"_rid\": \"R69IAIfCVFQ7AAAAAAAAAA==\", \"_self\": \"dbs/R69IAA==/colls/R69IAIfCVFQ=/docs/R69IAIfCVFQ7AAAAAAAAAA==/\", \"_etag\": \"\\\"00000000-0000-0000-9574-9bf76b6101d9\\\"\", \"_attachments\": \"attachments/\", \"_ts\": 1685725604}"}

i could not manage it. functionaltest is OK . but i stuck at unit test.

答案1

得分: 0

>在提交中使用上面的参考,我尝试了使用Fast Api进行的示例触发器,来源于此SO

def test_read_main(): 
    response = client.get("/")
    assert response.status_code == 200 
    assert response.json() == {"msg": "Hello World"}
import json
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_get_data_by_version():
    response = client.get("/marketplace/V1")
    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/json"
    data = response.json()
    assert len(data) == 1 
    assert data[0]["name"] == "demo_contrac1" 

输出:

Pytest Http functions

  • 获取更多详细信息,请参阅此链接
英文:

>using the above Reference in commits I tried a sample trigger with Fast Api from this SO


def test_read_main(): response = client.get("/")
 assert response.status_code == 200 
 assert response.json() == {"msg": "Hello World"}

import json
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_get_data_by_version():
    response = client.get("/marketplace/V1")
    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/json"
    data = response.json()
    assert len(data) == 1 
    assert data[0]["name"] == "demo_contrac1" 

Output:

Pytest Http functions

  • For more details refer this link.

huangapple
  • 本文由 发表于 2023年6月5日 22:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76407393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定