Skip to content

Commit

Permalink
consolidate duplicate warnings/add error #28
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Apr 28, 2020
1 parent 60625c4 commit af6bb44
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 13 deletions.
8 changes: 4 additions & 4 deletions drf_spectacular/management/commands/spectacular.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ def handle(self, *args, **options):
generator = generator_class(urlconf=options['urlconf'])
schema = generator.get_schema(request=None, public=True)

if options['fail_on_warn'] and GENERATOR_STATS.warn_counter:
raise RuntimeError(
f'Failing as requested due to {GENERATOR_STATS.warn_counter} warnings'
)
GENERATOR_STATS.emit_summary()

if options['fail_on_warn'] and GENERATOR_STATS:
raise RuntimeError(f'Failing as requested due to warnings')
if options['validate']:
validate_schema(schema)

Expand Down
10 changes: 5 additions & 5 deletions drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from drf_spectacular.plumbing import (
build_basic_type, warn, anyisinstance, force_instance, is_serializer,
follow_field_source, is_field, is_basic_type, build_array_type,
ComponentRegistry, ResolvedComponent, build_parameter_type
ComponentRegistry, ResolvedComponent, build_parameter_type, error,
)
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
Expand Down Expand Up @@ -365,7 +365,7 @@ def _map_model_field(self, field):
elif isinstance(field, models.ForeignKey):
return self._map_model_field(field.target_field)
else:
warn(
error(
f'could not resolve model field "{field}" due to missing mapping.'
'either your field is custom and not based on a known subclasses '
'or we missed something. let us know.'
Expand Down Expand Up @@ -671,15 +671,15 @@ def _get_serializer(self):
elif hasattr(view, 'serializer_class'):
return view.serializer_class
else:
warn(
error(
f'Unable to guess serializer for {view.__class__.__name__}. This is graceful '
f'fallback handling for APIViews. Consider using GenericAPIView as view base '
f'class, if view is under your control. ignoring view for now. '
)
else:
warn('Encountered unknown view base class. please report this issue. ignoring for now')
error('Encountered unknown view base class. please report this issue. ignoring for now')
except Exception as exc:
warn(
error(
f'Exception raised while getting serializer from {view.__class__.__name__}. Hint: '
f'Is get_serializer_class() returning None or is get_queryset() not working without '
f'a request? Ignoring the view for now. (Exception: {exc})'
Expand Down
36 changes: 32 additions & 4 deletions drf_spectacular/plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,47 @@


class GeneratorStats:
warn_counter = 0
_warn_cache = defaultdict(int)
_error_cache = defaultdict(int)

def __bool__(self):
return bool(self._warn_cache or self._error_cache)

def reset(self):
self._warn_cache.clear()
self._error_cache.clear()

def emit(self, msg, severity):
assert severity in ['warning', 'error']
msg = str(msg)
cache = self._warn_cache if severity == 'warning' else self._error_cache
if msg not in cache:
print(f'{severity.capitalize()} #{len(cache)}: {msg}', file=sys.stderr)
cache[msg] += 1

def emit_summary(self):
if self._warn_cache or self._error_cache:
print(
f'\nSchema generation summary:\n'
f'Warnings: {sum(self._warn_cache.values())} ({len(self._warn_cache)} unique)\n'
f'Errors: {sum(self._error_cache.values())} ({len(self._error_cache)} unique)\n',
file=sys.stderr
)


GENERATOR_STATS = GeneratorStats()


def warn(msg):
GENERATOR_STATS.warn_counter += 1
print(f'WARNING #{GENERATOR_STATS.warn_counter}: {msg}', file=sys.stderr)
GENERATOR_STATS.emit(msg, 'warning')


def error(msg):
GENERATOR_STATS.emit(msg, 'error')


def reset_generator_stats():
GENERATOR_STATS.warn_counter = 0
GENERATOR_STATS.reset()


def anyisinstance(obj, type_list):
Expand Down

0 comments on commit af6bb44

Please sign in to comment.