Ejemplo n.º 1
0
    def top_level(self, request, api_name=None):
        """
        A view that returns a serialized list of all resources registers
        to the ``Api``. Useful for discovery.
        """
        serializer = Serializer()

        if api_name is None:
            api_name = self.api_name

        available_resources = dict((name, {
            'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                'api_name': api_name,
                'resource_name': name,
            }),
            'schema': self._build_reverse_url("api_get_schema", kwargs={
                'api_name': api_name,
                'resource_name': name,
            }),
        }) for name in self._registry.iterkeys())

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 2
0
    def top_level(self, request, api_name=None):
        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            available_resources[name] = {
                'list_endpoint': self._build_reverse_url('api_dispatch_list', kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
                'schema': self._build_reverse_url('api_get_schema', kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
            }

            if request.GET.get('include_schemas', False) is not False:
                available_resources[name]['schema_detailed'] = self._registry[name].build_schema()

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')
            
            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 3
0
 def obj_update(self, bundle, skip_errors=False, **kwargs):
     from tastypie.serializers import Serializer
     from models import ProgramFeature
     
     serdes = Serializer()
     deserialized = None
     
     try:
         deserialized = serdes.deserialize(bundle.request.body, format=bundle.request.META.get('CONTENT_TYPE', 'application/json'))
     except Exception:
         deserialized = None
     
     if deserialized is None:
         return ImmediateHttpResponse(response = http.HttpBadRequest('Empty update data'))
     
     time_difference = datetime.strptime(deserialized['new_end_time'], "%Y-%m-%d %H:%M:%S") - datetime.strptime(deserialized['old_end_time'], "%Y-%m-%d %H:%M:%S")
     
     Presentation.objects.filter(startTime__gte=deserialized['old_end_time']).update(startTime=F('startTime') + time_difference)
     Presentation.objects.filter(startTime__gte=deserialized['old_end_time']).update(endTime=F('endTime') + time_difference)
     
     later_presentations = Presentation.objects.filter(startTime__gte=deserialized['old_end_time'])
     
     changed_presentation = Presentation.objects.get(startTime=deserialized['old_start_time'])
     changed_presentation.startTime = deserialized['new_start_time']
     changed_presentation.endTime = deserialized['new_end_time']
     changed_presentation.save()
Ejemplo n.º 4
0
Archivo: utils.py Proyecto: bne/hortee
 def serialized(self, request, api_name=None, desired_format=None):
     """
     Nabbed from top_level of the parent class
     Would be nice if this was abstracted as it's good for auto discovery
     to be rendered as json on initial page load
     """
     serializer = Serializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
         
     if desired_format is None:
         desired_format = determine_format(request, serializer)
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", 
             kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     return serializer.serialize(available_resources, desired_format)
Ejemplo n.º 5
0
Archivo: views.py Proyecto: eads/panda
def index(request):
    """
    Page shell for the client-side application.

    Bootstraps read-once data onto the page.
    """
    serializer = Serializer()
    cr = CategoryResource()

    categories = list(Category.objects.annotate(dataset_count=Count('datasets')))

    bundles = [cr.build_bundle(obj=c) for c in categories]
    categories_bootstrap = [cr.full_dehydrate(b) for b in bundles]

    uncategorized = Category(
        id=settings.PANDA_UNCATEGORIZED_ID,
        slug=settings.PANDA_UNCATEGORIZED_SLUG,
        name=settings.PANDA_UNCATEGORIZED_NAME)
    uncategorized.__dict__['dataset_count'] = Dataset.objects.filter(categories=None).count() 
    uncategorized_bundle = cr.full_dehydrate(cr.build_bundle(obj=uncategorized))

    categories_bootstrap.append(uncategorized_bundle)

    return render_to_response('index.html', {
        'settings': settings,
        'demo_mode': int(config_value('MISC', 'DEMO_MODE')),
        'bootstrap_data': serializer.to_json({
            'categories': categories_bootstrap
        })
    })
Ejemplo n.º 6
0
 def dbDecode(dataString):
     assert_arg_type(dataString, basestring)
     
     ## this logic is poor - I believe the best way is to define a standard set of 
     ## representation formats and use try..except clauses to parse the incoming string
     ## according to the defined formats (formats: text, json, xml)
     ## For now we treat it as a default of text
     
     ## use tastypie's serializer to do the testing 
     from tastypie.serializers import Serializer
     ## instantiate a serializer to test
     serdes = Serializer()
     
     dataobj = None
     val = None
     try:
         val = serdes.from_xml(dataString)
     except Exception:
         val = None
     
     if val is None:
         try:
             from django.utils import simplejson
             #val = serdes.from_json(dataString)
             val = simplejson.loads(dataString, encoding='utf-8')
         except Exception, ex:
             val = None
         
         if not isinstance(val, (dict, list)):
             val = str(dataString)
             dataobj = Data(val, data_format = Data.TEXT)
         else:
             dataobj = Data(val, data_format = Data.JSON)
Ejemplo n.º 7
0
 def obj_update(self, bundle, skip_errors=False, **kwargs):
     """
     Could be an intentional action that the default obj_update treats DoesNotExist and MultipleObjectReturned
     as acceptable exceptions which get transformed into a CREATE operation.
     We don't want such a behavior. So we catch does exceptions and throw an BadRequest message
     """ 
     from tastypie.serializers import Serializer
        
     try:
         serdes = Serializer()
         deserialized = None
         try:
             deserialized = serdes.deserialize(bundle.request.raw_post_data, 
                                 format=bundle.request.META.get('CONTENT_TYPE', 'application/json'))
         except Exception:
             deserialized = None
         del serdes
                 
         if deserialized is None:
             return ImmediateHttpResponse(response = http.HttpBadRequest())
         
         if 'unregister_c2dm' in deserialized and deserialized['unregister_c2dm'] == True:
             bundle.data['c2dm_id'] = None
         
         updated_bundle = super(UserResource, self).obj_update(bundle, skip_errors=skip_errors, **kwargs)
         return updated_bundle
     except (NotFound, MultipleObjectsReturned):
         raise ImmediateHttpResponse(response = http.HttpBadRequest())
Ejemplo n.º 8
0
 def test_to_xml(self):
     serializer = Serializer()
     sample_1 = self.get_sample1()
     self.assertEqual(
         serializer.to_xml(sample_1),
         "<?xml version='1.0' encoding='utf-8'?>\n<response><age type=\"integer\">27</age><name>Daniel</name><date_joined>2010-03-27</date_joined></response>",
     )
Ejemplo n.º 9
0
def login(request, **kwargs):
    # self.method_check(request, allowed=['post'])
    # self.is_authenticated(request)
    # self.throttle_check(request)

    developer_key = request.GET.get('developer_key')
    username = request.GET.get('username')
    password = request.GET.get('password')

    if not developer_key or not username or not password:
        return HttpUnauthorized()

    try:
        dev_key = DeveloperApiKey.objects.get(key=developer_key, approved=True)
    except DeveloperApiKey.DoesNotExist:
        return HttpUnauthorized()

    user = authenticate(username=username, password=password)

    if user:
        try:
            key = UserApiKey.objects.get(user=user, developer_key=dev_key)
        except  UserApiKey.DoesNotExist:
            key = UserApiKey(user=user, developer_key=dev_key)
            key.save()

        # self.log_throttled_access(request)
        serializer = Serializer()
        desired_format = determine_format(request, serializer)
        serialized = serializer.serialize({'key' : key.key}, desired_format)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
    else:
        return HttpUnauthorized()
Ejemplo n.º 10
0
 def tastypie_resource_serialize(data):
     data_resource = get_resource_class(type(data))
     bundle = data_resource.build_bundle(obj=data, request=None)
     bundle.request.path = "/"
     serialized = Serializer().serialize(data_resource.full_dehydrate(bundle).data)
     serialized = serialized.replace("'", '\\"')
     return serialized
Ejemplo n.º 11
0
def send_invitation(request):
    """
        Send an invitation to another person via email. NOT TESTED YET
    """
    if request.user.is_authenticated() and request.user.is_active:
        if 'email' in request.POST:
            email = request.POST['email']
        else:
            return HttpResponseBadRequest('Mandatory email parameter not provided.')

        if 'message' in request.POST:
            message = request.POST['message']
        else:
            message = 'Tritt score.it bei und sehe deine Handballergebnisse online!'

        profile = None
        if 'profile' in request.POST:
            serializer = Serializer()
            profile = serializer.deserialize(request.POST['profile'])

        subject = '{0} {1} lädt dich zu Score.it ein!'.format(request.user.first_name, request.user.last_name)

        if profile:
            profile_link = 'http://score-it.de/?a=invite&p={0}'.format(profile.id)
            body = '{0} {1} hat ein Spielerprofil bei Score.it für dich erstellt. Melde dich jetzt bei Score.it an, um deine Handballergebnisse online abzurufen! Zum anmelden, klicke einfach folgenden Link: {3}'.format(request.user.first_name, request.user.last_name, profile_link)
        else:
            body = '{0} {1} hat dir eine Einladung zu der Sportplatform Score.it geschickt:<br>{2}Um dich anzumelden, besuche einfach http://score-it.de/!'.format(request.user.first_name, request.user.last_name, message)

        sender = '*****@*****.**'
        recipients = [email]
        send_mail(subject, body, sender, recipients)
        return HttpResponse('')
    else:
        return HttpUnauthorized('Authentication through active user required.')
Ejemplo n.º 12
0
 def test_to_json_decimal_list_dict(self):
     serializer = Serializer()
     resource = self.another_obj_list[0]
     self.assertEqual(
         serializer.to_json(resource),
         '{"aliases": ["Mr. Smith", "John Doe"], "content": "This is my very first post using my shiny new API. Pretty sweet, huh?", "created": "2010-03-30T20:05:00", "id": "1", "is_active": true, "meta": {"threat": "high"}, "owed": "102.57", "resource_uri": "", "slug": "first-post", "title": "First Post!", "updated": "2010-03-30T20:05:00"}',
     )
Ejemplo n.º 13
0
 def test_to_xml_single(self):
     serializer = Serializer()
     resource = self.obj_list[0]
     self.assertEqual(
         serializer.to_xml(resource),
         "<?xml version='1.0' encoding='utf-8'?>\n<object><updated>2010-03-30T20:05:00</updated><created>2010-03-30T20:05:00</created><title>First Post!</title><is_active type=\"boolean\">True</is_active><slug>first-post</slug><content>This is my very first post using my shiny new API. Pretty sweet, huh?</content><id>1</id><resource_uri></resource_uri></object>",
     )
Ejemplo n.º 14
0
 def test_to_json_single(self):
     serializer = Serializer()
     resource = self.obj_list[0]
     self.assertEqual(
         serializer.to_json(resource),
         '{"content": "This is my very first post using my shiny new API. Pretty sweet, huh?", "created": "2010-03-30T20:05:00", "id": "1", "is_active": true, "resource_uri": "", "slug": "first-post", "title": "First Post!", "updated": "2010-03-30T20:05:00"}',
     )
Ejemplo n.º 15
0
 def top_level(self, request, api_name=None):
     """
     A view that returns a serialized list of all resources registers
     to the ``Api``. Useful for discovery.
     """
     serializer = Serializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     desired_format = determine_format(request, serializer)
     serialized = serializer.serialize(available_resources, desired_format)
     return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 16
0
 def build_response(self):
     from tastypie.serializers import Serializer
     serializer = Serializer()
     return HttpResponse(
         content=serializer.serialize(self.response_data),
         content_type=build_content_type('application/json')
     )
Ejemplo n.º 17
0
 def test_to_xml2(self):
     serializer = Serializer()
     sample_2 = self.get_sample2()
     self.assertEqual(
         serializer.to_xml(sample_2),
         '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<response><somelist type="list"><value>hello</value><value type="integer">1</value><value type="null"/></somelist><somehash type="hash"><pi type="float">3.14</pi><foo>bar</foo></somehash><false type="boolean">False</false><true type="boolean">True</true><somestring>hello</somestring></response>',
     )
Ejemplo n.º 18
0
def index(request):
    """
    Page shell for the client-side application.

    Bootstraps read-once data onto the page.
    """
    serializer = Serializer()
    cr = CategoryResource()

    categories = list(Category.objects.annotate(dataset_count=Count('datasets')))

    bundles = [cr.build_bundle(obj=c) for c in categories]
    categories_bootstrap = [cr.full_dehydrate(b) for b in bundles]

    uncategorized = Category(
        id=settings.PANDA_UNCATEGORIZED_ID,
        slug=settings.PANDA_UNCATEGORIZED_SLUG,
        name=settings.PANDA_UNCATEGORIZED_NAME)
    uncategorized.__dict__['dataset_count'] = Dataset.objects.filter(categories=None).count() 
    uncategorized_bundle = cr.full_dehydrate(cr.build_bundle(obj=uncategorized))

    categories_bootstrap.append(uncategorized_bundle)

    return render_to_response('index.html', {
        'settings': settings,
        'max_upload_size': int(config_value('MISC', 'MAX_UPLOAD_SIZE')),
        'email_enabled': int(config_value('EMAIL', 'EMAIL_ENABLED')),
        'demo_mode_enabled': int(config_value('MISC', 'DEMO_MODE_ENABLED')),
        'bootstrap_data': serializer.to_json({
            'categories': categories_bootstrap
        }),
        'moment_lang_code': settings.MOMENT_LANGUAGE_MAPPING.get(settings.LANGUAGE_CODE, None),
    })
Ejemplo n.º 19
0
    def test_from_json(self):
        serializer = Serializer()

        sample_1 = serializer.from_json('{"age": 27, "date_joined": "2010-03-27", "name": "Daniel"}')
        self.assertEqual(len(sample_1), 3)
        self.assertEqual(sample_1["name"], "Daniel")
        self.assertEqual(sample_1["age"], 27)
        self.assertEqual(sample_1["date_joined"], u"2010-03-27")
Ejemplo n.º 20
0
    def test_to_plist(self):
        serializer = Serializer()

        sample_1 = self.get_sample1()
        self.assertEqual(
            serializer.to_plist(sample_1),
            "bplist00bybiplist1.0\x00\xd3\x01\x02\x03\x04\x05\x06SageTname[date_joined\x10\x1bf\x00D\x00a\x00n\x00i\x00e\x00lZ2010-03-27\x15\x1c %13@\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00K",
        )
Ejemplo n.º 21
0
 def test_to_xml_nested(self):
     serializer = Serializer()
     resource = self.obj_list[0]
     data = {"stuff": {"foo": "bar", "object": resource}}
     self.assertEqual(
         serializer.to_xml(data),
         "<?xml version='1.0' encoding='utf-8'?>\n<response><stuff type=\"hash\"><foo>bar</foo><object><updated>2010-03-30T20:05:00</updated><created>2010-03-30T20:05:00</created><title>First Post!</title><is_active type=\"boolean\">True</is_active><slug>first-post</slug><content>This is my very first post using my shiny new API. Pretty sweet, huh?</content><id>1</id><resource_uri></resource_uri></object></stuff></response>",
     )
Ejemplo n.º 22
0
    def test_to_plist(self):
        if not biplist:
            return

        serializer = Serializer()

        sample_1 = self.get_sample1()
        self.assertEqual(serializer.to_plist(sample_1), 'bplist00bybiplist1.0\x00\xd4\x01\x02\x03\x04\x05\x06\x07\x08WsnowmanSageTname[date_joineda&\x03\x10\x1bf\x00D\x00a\x00n\x00i\x00e\x00lZ2010-03-27\x15\x1e&*/;>@M\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00X')
Ejemplo n.º 23
0
 def test_to_json_nested(self):
     serializer = Serializer()
     resource = self.obj_list[0]
     data = {"stuff": {"foo": "bar", "object": resource}}
     self.assertEqual(
         serializer.to_json(data),
         '{"stuff": {"foo": "bar", "object": {"content": "This is my very first post using my shiny new API. Pretty sweet, huh?", "created": "2010-03-30T20:05:00", "id": "1", "is_active": true, "resource_uri": "", "slug": "first-post", "title": "First Post!", "updated": "2010-03-30T20:05:00"}}}',
     )
Ejemplo n.º 24
0
    def test_from_json(self):
        serializer = Serializer()

        sample_1 = serializer.from_json('{"age": 27, "date_joined": "2010-03-27", "name": "Daniel"}')
        self.assertEqual(len(sample_1), 3)
        self.assertEqual(sample_1['name'], 'Daniel')
        self.assertEqual(sample_1['age'], 27)
        self.assertEqual(sample_1['date_joined'], u'2010-03-27')
Ejemplo n.º 25
0
    def test_to_plist(self):
        if not biplist:
            return

        serializer = Serializer()

        sample_1 = self.get_sample1()
        self.assertTrue(serializer.to_plist(sample_1).startswith(b'bplist00bybiplist1.0'))
Ejemplo n.º 26
0
    def test_from_plist(self):
        serializer = Serializer()

        sample_1 = serializer.from_plist('bplist00bybiplist1.0\x00\xd3\x01\x02\x03\x04\x05\x06SageTname[date_joined\x10\x1bf\x00D\x00a\x00n\x00i\x00e\x00lZ2010-03-27\x15\x1c %13@\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00K')
        self.assertEqual(len(sample_1), 3)
        self.assertEqual(sample_1['name'], 'Daniel')
        self.assertEqual(sample_1['age'], 27)
        self.assertEqual(sample_1['date_joined'], u'2010-03-27')
Ejemplo n.º 27
0
    def test_to_jsonp(self):
        serializer = Serializer()

        sample_1 = self.get_sample1()
        options = {'callback': 'myCallback'}
        serialized = serializer.to_jsonp(sample_1, options=options)
        serialized_json = serializer.to_json(sample_1)
        self.assertEqual('myCallback(%s)' % serialized_json,
                         serialized)
Ejemplo n.º 28
0
    def test_from_plist(self):
        serializer = Serializer()

        sample_1 = serializer.from_plist(b'bplist00bybiplist1.0\x00\xd4\x01\x02\x03\x04\x05\x06\x07\x08WsnowmanSageTname[date_joineda&\x03\x10\x1bf\x00D\x00a\x00n\x00i\x00e\x00lZ2010-03-27\x15\x1e&*/;>@M\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00X')
        self.assertEqual(len(sample_1), 4)
        self.assertEqual(sample_1['name'], 'Daniel')
        self.assertEqual(sample_1['age'], 27)
        self.assertEqual(sample_1['date_joined'], '2010-03-27')
        self.assertEqual(sample_1['snowman'], u'☃')
Ejemplo n.º 29
0
 def test_round_trip_xml(self):
     serializer = Serializer()
     sample_data = self.get_sample2()
     serialized = serializer.to_xml(sample_data)
     # "response" tags need to be changed to "request" to deserialize properly.
     # A string substitution works here.
     serialized = serialized.replace('response', 'request')
     unserialized = serializer.from_xml(serialized)
     self.assertEqual(sample_data, unserialized)
Ejemplo n.º 30
0
 def test_to_xml_nested(self):
     serializer = Serializer()
     resource = self.obj_list[0]
     data = {
         'stuff': {
             'foo': 'bar',
             'object': resource,
         }
     }
     self.assertEqual(serializer.to_xml(data), '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<response><stuff type="hash"><foo>bar</foo><object><updated>2010-03-30T20:05:00</updated><created>2010-03-30T20:05:00</created><title>First Post!</title><is_active type="boolean">True</is_active><slug>first-post</slug><content>This is my very first post using my shiny new API. Pretty sweet, huh?</content><id>1</id><resource_uri></resource_uri></object></stuff></response>')
Ejemplo n.º 31
0
    def test_format_time(self):
        serializer = Serializer()
        self.assertEqual(serializer.format_time(datetime.time(2, 31, 33)),
                         '02:31:33')

        serializer = Serializer(datetime_formatting='iso-8601')
        self.assertEqual(serializer.format_time(datetime.time(2, 31, 33)),
                         '02:31:33')

        serializer = Serializer(datetime_formatting='rfc-2822')
        self.assertEqual(serializer.format_time(datetime.time(2, 31, 33)),
                         u'02:31:33 -0600')

        serializer = Serializer(datetime_formatting='random-garbage')
        self.assertEqual(serializer.format_time(datetime.time(2, 31, 33)),
                         '02:31:33')

        # Stow.
        old_format = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING',
                             'iso-8601')

        settings.TASTYPIE_DATETIME_FORMATTING = 'iso-8601'
        serializer = Serializer()
        self.assertEqual(serializer.format_time(datetime.time(2, 31, 33)),
                         '02:31:33')

        settings.TASTYPIE_DATETIME_FORMATTING = 'rfc-2822'
        serializer = Serializer()
        self.assertEqual(serializer.format_time(datetime.time(2, 31, 33)),
                         u'02:31:33 -0600')

        settings.TASTYPIE_DATETIME_FORMATTING = 'random-garbage'
        serializer = Serializer()
        self.assertEqual(serializer.format_time(datetime.time(2, 31, 33)),
                         '02:31:33')

        # Restore.
        settings.TASTYPIE_DATETIME_FORMATTING = old_format
Ejemplo n.º 32
0
Archivo: api.py Proyecto: alejo8591/etv
 class Meta:
     queryset = User.objects.all()
     resource_name = 'user'
     excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser', 'last_login', 'date_joined', 'id']
     serializer = Serializer(formats=['json'])
Ejemplo n.º 33
0
    def test_format_date(self):
        serializer = Serializer()
        self.assertEqual(serializer.format_date(datetime.date(2010, 12, 16)),
                         '2010-12-16')

        serializer = Serializer(datetime_formatting='iso-8601')
        self.assertEqual(serializer.format_date(datetime.date(2010, 12, 16)),
                         '2010-12-16')

        serializer = Serializer(datetime_formatting='rfc-2822')
        self.assertEqual(serializer.format_date(datetime.date(2010, 12, 16)),
                         u'16 Dec 2010')

        serializer = Serializer(datetime_formatting='random-garbage')
        self.assertEqual(serializer.format_date(datetime.date(2010, 12, 16)),
                         '2010-12-16')

        # Stow.
        old_format = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING',
                             'iso-8601')

        settings.TASTYPIE_DATETIME_FORMATTING = 'iso-8601'
        serializer = Serializer()
        self.assertEqual(serializer.format_date(datetime.date(2010, 12, 16)),
                         '2010-12-16')

        settings.TASTYPIE_DATETIME_FORMATTING = 'rfc-2822'
        serializer = Serializer()
        self.assertEqual(serializer.format_date(datetime.date(2010, 12, 16)),
                         u'16 Dec 2010')

        settings.TASTYPIE_DATETIME_FORMATTING = 'random-garbage'
        serializer = Serializer()
        self.assertEqual(serializer.format_date(datetime.date(2010, 12, 16)),
                         '2010-12-16')

        # Restore.
        settings.TASTYPIE_DATETIME_FORMATTING = old_format
