Example #1
0
    def test_decode_as_type(self):
        @decode.from_object()
        class Person(object):
            def __init__(self, first_name, last_name):
                self.first_name = first_name
                self.last_name = last_name

        @decode.from_object()
        class Job(object):
            def __init__(self, title):
                self.title = title

        json_str = '{"__type__": "Person", ' '"first_name": "shawn", ' '"last_name": "adams"}'

        self.assertEqual(decode._as_type_context.top, None)

        with decode.ensure_type(Person):
            self.assertEqual(decode._as_type_context.top, Person)
            decode.loader(json_str)

            # Test nested context
            with decode.ensure_type(Job):
                self.assertEqual(decode._as_type_context.top, Job)
                with self.assertRaises(ValidationError):
                    decode.loader(json_str)

            self.assertEqual(decode._as_type_context.top, Person)

        self.assertEqual(decode._as_type_context.top, None)
Example #2
0
def main():
    address = Address(7, 'Bamboo Av', 'Earlwood')
    print 'address='
    js = dumper(address, indent=4)
    print js
    print loader(js)

    job = Job('Engineer', True)
    print 'job='
    js = dumper(job, indent=4)
    print js
    print loader(js)

    dob = datetime.strptime('1968-08-08 06:00:00', '%Y-%m-%d %H:%M:%S')
    person = Person(0, 'David Edson', dob, 'Chief Engineer', address, [job])
    print 'person='
    js = dumper(person, indent=4)
    print js
    other = loader(js)
    print other

    print
    addressSchema = AddressSchema()
    print addressSchema, dumper(addressSchema, indent=4)
    jobSchema = JobSchema()
    print jobSchema, dumper(jobSchema, indent=4)
    personSchema = PersonSchema()
    print personSchema, dumper(personSchema, indent=4)

    return
Example #3
0
 def test_supplied_handler_dict_overrides_from_object(self):
     """
     Test that a class decorated with from_object can have its
     handler and schema overriden with a supplied dict to
     decode.object_hook
     """
     from jsonweb.decode import from_object, loader
     
     @from_object()
     class Person(object):
         def __init__(self, first_name, last_name):
             self.first_name = first_name
             self.last_name = last_name
             
     did_run = []
     def person_decoder(cls, obj):
         did_run.append(True)
         return cls(obj["first_name"], obj["last_name"])
     
     json_str = '{"__type__": "Person", "first_name": "shawn", "last_name": "adams"}'   
     person = loader(json_str)
     self.assertTrue(isinstance(person, Person))
     
     handlers = {"Person": {"handler": person_decoder}}      
     person = loader(json_str, handlers=handlers)
     self.assertTrue(isinstance(person, Person))
     self.assertTrue(did_run)
Example #4
0
    def test_decode_as_type(self):
        @decode.from_object()
        class Person(object):
            def __init__(self, first_name, last_name):
                self.first_name = first_name
                self.last_name = last_name

        @decode.from_object()
        class Job(object):
            def __init__(self, title):
                self.title = title

        json_str = ('{"__type__": "Person", '
                    '"first_name": "shawn", '
                    '"last_name": "adams"}')

        self.assertEqual(decode._as_type_context.top, None)

        with decode.ensure_type(Person):
            self.assertEqual(decode._as_type_context.top, Person)
            decode.loader(json_str)

            # Test nested context
            with decode.ensure_type(Job):
                self.assertEqual(decode._as_type_context.top, Job)
                with self.assertRaises(ValidationError):
                    decode.loader(json_str)

            self.assertEqual(decode._as_type_context.top, Person)

        self.assertEqual(decode._as_type_context.top, None)
Example #5
0
    def test_map_schema_func(self):

        class PersonSchema(ObjectSchema):
            first_name = String()
            last_name = String()
           
        @from_object()
        class Person(object):
            def __init__(self, first_name, last_name):
                self.first_name = first_name
                self.last_name = last_name        
                    
        bind_schema("Person", PersonSchema)
        with self.assertRaises(ValidationError) as context:
            loader('{"__type__": "Person"}')
Example #6
0
 def test_supplied_handler_missing_required_attrs_raise_error(self):
     """
     KeyErrors raised from within supplied object handlers should be caught and
     turned into ObjectAttributeErrors.
     """
     
     from jsonweb.decode import from_object, loader, ObjectAttributeError
     
     def person_handler(cls, obj):
         return cls(
             obj['first_name'],
             obj['last_name']
         )
     
     @from_object(person_handler)
     class Person(object):
         def __init__(self, first_name, last_name):
             self.first_name = first_name
             self.last_name = last_name
             
     json_str = '{"__type__": "Person", "first_name": "shawn"}'
     with self.assertRaises(ObjectAttributeError) as context:
         person = loader(json_str)
         
     exc = context.exception
     
     self.assertEqual(exc.extras["attribute"], "last_name")
     self.assertEqual(str(exc), "Missing last_name attribute for Person.")
