Ejemplo n.º 1
0
    def test_dehydrate(self):
        api = Api()
        msg_uri = api.resources['message'].get_resource_list_uri()
        client = Client()
        future_data = {
            'description' : 'soy una descripcion',
            'message' : 'yo no deberia estar aca',
            'time_to_reveal' : 6000,
            'admin_code' : "ASDSAAFA",
        }
        past_data = {
            'description' : 'soy una descripcion',
            'message' : 'yo si',
            'time_to_reveal' : -6000,
            'admin_code' : "ASDSAAFA",
        }

        response = client.post(msg_uri, future_data, parse='json')
        self.assertEqual(201, response.status_code, response.content)
        future_uri = response._headers['location'][1]

        response = client.post(msg_uri, past_data, parse='json')
        self.assertEqual(201, response.status_code, response.content)
        past_uri = response._headers['location'][1]

        response = client.get(past_uri, parse='json')
        self.assertTrue( 'code' in response.data.keys() and len(response.data['code']) )
        self.assertTrue( 'admin_code' not in response.data.keys())
        self.assertEqual(200, response.status_code, response.content)
        self.assertEqual(past_data['message'], response.data['message'])

        response = client.get(future_uri, parse='json')
        self.assertEqual(200, response.status_code)
        self.assertTrue( 'code' in response.data.keys() and len(response.data['code']) )
        self.assertEqual("",response.data['message'])
Ejemplo n.º 2
0
    def test_change_admin_code(self):
        api = Api()
        client = Client()

        (location, obj) = api.resources['message'].create_test_resource()
        old_code = obj.admin_code
        new_code = "GDFGACVAS"
        patch_data = {"admin_code": new_code}
        response = client.patch(location, patch_data, parse='json')
        obj = obj.__class__.objects.get(id=obj.id)
        self.assertEqual(old_code, obj.admin_code)

        print location
Ejemplo n.º 3
0
    def test_change_admin_code(self):
        api = Api()
        client = Client()

        (location, obj) = api.resources['message'].create_test_resource()
        old_code = obj.admin_code
        new_code = "GDFGACVAS"
        patch_data = { "admin_code" :  new_code }
        response = client.patch(location, patch_data, parse='json')
        obj = obj.__class__.objects.get(id=obj.id)
        self.assertEqual(old_code, obj.admin_code)

        print location
Ejemplo n.º 4
0
    def multi_readonly_post(self, resource_name, resource, field_name, field):
        client = Client()

        if field.readonly and resource.can_create() :
            post_data = resource.get_example_data('POST')
            
            bad_value = UnderResourceFields.generate_field_test_data(field)
            post_data[field_name] = bad_value

            post_response = client.post(resource.get_resource_list_uri(), post_data, parse='json')
            if post_response.status_code == 201:
                (prop, location) = post_response._headers['location']
                get_response = client.get(location, parse='json')
                msg = "%s.%s can be setted by a POST request even though it's readonly!."
                msg %= (resource_name, field_name)
                self.assertNotEqual(get_response.get(field_name,''), bad_value, msg)
Ejemplo n.º 5
0
    def multi_example_get_data(self, resource_name, resource):
        #only if resource allows detail GET
        if 'GET' not in resource._meta.detail_allowed_methods:
            return

        client = Client()
        if self.api.resource_allows_method(resource_name, 'GET'):
            resource.create_test_resource()
            get_response = client.get(resource.get_resource_list_uri())
            response_dict = json.loads(get_response.content)

            if len(response_dict['objects']) > 0:
                object_keys = set(response_dict['objects'][0].keys())
                expected_keys = set(resource._meta.examples['GET'].keys())

                msg = "GET example data does not match the example for resource %s - %s vs %s"
                msg %= (resource_name, expected_keys, object_keys)
                self.assertEqual(expected_keys, object_keys, msg)
Ejemplo n.º 6
0
    def multi_example_get_data(self, resource_name, resource):
        #only if resource allows detail GET
        if 'GET' not in resource._meta.detail_allowed_methods:
            return

        client = Client()
        if self.api.resource_allows_method(resource_name, 'GET'):
            resource.create_test_resource() 
            get_response = client.get(resource.get_resource_list_uri())
            response_dict = json.loads(get_response.content)

            if len(response_dict['objects']) > 0:
                object_keys = set(response_dict['objects'][0].keys())
                expected_keys = set(resource._meta.examples['GET'].keys())

                msg = "GET example data does not match the example for resource %s - %s vs %s"
                msg %= (resource_name, expected_keys, object_keys)
                self.assertEqual(expected_keys, object_keys, msg)
