Example #1
0
 def test_camel_to_under_input_untouched_for_sequence(self):
     data = [
         {'firstInput': 1},
         {'secondInput': 2},
     ]
     reference_input = deepcopy(data)
     camelize(data)
     self.assertEqual(data, reference_input)
Example #2
0
    async def test_subscribe_list(self):
        payload = {
            "type": "subscribe",
            "id": 1,
            "action": "list",
            "model": "ohq.Announcement",
            "view_kwargs": {
                "course_pk": self.course.id
            },
        }
        await self.client.send_json_to(payload)
        self.assertTrue(await self.client.receive_nothing())

        new_announcement = await db(Announcement.objects.create
                                    )(course=self.course,
                                      author=self.professor,
                                      content="New announcement")
        response = await self.client.receive_json_from()
        expected = {
            "type": "broadcast",
            "id": 1,
            "model": "ohq.Announcement",
            "instance":
            camelize(AnnouncementSerializer(new_announcement).data),
            "action": "CREATED",
        }
        self.assertEqual(expected, response)

        new_announcement.content = "Updated content"
        await db(new_announcement.save)()
        response = await self.client.receive_json_from()
        expected = {
            "type": "broadcast",
            "id": 1,
            "model": "ohq.Announcement",
            "instance":
            camelize(AnnouncementSerializer(new_announcement).data),
            "action": "UPDATED",
        }
        self.assertEqual(expected, response)

        annoucement_id = new_announcement.id
        await db(new_announcement.delete)()
        response = await self.client.receive_json_from()
        expected = {
            "type": "broadcast",
            "id": 1,
            "model": "ohq.Announcement",
            "instance": {
                "pk": annoucement_id,
                "id": annoucement_id
            },
            "action": "DELETED",
        }
        self.assertEqual(expected, response)
Example #3
0
    def get(request):
        if 'uuid' not in request.query_params:
            raise HttpException('uuid field not provided', Errors.BAD_REQUEST)

        try:
            uuid_data = uuid.UUID(request.query_params['uuid']).hex
        except Exception as ex:
            raise HttpException('Wrong uuid format: %s' % str(ex),
                                Errors.BAD_REQUEST)

        game_session = GameSessionRepository.get_session(uuid_data)

        language_code = request.META.get('HTTP_LANGUAGE',
                                         DEFAULT_LANGUAGE_CODE).lower()
        categories = RequestToCategoriesMapper.map(request.query_params)
        question, is_last = QuestionRepository.get_random_question(
            categories, game_session)
        return Response(
            {
                'question':
                camelize(
                    QuestionSerializer(question,
                                       context={
                                           'language_code': language_code
                                       }).data),
                'isLast':
                is_last
            },
            status=200)
 def test_compatibility(self):
     input = {
         "title_display": 1,
         "a_list": [1, "two_three", {"three_four": 5}],
         "a_tuple": ("one_two", 3)
     }
     self.assertEqual(underscoreize(camelize(input)), input)
Example #5
0
 def test_camelize_iterates_over_generator(self):
     data = self._underscore_generator()
     output = [
         {'simpleIsBetter': 'than complex'},
         {'thatIs': 'correct'},
     ]
     self.assertEqual(camelize(data), output)
    def render(self, data, media_type, context, **kwargs):
        """wrap the data into a custom format
        If data has been wrapped already, do nothing
        """
        response = context.get('response')
        if isinstance(response, (SuccessResponse, FailedResponse)):
            return super().render(data, media_type, context, **kwargs)

        status_code = response.status_code
        success = status_code < status.HTTP_300_MULTIPLE_CHOICES
        status_message = "Success" if success else "Error"
        if not success:
            logger.info(f'render:{data}...')
            status_message = MSG_CODE[status_code]

            data = None
        data = camelize(data)

        data = {
            "success": success,
            "statusCode": status_code,
            "statusMessage": status_message,
            "data": data,
        }
        # Always return status 200
        context['response'].status_code = status.HTTP_200_OK
        return super().render(data, media_type, context, **kwargs)
 def test_recursive_with_ignored_keys(self):
     ignore_fields = ("ignore_me", "newKey")
     data = {
         "ignore_me": {
             "no_change_recursive": 1
         },
         "change_me": {
             "change_recursive": 2
         },
         "new_key": {
             "also_no_change": 3
         },
     }
     output = {
         "ignoreMe": {
             "no_change_recursive": 1
         },
         "changeMe": {
             "changeRecursive": 2
         },
         "newKey": {
             "also_no_change": 3
         },
     }
     self.assertEqual(camelize(data, ignore_fields=ignore_fields), output)
