Self hosted FLOSS fitness/workout, nutrition and weight tracker
Abort product downloads on any HTTP error
Roland Geidercfb16bdf018c
diff --git a/wger/nutrition/management/products.py b/wger/nutrition/management/products.pyindex 596eec3a3..9e5b88313 100644--- a/wger/nutrition/management/products.py+++ b/wger/nutrition/management/products.py@@ -174,11 +174,9 @@ class ImportProductCommand(BaseCommand):self.stdout.write(f'Downloading {url}... (this may take a while)')response = requests.get(url, stream=True, headers=wger_headers())+ response.raise_for_status()total_size = int(response.headers.get('content-length', 0))- if response.status_code == 404:- raise Exception(f'Could not open {url}!')-with open(destination, 'wb') as fid:with tqdm(total=total_size, unit='B', unit_scale=True, desc='Downloading') as pbar:for chunk in response.iter_content(chunk_size=50 * 1024):diff --git a/wger/nutrition/tests/test_import_products.py b/wger/nutrition/tests/test_import_products.pyindex 298373858..107f8a971 100644--- a/wger/nutrition/tests/test_import_products.py+++ b/wger/nutrition/tests/test_import_products.py@@ -28,6 +28,7 @@ import requests# wgerfrom wger.core.tests.base_testcase import WgerTestCasefrom wger.nutrition.consts import OFF_FULL_DUMP_URL+from wger.nutrition.management.products import ImportProductCommandfrom wger.nutrition.models import Ingredient@@ -201,3 +202,23 @@ class ImportOffDeltaTestCase(WgerTestCase):with self.assertRaises(requests.HTTPError):self.run_delta_import(response)+++class DownloadFileTestCase(WgerTestCase):+ """+ Tests downloading the product dumps+ """++ def test_error_response_is_not_saved_as_file(self):+ response = mock.Mock(status_code=403, headers={})+ response.iter_content.return_value = [b'<html>403 Forbidden</html>']+ response.raise_for_status.side_effect = requests.HTTPError('403 Forbidden')++ with tempfile.TemporaryDirectory() as folder:+ destination = os.path.join(folder, 'dump.json.gz')++ with mock.patch('requests.get', return_value=response):+ with self.assertRaises(requests.HTTPError):+ ImportProductCommand().download_file('https://example.com/dump', destination)++ self.assertFalse(os.path.exists(destination))