Ejemplo n.º 7
0
    def multi_readonly_post(self, resource_name, resource, field_name, field):
        client = Client()

        if field.readonly and resource.can_create():
            post_data = resource.get_example_data('POST')

            bad_value = UnderResourceFields.generate_field_test_data(field)
            post_data[field_name] = bad_value

            post_response = client.post(resource.get_resource_list_uri(),
                                        post_data,
                                        parse='json')
            if post_response.status_code == 201:
                (prop, location) = post_response._headers['location']
                get_response = client.get(location, parse='json')
                msg = "%s.%s can be setted by a POST request even though it's readonly!."
                msg %= (resource_name, field_name)
                self.assertNotEqual(get_response.get(field_name, ''),
                                    bad_value, msg)
Ejemplo n.º 8
0
    def multi_readonly_patch(self, resource_name, resource, field_name, field):
        client = Client()
        api = Api()

        if field.readonly and resource.can_create() :
            #Create a resource to modify it
            (location, obj) = resource.create_test_resource()
            bad_value = UnderResourceFields.generate_field_test_data(field)

            #authenticate to be allowed to modify the resource
            post_data = api.resources['userprofile'].get_example_data('POST')
            client.login(username=post_data['email'], password=post_data['password'])

            #attempt to PATCH
            patch_data = {}
            patch_data[field_name] = bad_value
            patch_response = client.patch(location,patch_data, parse='json')
            get_response = client.get(location, parse='json')

            msg = "%s.%s can be changed by a PATCH request even though it's readonly!."
            msg %= (resource_name, field_name)
            self.assertNotEqual(get_response.data.get(field_name,None), bad_value,msg)
Ejemplo n.º 9
0
    def multi_example_data(self, resource_name, resource):
        #Check existence
        client = Client()
        for method in ['POST', 'GET']:
            try:
                if self.api.resource_allows_method(resource_name, method):
                    get_example = resource._meta.examples[method]
            except (AttributeError, KeyError):
                message = "Missing example %s data for %s resource." 
                message %= (method, resource_name) 
                self.assertTrue(False,message)

        #Test POST
        if resource.can_create():
            post_response = client.post(resource.get_resource_list_uri(), 
                    resource.get_example_data('POST'))

            #TODO: find a better way to ignore missing resources on test
            if not post_response.content.startswith("Could not find the provided object via resource URI"):
                msg = "Failed to POST example data for resource '%s': %s" 
                msg %= (resource_name, post_response.content)
                self.assertEqual(post_response.status_code, 201, msg)
Ejemplo n.º 10
0
    def multi_example_data(self, resource_name, resource):
        #Check existence
        client = Client()
        for method in ['POST', 'GET']:
            try:
                if self.api.resource_allows_method(resource_name, method):
                    get_example = resource._meta.examples[method]
            except (AttributeError, KeyError):
                message = "Missing example %s data for %s resource."
                message %= (method, resource_name)
                self.assertTrue(False, message)

        #Test POST
        if resource.can_create():
            post_response = client.post(resource.get_resource_list_uri(),
                                        resource.get_example_data('POST'))

            #TODO: find a better way to ignore missing resources on test
            if not post_response.content.startswith(
                    "Could not find the provided object via resource URI"):
                msg = "Failed to POST example data for resource '%s': %s"
                msg %= (resource_name, post_response.content)
                self.assertEqual(post_response.status_code, 201, msg)