Example #8
0
 def mapper(game):
     return {
         'characters': camelize([*data.filter(game=game).values()]),
         'game_sumary': game.sumary,
         'game_name': game.name,
         'game_id': game.id,
     }
Example #9
0
 def __init__(self, errors=None, *args, **kwargs):
     super().__init__(*args, **kwargs)
     if errors is not None:
         if isinstance(errors, dict):
             errors = [errors]
         for error in camelize(errors):
             self.detail.update(error)
    def test_authenticated_user_can_get_user_data(self):
        user = UserFactory(is_active=True)
        self.client.force_login(user)

        response = self.client.get(reverse('users:me'))
        self.assertEqual(response.status_code, 200)
        self.assertDictEqual(response.json(),
                             camelize(MeSerializer(user).data))
 def test_under_to_camel(self):
     input = {
         "title_display": 1
     }
     output = {
         "titleDisplay": 1
     }
     self.assertEqual(camelize(input), output)
Example #12
0
def create_auth_token(sender, instance=None, created=False, **kwargs):
    channel = 'game_{0}'.format(instance.pk)
    async_to_sync(channel_layer.group_send)(channel, {
        'type':
        'game',
        'game':
        json.dumps(camelize(GameDetailSerializer(instance=instance).data))
    })
Example #13
0
 def test_compatibility(self):
     input = {
         "title_display": 1,
         "a_list": [1, "two_three", {
             "three_four": 5
         }],
         "a_tuple": ("one_two", 3)
     }
     self.assertEqual(underscoreize(camelize(input)), input)
    def test_log_in(self):
        data = {'email': self.user.email, 'password': USER_PASSWORD}

        response = self.client.post(reverse('users:login'), data=data)
        self.assertEqual(response.status_code, 200)
        self.assertDictEqual(response.json(),
                             camelize(MeSerializer(self.user).data))

        self.assertIn('_auth_user_id', self.client.session)
Example #15
0
    def construct_message(self,
                          data: dict,
                          instance: models.Model = None) -> dict:
        """
        Construct the message to send to the notification component.

        Using the response data from the view/action, we introspect this data
        to send the appropriate response. By convention, every resource
        includes its own absolute url in the 'url' key - we can use this to
        look up the object it points to. By convention, relations use the name
        of the resource, so for sub-resources we can use this to get a
        reference back to the main resource.
        """
        kanaal = self.get_kanaal()
        assert isinstance(kanaal,
                          Kanaal), "`kanaal` should be a `Kanaal` instance"

        model = self.get_queryset().model

        if model is kanaal.main_resource:
            # look up the object in the database from its absolute URL
            resource_path = urlparse(data["url"]).path
            resource = instance or get_resource_for_path(resource_path)

            main_object = resource
            main_object_url = data["url"]
            main_object_data = data
        else:
            # lookup the main object from the URL
            main_object_url = self.get_notification_main_object_url(
                data, kanaal)
            main_object_path = urlparse(main_object_url).path
            main_object = get_resource_for_path(main_object_path)

            # get main_object data formatted by serializer
            view = get_viewset_for_path(main_object_path)
            serializer_class = view.get_serializer_class()
            serializer = serializer_class(main_object,
                                          context={"request": self.request})
            main_object_data = serializer.data

        message_data = {
            "kanaal": kanaal.label,
            "hoofd_object": main_object_url,
            "resource": model._meta.model_name,
            "resource_url": data["url"],
            "actie": self.action,
            "aanmaakdatum": timezone.now(),
            # each channel knows which kenmerken it has, so delegate this
            "kenmerken": kanaal.get_kenmerken(main_object, main_object_data),
        }

        # let the serializer & render machinery shape the data the way it
        # should be, suitable for JSON in/output
        serializer = NotificatieSerializer(instance=message_data)
        return camelize(serializer.data)
 def test_under_to_camel_dict(self):
     input = {
         "title_display": 1
     }
     output = {
         "titleDisplay": 1
     }
     result = camelize(input)
     self.assertEqual(result, output)
     self.assertIsNot(result, input, "should not change original dict")
Example #17
0
 def test_tuples(self):
     data = {
         "multiple_values": (1, 2),
         "data": [1, 3, 4]
     }
     output = {
         "multipleValues": [1, 2],
         "data": [1, 3, 4]
     }
     self.assertEqual(camelize(data), output)
 def test_under_to_camel_tuple(self):
     input = (
         {"title_display": 1},
     )
     output = (
         {"titleDisplay": 1},
     )
     result = camelize(input)
     self.assertEqual(result, output)
     self.assertIsNot(result, input, "should not change original tuple")
