使用pytest进行单元测试URLs。

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

Unit tests urls with pytest

问题

You can handle the "MissingSchema" error by specifying the complete URL, including the scheme (e.g., http or https) when using it in your requests. In your case, you want to use relative URLs like "/marketplace", "/marketplace/themes", and "/marketplace/2" instead of absolute URLs.

To do this, you can define a base URL and then append the relative paths to it when making requests. Here's an example of how you can modify your code to handle this:

base_url = "http://localhost:7071"

def test_get_all_data():
    url = f"{base_url}/marketplace"
    # Rest of your code...

def test_get_existing_themes():
    url = f"{base_url}/marketplace/themes"
    # Rest of your code...

def test_get_data_by_id():
    url = f"{base_url}/marketplace/2"
    # Rest of your code...

By using f-strings or string concatenation, you can construct the complete URLs with the base URL and the relative paths, which should resolve the "MissingSchema" error.

英文:

I have this code:

import azure.functions as func
import sys
from fastapi.testclient import TestClient
import unittest
import pytest
import azure.functions as func
import os
from azure.cosmos import CosmosClient
import requests
import json
database_name = os.environ["cosmosDatabase"]
container_name = os.environ["cosmosColl"]
client = CosmosClient.from_connection_string(os.environ["CosmosDBConnStr"])
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)
dummy_data = {
"Name": "abc",
"Version": "V1",
"Maturity Level": "2",
"Description": "De eisvoorzorgsmaatregelen tabel in onderdeel van de KLIC dataset. Deze tabel geeft een overzicht van de eisvoorzorgsmaatregelen binnen een bepaald vlak (geometrie). De KLIC dataset is voor medewerkers van de gemeente Amsterdam en bedoeld om inzicht te geven in waar welke de kabels en leidingen in de gemeente Amsterdam liggen en van wie ze zijn. Als uitvoerder (in de wet genoemd ‘grondroerder’) ben je wettelijk verplicht vooraf een KLIC-melding te doen, het gebruik van deze dataset vervangt deze plicht niet.",
"Business goal": "",
"Theme": "Bouwen",
"Collection": "Ondergrond",
"Data Team": "Stedelijke Ontwikkeling en Beheer (SOEB)",
"Data Product Owner": "Maayke Mars",
"Data Steward": "",
"Language": "Nederland",
"Confidentiality": "Confidential",
"BIO Quickscan": "Done",
"Privacy": "Niet persoonlijk identificeerbaar",
"Privacy Quickscan": "Done",
"Geo Data": "",
"History Start": "",
"Refresh Rate": "",
"End Date": "",
"Schema": {
"Tables": {
"name": "klicEisvoorzorgsmaatregelen",
"attributes": {
"id": {
"type": "integer",
"description": "Unieke id van het object"
},
"schema": {
"$ref": "https://schemas.data.amsterdam.nl/schema@v1.1.1#/definitions/schema"
},
"thema": {
"type": "string",
"description": "Thema of discipline waar eisvoorzorgsmaatregel toe behoort"
},
"class": {
"type": "string",
"description": "ID van cluster (niet uniek)"
},
"broncode": {
"type": "string",
"description": "Broncode van de beheerder."
},
"beheerder": {
"type": "string",
"description": "Naam van geclusturde plannen"
},
"evNet": {
"type": "string",
"description": "De naam van het eisvoorzorgnetwerk"
},
"bestand": {
"type": "string",
"description": "De naam van het meegeleverde PDF bestand die gekoppeld is aan de geometrie"
},
"opvraagdatum": {
"type": "string",
"format": "date-time",
"description": "De datum en het tijdstip waarop het Klic orientatieverzoek is uitgevoerd waarmee de gegevens zijn opgevraagd."
},
"geometrie": {
"$ref": "https://geojson.org/schema/Polygon.json",
"description": "Geometrie in RD (epsg:28992)"
},
"rgbHexPmkl": {
"type": "string",
"description": "Hex kleurcode volgens PMKL standaard"
},
"rgbHexNlcs": {
"type": "string",
"description": "Hex kleurcode volgens NLCS standaard"
},
"laagnaam1": {
"type": "string",
"description": "STATUS-DISCIPLINE"
},
"laagnaam2": {
"type": "string",
"description": "HOOFDGROEP-OBJECT"
},
"laagnaam3": {
"type": "string",
"description": "SUBOBJECT1"
},
"laagnaam4": {
"type": "string",
"description": "ELEMENT"
},
"laagnaam5": {
"type": "string",
"description": "Aanvulling van STATUS attribuut"
},
"nlcsCodering": {
"type": "string",
"description": "Nederlandse CAD Standaard"
}
}
}
},
"Creation Date": 1686130035,
"id": "2"
}
container.create_item(body=dummy_data)
def test_get_all_data():
url = "http://localhost:7071/marketplace"
resp = requests.get(url)
resp_body = resp.json()
if "documents" in resp_body:
documents = resp_body["_HttpResponse__body"]
documents_data = json.loads(documents)
name = documents_data[0].get("Name")
assert name == "abc"
assert resp.status_code ==200 
def test_get_existing_themes():
dummy_data = {
"Name": "abc",
"Version": "V1",
"Maturity Level": "2",
"Description": "De eisvoorzorgsmaatregelen tabel in onderdeel van de KLIC dataset. Deze tabel geeft een overzicht van de eisvoorzorgsmaatregelen binnen een bepaald vlak (geometrie). De KLIC dataset is voor medewerkers van de gemeente Amsterdam en bedoeld om inzicht te geven in waar welke de kabels en leidingen in de gemeente Amsterdam liggen en van wie ze zijn. Als uitvoerder (in de wet genoemd ‘grondroerder’) ben je wettelijk verplicht vooraf een KLIC-melding te doen, het gebruik van deze dataset vervangt deze plicht niet.",
"Business goal": "",
"Theme": "Verkeer",
"Collection": "Ondergrond",
"Data Team": "Stedelijke Ontwikkeling en Beheer (SOEB)",
"Data Product Owner": "Maayke Mars",
"Data Steward": "",
"Language": "Nederland",
"Confidentiality": "Confidential",
"BIO Quickscan": "Done",
"Privacy": "Niet persoonlijk identificeerbaar",
"Privacy Quickscan": "Done",
"Geo Data": "",
"History Start": "",
"Refresh Rate": "",
"End Date": "",
"Schema": {
"Tables": {
"name": "klicEisvoorzorgsmaatregelen",
"attributes": {
"id": {
"type": "integer",
"description": "Unieke id van het object"
},
"schema": {
"$ref": "https://schemas.data.amsterdam.nl/schema@v1.1.1#/definitions/schema"
},
"thema": {
"type": "string",
"description": "Thema of discipline waar eisvoorzorgsmaatregel toe behoort"
},
"class": {
"type": "string",
"description": "ID van cluster (niet uniek)"
},
"broncode": {
"type": "string",
"description": "Broncode van de beheerder."
},
"beheerder": {
"type": "string",
"description": "Naam van geclusturde plannen"
},
"evNet": {
"type": "string",
"description": "De naam van het eisvoorzorgnetwerk"
},
"bestand": {
"type": "string",
"description": "De naam van het meegeleverde PDF bestand die gekoppeld is aan de geometrie"
},
"opvraagdatum": {
"type": "string",
"format": "date-time",
"description": "De datum en het tijdstip waarop het Klic orientatieverzoek is uitgevoerd waarmee de gegevens zijn opgevraagd."
},
"geometrie": {
"$ref": "https://geojson.org/schema/Polygon.json",
"description": "Geometrie in RD (epsg:28992)"
},
"rgbHexPmkl": {
"type": "string",
"description": "Hex kleurcode volgens PMKL standaard"
},
"rgbHexNlcs": {
"type": "string",
"description": "Hex kleurcode volgens NLCS standaard"
},
"laagnaam1": {
"type": "string",
"description": "STATUS-DISCIPLINE"
},
"laagnaam2": {
"type": "string",
"description": "HOOFDGROEP-OBJECT"
},
"laagnaam3": {
"type": "string",
"description": "SUBOBJECT1"
},
"laagnaam4": {
"type": "string",
"description": "ELEMENT"
},
"laagnaam5": {
"type": "string",
"description": "Aanvulling van STATUS attribuut"
},
"nlcsCodering": {
"type": "string",
"description": "Nederlandse CAD Standaard"
}
}
}
},
"Creation Date": 1686130035,
"id": "2"
}
container.create_item(body=dummy_data)
url = "http://localhost:7071/marketplace/themes"
resp = requests.get(url)
resp_body = resp.json()
themes = resp_body["_HttpResponse__body"]
themes_data = json.loads(themes)
assert "Verkeer" in themes_data
assert resp.status_code ==200
container.delete_item(item= "2", partition_key='abc')  # Assuming '2' is the value of the item's 'id' property
def test_get_data_by_id():
dummy_data = {
"Name": "abc",
"Version": "V1",
"Maturity Level": "2",
"Description": "De eisvoorzorgsmaatregelen tabel in onderdeel van de KLIC dataset. Deze tabel geeft een overzicht van de eisvoorzorgsmaatregelen binnen een bepaald vlak (geometrie). De KLIC dataset is voor medewerkers van de gemeente Amsterdam en bedoeld om inzicht te geven in waar welke de kabels en leidingen in de gemeente Amsterdam liggen en van wie ze zijn. Als uitvoerder (in de wet genoemd ‘grondroerder’) ben je wettelijk verplicht vooraf een KLIC-melding te doen, het gebruik van deze dataset vervangt deze plicht niet.",
"Business goal": "",
"Theme": "Bouwen",
"Collection": "Ondergrond",
"Data Team": "Stedelijke Ontwikkeling en Beheer (SOEB)",
"Data Product Owner": "Maayke Mars",
"Data Steward": "",
"Language": "Nederland",
"Confidentiality": "Confidential",
"BIO Quickscan": "Done",
"Privacy": "Niet persoonlijk identificeerbaar",
"Privacy Quickscan": "Done",
"Geo Data": "",
"History Start": "",
"Refresh Rate": "",
"End Date": "",
"Schema": {
"Tables": {
"name": "klicEisvoorzorgsmaatregelen",
"attributes": {
"id": {
"type": "integer",
"description": "Unieke id van het object"
},
"schema": {
"$ref": "https://schemas.data.amsterdam.nl/schema@v1.1.1#/definitions/schema"
},
"thema": {
"type": "string",
"description": "Thema of discipline waar eisvoorzorgsmaatregel toe behoort"
},
"class": {
"type": "string",
"description": "ID van cluster (niet uniek)"
},
"broncode": {
"type": "string",
"description": "Broncode van de beheerder."
},
"beheerder": {
"type": "string",
"description": "Naam van geclusturde plannen"
},
"evNet": {
"type": "string",
"description": "De naam van het eisvoorzorgnetwerk"
},
"bestand": {
"type": "string",
"description": "De naam van het meegeleverde PDF bestand die gekoppeld is aan de geometrie"
},
"opvraagdatum": {
"type": "string",
"format": "date-time",
"description": "De datum en het tijdstip waarop het Klic orientatieverzoek is uitgevoerd waarmee de gegevens zijn opgevraagd."
},
"geometrie": {
"$ref": "https://geojson.org/schema/Polygon.json",
"description": "Geometrie in RD (epsg:28992)"
},
"rgbHexPmkl": {
"type": "string",
"description": "Hex kleurcode volgens PMKL standaard"
},
"rgbHexNlcs": {
"type": "string",
"description": "Hex kleurcode volgens NLCS standaard"
},
"laagnaam1": {
"type": "string",
"description": "STATUS-DISCIPLINE"
},
"laagnaam2": {
"type": "string",
"description": "HOOFDGROEP-OBJECT"
},
"laagnaam3": {
"type": "string",
"description": "SUBOBJECT1"
},
"laagnaam4": {
"type": "string",
"description": "ELEMENT"
},
"laagnaam5": {
"type": "string",
"description": "Aanvulling van STATUS attribuut"
},
"nlcsCodering": {
"type": "string",
"description": "Nederlandse CAD Standaard"
}
}
}
},
"Creation Date": 1686130035,
"id": "2"
}
container.create_item(body=dummy_data)
url = "http://localhost:7071/marketplace/2"
resp = requests.get(url)
resp_body = resp.json()
document = json.loads(resp_body["_HttpResponse__body"])
name = document["Name"]
assert name == "abc"
assert resp.status_code == 200
container.delete_item(item= "2", partition_key='abc')  # Assuming '2' is the value of the item's 'id' property
container.delete_item(item= "2", partition_key='abc')  # Assuming '2' is the value of the item's 'id' property