Ejemplo n.º 11
0
    def test_dehydrate(self):
        api = Api()
        msg_uri = api.resources['message'].get_resource_list_uri()
        client = Client()
        future_data = {
            'description': 'soy una descripcion',
            'message': 'yo no deberia estar aca',
            'time_to_reveal': 6000,
            'admin_code': "ASDSAAFA",
        }
        past_data = {
            'description': 'soy una descripcion',
            'message': 'yo si',
            'time_to_reveal': -6000,
            'admin_code': "ASDSAAFA",
        }

        response = client.post(msg_uri, future_data, parse='json')
        self.assertEqual(201, response.status_code, response.content)
        future_uri = response._headers['location'][1]

        response = client.post(msg_uri, past_data, parse='json')
        self.assertEqual(201, response.status_code, response.content)
        past_uri = response._headers['location'][1]

        response = client.get(past_uri, parse='json')
        self.assertTrue('code' in response.data.keys()
                        and len(response.data['code']))
        self.assertTrue('admin_code' not in response.data.keys())
        self.assertEqual(200, response.status_code, response.content)
        self.assertEqual(past_data['message'], response.data['message'])

        response = client.get(future_uri, parse='json')
        self.assertEqual(200, response.status_code)
        self.assertTrue('code' in response.data.keys()
                        and len(response.data['code']))
        self.assertEqual("", response.data['message'])
Ejemplo n.º 12
0
    def multi_readonly_patch(self, resource_name, resource, field_name, field):
        client = Client()
        api = Api()

        if field.readonly and resource.can_create():
            #Create a resource to modify it
            (location, obj) = resource.create_test_resource()
            bad_value = UnderResourceFields.generate_field_test_data(field)

            #authenticate to be allowed to modify the resource
            post_data = api.resources['userprofile'].get_example_data('POST')
            client.login(username=post_data['email'],
                         password=post_data['password'])

            #attempt to PATCH
            patch_data = {}
            patch_data[field_name] = bad_value
            patch_response = client.patch(location, patch_data, parse='json')
            get_response = client.get(location, parse='json')

            msg = "%s.%s can be changed by a PATCH request even though it's readonly!."
            msg %= (resource_name, field_name)
            self.assertNotEqual(get_response.data.get(field_name, None),
                                bad_value, msg)
Ejemplo n.º 13
0
 def setUp(self):
     self.client = Client()
     self.api = Api()
     self.users_list_url = self.api.get_resource_list_uri('userprofile')
     self.user_post_data = self.api.get_resource_example_data(
         'userprofile', 'POST')