Example #19
0
 def get(request):
     language_code = request.META.get('HTTP_LANGUAGE',
                                      DEFAULT_LANGUAGE_CODE).lower()
     categories = CategoryRepository.get_all_categories()
     return Response(camelize(
         CategorySerializer(categories,
                            context={
                                'language_code': language_code
                            },
                            many=True).data),
                     status=200)
Example #20
0
    def post(self, request, *args, **kwargs):
        countrycode = kwargs.get('code', None)
        search = request.data.get('search', None)

        if search is None:
            raise exceptions.SearchFieldRequiered()

        pagination = RequestToPaginationMapper.map(request)
        data = GeodataRepository.searchCities(countrycode, search, pagination)
        results = GeodataCitiesSerializer2(data, many=True)
        return Response(camelize(results.data), status=200)
    def test_retrieve_company_users(self):
        """
         - retrieve company users by non permission users
         - retrieve company users by permission users
         - retrieve non-existing company users
        """
        # retrieve company users by non permission users
        non_permission_users = [
            self.community_user, self.gluu_user,
            self.gluu_named, self.gluu_admin
        ]

        for user in non_permission_users:
            self.client.credentials(
                HTTP_AUTHORIZATION='Token ' + user.token
            )
            response = self.client.get(
                reverse(
                    'profiles:company-users',
                    kwargs={'pk': self.openiam.id}
                ),
            )
            self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        # retrieve company users by permission users
        permission_users = [
            self.openiam_user, self.openiam_named, self.openiam_admin,
            self.staff, self.manager
        ]
        company_serializer = CompanySerializer(self.openiam)
        for user in permission_users:
            self.client.credentials(
                HTTP_AUTHORIZATION='Token ' + user.token
            )
            response = self.client.get(
                reverse(
                    'profiles:company-users',
                    kwargs={'pk': self.openiam.id}
                ),
            )
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(
                response.data['results'], camelize(company_serializer.data)
            )

        # retrieve non-existing company users by community user
        self.client.credentials(
            HTTP_AUTHORIZATION='Token ' + self.manager.token
        )
        response = self.client.get(
            reverse('profiles:company-users', kwargs={'pk': 0}),
        )
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Example #22
0
    def get(self, request, *args, **kwargs):
        search = request.data.get('search')

        countrycode = kwargs.get('code', None)
        """snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)"""

        data = GeodataRepository.searchCities(countrycode, str(search))
        # results = GeodataCitiesSerializer(data, many=True)
        results = GeodataCitiesSerializer2(data, many=True)
        return Response(camelize(results.data), status=200)
 def test_under_to_camel_nested(self):
     input = {
         "title_display": 1,
         "a_list": [1, "two_three", {"three_four": 5}],
         "a_tuple": ("one_two", 3)
     }
     output = {
         "titleDisplay": 1,
         "aList": [1, "two_three", {"threeFour": 5}],
         "aTuple": ("one_two", 3)
     }
     self.assertEqual(camelize(input), output)
Example #24
0
 def update_key_for_renderer(key, view, request):
     renderer, media_type = view.perform_content_negotiation(
             request, force=True)
     if type(renderer).__name__ == 'CamelCaseJSONRenderer':
         try:
             from djangorestframework_camel_case.util import camelize
             return list(camelize({key: None}).keys())[0]
         except ImportError:
             warnings.warn(
                 'djangorestframework-camel-case is not installed, '
                 'source keys may not render properly'
             )
     return key
Example #25
0
    def make_todo_sub_response(
        self, todo, action, request_id, serializer=TodoSerializer
    ):
        response = {
            "type": "broadcast",
            "id": request_id,
            "model": "test_app.Todo",
            "action": action,
            "instance": camelize(serializer(todo).data),
        }
        if action == "DELETED":
            response["instance"] = {"pk": todo.pk, "id": todo.id}

        return response
Example #26
0
def camelize_serializer_fields(result, generator, request, public):
    from djangorestframework_camel_case.util import camelize, camelize_re, underscore_to_camel

    for component in generator.registry._components.values():
        if 'properties' in component.schema:
            component.schema['properties'] = camelize(
                component.schema['properties'])
        if 'required' in component.schema:
            component.schema['required'] = [
                re.sub(camelize_re, underscore_to_camel, key)
                for key in component.schema['required']
            ]

    # inplace modification of components also affect result dict, so regeneration is not necessary
    return result
Example #27
0
 def test_under_to_camel_nested(self):
     input = {
         "title_display": 1,
         "a_list": [1, "two_three", {
             "three_four": 5
         }],
         "a_tuple": ("one_two", 3)
     }
     output = {
         "titleDisplay": 1,
         "aList": [1, "two_three", {
             "threeFour": 5
         }],
         "aTuple": ("one_two", 3)
     }
     self.assertEqual(camelize(input), output)