Example #7
0
 def test_stacked_decorators(self):
     from jsonweb.encode import to_object, dumper
     from jsonweb.decode import from_object, loader
             
     def person_handler(cls, obj):
         return cls(
             obj['first_name'],
             obj['last_name']
         )                
             
     @to_object(suppress=["foo"])
     @from_object(person_handler)
     class Person(object):
         def __init__(self, first_name, last_name):
             self.foo = "bar"
             self.first_name = first_name
             self.last_name = last_name
             
     person = Person("shawn", "adams")
     json_str = dumper(person)
     del person
     person = loader(json_str)
     self.assertTrue(isinstance(person, Person))
              
     
Example #8
0
def main():
    try:
        fp = open(args.file)
        js = json.load(fp)
        fp.close()
    
        js['__type__'] = args.type
        for key in ['StartTime','Time','EndTime']:
            if key in js.keys():
                js[key]= js[key].replace('Z','000')
        
        if args.verbose:
            sys.stderr.write('json:')
            json.dump(js, sys.stderr, indent=4)
            sys.stderr.write('\n')

        object = loader(json.dumps(js))
        if args.type == 'Message':
            print '{0:<12} {1:<20} {2:<.40} {3:<.40}'.format(
                object.EC2InstanceId, 
                object.Time.strftime(format="%Y-%m-%d %H:%M:%S"),
                object.AutoScalingGroupName, 
                object.Description
            )
        else:
            print dumper(object,indent=4)
    except:
        None
    return
Example #9
0
    def test_schemas_do_not_run_when_validate_kw_is_false(self):

        class PersonSchema(ObjectSchema):
            first_name = String()
            last_name = String()
            
        @from_object(schema=PersonSchema)
        class Person(object):
            def __init__(self, first_name, last_name):
                self.first_name = first_name
                self.last_name = last_name
        
        json_str = '{"__type__": "Person", "last_name": "adams"}'
        with self.assertRaises(ValidationError):
            loader(json_str)
        with self.assertRaises(ObjectDecodeError):
            loader(json_str, validate=False)
Example #10
0
 def json(self):
     if self.mimetype != 'application/json':
         # Should we be more specific here?
         raise JsonWebBadRequest
     request_charset = self.mimetype_params.get('charset')
     try:
         return decode.loader(self.data, encoding=request_charset)
     except schema.ValidationError, e:
         return self.on_json_validation_error(e)
Example #11
0
 def json(self):
     if self.mimetype != "application/json":
         # Should we be more specific here?
         raise JsonWebBadRequest
     request_charset = self.mimetype_params.get("charset")
     try:
         return decode.loader(self.data, encoding=request_charset)
     except schema.ValidationError, e:
         return self.on_json_validation_error(e)
Example #12
0
    def test_map_schema_called_before_class_is_decorated(self):
        """
        Test binding a schema to a class before it is defined works.
        """

        class PersonSchema(ObjectSchema):
            first_name = String()
            last_name = String()

        bind_schema("Person", PersonSchema)
        
        @from_object()
        class Person(object):
            def __init__(self, first_name, last_name):
                self.first_name = first_name
                self.last_name = last_name        

        with self.assertRaises(ValidationError):
            loader('{"__type__": "Person"}')
Example #13
0
 def test_decodes_to_class_instance(self):
     from jsonweb.decode import from_object, loader
             
     @from_object()
     class Person(object):
         def __init__(self, first_name, last_name):
             self.first_name = first_name
             self.last_name = last_name
                             
     json_str = '{"__type__": "Person", "first_name": "shawn", "last_name": "adams"}'
     person = loader(json_str)
     
     self.assertTrue(isinstance(person, Person))        
     self.assertEqual(person.first_name, "shawn")
     self.assertEqual(person.last_name, "adams")  