Ejemplo n.º 14
0
class TestUserProfile(TestCase):
    def setUp(self):
        self.client = Client()
        self.api = Api()
        self.users_list_url = self.api.get_resource_list_uri('userprofile')
        self.user_post_data = self.api.get_resource_example_data(
            'userprofile', 'POST')

    def test_basic_operations(self):
        user_data = {
            "username": "******",
            "password": "******",
            "email": "*****@*****.**"
        }

        #Create a userprofile
        user = User.objects.create_user(**user_data)
        profile = UserProfile(user=user, facebook_id=31337)

        profile.username = "******"
        #Set some properties
        patch = {"facebook_id": 666}
        profile.set(**patch)

        #Get them, and check if they are returned
        self.assertEqual(profile.username, "jia200x")
        self.assertEqual(profile.user.username, "jia200x")
        self.assertEqual(profile.facebook_id, 666)

    def test_get(self):
        user = User.objects.create_user(username="******",
                                        email="*****@*****.**",
                                        password="******")
        user.save()
        profile = UserProfile.get(user)
        self.assertEqual('test1', profile.username)

    def test_missing_email(self):
        del self.user_post_data['email']
        post_response = self.client.post(self.users_list_url,
                                         self.user_post_data,
                                         parse='json')
        self.assertEqual(400, post_response.status_code)  # 400: CLIENT ERROR
        self.assertEqual(['email'], post_response.data.keys())

    def test_missing_password(self):
        del self.user_post_data['password']
        post_response = self.client.post(self.users_list_url,
                                         self.user_post_data,
                                         parse='json')
        self.assertEqual(400, post_response.status_code)  # 400: CLIENT ERROR
        self.assertEqual(['password'], post_response.data.keys())

    def test_change_password(self):
        client = self.client
        old_password = "******"
        new_password = "******"

        #obtain a test user profile
        (location,
         profile) = self.api.resources['userprofile'].create_test_resource(
             {'password': old_password})
        #login with the profile
        self.assertTrue(
            client.login(username=profile.email, password=old_password))

        #change password patch
        patch_data = {"password": new_password}
        response = client.patch(location, patch_data)

        #Attempt with new password
        self.assertEqual(202, response.status_code, response.content)
        #Try to login again with old password
        client.logout()
        self.assertFalse(
            client.login(username=profile.email, password=old_password))
        #Try with the new one
        self.assertTrue(
            client.login(username=profile.email, password=new_password))

    def test_resource(self):
        client = self.client

        #test POST
        post_response = client.post(self.users_list_url, self.user_post_data)
        self.assertEqual(post_response.status_code, 201, post_response.content)

        #test matching GET
        get_response = client.get(self.users_list_url, parse='json')
        self.assertEqual(get_response.status_code, 200, get_response.content)

        userprofile_dict = get_response.data['objects'][0]
        userprofile_keys = userprofile_dict.keys()

        self.assertTrue('email' in userprofile_keys)
        self.assertTrue('facebook_id' in userprofile_keys)

        #test attempt unauthorized put
        put_data = dict(self.user_post_data)
        put_data['first_name'] = "darth"
        put_response = client.put(userprofile_dict['resource_uri'], put_data)
        self.assertEqual(put_response.status_code, 401,
                         put_response.content)  #UNAUTHORIZED

        #test authenticate
        rpc_response = client.rpc('authenticate',
                                  email=self.user_post_data['email'],
                                  password=self.user_post_data['password'])
        self.assertEqual(200, rpc_response.status_code, rpc_response.content)

        #test PUT
        put_data = self.user_post_data
        put_data['first_name'] = "darth"
        put_response = client.put(userprofile_dict['resource_uri'], put_data)

        self.assertEqual(put_response.status_code, 204, put_response.content)

        #test PATCH
        patch_data = dict(put_data)
        patch_response = client.patch(userprofile_dict['resource_uri'],
                                      {'last_name': 'vader'})
        self.assertEqual(patch_response.status_code, 202,
                         patch_response.content)

        #test PATCH to superuser (not allowed)
        patch_data = {'is_superuser': True, 'is_staff': True}
        patch_response = client.patch(userprofile_dict['resource_uri'],
                                      patch_data)
        user_id = int(userprofile_dict['resource_uri'].split('/')[-2])
        user = User.objects.get(id=user_id)
        self.assertFalse(user.is_superuser,
                         "Allowed user to made himself superuser!")
        self.assertFalse(user.is_staff, "Allowed user to made himself staff!")

        #test PATCH to facebook_id (not allowed)
        patch_data = {'facebook_id': 12345678}
        patch_response = client.patch(userprofile_dict['resource_uri'],
                                      patch_data)
        user_id = int(userprofile_dict['resource_uri'].split('/')[-2])
        user = User.objects.get(id=user_id)
        profile = UserProfile.get(user)
        self.assertNotEqual(
            12345678, profile.facebook_id,
            "Allowed user to change his own facebook_id by POST/PUT!")

        #test matching GET
        get_response = client.get(userprofile_dict['resource_uri'],
                                  parse='json')
        userprofile_dict = get_response.data
        expected_data = dict(put_data)
        del expected_data['password']
        expected_data['last_name'] = 'vader'

        self.assertEqual(get_response.status_code, 200, get_response.content)
        self.assertDictContainsSubset(expected_data, userprofile_dict)
Ejemplo n.º 15
0
 def setUp(self):
     self.client = Client()
     self.api = Api()
     self.users_list_url = self.api.get_resource_list_uri('userprofile')
     self.user_post_data = self.api.get_resource_example_data('userprofile','POST')