Example #28
0
    def test_retrieve_info(self):
        """
         - retrieve info
         - retrieve non-existing info
        """
        # retrieve info
        serializer = UserRoleSerializer(self.role)
        response = self.client.get(
            reverse('info:role-detail', kwargs={'pk': self.role.id}))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['results'], camelize(serializer.data))

        # retrieve non-existing info
        response = self.client.get(
            reverse('info:role-detail', kwargs={'pk': 0}))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Example #29
0
def send_notifications(action, user_uuid, data):
    CHANNEL_NAME = '{}.{}'.format(
        settings.SERVICE_SHORT_NAME,
        settings.SERVICE_SHORT_NAME)
    REDIS_PREFIX = 'broker'
    connection = redis.Redis(
        host=settings.REDIS_HOST,
        port=settings.REDIS_PORT,
        db=settings.REDIS_AUTH_DB,)
    data.update({'action': action})
    redis_data = {
        'subscription': CHANNEL_NAME,
        'data': camelize(data),
        'uuid': str(user_uuid)}
    connection.publish(
        '{}{}'.format(REDIS_PREFIX, CHANNEL_NAME),
        json.dumps(redis_data))
    def validate(self, attrs):
        validated_attrs = super().validate(attrs)
        # check if exchange exists
        try:
            kanaal = Kanaal.objects.get(naam=validated_attrs['kanaal'])
        except ObjectDoesNotExist:
            raise serializers.ValidationError(
                {'kanaal': _('Kanaal met deze naam bestaat niet.')},
                code='message_kanaal')

        # check if msg kenmerken are consistent with kanaal filters
        kenmerken_names = list(validated_attrs['kenmerken'].keys())
        if not kanaal.match_filter_names(kenmerken_names):
            raise serializers.ValidationError(
                {'kenmerken': _("Kenmerken aren't consistent with kanaal filters")},
                code='kenmerken_inconsistent')

        # ensure we're still camelCasing
        return camelize(validated_attrs)
Example #31
0
 def test_under_to_camel_keys(self):
     data = {
         "two_word": 1,
         "long_key_with_many_underscores": 2,
         "only_1_key": 3,
         "only_one_letter_a": 4,
         "b_only_one_letter": 5,
         "only_c_letter": 6,
         "mix_123123a_and_letters": 7,
     }
     output = {
         "twoWord": 1,
         "longKeyWithManyUnderscores": 2,
         "only1Key": 3,
         "onlyOneLetterA": 4,
         "bOnlyOneLetter": 5,
         "onlyCLetter": 6,
         "mix123123aAndLetters": 7
     }
     self.assertEqual(camelize(data), output)
 def render(self, data, *args, **kwargs):
     status_code = status.HTTP_200_OK
     if args[1] is not None \
             and args[1].get("response", None) is not None \
             and (args[1].get("response", None).get('status_code', None) is not None
                  or hasattr(args[1].get("response", None), 'status_code')):
         status_code = args[1]["response"].status_code
     if not isinstance(data, JSend):
         j_send = JSend()
         j_send.status = JSendUtility.get_status_by_status_code(status_code)
         j_send.code = status_code
         j_send.data = data
         j_send_serializer = JSendSerializer(data=j_send.__dict__)
     else:
         if data.code is None:
             data.code = status_code
         if data.status is None:
             data.status = JSendUtility.get_status_by_status_code(
                 status_code)
         j_send_serializer = JSendSerializer(data=data.__dict__)
     j_send_serializer.is_valid(True)
     return super(CamelCaseJSONRenderer,
                  self).render(camelize(j_send_serializer.data), *args,
                               **kwargs)
Example #33
0
 def save(self) -> None:
     os.makedirs(os.path.join(self.jobdir, 'excel_tmp'), exist_ok=True)
     with open(os.path.join(self.jobdir, 'summary.json'), 'w') as f:
         d = camelize(JobSerializer(self).data, ignore_fields=('cloning_options', 'nuclease_options'))
         del d['organism']['scaffolds']
         json.dump(d, f, indent=4)
Example #34
0
 def save_result(self, result, edit_index):
     with open(os.path.join(self.jobdir, f'edit{edit_index}.json'), 'w') as f:
         json.dump(camelize(result), f, indent=4)
 def render(self, data, *args, **kwargs):
     return super(CamelCaseJSONRenderer, self).render(camelize(data), *args,
                                                      **kwargs)
 def test_compatibility(self):
     input = {
         "title_245a_display": 1
     }
     self.assertEqual(underscoreize(camelize(input)), input)