Here, I would like to use my URLs as "/marketplace", "/marketplace/themes", "/marketplace/2" instead of these "http://localhost:7071/marketplace", "http://localhost:7071/marketplace/themes", "http://localhost:7071/marketplace/2". But when I do that I am getting the error: requests.exceptions.MissingSchema: Invalid URL '/marketplace': No scheme supplied. Perhaps you meant https:///marketplace?

How can I handle this error?

答案1

得分: 0

Unit tests urls with pytest

将使用 pytest 单元测试 URL。

使用此解析URL

from urllib.parse import urljoin
base_url = "http://localhost:7071"
endpoints = ["/marketplace", "/marketplace/themes", "/marketplace/2"]
for endpoint in endpoints:
    full_url = urljoin(base_url, endpoint)
    print(f"GET request to: {full_url}")
    print("Hello, World!")
    print()

Unit test case:

from urllib.parse import urljoin
import pytest
def generate_url(base_url, endpoint):
    return urljoin(base_url, endpoint)
def test_urls():
    base_url = "http://localhost:7071"
    endpoints = [
        ("/marketplace", "http://localhost:7071/marketplace"),
        ("/marketplace/themes", "http://localhost:7071/marketplace/themes"),
        ("/marketplace/2", "http://localhost:7071/marketplace/2")
    ]
    for endpoint, expected_url in endpoints:
        generated_url = generate_url(base_url, endpoint)
        assert generated_url == expected_url

Output:

使用pytest进行单元测试URLs。

英文:

Unit tests urls with pytest

will Give sample reference how to unit with URL.

> Used this Parse URLs .

from  urllib.parse  import  urljoin
base_url = "http://localhost:7071"
endpoints = ["/marketplace",  "/marketplace/themes",  "/marketplace/2"]
for  endpoint  in  endpoints:
full_url = urljoin(base_url,  endpoint)
print(f"GET request to: {full_url}")
print("Hello, World!")
print()

Unit test case:

from  urllib.parse  import  urljoin
import  pytest
def  generate_url(base_url,  endpoint):

return  urljoin(base_url,  endpoint)
def  test_urls():
base_url = "http://localhost:7071"
endpoints = [
("/marketplace",  "http://localhost:7071/marketplace"),

("/marketplace/themes",  "http://localhost:7071/marketplace/themes"),

("/marketplace/2",  "http://localhost:7071/marketplace/2")

]
for  endpoint,  expected_url  in  endpoints:
generated_url = generate_url(base_url,  endpoint)
assert  generated_url == expected_url

Output:

使用pytest进行单元测试URLs。

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

发表评论

匿名网友

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

确定