Exemple #1
0
def test_ma_fields_patched_required():
    ma_fields = {key: value
                 for key, value in vars(fields).items()
                 if safe_issubclass(value, ma.fields.Field)}
    for key, value in ma_fields.items():
        assert value._rf_patched  # noqa
        if value is fields.Nested:
            # Nested field require to pass positional argument - Schema
            field_obj = value(ma.Schema())
        elif value is fields.List:
            # List field required to pass positional argument - Field
            field_obj = value(fields.Str())
        elif value is fields.Tuple:
            # Tuple field required to pass positional argument - tuple
            field_obj = value(tuple())
        elif value is fields.Constant:
            # Tuple field required to pass positional argument - constant
            field_obj = value(1)
        elif value is fields.Pluck:
            # Pluck field required to pass two positional arguments - Schema and field_name
            field_obj = value(ma.Schema(), field_name="test")
        elif value is fields.Enum:
            # Pluck field required to pass two positional arguments - Schema and field_name
            field_obj = value(enum.Enum)
        else:
            field_obj = value()

        assert field_obj.required, (
            f"`required` default True was not patched for {value.__name__} field"
        )
Exemple #2
0
    def test_default_mimetype_for_non_null_response_schema(self):
        rebar = Rebar()
        registry = rebar.create_handler_registry(default_mimetype="content/type")

        @registry.handles(
            rule="/me", method="DELETE", response_body_schema={204: m.Schema()}
        )
        def delete_me():
            return {}, 204

        app = create_rebar_app(rebar)
        resp = app.test_client().delete(path="/me")

        self.assertEqual(resp.status_code, 204)
        self.assertEqual(resp.data.decode("utf-8"), "")
        self.assertEqual(resp.headers["Content-Type"], "content/type")
    class GET(BaseHandler):
        deserializer_schema = ma.Schema()
        serializer_schema = DashboardSerializer(many=False)
        meta_serializer = DashboardMetaSerializer(many=False)

        def _data(self, request, cleaned, *args, **kwargs):
            data = {
                "aggregations": self._get_aggregations(request.user),
            }
            if 'schedules' in data['aggregations']:
                notifications = request.user.schedule_dashboard_notifications
                data['aggregations']['schedules'].update({
                    'notifications':
                    notifications,
                    'notifications_count':
                    notifications.count(),
                })
            return data

        # @cache_memoize(60 * 2, args_rewrite=lambda self, user: (user.id, ))
        def _get_aggregations(self, user):
            result = {
                'subscriptions': self._get_user_subscriptions(user),
            }
            if user.has_access_to_academy_in_dashboard:
                result.update({'academy': self._get_academy_aggregations()})

            if user.has_access_to_laboratory_in_dashboard:
                result.update({'lab': self._get_laboratory_aggregations()})
            if user.has_access_to_suggestions_in_dashboard:
                result.update(
                    {'suggestions': self._get_suggestions_aggregations()})
            if user.has_access_to_meetings_in_dashboard:
                result.update({'meetings': self._get_meetings_aggregations()})
            schedules_aggregations = Schedule.get_dashboard_aggregations_for(
                user)
            if schedules_aggregations:
                result.update({'schedules': schedules_aggregations})

            result.update(
                {'fav_charts': self._get_fav_charts_aggregations(user)})
            if user.is_superuser:
                result.update({
                    'analytical_tools': self._get_analytical_tools(),
                    'cms_url': settings.CMS_URL
                })
            return result

        @staticmethod
        def _get_user_subscriptions(user: User):
            return {
                "datasets":
                Subscription.objects.filter(
                    user=user,
                    watcher__object_name='datasets.Dataset',
                ).count(),
                "queries":
                user.subscriptions.filter(
                    watcher__object_name='query', ).count(),
            }

        @staticmethod
        def _get_laboratory_aggregations():
            return {
                'analyses':
                LabEvent.objects.filter(event_type='analysis', ).count(),
                'researches':
                LabEvent.objects.filter(event_type='research', ).count(),
            }

        @staticmethod
        def _get_meetings_aggregations():
            today = timezone.now().date()
            objs = Meeting.objects.published()
            return {
                'planned': objs.filter(start_date__gte=today).count(),
                'finished': objs.filter(start_date__lt=today).count(),
            }

        @staticmethod
        def _get_academy_aggregations():
            courses = Course.objects.with_schedule()
            return {
                state: courses.filter(_course_state=state).count()
                for state in Course.COURSE_STATES
            }

        @staticmethod
        def _get_suggestions_aggregations():
            objs = AcceptedDatasetSubmission.objects.filter(
                status__in=AcceptedDatasetSubmission.PUBLISHED_STATUSES)
            return {
                'active': objs.filter(is_active=True).count(),
                'inactive': objs.filter(is_active=False).count(),
            }

        @staticmethod
        def _get_fav_charts_aggregations(user: User):
            _default = {'slot-1': {}, 'slot-2': {}}
            fav_charts = user.fav_charts or {}
            _default.update(fav_charts)
            for key, item in _default.items():
                if item:
                    _default[key][
                        'thumb_url'] = f'{settings.BASE_URL}/pn-apps/charts/{key}.png'

            return _default

        @staticmethod
        def _get_analytical_tools():
            return [{
                'name': 'Kibana',
                'url': settings.KIBANA_URL
            }, {
                'name': 'Metabase',
                'url': settings.METABASE_URL
            }]