Ejemplo n.º 16
0
class TestUserProfile(TestCase):
    def setUp(self):
        self.client = Client()
        self.api = Api()
        self.users_list_url = self.api.get_resource_list_uri('userprofile')
        self.user_post_data = self.api.get_resource_example_data('userprofile','POST')

    def test_basic_operations(self):
        user_data = {
            "username":"******",
            "password":"******",
            "email" : "*****@*****.**"
        }

        #Create a userprofile
        user=User.objects.create_user(**user_data)
        profile = UserProfile(user=user, facebook_id=31337)
       
        profile.username = "******"
        #Set some properties
        patch = {"facebook_id":666}
        profile.set(**patch)

        #Get them, and check if they are returned
        self.assertEqual(profile.username,"jia200x")
        self.assertEqual(profile.user.username,"jia200x")
        self.assertEqual(profile.facebook_id,666)

    def test_get(self):
        user = User.objects.create_user(username="******",
            email="*****@*****.**", password="******")
        user.save()
        profile = UserProfile.get(user)
        self.assertEqual('test1', profile.username)

    def test_missing_email(self):
        del self.user_post_data['email']
        post_response = self.client.post(self.users_list_url, 
            self.user_post_data, parse='json')
        self.assertEqual(400, post_response.status_code) # 400: CLIENT ERROR
        self.assertEqual(['email'], post_response.data.keys())

    def test_missing_password(self):
        del self.user_post_data['password']
        post_response = self.client.post(self.users_list_url, 
                self.user_post_data, parse='json')
        self.assertEqual(400, post_response.status_code) # 400: CLIENT ERROR
        self.assertEqual(['password'], post_response.data.keys())

    def test_change_password(self):
        client = self.client
        old_password = "******"
        new_password = "******" 

        #obtain a test user profile
        (location, profile) = self.api.resources['userprofile'].create_test_resource({'password' : old_password})
        #login with the profile
        self.assertTrue(client.login(username=profile.email, password=old_password))

        #change password patch
        patch_data = { "password" : new_password }
        response = client.patch(location, patch_data)

        #Attempt with new password
        self.assertEqual(202, response.status_code, response.content)
        #Try to login again with old password
        client.logout()
        self.assertFalse(client.login(username=profile.email, password=old_password))
        #Try with the new one
        self.assertTrue(client.login(username=profile.email, password=new_password))

    def test_resource(self):
        client = self.client

        #test POST
        post_response = client.post(self.users_list_url, self.user_post_data)
        self.assertEqual(post_response.status_code, 201, post_response.content)

        #test matching GET
        get_response = client.get(self.users_list_url, parse='json')
        self.assertEqual(get_response.status_code, 200, get_response.content)

        userprofile_dict = get_response.data['objects'][0]
        userprofile_keys = userprofile_dict.keys()

        self.assertTrue('email' in userprofile_keys)
        self.assertTrue('facebook_id' in userprofile_keys)

        #test attempt unauthorized put
        put_data = dict(self.user_post_data)
        put_data['first_name'] = "darth"
        put_response = client.put(userprofile_dict['resource_uri'],put_data)
        self.assertEqual(put_response.status_code, 401, put_response.content) #UNAUTHORIZED

        #test authenticate
        rpc_response = client.rpc('authenticate', 
            email=self.user_post_data['email'], password=self.user_post_data['password'])
        self.assertEqual(200,rpc_response.status_code, rpc_response.content)

        #test PUT
        put_data = self.user_post_data
        put_data['first_name'] = "darth"
        put_response = client.put(userprofile_dict['resource_uri'], put_data)

        self.assertEqual(put_response.status_code, 204, put_response.content)

        #test PATCH
        patch_data = dict(put_data)
        patch_response = client.patch(userprofile_dict['resource_uri'], {'last_name':'vader'})
        self.assertEqual(patch_response.status_code, 202, patch_response.content)

        #test PATCH to superuser (not allowed)
        patch_data = {'is_superuser': True, 'is_staff' : True}
        patch_response = client.patch(userprofile_dict['resource_uri'], patch_data)
        user_id = int(userprofile_dict['resource_uri'].split('/')[-2])
        user = User.objects.get(id=user_id)
        self.assertFalse(user.is_superuser,"Allowed user to made himself superuser!")
        self.assertFalse(user.is_staff,"Allowed user to made himself staff!")

        #test PATCH to facebook_id (not allowed)
        patch_data = {'facebook_id' : 12345678}
        patch_response = client.patch(userprofile_dict['resource_uri'], patch_data)
        user_id = int(userprofile_dict['resource_uri'].split('/')[-2])
        user = User.objects.get(id=user_id)
        profile = UserProfile.get(user)
        self.assertNotEqual(12345678,profile.facebook_id,"Allowed user to change his own facebook_id by POST/PUT!")

        #test matching GET
        get_response = client.get(userprofile_dict['resource_uri'], parse='json')
        userprofile_dict = get_response.data
        expected_data = dict(put_data)
        del expected_data['password']
        expected_data['last_name'] = 'vader'

        self.assertEqual(get_response.status_code, 200, get_response.content)
        self.assertDictContainsSubset(expected_data, userprofile_dict)