Skip to content

Improve Error class #1882

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 2 additions & 9 deletions import_export/resources.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import functools
import inspect
import logging
import traceback
from collections import OrderedDict
from copy import deepcopy
from html import escape
Expand Down Expand Up @@ -678,10 +677,7 @@ def after_init_instance(self, instance, new, row, **kwargs):
def handle_import_error(self, result, error, raise_errors=False):
logger.debug(error, exc_info=error)
if result:
tb_info = traceback.format_exc()
result.append_base_error(
self.get_error_result_class()(error, traceback=tb_info)
)
result.append_base_error(self.get_error_result_class()(error))
if raise_errors:
raise exceptions.ImportError(error)

Expand Down Expand Up @@ -783,11 +779,8 @@ def import_row(self, row, instance_loader, **kwargs):
# when only the original error is likely to be relevant
if not isinstance(e, TransactionManagementError):
logger.debug(e, exc_info=e)
tb_info = traceback.format_exc()
row_result.errors.append(
self.get_error_result_class()(
e, traceback=tb_info, row=row, number=kwargs["row_number"]
)
self.get_error_result_class()(e, row=row, number=kwargs["row_number"])
)

return row_result
Expand Down
25 changes: 23 additions & 2 deletions import_export/results.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
import logging
import sys
import traceback
from collections import OrderedDict

from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.encoding import force_str
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from tablib import Dataset

logger = logging.getLogger(__name__)


class Error:
def __init__(self, error, traceback=None, row=None, number=None):
def __init__(self, error, row=None, number=None):
self.error = error
self.traceback = traceback
self.row = row
self.number = number

def __repr__(self):
result = f"<Error: {self.error!r}"
if self.row is not None:
result += f" at row {self.row}"
if self.number is not None:
result += f" at number {self.number}"
result += ">"
return result

@cached_property
def traceback(self):
if sys.version_info >= (3, 10):
lines = traceback.format_exception(self.error)
else:
lines = traceback.format_exception(
None, self.error, self.error.__traceback__
)
return "".join(lines)


class RowResult:
"""Container for values relating to a row import."""
Expand Down
1 change: 1 addition & 0 deletions tests/core/tests/admin_integration/test_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,7 @@ def test_result_error_display_traceback_only(self):
self.assertNotIn("import-error-display-message", content)
self.assertNotIn("import-error-display-row", content)
self.assertIn("import-error-display-traceback", content)
self.assertIn("Traceback (most recent call last)", content)


class ConfirmImportEncodingTest(AdminTestMixin, TestCase):
Expand Down
39 changes: 37 additions & 2 deletions tests/core/tests/test_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,48 @@

from core.models import Book
from django.core.exceptions import ValidationError
from django.test.testcases import TestCase
from django.test import SimpleTestCase
from tablib import Dataset

from import_export.results import Error, Result, RowResult


class ResultTest(TestCase):
class ErrorTest(SimpleTestCase):
def test_repr_no_details(self):
try:
1 / 0
except Exception as exc:
error = Error(exc)

self.assertEqual(repr(error), "<Error: ZeroDivisionError('division by zero')>")

def test_repr_all_details(self):
try:
1 / 0
except Exception as exc:
error = Error(exc, row=1, number=2)

self.assertEqual(
repr(error),
"<Error: ZeroDivisionError('division by zero') at row 1 at number 2>",
)

def test_traceback(self):
try:
1 / 0
except Exception as exc:
error = Error(exc)

self.assertTrue(
error.traceback.startswith("Traceback (most recent call last):\n")
)
self.assertIn(
"ZeroDivisionError: division by zero\n",
error.traceback,
)


class ResultTest(SimpleTestCase):
def setUp(self):
self.result = Result()
headers = ["id", "book_name"]
Expand Down
Loading