Ejemplo n.º 34
0
 def test_from_xml2(self):
     serializer = Serializer()
     data = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<request><somelist type="list"><value>hello</value><value type="integer">1</value><value type="null"/></somelist><somehash type="hash"><pi type="float">3.14</pi><foo>bar</foo></somehash><false type="boolean">False</false><true type="boolean">True</true><somestring>hello</somestring></request>'
     self.assertEqual(serializer.from_xml(data), self.get_sample2())
Ejemplo n.º 35
0
 class Meta:
     queryset = Region.objects.all()
     resource_name = 'regions'
     serializer = Serializer(formats=['xml', 'json'])
Ejemplo n.º 36
0
 class Meta:
     queryset = Country.objects.all()
     resource_name = 'countries'
     excludes = ['polygon', 'code']
     include_resource_uri = False
     serializer = Serializer(formats=['xml', 'json'])
Ejemplo n.º 37
0
    def test_init(self):
        serializer_1 = Serializer()
        self.assertEqual(serializer_1.formats,
                         ['json', 'jsonp', 'xml', 'yaml', 'html', 'plist'])
        self.assertEqual(
            serializer_1.content_types, {
                'xml': 'application/xml',
                'yaml': 'text/yaml',
                'json': 'application/json',
                'jsonp': 'text/javascript',
                'html': 'text/html',
                'plist': 'application/x-plist'
            })
        self.assertEqual(serializer_1.supported_formats, [
            'application/json', 'text/javascript', 'application/xml',
            'text/yaml', 'text/html', 'application/x-plist'
        ])

        serializer_2 = Serializer(formats=['json', 'xml'])
        self.assertEqual(serializer_2.formats, ['json', 'xml'])
        self.assertEqual(
            serializer_2.content_types, {
                'xml': 'application/xml',
                'yaml': 'text/yaml',
                'json': 'application/json',
                'jsonp': 'text/javascript',
                'html': 'text/html',
                'plist': 'application/x-plist'
            })
        self.assertEqual(serializer_2.supported_formats,
                         ['application/json', 'application/xml'])

        serializer_3 = Serializer(formats=['json', 'xml'],
                                  content_types={
                                      'json': 'text/json',
                                      'xml': 'application/xml'
                                  })
        self.assertEqual(serializer_3.formats, ['json', 'xml'])
        self.assertEqual(serializer_3.content_types, {
            'xml': 'application/xml',
            'json': 'text/json'
        })
        self.assertEqual(serializer_3.supported_formats,
                         ['text/json', 'application/xml'])

        serializer_4 = Serializer(formats=['plist', 'json'],
                                  content_types={
                                      'plist': 'application/x-plist',
                                      'json': 'application/json'
                                  })
        self.assertEqual(serializer_4.formats, ['plist', 'json'])
        self.assertEqual(serializer_4.content_types, {
            'plist': 'application/x-plist',
            'json': 'application/json'
        })
        self.assertEqual(serializer_4.supported_formats,
                         ['application/x-plist', 'application/json'])

        self.assertRaises(ImproperlyConfigured,
                          Serializer,
                          formats=['json', 'xml'],
                          content_types={'json': 'text/json'})