Example #14
0
 def test_class_kw_args_are_optional(self):
     from jsonweb.decode import from_object, loader
     """
     Test that class keyword agruments are optional
     """
             
     @from_object()
     class Person(object):
         def __init__(self, first_name, last_name, job=None):
             self.first_name = first_name
             self.last_name = last_name
             self.job = job
                             
     json_str = '{"__type__": "Person", "first_name": "shawn", "last_name": "adams"}'
     person = loader(json_str)
     
     self.assertTrue(isinstance(person, Person))        
     self.assertEqual(person.first_name, "shawn")
     self.assertEqual(person.last_name, "adams")
     self.assertEqual(person.job, None)
     
     json_str = '{"__type__": "Person", "first_name": "shawn", "last_name": "adams", "job": "Jedi Knight"}'
     person = loader(json_str)
     self.assertEqual(person.job, "Jedi Knight")
Example #15
0
 def test_supplied_type_with_as_type(self):
     """
     Test that specifying an explicit type with ``as_type``
     decodes a json string this is missing the ``__type__`` key.
     """
     from jsonweb.decode import from_object, loader
     
     @from_object()
     class Person(object):
         def __init__(self, first_name, last_name):
             self.first_name = first_name
             self.last_name = last_name
             
     json_str = '{"first_name": "shawn", "last_name": "adams"}'
     self.assertTrue(isinstance(loader(json_str, as_type="Person"), Person))
     json_str = '''[
         {"first_name": "shawn", "last_name": "adams"},
         {"first_name": "luke", "last_name": "skywalker"}
     ]'''
     persons = loader(json_str, as_type="Person")
     self.assertTrue(isinstance(persons, list))
     self.assertEqual(len(persons), 2)
     self.assertTrue(isinstance(persons[0], Person))
     self.assertTrue(isinstance(persons[1], Person))        
Example #16
0
 def test_supplied_handler_decodes_to_class_instance(self):
     from jsonweb.decode import from_object, loader
     
     def person_handler(cls, obj):
         return cls(
             obj['first_name'],
             obj['last_name']
         )
     
     @from_object(person_handler)
     class Person(object):
         def __init__(self, first_name, last_name):
             self.first_name = first_name
             self.last_name = last_name
             
     json_str = '{"__type__": "Person", "first_name": "shawn", "last_name": "adams"}'
     person = loader(json_str)
     
     self.assertTrue(isinstance(person, Person))
Example #17
0
    def test_EnsureType_invoked_via_List_validator_honors_string_class_names(self):

        class JobSchema(ObjectSchema):
            id = Integer()
            title = String()
            
        class PersonSchema(ObjectSchema):
            first_name = String()
            last_name = String()
            jobs = List(EnsureType("Job"))
            
        @from_object(schema=JobSchema)
        class Job(object):
            def __init__(self, id, title):
                self.id = id
                self.title = title
                
        @from_object(schema=PersonSchema)
        class Person(object):
            def __init__(self, first_name, last_name, jobs):
                self.first_name = first_name
                self.last_name = last_name
                self.jobs = jobs
        
        obj = {
            "__type__": "Person",
            "first_name": "Shawn",
            "last_name": "Adams", 
            "id": 1, 
            "test": 12.0, 
            "jobs": [{
                "__type__": "Job",
                "title": "zoo keeper", 
                "id": 1
            }]
        }
                
        person = loader(json.dumps(obj))
        self.assertTrue(isinstance(person, Person))
        self.assertTrue(isinstance(person.jobs, list))
        self.assertTrue(isinstance(person.jobs[0], Job))        
Example #18
0
 def test_supplied_handler_dict(self):
     """
     Test that supplied ``handlers`` dict decodes objects.
     """
     from jsonweb.decode import loader
     
     class Person(object):
         def __init__(self, first_name, last_name):
             self.first_name = first_name
             self.last_name = last_name
             
     def person_decoder(cls, obj):
         return cls(obj["first_name"], obj["last_name"])
                 
     handlers = {"Person": {"cls": Person, "handler": person_decoder}}
     
     json_str = '{"__type__": "Person", "first_name": "shawn", "last_name": "adams"}'    
     person = loader(json_str, handlers=handlers)
     self.assertTrue(isinstance(person, Person))        
     self.assertEqual(person.first_name, "shawn")
     self.assertEqual(person.last_name, "adams")
Example #19
0
 def test_decode_encode(self, policy):
     " Test that encoding/decoding save all policy serializable features "
     policy_repr = encode.dumper(policy)
     new_policy = decode.loader(policy_repr)
     assert policy == new_policy
 def test_decode_encode(self, policy):
     """Test that encoding/decoding save all policy serializable features"""
     policy_repr = encode.dumper(policy)
     new_policy = decode.loader(policy_repr)
     assert policy == new_policy