Skip to content

Commit

Permalink
Switch from requests to httpx
Browse files Browse the repository at this point in the history
And from respones to pytest-httpx.
  • Loading branch information
jodal committed Nov 15, 2023
1 parent 4328ed8 commit 66ea1c9
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 51 deletions.
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ classifiers = [
[tool.poetry.dependencies]
python = ">= 3.8.0"
attrs = ">= 22.2"
requests = ">= 2.28.1"
httpx = ">= 0.24"

[tool.poetry.group.dev.dependencies]
nox = "^2023.4.22"
Expand All @@ -41,7 +41,7 @@ ruff = "^0.1.4"
coverage = { extras = ["toml"], version = "^7.3.2" }
pytest = "^7.4.2"
pytest-cov = "^4.1.0"
responses = "^0.24.0"
pytest-httpx = "0.22.0"

[tool.poetry.group.typing.dependencies]
types-requests = "^2.31.0.10"
Expand Down
4 changes: 2 additions & 2 deletions src/brreg/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ def __init__(
*,
method: Optional[str],
url: Optional[str],
status: Optional[int],
status_code: Optional[int],
) -> None:
super().__init__(f"REST API exception: {msg}")
self.method = method
self.url = url
self.status = status
self.status_code = status_code
11 changes: 6 additions & 5 deletions src/brreg/enhetsregisteret/_client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Optional

import requests
import httpx

from brreg import BrregError, BrregRestError

Expand All @@ -18,21 +18,22 @@ def get_enhet(organisasjonsnummer: str) -> Optional[Enhet]:
Raises :class:`BrregRestException` if a REST exception occures
Raises :class:`BrregException` if an unhandled exception occures
"""
res: Optional[httpx.Response] = None
try:
res = requests.get(f"{BASE_URL}/enheter/{organisasjonsnummer}")
res = httpx.get(f"{BASE_URL}/enheter/{organisasjonsnummer}")

if res.status_code in (404, 410):
return None

res.raise_for_status()

return Enhet.from_json(res.json())
except requests.RequestException as exc:
except httpx.HTTPError as exc:
raise BrregRestError(
str(exc),
method=(exc.request.method if exc.request else None),
url=(exc.request.url if exc.request else None),
status=getattr(exc.response, "status_code", None),
url=(str(exc.request.url) if exc.request else None),
status_code=(res.status_code if res else None),
) from exc
except Exception as exc:
raise BrregError(exc) from exc
97 changes: 55 additions & 42 deletions tests/test_enhetsregisteret.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
from datetime import date

import httpx
import pytest
import responses
from pytest_httpx import HTTPXMock

from brreg import BrregRestError, enhetsregisteret


@responses.activate
def test_get_enhet(organization_details_response: bytes) -> None:
responses.add(
responses.GET,
"https://data.brreg.no/enhetsregisteret/api/enheter/818511752",
body=organization_details_response,
status=200,
content_type="application/json",
def test_get_enhet(
httpx_mock: HTTPXMock,
organization_details_response: bytes,
) -> None:
httpx_mock.add_response( # pyright: ignore[reportUnknownMemberType]
method="GET",
url="https://data.brreg.no/enhetsregisteret/api/enheter/818511752",
status_code=200,
headers={"content-type": "application/json"},
content=organization_details_response,
)

org = enhetsregisteret.get_enhet("818511752")
Expand Down Expand Up @@ -50,14 +53,16 @@ def test_get_enhet(organization_details_response: bytes) -> None:
assert org.slettedato is None


@responses.activate
def test_get_enhet_when_deleted(deleted_organization_details_response: bytes) -> None:
responses.add(
responses.GET,
"https://data.brreg.no/enhetsregisteret/api/enheter/815597222",
body=deleted_organization_details_response,
status=200,
content_type="application/json",
def test_get_enhet_when_deleted(
httpx_mock: HTTPXMock,
deleted_organization_details_response: bytes,
) -> None:
httpx_mock.add_response( # pyright: ignore[reportUnknownMemberType]
method="GET",
url="https://data.brreg.no/enhetsregisteret/api/enheter/815597222",
status_code=200,
headers={"content-type": "application/json"},
content=deleted_organization_details_response,
)

org = enhetsregisteret.get_enhet("815597222")
Expand All @@ -71,41 +76,44 @@ def test_get_enhet_when_deleted(deleted_organization_details_response: bytes) ->
assert org.slettedato == date(2017, 10, 20)


@responses.activate
def test_get_enhet_when_gone() -> None:
responses.add(
responses.GET,
"https://data.brreg.no/enhetsregisteret/api/enheter/818511752",
status=410,
content_type="application/json",
def test_get_enhet_when_gone(
httpx_mock: HTTPXMock,
) -> None:
httpx_mock.add_response( # pyright: ignore[reportUnknownMemberType]
method="GET",
url="https://data.brreg.no/enhetsregisteret/api/enheter/818511752",
status_code=410,
headers={"content-type": "application/json"},
)

org = enhetsregisteret.get_enhet("818511752")

assert org is None


@responses.activate
def test_get_enhet_when_not_found() -> None:
responses.add(
responses.GET,
"https://data.brreg.no/enhetsregisteret/api/enheter/818511752",
status=404,
content_type="application/json",
def test_get_enhet_when_not_found(
httpx_mock: HTTPXMock,
) -> None:
httpx_mock.add_response( # pyright: ignore[reportUnknownMemberType]
method="GET",
url="https://data.brreg.no/enhetsregisteret/api/enheter/818511752",
status_code=404,
headers={"content-type": "application/json"},
)

org = enhetsregisteret.get_enhet("818511752")

assert org is None


@responses.activate
def test_get_enhet_when_http_error() -> None:
responses.add(
responses.GET,
"https://data.brreg.no/enhetsregisteret/api/enheter/818511752",
status=400,
content_type="application/json",
def test_get_enhet_when_http_error(
httpx_mock: HTTPXMock,
) -> None:
httpx_mock.add_response( # pyright: ignore[reportUnknownMemberType]
method="GET",
url="https://data.brreg.no/enhetsregisteret/api/enheter/818511752",
status_code=400,
headers={"content-type": "application/json"},
)

with pytest.raises(BrregRestError) as exc_info:
Expand All @@ -119,11 +127,16 @@ def test_get_enhet_when_http_error() -> None:
exc_info.value.url
== "https://data.brreg.no/enhetsregisteret/api/enheter/818511752"
)
assert exc_info.value.status == 400
assert exc_info.value.status_code == 400


@responses.activate
def test_get_organization_by_number_when_http_timeout() -> None:
def test_get_organization_by_number_when_http_timeout(
httpx_mock: HTTPXMock,
) -> None:
httpx_mock.add_exception( # pyright: ignore[reportUnknownMemberType]
httpx.ConnectTimeout("Connection refused"),
)

with pytest.raises(BrregRestError) as exc_info:
enhetsregisteret.get_enhet("818511752")

Expand All @@ -135,4 +148,4 @@ def test_get_organization_by_number_when_http_timeout() -> None:
exc_info.value.url
== "https://data.brreg.no/enhetsregisteret/api/enheter/818511752"
)
assert exc_info.value.status is None
assert exc_info.value.status_code is None

0 comments on commit 66ea1c9

Please sign in to comment.