Ejemplo n.º 38
0
 class Meta:
     queryset = Indicator.objects.all()
     resource_name = 'indicator'
     include_resource_uri = False
     serializer = Serializer(formats=['xml', 'json'])
Ejemplo n.º 39
0
class ResourceTestCase(TestCase):
    """
    A useful base class for the start of testing Tastypie APIs.
    """
    def setUp(self):
        super(ResourceTestCase, self).setUp()
        self.serializer = Serializer()
        self.api_client = TestApiClient()

    def get_credentials(self):
        """
        A convenience method for the user as a way to shorten up the
        often repetitious calls to create the same authentication.

        Raises ``NotImplementedError`` by default.

        Usage::

            class MyResourceTestCase(ResourceTestCase):
                def get_credentials(self):
                    return self.create_basic('daniel', 'pass')

                # Then the usual tests...

        """
        raise NotImplementedError(
            "You must return the class for your Resource to test.")

    def create_basic(self, username, password):
        """
        Creates & returns the HTTP ``Authorization`` header for use with BASIC
        Auth.
        """
        import base64
        return 'Basic %s' % base64.b64encode(':'.join([username, password]))

    def create_apikey(self, username, api_key):
        """
        Creates & returns the HTTP ``Authorization`` header for use with
        ``ApiKeyAuthentication``.
        """
        return 'ApiKey %s:%s' % (username, api_key)

    def create_digest(self, username, api_key, method, uri):
        """
        Creates & returns the HTTP ``Authorization`` header for use with Digest
        Auth.
        """
        from tastypie.authentication import hmac, sha1, uuid, python_digest

        new_uuid = uuid.uuid4()
        opaque = hmac.new(str(new_uuid), digestmod=sha1).hexdigest()
        return python_digest.build_authorization_request(
            username,
            method.upper(),
            uri,
            1,  # nonce_count
            digest_challenge=python_digest.build_digest_challenge(
                time.time(), getattr(settings, 'SECRET_KEY', ''),
                'django-tastypie', opaque, False),
            password=api_key)

    def create_oauth(self, user):
        """
        Creates & returns the HTTP ``Authorization`` header for use with Oauth.
        """
        from oauth_provider.models import Consumer, Token, Resource

        # Necessary setup for ``oauth_provider``.
        resource, _ = Resource.objects.get_or_create(
            url='test', defaults={'name': 'Test Resource'})
        consumer, _ = Consumer.objects.get_or_create(key='123',
                                                     defaults={
                                                         'name':
                                                         'Test',
                                                         'description':
                                                         'Testing...'
                                                     })
        token, _ = Token.objects.get_or_create(key='foo',
                                               token_type=Token.ACCESS,
                                               defaults={
                                                   'consumer': consumer,
                                                   'resource': resource,
                                                   'secret': '',
                                                   'user': user,
                                               })

        # Then generate the header.
        oauth_data = {
            'oauth_consumer_key': '123',
            'oauth_nonce': 'abc',
            'oauth_signature': '&',
            'oauth_signature_method': 'PLAINTEXT',
            'oauth_timestamp': str(int(time.time())),
            'oauth_token': 'foo',
        }
        return 'OAuth %s' % ','.join(
            [key + '=' + value for key, value in oauth_data.items()])

    def assertHttpOK(self, resp):
        """
        Ensures the response is returning a HTTP 200.
        """
        return self.assertEqual(resp.status_code, 200)

    def assertHttpCreated(self, resp):
        """
        Ensures the response is returning a HTTP 201.
        """
        return self.assertEqual(resp.status_code, 201)

    def assertHttpAccepted(self, resp):
        """
        Ensures the response is returning either a HTTP 202 or a HTTP 204.
        """
        return self.assertTrue(resp.status_code in [202, 204],
                               'status_code is %s' % resp.status_code)

    def assertHttpMultipleChoices(self, resp):
        """
        Ensures the response is returning a HTTP 300.
        """
        return self.assertEqual(resp.status_code, 300)

    def assertHttpSeeOther(self, resp):
        """
        Ensures the response is returning a HTTP 303.
        """
        return self.assertEqual(resp.status_code, 303)

    def assertHttpNotModified(self, resp):
        """
        Ensures the response is returning a HTTP 304.
        """
        return self.assertEqual(resp.status_code, 304)

    def assertHttpBadRequest(self, resp):
        """
        Ensures the response is returning a HTTP 400.
        """
        return self.assertEqual(resp.status_code, 400)

    def assertHttpUnauthorized(self, resp):
        """
        Ensures the response is returning a HTTP 401.
        """
        return self.assertEqual(resp.status_code, 401)

    def assertHttpForbidden(self, resp):
        """
        Ensures the response is returning a HTTP 403.
        """
        return self.assertEqual(resp.status_code, 403)

    def assertHttpNotFound(self, resp):
        """
        Ensures the response is returning a HTTP 404.
        """
        return self.assertEqual(resp.status_code, 404)

    def assertHttpMethodNotAllowed(self, resp):
        """
        Ensures the response is returning a HTTP 405.
        """
        return self.assertEqual(resp.status_code, 405)

    def assertHttpConflict(self, resp):
        """
        Ensures the response is returning a HTTP 409.
        """
        return self.assertEqual(resp.status_code, 409)

    def assertHttpGone(self, resp):
        """
        Ensures the response is returning a HTTP 410.
        """
        return self.assertEqual(resp.status_code, 410)

    def assertHttpTooManyRequests(self, resp):
        """
        Ensures the response is returning a HTTP 429.
        """
        return self.assertEqual(resp.status_code, 429)

    def assertHttpApplicationError(self, resp):
        """
        Ensures the response is returning a HTTP 500.
        """
        return self.assertEqual(resp.status_code, 500)

    def assertHttpNotImplemented(self, resp):
        """
        Ensures the response is returning a HTTP 501.
        """
        return self.assertEqual(resp.status_code, 501)

    def assertValidJSON(self, data):
        """
        Given the provided ``data`` as a string, ensures that it is valid JSON &
        can be loaded properly.
        """
        # Just try the load. If it throws an exception, the test case will fail.
        self.serializer.from_json(data)

    def assertValidXML(self, data):
        """
        Given the provided ``data`` as a string, ensures that it is valid XML &
        can be loaded properly.
        """
        # Just try the load. If it throws an exception, the test case will fail.
        self.serializer.from_xml(data)

    def assertValidYAML(self, data):
        """
        Given the provided ``data`` as a string, ensures that it is valid YAML &
        can be loaded properly.
        """
        # Just try the load. If it throws an exception, the test case will fail.
        self.serializer.from_yaml(data)

    def assertValidPlist(self, data):
        """
        Given the provided ``data`` as a string, ensures that it is valid
        binary plist & can be loaded properly.
        """
        # Just try the load. If it throws an exception, the test case will fail.
        self.serializer.from_plist(data)

    def assertValidJSONResponse(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, assert that
        you get back:

        * An HTTP 200
        * The correct content-type (``application/json``)
        * The content is valid JSON
        """
        self.assertHttpOK(resp)
        self.assertTrue(resp['Content-Type'].startswith('application/json'))
        self.assertValidJSON(resp.content)

    def assertValidXMLResponse(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, assert that
        you get back:

        * An HTTP 200
        * The correct content-type (``application/xml``)
        * The content is valid XML
        """
        self.assertHttpOK(resp)
        self.assertTrue(resp['Content-Type'].startswith('application/xml'))
        self.assertValidXML(resp.content)

    def assertValidYAMLResponse(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, assert that
        you get back:

        * An HTTP 200
        * The correct content-type (``text/yaml``)
        * The content is valid YAML
        """
        self.assertHttpOK(resp)
        self.assertTrue(resp['Content-Type'].startswith('text/yaml'))
        self.assertValidYAML(resp.content)

    def assertValidPlistResponse(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, assert that
        you get back:

        * An HTTP 200
        * The correct content-type (``application/x-plist``)
        * The content is valid binary plist data
        """
        self.assertHttpOK(resp)
        self.assertTrue(resp['Content-Type'].startswith('application/x-plist'))
        self.assertValidPlist(resp.content)

    def deserialize(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, this method
        checks the ``Content-Type`` header & attempts to deserialize the data based on
        that.

        It returns a Python datastructure (typically a ``dict``) of the serialized data.
        """
        return self.serializer.deserialize(resp.content,
                                           format=resp['Content-Type'])

    def serialize(self, data, format='application/json'):
        """
        Given a Python datastructure (typically a ``dict``) & a desired content-type,
        this method will return a serialized string of that data.
        """
        return self.serializer.serialize(data, format=format)

    def assertKeys(self, data, expected):
        """
        This method ensures that the keys of the ``data`` match up to the keys of
        ``expected``.

        It covers the (extremely) common case where you want to make sure the keys of
        a response match up to what is expected. This is typically less fragile than
        testing the full structure, which can be prone to data changes.
        """
        self.assertEqual(sorted(data.keys()), sorted(expected))
Ejemplo n.º 40
0
    json_indent = 2

    def to_json(self, data, options=None):
        options = options or {}
        data = self.to_simple(data, options)
        return json.dumps(data,
                          cls=json.JSONEncoder,
                          sort_keys=True,
                          ensure_ascii=False,
                          indent=self.json_indent) + "\n"


if settings.DEBUG:
    default_serializer = PrettyJSONSerializer()
else:
    default_serializer = Serializer()


class SearchObject(object):
    def __init__(self, hits=None, id=None):
        self.hits = hits
        self.id = id


class SearchAppResource(Resource):
    """Tastypie resource for simple-search"""
    hits = fields.ApiField(attribute='hits', null=True)

    class Meta:
        resource_name = 'simple-search'
        list_allowed_methods = ['get']
Ejemplo n.º 41
0
 def setUp(self):
     super(ResourceTestCase, self).setUp()
     self.serializer = Serializer()
     self.api_client = TestApiClient()
Ejemplo n.º 42
0
class TestApiClient(object):
    def __init__(self, serializer=None):
        """
        Sets up a fresh ``TestApiClient`` instance.

        If you are employing a custom serializer, you can pass the class to the
        ``serializer=`` kwarg.
        """
        self.client = Client()
        self.serializer = serializer

        if not self.serializer:
            self.serializer = Serializer()

    def get_content_type(self, short_format):
        """
        Given a short name (such as ``json`` or ``xml``), returns the full content-type
        for it (``application/json`` or ``application/xml`` in this case).
        """
        return self.serializer.content_types.get(short_format, 'json')

    def get(self,
            uri,
            format='json',
            data=None,
            authentication=None,
            **kwargs):
        """
        Performs a simulated ``GET`` request to the provided URI.

        Optionally accepts a ``data`` kwarg, which in the case of ``GET``, lets you
        send along ``GET`` parameters. This is useful when testing filtering or other
        things that read off the ``GET`` params. Example::

            from tastypie.test import TestApiClient
            client = TestApiClient()

            response = client.get('/api/v1/entry/1/', data={'format': 'json', 'title__startswith': 'a', 'limit': 20, 'offset': 60})

        Optionally accepts an ``authentication`` kwarg, which should be an HTTP header
        with the correct authentication data already setup.

        All other ``**kwargs`` passed in get passed through to the Django
        ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client
        for details.
        """
        content_type = self.get_content_type(format)
        kwargs['HTTP_ACCEPT'] = content_type

        # GET & DELETE are the only times we don't serialize the data.
        if data is not None:
            kwargs['data'] = data

        if authentication is not None:
            kwargs['HTTP_AUTHORIZATION'] = authentication

        return self.client.get(uri, **kwargs)

    def post(self,
             uri,
             format='json',
             data=None,
             authentication=None,
             **kwargs):
        """
        Performs a simulated ``POST`` request to the provided URI.

        Optionally accepts a ``data`` kwarg. **Unlike** ``GET``, in ``POST`` the
        ``data`` gets serialized & sent as the body instead of becoming part of the URI.
        Example::

            from tastypie.test import TestApiClient
            client = TestApiClient()

            response = client.post('/api/v1/entry/', data={
                'created': '2012-05-01T20:02:36',
                'slug': 'another-post',
                'title': 'Another Post',
                'user': '******',
            })

        Optionally accepts an ``authentication`` kwarg, which should be an HTTP header
        with the correct authentication data already setup.

        All other ``**kwargs`` passed in get passed through to the Django
        ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client
        for details.
        """
        content_type = self.get_content_type(format)
        kwargs['content_type'] = content_type

        if data is not None:
            kwargs['data'] = self.serializer.serialize(data,
                                                       format=content_type)

        if authentication is not None:
            kwargs['HTTP_AUTHORIZATION'] = authentication

        return self.client.post(uri, **kwargs)

    def put(self,
            uri,
            format='json',
            data=None,
            authentication=None,
            **kwargs):
        """
        Performs a simulated ``PUT`` request to the provided URI.

        Optionally accepts a ``data`` kwarg. **Unlike** ``GET``, in ``PUT`` the
        ``data`` gets serialized & sent as the body instead of becoming part of the URI.
        Example::

            from tastypie.test import TestApiClient
            client = TestApiClient()

            response = client.put('/api/v1/entry/1/', data={
                'created': '2012-05-01T20:02:36',
                'slug': 'another-post',
                'title': 'Another Post',
                'user': '******',
            })

        Optionally accepts an ``authentication`` kwarg, which should be an HTTP header
        with the correct authentication data already setup.

        All other ``**kwargs`` passed in get passed through to the Django
        ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client
        for details.
        """
        content_type = self.get_content_type(format)
        kwargs['content_type'] = content_type

        if data is not None:
            kwargs['data'] = self.serializer.serialize(data,
                                                       format=content_type)

        if authentication is not None:
            kwargs['HTTP_AUTHORIZATION'] = authentication

        return self.client.put(uri, **kwargs)

    def patch(self,
              uri,
              format='json',
              data=None,
              authentication=None,
              **kwargs):
        """
        Performs a simulated ``PATCH`` request to the provided URI.

        Optionally accepts a ``data`` kwarg. **Unlike** ``GET``, in ``PATCH`` the
        ``data`` gets serialized & sent as the body instead of becoming part of the URI.
        Example::

            from tastypie.test import TestApiClient
            client = TestApiClient()

            response = client.patch('/api/v1/entry/1/', data={
                'created': '2012-05-01T20:02:36',
                'slug': 'another-post',
                'title': 'Another Post',
                'user': '******',
            })

        Optionally accepts an ``authentication`` kwarg, which should be an HTTP header
        with the correct authentication data already setup.

        All other ``**kwargs`` passed in get passed through to the Django
        ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client
        for details.
        """
        content_type = self.get_content_type(format)
        kwargs['content_type'] = content_type

        if data is not None:
            kwargs['data'] = self.serializer.serialize(data,
                                                       format=content_type)

        if authentication is not None:
            kwargs['HTTP_AUTHORIZATION'] = authentication

        # This hurts because Django doesn't support PATCH natively.
        parsed = urlparse(uri)
        r = {
            'CONTENT_LENGTH': len(kwargs['data']),
            'CONTENT_TYPE': content_type,
            'PATH_INFO': self.client._get_path(parsed),
            'QUERY_STRING': parsed[4],
            'REQUEST_METHOD': 'PATCH',
            'wsgi.input': FakePayload(kwargs['data']),
        }
        r.update(kwargs)
        return self.client.request(**r)

    def delete(self,
               uri,
               format='json',
               data=None,
               authentication=None,
               **kwargs):
        """
        Performs a simulated ``DELETE`` request to the provided URI.

        Optionally accepts a ``data`` kwarg, which in the case of ``DELETE``, lets you
        send along ``DELETE`` parameters. This is useful when testing filtering or other
        things that read off the ``DELETE`` params. Example::

            from tastypie.test import TestApiClient
            client = TestApiClient()

            response = client.delete('/api/v1/entry/1/', data={'format': 'json'})

        Optionally accepts an ``authentication`` kwarg, which should be an HTTP header
        with the correct authentication data already setup.

        All other ``**kwargs`` passed in get passed through to the Django
        ``TestClient``. See https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client
        for details.
        """
        content_type = self.get_content_type(format)
        kwargs['content_type'] = content_type

        # GET & DELETE are the only times we don't serialize the data.
        if data is not None:
            kwargs['data'] = data

        if authentication is not None:
            kwargs['HTTP_AUTHORIZATION'] = authentication

        return self.client.delete(uri, **kwargs)
Ejemplo n.º 43
0
    def test_format_datetime(self):
        serializer = Serializer()
        self.assertEqual(
            serializer.format_datetime(
                datetime.datetime(2010, 12, 16, 2, 31, 33)),
            '2010-12-16T02:31:33')

        serializer = Serializer(datetime_formatting='iso-8601')
        self.assertEqual(
            serializer.format_datetime(
                datetime.datetime(2010, 12, 16, 2, 31, 33)),
            '2010-12-16T02:31:33')

        serializer = Serializer(datetime_formatting='iso-8601-strict')
        self.assertEqual(
            serializer.format_datetime(
                datetime.datetime(2010, 12, 16, 2, 31, 33, 10)),
            '2010-12-16T02:31:33')

        serializer = Serializer(datetime_formatting='rfc-2822')
        self.assertEqual(
            serializer.format_datetime(
                datetime.datetime(2010, 12, 16, 2, 31, 33)),
            u'Thu, 16 Dec 2010 02:31:33 -0600')

        serializer = Serializer(datetime_formatting='random-garbage')
        self.assertEqual(
            serializer.format_datetime(
                datetime.datetime(2010, 12, 16, 2, 31, 33)),
            '2010-12-16T02:31:33')

        # Stow.
        old_format = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING',
                             'iso-8601')

        settings.TASTYPIE_DATETIME_FORMATTING = 'iso-8601'
        serializer = Serializer()
        self.assertEqual(
            serializer.format_datetime(
                datetime.datetime(2010, 12, 16, 2, 31, 33)),
            '2010-12-16T02:31:33')

        settings.TASTYPIE_DATETIME_FORMATTING = 'iso-8601-strict'
        serializer = Serializer()
        self.assertEqual(
            serializer.format_datetime(
                datetime.datetime(2010, 12, 16, 2, 31, 33, 10)),
            '2010-12-16T02:31:33')

        settings.TASTYPIE_DATETIME_FORMATTING = 'rfc-2822'
        serializer = Serializer()
        self.assertEqual(
            serializer.format_datetime(
                datetime.datetime(2010, 12, 16, 2, 31, 33)),
            u'Thu, 16 Dec 2010 02:31:33 -0600')

        settings.TASTYPIE_DATETIME_FORMATTING = 'random-garbage'
        serializer = Serializer()
        self.assertEqual(
            serializer.format_datetime(
                datetime.datetime(2010, 12, 16, 2, 31, 33)),
            '2010-12-16T02:31:33')

        # Restore.
        settings.TASTYPIE_DATETIME_FORMATTING = old_format
Ejemplo n.º 44
0
Archivo: api.py Proyecto: alejo8591/etv
 class Meta:
     queryset = UserProfile.objects.all()
     resource_name = 'profile'
     serializer = Serializer(formats=['json'])
Ejemplo n.º 45
0
 def test_to_json_multirepr(self):
     serializer = Serializer()
     self.assertEqual(
         serializer.to_json(self.obj_list),
         '[{"content": "This is my very first post using my shiny new API. Pretty sweet, huh?", "created": "2010-03-30T20:05:00", "id": 1, "is_active": true, "resource_uri": "", "slug": "first-post", "title": "First Post!", "updated": "2010-03-30T20:05:00"}, {"content": "The dog ate my cat today. He looks seriously uncomfortable.", "created": "2010-03-31T20:05:00", "id": 2, "is_active": true, "resource_uri": "", "slug": "another-post", "title": "Another Post", "updated": "2010-03-31T20:05:00"}, {"content": "My neighborhood\'s been kinda weird lately, especially after the lava flow took out the corner store. Granny can hardly outrun the magma with her walker.", "created": "2010-04-01T20:05:00", "id": 4, "is_active": true, "resource_uri": "", "slug": "recent-volcanic-activity", "title": "Recent Volcanic Activity.", "updated": "2010-04-01T20:05:00"}, {"content": "Man, the second eruption came on fast. Granny didn\'t have a chance. On the upshot, I was able to save her walker and I got a cool shawl out of the deal!", "created": "2010-04-02T10:05:00", "id": 6, "is_active": true, "resource_uri": "", "slug": "grannys-gone", "title": "Granny\'s Gone", "updated": "2010-04-02T10:05:00"}]'
     )
Ejemplo n.º 46
0
    def _call(cls, host, cmd, args):
        cls.calls.append((cmd, args))
        cls.host_calls[host.fqdn].append((cmd, args))

        if not cls.succeed:
            cls._fail(host.fqdn)

        if (cmd, args) in cls.fail_commands:
            cls._fail(host.fqdn)

        mock_server = cls.mock_servers[host.address]

        log.info("invoke_agent %s %s %s" % (host, cmd, args))

        # This isn't really accurate because lnet is scanned asynchonously, but it is as close as we can get today
        # Fixme: Also I know think this is writing to the wrong thing and should be changing the mock_server entries.
        # to lnet_up, I guess the mock_server needs an lnet state really, rather than relying on nids present.
        if cmd == "load_lnet":
            synthetic_lnet_configuration(host, mock_server["nids"])
            return
        elif cmd == "device_plugin":
            # Only returns nid info today.
            return create_synthetic_device_info(host, mock_server, args["plugin"])
        elif cmd == "format_target":
            inode_size = None
            if "mkfsoptions" in args:
                inode_arg = re.search("-I (\d+)", args["mkfsoptions"])
                if inode_arg:
                    inode_size = int(inode_arg.group(1).__str__())

            if inode_size is None:
                # A 'foo' value
                inode_size = 777

            return {
                "uuid": uuid.uuid1().__str__(),
                "inode_count": 666,
                "inode_size": inode_size,
                "filesystem_type": "ext4",
            }
        elif cmd == "stop_target":
            ha_label = args["ha_label"]
            target = ManagedTarget.objects.get(ha_label=ha_label)
            return agent_result_ok
        elif cmd == "start_target":
            ha_label = args["ha_label"]
            target = ManagedTarget.objects.get(ha_label=ha_label)
            return agent_result(target.primary_host.nodename)
        elif cmd == "register_target":
            # Assume mount paths are "/mnt/testfs-OST0001" style
            mount_point = args["mount_point"]
            label = re.search("/mnt/([^\s]+)", mount_point).group(1)
            return {"label": label}
        elif cmd == "detect_scan":
            return mock_server["detect-scan"]
        elif cmd == "install_packages":
            return agent_result([])
        elif cmd == "register_server":
            api_client = TestApiClient()
            old_is_authenticated = CsrfAuthentication.is_authenticated
            try:
                CsrfAuthentication.is_authenticated = mock.Mock(return_value=True)
                api_client.client.login(username="******", password="******")
                fqdn = cls.mock_servers[host]["fqdn"]

                response = api_client.post(
                    args["url"] + "register/%s/" % args["secret"],
                    data={
                        "address": host,
                        "fqdn": fqdn,
                        "nodename": cls.mock_servers[host]["nodename"],
                        "capabilities": ["manage_targets"],
                        "version": cls.version,
                        "csr": helper.generate_csr(fqdn),
                    },
                )
                assert response.status_code == 201
                registration_data = Serializer().deserialize(response.content, format=response["Content-Type"])
                print("MockAgent.invoke returning %s" % registration_data)
                return registration_data
            finally:
                CsrfAuthentication.is_authenticated = old_is_authenticated
        elif cmd == "kernel_status":
            return {"running": "fake_kernel-0.1", "required": "fake_kernel-0.1", "available": ["fake_kernel-0.1"]}
        elif cmd == "selinux_status":
            return {"status": "Disabled"}
        elif cmd == "reboot_server":
            now = IMLDateTime.utcnow()
            log.info("rebooting %s; updating boot_time to %s" % (host, now))
            job_scheduler_notify.notify(host, now, {"boot_time": now})
        elif "socket.gethostbyname(socket.gethostname())" in cmd:
            if not mock_server["tests"]["hostname_valid"]:
                return "127.0.0.1"
            else:
                return mock_server["address"]
        elif "print os.uname()[1]" in cmd:
            return "%s\n%s" % (mock_server["nodename"], mock_server["fqdn"])
        elif "socket.getfqdn()" in cmd:
            return mock_server["fqdn"]
        elif "ping" in cmd:
            result = (0 if mock_server["tests"]["reverse_resolve"] else 2) + (
                0 if mock_server["tests"]["reverse_ping"] else 1
            )
            return result
        elif "ElectricFence" in cmd:
            return 0 if mock_server["tests"]["yum_can_update"] else 1
        elif "openssl version -a" in cmd:
            return 0 if mock_server["tests"]["openssl"] else 1
        elif "curl -k https" in cmd:
            return json.dumps({"host_id": host.id, "command_id": 0})
        elif cmd in [
            "configure_pacemaker",
            "unconfigure_pacemaker",
            "configure_target_store",
            "unconfigure_target_store",
            "deregister_server",
            "restart_agent",
            "shutdown_server",
            "host_corosync_config",
            "check_block_device",
            "set_conf_param",
            "purge_configuration",
        ]:
            return None
        elif cmd in [
            "configure_target_ha",
            "unconfigure_target_ha",
            "start_lnet",
            "stop_lnet",
            "unload_lnet",
            "unconfigure_lnet",
            "configure_corosync",
            "unconfigure_corosync",
            "start_corosync",
            "stop_corosync",
            "start_pacemaker",
            "stop_pacemaker",
            "configure_ntp",
            "unconfigure_ntp",
            "import_target",
            "export_target",
            "set_profile",
            "update_profile",
            "failover_target",
            "failback_target",
            "configure_network",
            "open_firewall",
            "close_firewall",
        ]:
            return agent_result_ok
        elif cmd == "get_corosync_autoconfig":
            return agent_result(
                {
                    "interfaces": {
                        "eth0": {"dedicated": False, "ipaddr": "192.168.0.1", "prefix": 24},
                        "eth1": {"dedicated": True, "ipaddr": "10.10.0.01", "prefix": 24},
                    },
                    "mcast_port": "666",
                }
            )
        else:
            assert False, (
                "The %s command is not in the known list for MockAgentRpc. Please add it then when people modify it a simple text search will let them know to change it here as well."
                % cmd
            )
Ejemplo n.º 47
0
 def test_to_xml_multirepr(self):
     serializer = Serializer()
     self.assertEqual(
         serializer.to_xml(self.obj_list),
         '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<objects><object type="hash"><content>This is my very first post using my shiny new API. Pretty sweet, huh?</content><created>2010-03-30T20:05:00</created><id type="integer">1</id><is_active type="boolean">True</is_active><resource_uri></resource_uri><slug>first-post</slug><title>First Post!</title><updated>2010-03-30T20:05:00</updated></object><object type="hash"><content>The dog ate my cat today. He looks seriously uncomfortable.</content><created>2010-03-31T20:05:00</created><id type="integer">2</id><is_active type="boolean">True</is_active><resource_uri></resource_uri><slug>another-post</slug><title>Another Post</title><updated>2010-03-31T20:05:00</updated></object><object type="hash"><content>My neighborhood\'s been kinda weird lately, especially after the lava flow took out the corner store. Granny can hardly outrun the magma with her walker.</content><created>2010-04-01T20:05:00</created><id type="integer">4</id><is_active type="boolean">True</is_active><resource_uri></resource_uri><slug>recent-volcanic-activity</slug><title>Recent Volcanic Activity.</title><updated>2010-04-01T20:05:00</updated></object><object type="hash"><content>Man, the second eruption came on fast. Granny didn\'t have a chance. On the upshot, I was able to save her walker and I got a cool shawl out of the deal!</content><created>2010-04-02T10:05:00</created><id type="integer">6</id><is_active type="boolean">True</is_active><resource_uri></resource_uri><slug>grannys-gone</slug><title>Granny\'s Gone</title><updated>2010-04-02T10:05:00</updated></object></objects>'
     )
Ejemplo n.º 48
0
 class Meta:
     queryset = Sector.objects.all()
     resource_name = 'sectors'
     serializer = Serializer(formats=['xml', 'json'])
Ejemplo n.º 49
0
 def test_unsafe_yaml(self):
     serializer = Serializer()
     evil_data = UnsafeObject()
     serialized = yaml.dump(evil_data)
     self.assertRaises(yaml.constructor.ConstructorError,
                       serializer.from_yaml, serialized)
Ejemplo n.º 50
0
 class Meta:
     queryset = Country.objects.all()
     resource_name = 'country-polygons'
     excludes = ['dac_country_code', 'dac_region_code', 'dac_region_name', 'iso3', 'language']
     include_resource_uri = False
     serializer = Serializer(formats=['xml', 'json'])
Ejemplo n.º 51
0
 def test_round_trip_yaml(self):
     serializer = Serializer()
     sample_data = self.get_sample2()
     serialized = serializer.to_yaml(sample_data)
     unserialized = serializer.from_yaml(serialized)
     self.assertEqual(sample_data, unserialized)
Ejemplo n.º 52
0
 class Meta:
     queryset = Activity.objects.all()
     resource_name = 'activity-list'
     max_limit = 100
     serializer = Serializer(formats=['xml', 'json'])
Ejemplo n.º 53
0
 class Meta:
     queryset = City.objects.all()
     resource_name = 'cities'
     include_resource_uri = False
     serializer = Serializer(formats=['xml', 'json'])