Skip to content

Commit

Permalink
fix load_upl command request error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Floris272 committed Dec 11, 2024
1 parent 63b8c98 commit 6c11dc7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
10 changes: 7 additions & 3 deletions src/open_producten/producttypen/management/commands/load_upl.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,13 @@ def _parse_csv_file(self, file: str):
def _parse_csv_url(self, url: str):
_check_if_csv_extension(url)

response = requests.get(url)
if response.status_code != 200:
raise CommandError(f"Url returned status code: {response.status_code}.")
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.ConnectionError:
raise CommandError(f"Could not connect to {url}")
except requests.exceptions.RequestException as e:
raise CommandError(e)

content = StringIO(response.text)
data = csv.DictReader(content)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.test import TestCase

import requests_mock
from requests.exceptions import ConnectionError

from open_producten.producttypen.models import UniformeProductNaam
from open_producten.producttypen.tests.factories import UniformeProductNaamFactory
Expand Down Expand Up @@ -33,19 +34,19 @@ def call_command(self, *args, **kwargs):

def test_call_command_without_file_and_url(self):
with self.assertRaisesMessage(
Exception, "Either --file or --url must be specified."
CommandError, "Either --file or --url must be specified."
):
self.call_command()

def test_call_command_wit_file_and_url(self):
with self.assertRaisesMessage(
Exception, "Only one of --file or --url can be specified."
CommandError, "Only one of --file or --url can be specified."
):
self.call_command("--file", self.path, "--url", "https://example.com")

def test_with_other_file_extension(self):
path = os.path.join(TESTS_DIR, "data/upl.txt")
with self.assertRaisesMessage(Exception, "File format is not csv."):
with self.assertRaisesMessage(CommandError, "File format is not csv."):
self.call_command("--file", path)

def test_with_csv_file(self):
Expand All @@ -70,7 +71,17 @@ def test_with_csv_url_404(self):
url="https://test/upl.csv",
)

with self.assertRaisesMessage(Exception, "Url returned status code: 404"):
with self.assertRaisesMessage(
CommandError, "404 Client Error: None for url: https://test/upl.csv"
):
self.call_command("--url", "https://test/upl.csv")

def test_wih_csv_url_connection_error(self):
self.requests_mock.get(exc=ConnectionError, url="https://test/upl.csv")

with self.assertRaisesMessage(
CommandError, "Could not connect to https://test/upl.csv"
):
self.call_command("--url", "https://test/upl.csv")

def test_parse_csv_url(self):
Expand Down

0 comments on commit 6c11dc7

Please sign in to comment.