Example #1
0
class InfoACLTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(os.path.dirname(__file__))

        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.app.registry.max_store.drop_collection('users')
        self.app.registry.max_store.drop_collection('activity')
        self.app.registry.max_store.drop_collection('contexts')
        self.app.registry.max_store.drop_collection('security')
        self.app.registry.max_store.drop_collection('conversations')
        self.app.registry.max_store.drop_collection('messages')
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    def test_get_public_settings(self):
        """
            Given i'm an unauthenticated user
            When i try to get max public settings
            Then i succeed
        """
        self.testapp.get('/info', status=200)

    def test_get_full_settings(self):
        """
            Given i'm an unauthenticated user
            When i try to get all max settings
            Then i get a Forbidden Error
        """
        self.testapp.get('/info/settings', status=401)

    def test_get_full_settings_authenticated(self):
        """
            Given i'm a regular user
            When i try to get all max settings
            Then i get a Forbidden Error
        """
        username = '******'
        self.create_user(username)
        self.testapp.get('/info/settings', headers=oauth2Header(username), status=403)

    def test_get_full_settings_as_manager(self):
        """
            Given i'm a Manager
            When i try to get all max settings
            Then i succeed
        """
        self.testapp.get('/info/settings', headers=oauth2Header(test_manager), status=200)

    def test_get_endpoints_info(self):
        """
            Given i'm an unauthenticated user
            When i try to get the endpoint definitions
            Then i succeed
        """
        self.testapp.get('/info/api', status=200)
Example #2
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

    # BEGIN TESTS

    def test_follow_user(self):
        """
        """
        username = '******'
        username2 = 'xavi'

        self.create_user(username)
        self.create_user(username2)

        res = self.testapp.post('/people/%s/follows/%s' % (username, username2), '', oauth2Header(username), status=201)
        self.assertEqual(res.json['verb'], 'follow')

        res = self.testapp.get('/people/%s' % (username), '', oauth2Header(username), status=200)
        self.assertEqual(username2, res.json['following'][0]['username'])

    def test_user_sees_followed_activity(self):
        """
        """
        from .mockers import user_status

        username = '******'
        username2 = 'xavi'

        self.create_user(username)
        self.create_user(username2)

        self.create_activity(username, user_status)
        self.create_activity(username2, user_status)

        res = self.testapp.post('/people/%s/follows/%s' % (username, username2), '', oauth2Header(username), status=201)
        self.assertEqual(res.json['verb'], 'follow')

        res = self.testapp.get('/people/%s/timeline' % (username), '', oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 2)
Example #3
0
 def setUp(self):
     conf_dir = os.path.dirname(__file__)
     self.app = loadapp('config:tests.ini', relative_to=conf_dir)
     self.reset_database(self.app)
     self.app.registry.max_store.security.insert(test_default_security)
     self.patched_post = patch('requests.post', new=partial(mock_post, self))
     self.patched_post.start()
     self.testapp = MaxTestApp(self)
Example #4
0
    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp("config:debug.ini", relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch("requests.post", new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)
Example #5
0
    def setUp(self):
        conf_dir = os.path.dirname(os.path.dirname(__file__))

        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.app.registry.max_store.drop_collection('users')
        self.app.registry.max_store.drop_collection('activity')
        self.app.registry.max_store.drop_collection('contexts')
        self.app.registry.max_store.drop_collection('security')
        self.app.registry.max_store.drop_collection('conversations')
        self.app.registry.max_store.drop_collection('messages')
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)
Example #6
0
    def setUp(self):
        self.conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=self.conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.app.registry.max_store.cloudapis.insert(test_cloudapis)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.patched_get = patch('requests.get', new=partial(mock_get, self))
        self.patched_get.start()

        self.testapp = MaxTestApp(self)
        self.create_user(test_manager)

        MaxAvatarsTestBase.setUp(self)
Example #7
0
    def setUp(self):
        conf_dir = os.path.dirname(os.path.dirname(__file__))

        self.app = loadapp("config:tests.ini", relative_to=conf_dir)
        self.app.registry.max_store.drop_collection("users")
        self.app.registry.max_store.drop_collection("activity")
        self.app.registry.max_store.drop_collection("contexts")
        self.app.registry.max_store.drop_collection("security")
        self.app.registry.max_store.drop_collection("conversations")
        self.app.registry.max_store.drop_collection("messages")
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch("requests.post", new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests_restricted_user_visibility.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    def tearDown(self):
        import pyramid.testing
        pyramid.testing.tearDown()

    # ############################################################################################################################
    #
    #  !!! IMPORTANT INFO !!! All this tests are run with the max.restricted_user_visibility_mode=True set in the .ini
    #  Tests for NonVisible users without restricted_user_visibility live in test_nonvisible.py, wich uses a different .ini
    #
    ##############################################################################################################################

    # Tests for listing people without sharing contexts (2 tests)

    def test_get_people_as_a_nonvisible_user_without_subscriptions(self):
        """
            Given i'm a nonvisible user
            When I search users
            And we don't share any context subscription
            Then I cannot see any of them
        """
        username_visible1 = 'user1'
        username_visible2 = 'user2'
        username_nonvisible1 = 'usernonvisible1'
        username_nonvisible2 = 'usernonvisible2'

        self.create_user(username_visible1)
        self.create_user(username_visible2)
        self.create_user(username_nonvisible1)
        self.create_user(username_nonvisible2)

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible2), "", oauth2Header(test_manager), status=201)

        res = self.testapp.get('/people', "", oauth2Header(username_nonvisible1), status=200)

        self.assertEqual(len(res.json), 0)

    def test_get_people_as_visible_user_without_subscriptions(self):
        """
            Given i'm a visible user
            When I search users
            And we don't share any context subscription
            Then I cannot see any of them
        """
        username_visible1 = 'user1'
        username_visible2 = 'user2'
        username_nonvisible1 = 'usernonvisible1'
        username_nonvisible2 = 'usernonvisible2'

        self.create_user(username_visible1)
        self.create_user(username_visible2)
        self.create_user(username_nonvisible1)
        self.create_user(username_nonvisible2)

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible2), "", oauth2Header(test_manager), status=201)

        res = self.testapp.get('/people', "", oauth2Header(username_visible1), status=200)

        self.assertEqual(len(res.json), 0)

    # Tests for listing people sharing contexts (2 tests)

    def test_get_people_as_nonvisible_user(self):
        """
            Given i'm a nonvisible person
            When I search users
            Then I can see all people on the same contexts as I, including other nonvisible users
        """
        from .mockers import subscribe_context, create_context
        username_visible1 = 'user1'
        username_visible2 = 'user2'
        username_nonvisible1 = 'usernonvisible1'
        username_nonvisible2 = 'usernonvisible2'

        self.create_user(username_visible1)
        self.create_user(username_visible2)
        self.create_user(username_nonvisible1)
        self.create_user(username_nonvisible2)

        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username_visible1, subscribe_context)
        self.admin_subscribe_user_to_context(username_nonvisible1, subscribe_context)
        self.admin_subscribe_user_to_context(username_nonvisible2, subscribe_context)

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible2), "", oauth2Header(test_manager), status=201)

        res = self.testapp.get('/people', "", oauth2Header(username_nonvisible1), status=200)

        self.assertEqual(len(res.json), 3)
        self.assertEqual(res.json[0]['username'], username_nonvisible2)
        self.assertEqual(res.json[1]['username'], username_nonvisible1)
        self.assertEqual(res.json[2]['username'], username_visible1)

    def test_get_people_as_visible_user(self):
        """
            Given i'm a visible user
            When I search users
            Then I can see only the visible people on the same contexts as I
        """
        from .mockers import subscribe_context, create_context
        username_visible1 = 'user1'
        username_visible2 = 'user2'
        username_visible3 = 'user3'
        username_nonvisible = 'usernonvisible'

        self.create_user(username_visible1)
        self.create_user(username_visible2)
        self.create_user(username_visible3)
        self.create_user(username_nonvisible)

        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username_visible1, subscribe_context)
        self.admin_subscribe_user_to_context(username_visible2, subscribe_context)

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible), "", oauth2Header(test_manager), status=201)

        res = self.testapp.get('/people', "", oauth2Header(username_visible1), status=200)

        self.assertEqual(len(res.json), 2)
        self.assertEqual(res.json[0]['username'], username_visible2)
        self.assertEqual(res.json[1]['username'], username_visible1)

    # Tests for start Conversations without sharing contexts (4 tests)

    def test_start_conversation_with_visible_as_nonvisible_without_sharing_contexts(self):
        from .mockers import message
        """
            Given i'm a nonvisible person
            When I try to start a conversation with a visible
            And we don't share any contexts
            Then I cannot start the conversation
        """
        username_visible1 = 'user1'
        username_nonvisible1 = 'usernonvisible1'

        self.create_user(username_visible1)
        self.create_user(username_nonvisible1)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_nonvisible1, username_visible1]

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_nonvisible1), status=403)

    def test_start_conversation_with_nonvisible_as_nonvisible_without_sharing_contexts(self):
        from .mockers import message
        """
            Given i'm a nonvisible person
            When I try to start a conversation with a nonvisible
            And we don't share any contexts
            Then I cannot start the conversation
        """
        username_nonvisible1 = 'usernonvisible1'
        username_nonvisible2 = 'usernonvisible2'

        self.create_user(username_nonvisible1)
        self.create_user(username_nonvisible2)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_nonvisible1, username_nonvisible2]

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible2), "", oauth2Header(test_manager), status=201)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_nonvisible1), status=403)

    def test_start_conversation_with_visible_as_visible_without_sharing_contexts(self):
        from .mockers import message
        """
            Given i'm a visible person
            When I try to start a conversation with a visible
            And we don't share any contexts
            Then I cannot start the conversation
        """
        username_visible1 = 'user1'
        username_visible2 = 'user2'

        self.create_user(username_visible1)
        self.create_user(username_visible2)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_visible2, username_visible1]

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_visible1), status=403)

    def test_start_conversation_with_nonvisible_as_visible_without_sharing_contexts(self):
        from .mockers import message
        """
            Given i'm a visible person
            When I try to start a conversation with a nonvisible
            And we don't share any contexts
            Then I cannot start the conversation
        """
        username_visible1 = 'user1'
        username_nonvisible1 = 'usernonvisible1'

        self.create_user(username_visible1)
        self.create_user(username_nonvisible1)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_nonvisible1, username_visible1]

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_visible1), status=403)

    # Tests for start Conversations sharing contexts (4 tests)

    def test_start_conversation_with_visible_as_nonvisible__sharing_contexts(self):
        from .mockers import message
        from .mockers import subscribe_context, create_context
        """
            Given i'm a nonvisible person
            When I try to start a conversation with a visible
            And we share a context
            Then I can start the conversation
        """
        username_visible1 = 'user1'
        username_nonvisible1 = 'usernonvisible1'

        self.create_user(username_visible1)
        self.create_user(username_nonvisible1)

        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username_visible1, subscribe_context)
        self.admin_subscribe_user_to_context(username_nonvisible1, subscribe_context)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_nonvisible1, username_visible1]

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_nonvisible1), status=201)

    def test_start_conversation_with_nonvisible_as_nonvisible_sharing_contexts(self):
        from .mockers import message
        from .mockers import subscribe_context, create_context
        """
            Given i'm a nonvisible person
            When I try to start a conversation with a nonvisible
            And we share a context
            Then I can start the conversation
        """
        username_nonvisible1 = 'usernonvisible1'
        username_nonvisible2 = 'usernonvisible2'

        self.create_user(username_nonvisible1)
        self.create_user(username_nonvisible2)

        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username_nonvisible1, subscribe_context)
        self.admin_subscribe_user_to_context(username_nonvisible2, subscribe_context)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_nonvisible1, username_nonvisible2]

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible2), "", oauth2Header(test_manager), status=201)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_nonvisible1), status=201)

    def test_start_conversation_with_visible_as_visible_sharing_contexts(self):
        from .mockers import message
        from .mockers import subscribe_context, create_context
        """
            Given i'm a visible person
            When I try to start a conversation with a visible
            And we share a context
            Then I can start the conversation
        """
        username_visible1 = 'user1'
        username_visible2 = 'user2'

        self.create_user(username_visible1)
        self.create_user(username_visible2)

        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username_visible1, subscribe_context)
        self.admin_subscribe_user_to_context(username_visible2, subscribe_context)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_visible2, username_visible1]

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_visible1), status=201)

    def test_start_conversation_with_nonvisible_as_visible_sharing_contexts(self):
        from .mockers import message
        from .mockers import subscribe_context, create_context
        """
            Given i'm a visible person
            When I try to start a conversation with a nonvisible
            And we share a context
            Then I cannot start the conversation
        """
        username_visible1 = 'user1'
        username_nonvisible1 = 'usernonvisible1'

        self.create_user(username_visible1)
        self.create_user(username_nonvisible1)

        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username_visible1, subscribe_context)
        self.admin_subscribe_user_to_context(username_nonvisible1, subscribe_context)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_nonvisible1, username_visible1]

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_visible1), status=403)
Example #9
0
class ContextACLTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(os.path.dirname(__file__))

        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.app.registry.max_store.drop_collection('users')
        self.app.registry.max_store.drop_collection('activity')
        self.app.registry.max_store.drop_collection('contexts')
        self.app.registry.max_store.drop_collection('security')
        self.app.registry.max_store.drop_collection('conversations')
        self.app.registry.max_store.drop_collection('messages')
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

    # Add context tests

    def test_add_context_as_manager(self):
        """
            Given a user that has the Manager role
            When i try to get create a context
            I succeed
        """
        from max.tests.mockers import create_context

        self.create_user(test_manager)
        self.testapp.post('/contexts', json.dumps(create_context), oauth2Header(test_manager), status=201)

    def test_add_context_as_non_manager(self):
        """
            Given a user that doesn't have the Manager role
            When i try to create a context
            I get a Forbidden exception
        """
        from max.tests.mockers import create_context
        username = '******'

        self.create_user(username)
        self.testapp.post('/contexts', json.dumps(create_context), oauth2Header(username), status=403)

    # View context tests

    def test_view_context_as_manager_with_acls(self):
        """
            Given i'm a user that has the Manager role
            When i try to update any context
            I succeed
            And I get the acls for that context
        """

        from max.tests.mockers import create_context
        self.create_user(test_manager)
        res = self.create_context(create_context)
        chash = res.json['hash']
        res = self.testapp.get('/contexts/%s?show_acls=1' % chash, "", oauth2Header(test_manager), status=200)
        self.assertGreater(len(res.json['acls']), 0)

    def test_view_context_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to update any context
            I succeed
        """

        from max.tests.mockers import create_context
        self.create_user(test_manager)
        res = self.create_context(create_context)
        chash = res.json['hash']
        self.testapp.get('/contexts/%s' % chash, "", oauth2Header(test_manager), status=200)

    def test_view_context_as_non_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to update any context
            I succeed
        """
        from max.tests.mockers import create_context
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        res = self.create_context(create_context)
        chash = res.json['hash']
        self.testapp.get('/contexts/%s' % chash, "", oauth2Header(username), status=200)

    # Get all contexts tests

    def test_get_all_contexts_as_manager(self):
        """
            Given a user that has the Manager role
            When i try to get all contexts
            I succeed
        """
        from max.tests.mockers import create_context

        self.create_user(test_manager)
        self.create_context(create_context)
        self.testapp.get('/contexts', "", oauth2Header(test_manager), status=200)

    def test_get_all_contexts_as_non_manager(self):
        """
            Given a user that doesn't have the Manager role
            When i try to get all contexts
            I get a Forbidden exception
        """
        from max.tests.mockers import create_context
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        self.create_context(create_context)
        self.testapp.get('/contexts', "", oauth2Header(username), status=403)

    # Modify context tests

    def test_modify_context_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to update any context
            I succeed
        """

        from max.tests.mockers import create_context
        self.create_user(test_manager)
        res = self.create_context(create_context)
        chash = res.json['hash']
        self.testapp.put('/contexts/%s' % chash, json.dumps({"twitterHashtag": "testhashtag"}), oauth2Header(test_manager), status=200)

    def test_modify_context_as_manager_non_owner(self):
        """
            Given i'm a user that has the Manager role
            And i'm not the owner of the context
            When i try to update any context
            I succeed
        """

        from max.tests.mockers import create_context
        self.create_user(test_manager)
        self.create_user(test_manager2)
        res = self.create_context(create_context)
        chash = res.json['hash']
        self.testapp.put('/contexts/%s' % chash, json.dumps({"twitterHashtag": "testhashtag"}), oauth2Header(test_manager2), status=200)

    def test_modify_context_as_owner(self):
        """
            Given i'm a user that don't jave the Manager role
            And is the owner of the context
            When i try to update the context
            I succeed
        """
        from max.tests.mockers import create_context
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        res = self.create_context(create_context, owner=username)
        chash = res.json['hash']
        self.testapp.put('/contexts/%s' % chash, json.dumps({"twitterHashtag": "testhashtag"}), oauth2Header(username), status=200)

    def test_modify_context_as_non_owner_non_manager(self):
        """
            Given i'm a user that don't jave the Manager role
            And is the owner of the context
            When i try to update the context
            I succeed
        """
        from max.tests.mockers import create_context
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        res = self.create_context(create_context)
        chash = res.json['hash']
        self.testapp.put('/contexts/%s' % chash, json.dumps({"twitterHashtag": "testhashtag"}), oauth2Header(username), status=403)

    # Delete context tests

    def test_delete_context_as_manager(self):
        """
            Given a user that has the Manager role
            When i try to remove a context
            I succeed
        """
        from max.tests.mockers import create_context
        self.create_user(test_manager)
        res = self.create_context(create_context)
        chash = res.json['hash']
        self.testapp.delete('/contexts/%s' % (chash,), "", oauth2Header(test_manager), status=204)

    def test_delete_context_as_manager_non_owner(self):
        """
            Given a user that has the Manager role
            And is not the owner of the context
            When i try to remove a context
            I succeed
        """
        from max.tests.mockers import create_context
        self.create_user(test_manager)
        self.create_user(test_manager2)
        res = self.create_context(create_context)
        chash = res.json['hash']
        self.testapp.delete('/contexts/%s' % (chash,), "", oauth2Header(test_manager2), status=204)

    def test_delete_context_as_owner(self):
        """
            Given a user that has doesn't have the Manager role
            And is the owner of the context
            When i try to remove a context
            I succeed
        """
        from max.tests.mockers import create_context
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        res = self.create_context(create_context, owner=username)
        chash = res.json['hash']
        self.testapp.delete('/contexts/%s' % (chash,), "", oauth2Header(username), status=204)

    def test_delete_context_as_non_manager_neither_owner(self):
        """
            Given a user that has doesn't have the Manager role
            And is not the owner of the context
            When i try to remove a context
            I get a Forbidden
        """
        from max.tests.mockers import create_context
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        res = self.create_context(create_context)
        chash = res.json['hash']
        self.testapp.delete('/contexts/%s' % (chash,), "", oauth2Header(username), status=403)

    # Test context authors

    def test_get_context_authors_as_manager(self):
        """
            Given a user that is Manager
            When i try to list context activity authors
            I succeed
        """
        from max.tests.mockers import create_context

        self.create_user(test_manager)
        res = self.create_context(create_context)
        chash = res.json['hash']
        self.testapp.get('/contexts/%s/activities/authors' % (chash,), "", oauth2Header(test_manager), status=200)

    def test_get_context_authors_as_non_manager(self):
        """
            Given a user that is not Manager
            When i try to list context activity authors
            I get a Forbidden
        """
        from max.tests.mockers import create_context
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        res = self.create_context(create_context, permissions={'read': 'subscribed'})
        chash = res.json['hash']
        self.testapp.get('/contexts/%s/activities/authors' % (chash,), "", oauth2Header(username), status=403)

    def test_get_context_authors_as_non_manager_public_context(self):
        """
            Given a user that is not Manager
            When i try to list context activity authors
            I get a Forbidden
        """
        from max.tests.mockers import create_context
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        res = self.create_context(create_context, permissions={'read': 'public'})
        chash = res.json['hash']
        self.testapp.get('/contexts/%s/activities/authors' % (chash,), "", oauth2Header(username), status=200)

    def test_get_count_context_authors_as_non_manager(self):
        """
            Given a user that is not Manager
            When i try to list the count of context activity authors
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        res = self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        chash = res.json['hash']
        self.testapp.head('/contexts/%s/activities/authors' % (chash,), oauth2Header(username), status=200)
Example #10
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

    def tearDown(self):
        import pyramid.testing
        pyramid.testing.tearDown()

    def test_add_nonvisible_role(self):
        username = '******'
        self.create_user(username)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username), "", oauth2Header(test_manager), status=201)

    # ############################################################################################################################
    #
    #  !!! IMPORTANT INFO !!! All this tests are run with the max.restricted_user_visibility_mode=False in set the .ini
    #  Tests for NonVisible users WITH restricted_user_visibility live in test_restricted_user_visibility.py, wich uses a different .ini
    #
    #  The tests on this file are the same tests on test_restricted_user_visibility.py but WITHOUT excluding the ones that test
    #  Users with shared contexts, And with different asserts, as here we have the restricted_user_visibility disabled,
    #  and shared subscriptions doesn't affect us
    #
    ##############################################################################################################################

    # Tests for listing people without sharing contexts (2 tests)

    def test_get_people_as_a_nonvisible_user_without_subscriptions(self):
        """
            Given i'm a nonvisible user
            When I search users
            Then I see everyone
        """
        username_visible1 = 'user1'
        username_visible2 = 'user2'
        username_nonvisible1 = 'usernonvisible1'
        username_nonvisible2 = 'usernonvisible2'

        self.create_user(username_visible1)
        self.create_user(username_visible2)
        self.create_user(username_nonvisible1)
        self.create_user(username_nonvisible2)

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible2), "", oauth2Header(test_manager), status=201)

        res = self.testapp.get('/people', "", oauth2Header(username_nonvisible1), status=200)

        self.assertEqual(len(res.json), 4)
        self.assertEqual(res.json[0]['username'], username_nonvisible2)
        self.assertEqual(res.json[1]['username'], username_nonvisible1)
        self.assertEqual(res.json[2]['username'], username_visible2)
        self.assertEqual(res.json[3]['username'], username_visible1)

    def test_get_people_as_visible_user_without_subscriptions(self):
        """
            Given i'm a visible user
            When I search users
            Then I only see the visible ones
        """
        username_visible1 = 'user1'
        username_visible2 = 'user2'
        username_nonvisible1 = 'usernonvisible1'
        username_nonvisible2 = 'usernonvisible2'

        self.create_user(username_visible1)
        self.create_user(username_visible2)
        self.create_user(username_nonvisible1)
        self.create_user(username_nonvisible2)

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible2), "", oauth2Header(test_manager), status=201)

        res = self.testapp.get('/people', "", oauth2Header(username_visible1), status=200)

        self.assertEqual(len(res.json), 2)
        self.assertEqual(res.json[0]['username'], username_visible2)
        self.assertEqual(res.json[1]['username'], username_visible1)

    # Tests for start Conversations without sharing contexts (4 tests)

    def test_start_conversation_with_visible_as_nonvisible_without_sharing_contexts(self):
        from .mockers import message
        """
            Given i'm a nonvisible person
            When I try to start a conversation with a visible
            Then I can start the conversation
        """
        username_visible1 = 'user1'
        username_nonvisible1 = 'usernonvisible1'

        self.create_user(username_visible1)
        self.create_user(username_nonvisible1)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_nonvisible1, username_visible1]

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_nonvisible1), status=201)

    def test_start_conversation_with_nonvisible_as_nonvisible_without_sharing_contexts(self):
        from .mockers import message
        """
            Given i'm a nonvisible person
            When I try to start a conversation with a nonvisible
            Then I can start the conversation
        """
        username_nonvisible1 = 'usernonvisible1'
        username_nonvisible2 = 'usernonvisible2'

        self.create_user(username_nonvisible1)
        self.create_user(username_nonvisible2)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_nonvisible1, username_nonvisible2]

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible2), "", oauth2Header(test_manager), status=201)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_nonvisible1), status=201)

    # In fact, this test is really a duplicate of some test in test_conversations, as
    # all users implied in conversation are regular users. Leaving it here for coherence
    def test_start_conversation_with_visible_as_visible_without_sharing_contexts(self):
        from .mockers import message
        """
            Given i'm a visible person
            When I try to start a conversation with a visible
            Then I can start the conversation
        """
        username_visible1 = 'user1'
        username_visible2 = 'user2'

        self.create_user(username_visible1)
        self.create_user(username_visible2)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_visible2, username_visible1]

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_visible1), status=201)

    def test_start_conversation_with_nonvisible_as_visible_without_sharing_contexts(self):
        from .mockers import message
        """
            Given i'm a visible person
            When I try to start a conversation with a nonvisible
            Then I cannot start the conversation
        """
        username_visible1 = 'user1'
        username_nonvisible1 = 'usernonvisible1'

        self.create_user(username_visible1)
        self.create_user(username_nonvisible1)

        message = deepcopy(message)
        message['contexts'][0]['participants'] = [username_nonvisible1, username_visible1]

        self.testapp.post('/admin/security/roles/%s/users/%s' % ('NonVisible', username_nonvisible1), "", oauth2Header(test_manager), status=201)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(username_visible1), status=403)
Example #11
0
class SubscriptionsACLTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(os.path.dirname(__file__))

        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.app.registry.max_store.drop_collection('users')
        self.app.registry.max_store.drop_collection('activity')
        self.app.registry.max_store.drop_collection('contexts')
        self.app.registry.max_store.drop_collection('security')
        self.app.registry.max_store.drop_collection('conversations')
        self.app.registry.max_store.drop_collection('messages')
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # Create subscription tests

    def test_subscribe_user_to_context_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to get subscribe another user to a context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)

    def test_subscribe_user_to_context_as_context_owner(self):
        """
            Given i'm a user that doesn't have the Manager role
            And i'm the owner of the context
            When i try to subscribe another user to a context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, owner=username)
        self.user_subscribe_user_to_context(other, subscribe_context, auth_user=username, expect=201)

    def test_self_subscribe_to_public_context_as_non_manager(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to subscribe myself to a public subscription context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)
        self.create_context(create_context, permissions={'subscribe': 'public'})
        self.user_subscribe_user_to_context(username, subscribe_context, expect=201)

    def test_self_subscribe_to_restricted_context_as_non_manager(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to subscribe myself to a restricted subscription context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)
        self.create_context(create_context, permissions={'subscribe': 'restricted'})
        self.user_subscribe_user_to_context(username, subscribe_context, expect=403)

    def test_subscribe_user_to_restricted_context_as_non_manager(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to subscribe another user to a restricted subscription context
            I get a Forbidden exception
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={'subscribe': 'restricted'})
        self.user_subscribe_user_to_context(username, subscribe_context, expect=403)

    def test_subscribe_user_to_public_context_as_non_manager(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to subscribe another user to a public subscription context
            I get a Forbidden exception
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={'subscribe': 'public'})
        self.user_subscribe_user_to_context(other, subscribe_context, auth_user=username, expect=403)

    # Unsubscribe tests

    def test_unsubscribe_user_from_context_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to unsubscribe another user from to a context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)
        self.create_context(create_context, permissions={'unsubscribe': 'restricted'})
        chash = sha1(subscribe_context['object']['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.admin_unsubscribe_user_from_context(username, chash, expect=204)

    def test_unsubscribe_user_from_context_as_context_owner(self):
        """
            Given i'm a user that doesn't have the Manager role
            And i'm the owner of the context
            When i try to unsubscribe another user from to a context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'unsubscribe': 'restricted'}, owner=username)
        chash = sha1(subscribe_context['object']['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        self.user_unsubscribe_user_from_context(other, chash, auth_user=username, expect=204)

    def test_self_unsubscribe_user_from_context_as_non_manager(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to unsubscribe another user from to a context
            I get a Forbidden Exception
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={'unsubscribe': 'restricted'})
        chash = sha1(subscribe_context['object']['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.user_unsubscribe_user_from_context(username, chash, auth_user=other, expect=403)

    def test_unsubscribe_user_from_context_allowed_unsubscribe_as_non_manager(self):
        """
            Given i'm a user that doesn't have the Manager role
            And i have permission to unsubscribe myself
            When i try to unsubscribe myself from the context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)
        self.create_context(create_context, permissions={'unsubscribe': 'subscribed'})
        chash = sha1(subscribe_context['object']['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.admin_unsubscribe_user_from_context(username, chash, expect=204)

    def test_unsubscribe_another_user_from_context_allowed_unsubscribe_as_non_manager(self):
        """
            Given i'm a user that doesn't have the Manager role
            And i have permission to unsubscribe myself
            When i try to unsubscribe other person from the context
            I get a Forbidden Exception
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={'unsubscribe': 'subscribed'})
        chash = sha1(subscribe_context['object']['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        self.user_unsubscribe_user_from_context(username, chash, auth_user=other, expect=403)

    # Get context subscriptions

    def test_get_context_subscriptions_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to get all subscriptions from a context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)
        self.create_context(create_context, permissions={'unsubscribe': 'restricted'})
        chash = sha1(subscribe_context['object']['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.testapp.get('/contexts/{}/subscriptions'.format(chash), "", headers=oauth2Header(test_manager), status=200)

    def test_get_context_subscriptions_as_owner(self):
        """
            Given i'm a user that doesn't have the Manager role
            And i'm the owner of the context
            When i try to get all subscriptions from a context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'unsubscribe': 'restricted'}, owner=username)
        chash = sha1(subscribe_context['object']['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        self.testapp.get('/contexts/{}/subscriptions'.format(chash), "", headers=oauth2Header(username), status=200)

    def test_get_context_subscriptions_as_non_manager_neither_owner(self):
        """
            Given i'm a user that doesn't have the Manager role
            And i'm not the owner of the context
            When i try to get all subscriptions from a context
            I get a Forbidden Exception
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'unsubscribe': 'restricted'}, owner=username)
        chash = sha1(subscribe_context['object']['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        self.testapp.get('/contexts/{}/subscriptions'.format(chash), "", headers=oauth2Header(other), status=403)

    def test_get_user_subscriptions_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to get all subscriptions from a user
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)
        self.create_context(create_context, permissions={'unsubscribe': 'restricted'})
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.testapp.get('/people/{}/subscriptions'.format(username), "", headers=oauth2Header(test_manager), status=200)

    def test_get_own_user_subscriptions(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to get all my subscriptions
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)

        self.create_context(create_context, permissions={'unsubscribe': 'restricted'}, owner=username)
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.testapp.get('/people/{}/subscriptions'.format(username), "", headers=oauth2Header(username), status=200)

    def test_get_user_subscriptions_as_non_manager_neither_own(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to get all subscriptions from another user
            I get a Forbidden Exception
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'unsubscribe': 'restricted'}, owner=username)
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.testapp.get('/people/{}/subscriptions'.format(username), "", headers=oauth2Header(other), status=403)

        # Test Grant subscription permissions

    def test_grant_permission_on_subscription_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to grant a permission on a user's suscription
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context

        url_hash = sha1(create_context['url']).hexdigest()
        username = '******'
        self.create_user(username)

        self.create_context(create_context, permissions={'read': 'subscribed'})
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        permission = 'write'
        self.testapp.put('/contexts/%s/permissions/%s/%s?permanent=1' % (url_hash, username, permission), "", oauth2Header(test_manager), status=201)

    def test_grant_permission_on_subscription_as_context_owner(self):
        """
            Given i'm a user that don't have the Manager role
            And i'm the owner of the context
            When i try to grant a permission on a user's suscription
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context

        url_hash = sha1(create_context['url']).hexdigest()
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'read': 'subscribed'}, owner=username)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        permission = 'write'
        self.testapp.put('/contexts/%s/permissions/%s/%s?permanent=1' % (url_hash, other, permission), "", oauth2Header(username), status=201)

    def test_grant_permission_on_subscription_as_non_manager_nor_owner(self):
        """
            Given i'm a user that don't have the Manager role
            And i'm not the owner of the context
            When i try to grant a permission on a user's suscription
            I get a Forbidden Exception
        """
        from max.tests.mockers import create_context, subscribe_context

        url_hash = sha1(create_context['url']).hexdigest()
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'read': 'subscribed'}, owner=username)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        permission = 'write'
        self.testapp.put('/contexts/%s/permissions/%s/%s?permanent=1' % (url_hash, other, permission), "", oauth2Header(other), status=403)

        # Test revoke subscription permissions

    def test_revoke_permission_on_subscription_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to revoke a permission on a user's suscription
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context

        url_hash = sha1(create_context['url']).hexdigest()
        username = '******'
        self.create_user(username)

        self.create_context(create_context, permissions={'read': 'subscribed'})
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        permission = 'write'
        self.testapp.delete('/contexts/%s/permissions/%s/%s?permanent=1' % (url_hash, username, permission), "", oauth2Header(test_manager), status=201)

    def test_revoke_permission_on_subscription_as_context_owner(self):
        """
            Given i'm a user that don't have the Manager role
            And i'm the owner of the context
            When i try to revoke a permission on a user's suscription
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context

        url_hash = sha1(create_context['url']).hexdigest()
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'read': 'subscribed'}, owner=username)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        permission = 'write'
        self.testapp.delete('/contexts/%s/permissions/%s/%s?permanent=1' % (url_hash, other, permission), "", oauth2Header(username), status=201)

    def test_revoke_permission_on_subscription_as_non_manager_nor_owner(self):
        """
            Given i'm a user that don't have the Manager role
            And i'm not the owner of the context
            When i try to revoke a permission on a user's suscription
            I get a Forbidden Exception
        """
        from max.tests.mockers import create_context, subscribe_context

        url_hash = sha1(create_context['url']).hexdigest()
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'read': 'subscribed'}, owner=username)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        permission = 'write'
        self.testapp.delete('/contexts/%s/permissions/%s/%s?permanent=1' % (url_hash, other, permission), "", oauth2Header(other), status=403)

        # Test revoke subscription permissions

    def test_reset_permission_defaults_on_subscription_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to reset all permission on a user's suscription to defaults
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context

        url_hash = sha1(create_context['url']).hexdigest()
        username = '******'
        self.create_user(username)

        self.create_context(create_context, permissions={'read': 'subscribed'})
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        self.testapp.post('/contexts/%s/permissions/%s/defaults' % (url_hash, username), "", oauth2Header(test_manager), status=200)

    def test_reset_permission_defaults_on_subscription_as_context_owner(self):
        """
            Given i'm a user that don't have the Manager role
            And i'm the owner of the context
            When i try to reset all permission on a user's suscription to defaults
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context

        url_hash = sha1(create_context['url']).hexdigest()
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'read': 'subscribed'}, owner=username)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        self.testapp.post('/contexts/%s/permissions/%s/defaults' % (url_hash, other), "", oauth2Header(username), status=200)

    def test_reset_permission_defaults_on_subscription_as_non_manager_nor_owner(self):
        """
            Given i'm a user that don't have the Manager role
            And i'm not the owner of the context
            When i try to reset all permission on a user's suscription to defaults
            I get a Forbidden Exception
        """
        from max.tests.mockers import create_context, subscribe_context

        url_hash = sha1(create_context['url']).hexdigest()
        username = '******'
        other = 'penny'

        self.create_user(username)
        self.create_user(other)

        self.create_context(create_context, permissions={'read': 'subscribed'}, owner=username)
        self.admin_subscribe_user_to_context(other, subscribe_context, expect=201)
        self.testapp.post('/contexts/%s/permissions/%s/defaults' % (url_hash, other), "", oauth2Header(other), status=403)
Example #12
0
class FunctionalTests(unittest.TestCase, MaxTestBase, MaxAvatarsTestBase):

    def setUp(self):
        self.conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=self.conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    def tearDown(self):
        shutil.rmtree('{}/exceptions'.format(self.conf_dir))

    # BEGIN TESTS

    def test_root(self):
        """
            Test site root is accessible and returns html
        """
        res = self.testapp.get('/', status=200)
        self.assertEqual(res.content_type, 'text/html')

    def test_bad_test_call_warning(self):
        """
            Test calling a service with missing body parameter, and the authorization as body.
            As this will only probably happen in tests, The error message is targeted so.
        """
        username = '******'
        self.create_user(username)
        res = self.testapp.post('/people/%s/activities' % username, oauth2Header(test_manager), status=401)
        self.assertEqual(res.json['error_description'], u'Authorization found in url params, not in request. Check your tests, you may be passing the authentication headers as the request body...')

    @patch('max.models.user.User.insert', fucked_up_insert)
    def test_generic_exception_catching(self):
        """
            Test calling a webservice mocked to force an exception, to test the scavenger
            that formats beautiful json error messages for uncatched exceptions
        """
        username = '******'
        res = self.create_user(username, expect=500)
        self.assertEqual(res.json['error'], 'ServerError')
        self.assertIn('BEGIN EXCEPTION REPORT', res.json['error_description'])
        self.assertIn('END EXCEPTION REPORT', res.json['error_description'])

    def test_bad_body_content_parsing(self):
        """
            Test calling a service with a list on post body, that expects a json object.
            It should fail
        """
        username = '******'
        self.testapp.post('/people/%s' % username, '[]', oauth2Header(username), status=400)

    def test_post_tunneling_on_delete(self):
        """
            Test that calling a endpoint with DELETE indirectly within a POST
            actually calls the real delete method
        """
        from .mockers import user_status
        username = '******'
        self.create_user(username)
        res = self.create_activity(username, user_status)
        activity_id = res.json['id']
        headers = oauth2Header(test_manager)
        headers['X-HTTP-Method-Override'] = 'DELETE'
        self.testapp.post('/activities/{}'.format(activity_id), '', headers, status=204)

    def test_compat_id_match(self):
        """
        """
        username = '******'
        self.create_user(username)
        headers = oauth2Header(username)
        headers['X-Max-Compat-ID'] = 'test'
        self.testapp.get('/people', headers=headers, status=200)

    def test_compat_id_mismatch(self):
        """
        """
        username = '******'
        self.create_user(username)
        headers = oauth2Header(username)
        headers['X-Max-Compat-ID'] = 'test2'
        self.testapp.get('/people', headers=headers, status=412)

    def test_post_tunneling_on_put(self):
        """
            Test that calling a endpoint with PUT indirectly within a POST
            actually calls the real PUT method
        """
        username = '******'
        self.create_user(username)
        headers = oauth2Header(username)
        headers['X-HTTP-Method-Override'] = 'PUT'
        res = self.testapp.post('/people/{}'.format(username), json.dumps({"displayName": "Lionel Messi"}), headers, status=200)
        self.assertEqual(res.request.method, 'PUT')
        self.assertEqual(res.json['displayName'], 'Lionel Messi')

    def test_post_tunneling_on_get(self):
        """
            Test that calling a endpoint with GET indirectly within a POST
            with the headers as post data
            actually calls the real GET method with the "post data headers" injected on real headers
        """
        username = '******'
        self.create_user(username)
        params = oauth2Header(username)
        params['X-HTTP-Method-Override'] = 'GET'
        res = self.testapp.post('/people', params, status=200)
        self.assertEqual(res.request.method, 'GET')
        self.assertEqual(res.request.headers['X-Oauth-Username'], params['X-Oauth-Username'])
        self.assertEqual(res.request.headers['X-Oauth-Scope'], params['X-Oauth-Scope'])
        self.assertEqual(res.request.headers['X-Oauth-Token'], params['X-Oauth-Token'])

    def test_image_rotation_180(self):
        from max.utils.image import rotate_image_by_EXIF
        from PIL import Image

        image = Image.open('{}/truita2.jpg'.format(self.conf_dir))
        rotated = rotate_image_by_EXIF(image)
        self.assertNotEqual(image, rotated)

    def test_image_rotation_no_rotation(self):
        from max.utils.image import rotate_image_by_EXIF
        from PIL import Image

        image = Image.open('{}/avatar.png'.format(self.conf_dir))
        rotated = rotate_image_by_EXIF(image)
        self.assertEqual(image, rotated)

    # __del__ is patched to avoid "ignored exceptions", just to avoid visual noise on test output.
    @patch('pymongo.cursor.Cursor.__del__', noop)
    @patch('pymongo.cursor.Cursor.__init__', mocked_cursor_init)
    def test_mongodb_autoreconnect(self):
        """
            Test that if mongodb disconnects once was connected, a autoreconect loop
            will start waiting for mongodb to recover
        """
        from max.tests.base import FAILURES
        FAILURES.set(3)

        username = '******'
        self.create_user(username)
        self.testapp.get('/people/{}'.format(username), '', headers=oauth2Header(test_manager), status=200)

    # __del__ is patched to avoid "ignored exceptions", just to avoid visual noise on test output.
    @patch('pymongo.cursor.Cursor.__del__', noop)
    @patch('pymongo.cursor.Cursor.__init__', partial(mocked_cursor_init, raise_at_end=True))
    def test_mongodb_autoreconnect_and_crash(self):
        """
            Test that if mongodb disconnects once was connected, a autoreconect loop
            will start waiting for mongodb to recover, And if a different exception raises
            in between, loop will exit and raise the exception
        """
        from max.tests.base import FAILURES
        FAILURES.set(3)

        username = '******'
        res = self.create_user(username, expect=500)
        self.assertEqual(res.json['error'], 'ServerError')

    def test_request_dumper(self):
        """
            Test request dumper logs requests when activated on
            assigned signal USER1 handler
        """
        import io
        import logging
        import signal
        from max.tweens import request_logger

        # Intercept logger to a variable
        request_logger.setLevel(logging.DEBUG)
        log_capture_string = io.StringIO()
        log_handler = logging.StreamHandler(log_capture_string)
        log_handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(message)s')
        log_handler.setFormatter(formatter)
        request_logger.addHandler(log_handler)

        # Retrieve the assigned handler
        handler = signal.getsignal(signal.SIGUSR1)

        handler()  # Enable request dumper
        self.create_user('messi')
        handler()  # Disable request dumper

        # Read lines from captured log
        log_capture_string.seek(0)
        lines = log_capture_string.readlines()
        log_capture_string.close()

        self.assertGreater(len(lines), 2)
        self.assertEqual(lines[0].strip(), 'Enabling request dumper')
        self.assertEqual(lines[-1].strip(), 'Disabling request dumper')

    def test_api_info(self):
        """
            Test that api info endpoint reports all non-info routes
            Test (single route) that expected keys are present on route and method levels
        """
        from max.routes import RESOURCES
        defined_routes = [route_name for route_name in RESOURCES.keys() if not route_name.startswith('info')]

        res = self.testapp.get('/info/api', status=200)

        api_route_names = res.json.keys()
        self.assertIsInstance(res.json, dict)
        self.assertItemsEqual(api_route_names, defined_routes)
        self.assertItemsEqual(res.json['user'].keys(), [u'category', u'name', u'url', u'route', u'filesystem', u'id', u'methods'])
        self.assertItemsEqual(res.json['user']['methods']['GET'].keys(), [u'rest_params', u'query_params', u'documentation', u'description', u'permission', u'modifiers', u'payload'])

    def test_api_info_by_category(self):
        """
        """
        from max.routes import RESOURCES
        defined_categories = list(set([route.get('category') for name, route in RESOURCES.items() if route.get('category')]))
        res = self.testapp.get('/info/api?by_category=1', status=200)

        listed_categories = [category['name'] for category in res.json]

        self.assertIsInstance(res.json, list)
        self.assertItemsEqual(defined_categories, listed_categories)
        self.assertItemsEqual(res.json[0].keys(), [u'name', u'resources', u'id'])

    def test_raw_request_parsing(self):
        """
        """
        from max.exceptions.scavenger import format_raw_request
        from .mockers import mock_request

        res = format_raw_request(mock_request)
        replaced_image = "Content-type: image/png\r\n\r\n<Image data 20496 bytes>\r\n"
        self.assertIn(replaced_image, res)

    def test_raw_request_parsing_error(self):
        """
        """
        from max.exceptions.scavenger import format_raw_request
        from .mockers import mock_request_bad_request

        res = format_raw_request(mock_request_bad_request)
        self.assertIn('*** Error parsing request ***', res)
        self.assertIn('*** End traceback ***', res)

    def test_raw_request_parsing_bad_encoding_error(self):
        """
        """
        from max.exceptions.scavenger import format_raw_request
        from .mockers import mock_request_bad_encoding

        res = format_raw_request(mock_request_bad_encoding)
        self.assertIn('*** Unicode Decode Error parsing request, request trunked at byte 569 ***', res)

    def test_raw_response_parsing(self):
        MaxAvatarsTestBase.setUp(self)
        from max.exceptions.scavenger import format_raw_response
        res = self.testapp.get('/people/test_manager/avatar')
        parsed = format_raw_response(res)
        self.assertIn('<Image data 3909 bytes>', parsed)
        MaxAvatarsTestBase.tearDown(self)
Example #13
0
class TimelineACLTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(os.path.dirname(__file__))

        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.app.registry.max_store.drop_collection('users')
        self.app.registry.max_store.drop_collection('activity')
        self.app.registry.max_store.drop_collection('contexts')
        self.app.registry.max_store.drop_collection('security')
        self.app.registry.max_store.drop_collection('conversations')
        self.app.registry.max_store.drop_collection('messages')
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # View user timeline

    def test_get_timeline(self):
        """
            Given i'm a regular user
            When i try to get my timeline
            I succeed
        """
        username = '******'
        self.create_user(username)
        self.testapp.get('/people/%s/timeline' % username, '', oauth2Header(username), status=200)

    def test_get_timeline_as_manager(self):
        """
            Given i'm a Manager user
            When i try to get another user's timeline
            I succeed
        """
        username = '******'
        self.create_user(username)
        self.testapp.get('/people/%s/timeline' % username, '', oauth2Header(test_manager), status=200)

    def test_get_timeline_as_other(self):
        """
            Given i'm a regular user
            When i try to get another user's timeline
            I get a Forbidden Exception
        """
        username = '******'
        other = 'penny'
        self.create_user(username)
        self.create_user(other)

        self.testapp.get('/people/%s/timeline' % username, '', oauth2Header(other), status=403)

    # View user timeline authors

    def test_get_timeline_authors(self):
        """
            Given i'm a regular user
            When i try to get my timeline authors
            I succeed
        """
        username = '******'
        self.create_user(username)
        self.testapp.get('/people/%s/timeline/authors' % username, '', oauth2Header(username), status=200)

    def test_get_timeline_authors_as_manager(self):
        """
            Given i'm a Manager user
            When i try to get another user's timeline authors
            I succeed
        """
        username = '******'
        self.create_user(username)
        self.testapp.get('/people/%s/timeline/authors' % username, '', oauth2Header(test_manager), status=200)

    def test_get_timeline_authors_as_other(self):
        """
            Given i'm a regular user
            When i try to get another user's timeline authors
            I get a Forbidden Exception
        """
        username = '******'
        other = 'penny'
        self.create_user(username)
        self.create_user(other)

        self.testapp.get('/people/%s/timeline/authors' % username, '', oauth2Header(other), status=403)
Example #14
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)
    # BEGIN TESTS

    def test_invalid_token(self):
        username = '******'
        res = self.testapp.post('/people/%s' % username, json.dumps({}), oauth2Header(test_manager, token='bad token'), status=401)
        self.assertEqual(res.json['error_description'], 'Invalid token.')

    def test_invalid_token_TEMPORARY(self):
        from hashlib import sha1
        from .mockers import create_context

        mindundi = 'messi'
        self.create_user(mindundi)
        self.create_context(create_context, owner=mindundi)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterHashtag": "assignatura1"}), oauth2Header(mindundi, token='bad token'), status=401)
        self.assertEqual(res.json['error_description'], 'Invalid token.')

    def test_invalid_scope(self):
        username = '******'
        headers = oauth2Header(test_manager)
        headers['X-Oauth-Scope'] = 'Invalid scope'
        res = self.testapp.post('/people/%s' % username, "", headers, status=401)
        self.assertEqual(res.json['error_description'], 'The specified scope is not allowed for this resource.')

    def test_invalid_scope_TEMPORARY(self):
        from hashlib import sha1
        from .mockers import create_context

        mindundi = 'messi'
        headers = oauth2Header(test_manager)
        headers['X-Oauth-Scope'] = 'Invalid scope'
        self.create_user(mindundi)
        self.create_context(create_context, owner=mindundi)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterHashtag": "assignatura1"}), headers, status=401)
        self.assertEqual(res.json['error_description'], 'The specified scope is not allowed for this resource.')

    def test_required_user_not_found(self):
        from hashlib import sha1
        from .mockers import create_context

        mindundi = 'messi'
        self.create_context(create_context, owner=mindundi)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterHashtag": "assignatura1"}), oauth2Header(mindundi), status=400)
        self.assertEqual(res.json['error_description'], 'Unknown actor identified by: messi')

    def test_post_activity_no_auth_headers(self):
        from .mockers import user_status
        username = '******'
        self.create_user(username)
        res = self.testapp.post('/people/%s/activities' % username, json.dumps(user_status), status=401)
        result = json.loads(res.text)
        self.assertEqual(result.get('error', None), 'Unauthorized')
Example #15
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    def tearDown(self):
        self.patched_post.stop()

    # BEGIN TESTS

    def test_create_activity_strip_tags(self):
        """ doctest .. http:post:: /people/{username}/activities """
        from .mockers import user_status
        username = '******'
        self.create_user(username)
        res = self.testapp.post('/people/%s/activities' % username, json.dumps(user_status), oauth2Header(username), status=201)
        self.assertEqual(res.json['object']['content'], u"[A] Testejant la creació d'un canvi d'estatus")

    def test_post_comment_strip_tags(self):
        """ doctest .. http:post:: /activities/{activity}/comments """
        from .mockers import user_status, user_comment
        from .mockers import subscribe_context, create_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity = self.create_activity(username, user_status)
        activity = activity.json
        res = self.testapp.post('/activities/%s/comments' % str(activity.get('id')), json.dumps(user_comment), oauth2Header(username), status=201)
        self.assertEqual(res.json['object']['content'], u"[C] Testejant un comentari nou a una activitat")

    def test_post_message_to_conversation_strip_tags(self):
        """ doctest .. http:post:: /conversations """
        from .mockers import message_with_tags
        sender = 'messi'
        recipient = 'xavi'
        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(message_with_tags), oauth2Header(sender), status=201)
        self.assertEqual(res.json['object']['content'], u'A <strong>text</strong> A')

    def test_post_activity_shortens_url(self):
        """  """
        from .mockers import user_status_with_url
        username = '******'
        self.create_user(username)
        res = self.create_activity(username, user_status_with_url)
        self.assertIn('bit.ly', res.json['object']['content'],)

    @httpretty.activate
    def test_url_shortened_bitly_failure(self):
        from max.utils.formatting import shortenURL

        http_mock_bitly(status=500)
        url = 'http://example.com'
        bitly_username = '******'
        bitly_api_key = 'R_1123ce7d9aea4d699f65af02912c048e'
        newurl = shortenURL(url, bitly_username, bitly_api_key)
        self.assertEqual(url, newurl)

    @httpretty.activate
    def test_url_shortened_parsing_failure(self):
        from max.utils.formatting import shortenURL

        http_mock_bitly(status=500, body="invalid json")
        url = 'http://example.com'
        bitly_username = '******'
        bitly_api_key = 'R_1123ce7d9aea4d699f65af02912c048e'
        newurl = shortenURL(url, bitly_username, bitly_api_key)
        self.assertEqual(url, newurl)

    @httpretty.activate
    def test_url_shortened(self):
        from max.utils.formatting import shortenURL

        http_mock_bitly()
        url = 'http://example.com'
        bitly_username = '******'
        bitly_api_key = 'R_1123ce7d9aea4d699f65af02912c048e'
        newurl = shortenURL(url, bitly_username, bitly_api_key)
        self.assertEqual(newurl, "http://shortened.url")

    @httpretty.activate
    def test_url_secure_shortened(self):
        from max.utils.formatting import shortenURL

        http_mock_bitly()
        url = 'http://example.com'
        bitly_username = '******'
        bitly_api_key = 'R_1123ce7d9aea4d699f65af02912c048e'
        newurl = shortenURL(url, bitly_username, bitly_api_key, secure=True)
        self.assertEqual(newurl, "https://shortened.url")
Example #16
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # BEGIN TESTS

    def test_has_remaining_items(self):
        """
            Given there are more than 10 users
            When i query 10 users
            I get a X-Has-Remaining-Items header
        """
        # Create 9 users +  1 already existing (test_manager)
        for i in range(10):
            self.create_user('user-{}'.format(i))

        res = self.testapp.get('/people', headers=oauth2Header(test_manager), status=200)
        self.assertEqual(len(res.json), 10)
        self.assertEqual(res.headers['X-Has-Remaining-Items'], '1')

    def test_not_has_remaining_items_wihout_limit(self):
        """
            Given there are more than 10 users
            When i query unlimited users
            I don't get a X-Has-Remaining-Items header
        """
        # Create 9 users +  1 already existing (test_manager)
        for i in range(10):
            self.create_user('user-{}'.format(i))

        res = self.testapp.get('/people?limit=0', headers=oauth2Header(test_manager), status=200)
        self.assertEqual(len(res.json), 11)
        self.assertNotIn('X-Has-Remaining-Items', res.headers)

    def test_not_has_remaining_items(self):
        """
            Given there are exactly 10 users
            When i query 10 users
            I don't get a X-Has-Remaining-Items header
        """
        # Create 9 users +  1 already existing (test_manager)
        for i in range(9):
            self.create_user('user-{}'.format(i))

        res = self.testapp.get('/people', headers=oauth2Header(test_manager), status=200)
        self.assertEqual(len(res.json), 10)
        self.assertNotIn('X-Has-Remaining-Items', res.headers)

    def test_activities_keyword_generation(self):
        """
                Tests that all words passing regex are included in keywords
                Tests that username that creates the activity is included in keywords
                Tests that displayName of user that creates the activity is included in keywords
                Tests that username that creates the comment is included in keywords
                Tests that displayName of user that creates the comment is included in keywords
                Tests that a keyword of a comment is included in keywords
        """
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context, user_comment

        username = '******'
        username2 = 'xavi'
        self.create_user(username, displayName="Lionel Messi")
        self.create_user(username2, displayName="Xavi Hernandez")
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username2, subscribe_context)
        activity = self.create_activity(username, user_status_context).json
        res = self.testapp.post('/activities/%s/comments' % str(activity['id']), json.dumps(user_comment), oauth2Header(username2), status=201)
        res = self.testapp.get('/activities/%s' % str(activity['id']), json.dumps({}), oauth2Header(username), status=200)
        expected_keywords = [u'activitat', u'canvi', u'comentari', u'creaci\xf3', u'estatus', u'hernandez', u'lionel', u'messi', u'nou', u'testejant', u'una', u'xavi']
        response_keywords = res.json['keywords']
        response_keywords.sort()
        self.assertListEqual(response_keywords, expected_keywords)

    def test_activities_keyword_generation_after_comment_delete(self):
        """
            test that the keywords supplied by a comment disappers from activity when deleting the comment
        """
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context, user_comment

        username = '******'
        username2 = 'xavi'
        self.create_user(username, displayName="Lionel Messi")
        self.create_user(username2, displayName="Xavi Hernandez")
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username2, subscribe_context)
        activity = self.create_activity(username, user_status_context).json
        res = self.testapp.post('/activities/%s/comments' % str(activity['id']), json.dumps(user_comment), oauth2Header(username2), status=201)
        comment_id = res.json['id']
        res = self.testapp.delete('/activities/%s/comments/%s' % (str(activity['id']), comment_id), "", oauth2Header(username2), status=204)
        res = self.testapp.get('/activities/%s' % str(activity['id']), json.dumps({}), oauth2Header(username), status=200)
        expected_keywords = [u'canvi', u'creaci\xf3', u'estatus', u'lionel', u'messi', u'testejant']
        response_keywords = res.json['keywords']
        response_keywords.sort()
        self.assertListEqual(response_keywords, expected_keywords)

    def test_activities_hashtag_generation(self):
        """
                Tests that all hashtags passing regex are included in _hashtags
                Tests that a hashtag of a comment is included in hashtags
        """
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context_with_hashtag, user_comment_with_hashtag

        username = '******'
        self.create_user(username)
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        res = self.create_activity(username, user_status_context_with_hashtag)
        activity = json.loads(res.text)
        res = self.testapp.post('/activities/%s/comments' % str(activity.get('id')), json.dumps(user_comment_with_hashtag), oauth2Header(username), status=201)
        res = self.testapp.get('/activities/%s' % str(activity.get('id')), json.dumps({}), oauth2Header(username), status=200)
        result = json.loads(res.text)
        expected_hashtags = [u'canvi', u'comentari', u'nou']
        self.assertListEqual(result['object']['hashtags'], expected_hashtags)

    def test_context_activities_hashtag_search(self):
        """
        """
        from .mockers import context_query
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context

        username = '******'
        self.create_user(username)
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)
        self.create_activity(username, user_status_context, note='text with hashtag #test')

        res = self.testapp.get('/contexts/%s/activities?hashtag=test' % (context_query['context']), '', oauth2Header(username), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 1)

    def test_context_activities_keyword_search(self):
        """
        """
        from .mockers import context_query
        from .mockers import context_query_kw_search
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context

        username = '******'
        self.create_user(username)
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)

        res = self.testapp.get('/contexts/%s/activities' % (context_query['context']), context_query_kw_search, oauth2Header(username), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 1)

    def test_context_comments_keyword_search(self):
        """
        """
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context
        from .mockers import user_comment

        username = '******'
        self.create_user(username)
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)
        activity_1_id = self.create_activity(username, user_status_context, note='Second activity').json['id']

        res = self.testapp.post('/activities/%s/comments' % activity_1_id, json.dumps(user_comment), oauth2Header(username), status=201)
        res = self.testapp.get('/activities/comments', {'keyword': ['comentari']}, oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0]['object']['inReplyTo'][0]['id'], activity_1_id)

    def test_context_activities_actor_search(self):
        """
        """
        from .mockers import context_query
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context

        username = '******'
        self.create_user(username)
        username2 = 'xavi'
        self.create_user(username2)
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username2, subscribe_context)
        self.create_activity(username, user_status_context)
        self.create_activity(username, user_status_context, note="second")
        self.create_activity(username2, user_status_context)

        res = self.testapp.get('/contexts/%s/activities?actor=%s' % (context_query['context'], username), '', oauth2Header(username), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 2)
        self.assertEqual(result[0].get('actor', None).get('username'), 'messi')
        self.assertEqual(result[1].get('actor', None).get('username'), 'messi')

    def test_timeline_activities_actor_search(self):
        """
        """
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context

        username = '******'
        self.create_user(username)
        username2 = 'xavi'
        self.create_user(username2)
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username2, subscribe_context)
        self.create_activity(username, user_status_context)
        self.create_activity(username, user_status_context, note="second")
        self.create_activity(username2, user_status_context)
        self.create_activity(username2, user_status_context, note="second")

        res = self.testapp.get('/people/%s/timeline?actor=%s' % (username, username), '', oauth2Header(username), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 2)
        self.assertEqual(result[0].get('actor', None).get('username'), 'messi')
        self.assertEqual(result[1].get('actor', None).get('username'), 'messi')

    def test_timeline_user_filter_activities_by_other_actor_and_not_permission_in_community(self):
        """
        """
        from .mockers import create_context, create_contextA
        from .mockers import subscribe_context, user_status_context

        username = '******'
        self.create_user(username)
        username2 = 'xavi'
        self.create_user(username2)
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)
        self.create_activity(username, user_status_context, note="second")

        res = self.testapp.get('/people/%s/timeline?actor=%s' % (username2, username), '', oauth2Header(username2), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 0)

    def test_timeline_user_filter_activities_by_other_actor_and_have_permission_community(self):
        """
        """
        from .mockers import create_context, create_contextA
        from .mockers import subscribe_context, user_status_context

        username = '******'
        self.create_user(username)
        username2 = 'xavi'
        self.create_user(username2)
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username2, subscribe_context)
        self.create_activity(username, user_status_context)
        self.create_activity(username, user_status_context, note="second")

        res = self.testapp.get('/people/%s/timeline?actor=%s' % (username2, username), '', oauth2Header(username2), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 2)
        self.assertEqual(result[0].get('actor', None).get('username'), 'messi')
        self.assertEqual(result[1].get('actor', None).get('username'), 'messi')

    def test_contexts_search(self):
        """
            Given an admin user
            When I search for all contexts
            Then I get them all
        """
        from .mockers import create_context, create_contextA, create_contextB

        self.create_context(create_context)
        self.create_context(create_contextA)
        self.create_context(create_contextB)
        res = self.testapp.get('/contexts', '', oauth2Header(test_manager), status=200)
        self.assertEqual(len(res.json), 3)

    def test_contexts_search_with_tags(self):
        """
            Given an admin user
            When I search for contexts with a tag
            Then I get tthe ones with that tag
        """
        from .mockers import create_context, create_contextA, create_contextB
        from .mockers import context_search_by_tags

        self.create_context(create_context)   # Tagged "Assignatura"
        self.create_context(create_contextA)  # Tagged "Assignatura"
        self.create_context(create_contextB)  # Not tagged
        res = self.testapp.get('/contexts?tags', context_search_by_tags, oauth2Header(test_manager), status=200)
        self.assertEqual(len(res.json), 2)

    def test_public_contexts_search_with_tags(self):
        """
            Given a plain user
            When I search for public contexts with a tag
            Then I get the ones with that tag
        """
        from .mockers import create_context, create_contextA, create_contextB
        from .mockers import context_search_by_tags

        username = '******'
        self.create_user(username)

        self.create_context(create_context)
        self.create_context(create_contextA, permissions=dict(read='subscribed', write='subscribed', subscribe='restricted', invite='subscribed'))
        self.create_context(create_contextB)
        res = self.testapp.get('/contexts/public?tags', context_search_by_tags, oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 1)

    def test_search_with_invalid_parameters(self):
        """
            Given a plain user
            When I do a search with invalid parameters
            Then I get a Bad Request Error
        """
        username = '******'
        self.create_user(username)
        fake_id = '519200000000000000000000'
        self.testapp.get('/people?limit=a', '', oauth2Header(username), status=400)
        self.testapp.get('/people?after=0', '', oauth2Header(username), status=400)
        self.testapp.get('/people?before=0', '', oauth2Header(username), status=400)
        self.testapp.get('/people?before={0}&after={0}'.format(fake_id), '', oauth2Header(username), status=400)

    def test_context_timeline_favorites_search(self):
        """
        """
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context

        username = '******'
        self.create_user(username)
        username2 = 'xavi'
        self.create_user(username2)
        self.create_context(create_context, permissions=dict(read='public', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username2, subscribe_context)
        res = self.create_activity(username, user_status_context)
        activity1_id = res.json['id']
        self.create_activity(username, user_status_context, note="second")
        res = self.create_activity(username2, user_status_context)
        activity3_id = res.json['id']
        self.create_activity(username2, user_status_context, note="second")

        self.favorite_activity(username, activity1_id)
        self.favorite_activity(username, activity3_id)

        res = self.testapp.get('/people/%s/timeline?favorites=true' % (username), '', oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 2)
        self.assertEqual(res.json[0]['id'], activity3_id)
        self.assertEqual(res.json[1]['id'], activity1_id)
Example #17
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # BEGIN TESTS

    def test_favorite_activity(self):
        """
           Given a plain user
           and a regular context
           When i post an activity in a context
           Then someone else can favorite this activity
        """
        from .mockers import user_status_context
        from .mockers import subscribe_context, create_context
        username = '******'
        username_not_me = 'xavi'
        self.create_user(username)
        self.create_user(username_not_me)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username_not_me, subscribe_context)
        res = self.create_activity(username, user_status_context)
        activity_id = res.json['id']
        res = self.testapp.post('/activities/%s/favorites' % activity_id, '', oauth2Header(username_not_me), status=201)
        activity = self.testapp.get('/activities/%s' % activity_id, '', oauth2Header(username), status=200)

        self.assertEqual(res.json['object']['favorites'][0]['username'], username_not_me)
        self.assertEqual(res.json['object']['favorited'], True)
        self.assertEqual(res.json['object']['favoritesCount'], 1)

        self.assertEqual(activity.json['favorites'][0]['username'], username_not_me)
        self.assertEqual(activity.json['favorited'], False)
        self.assertEqual(activity.json['favoritesCount'], 1)

    def test_favorite_already_favorited_activity(self):
        """
           Given a plain user
           and a regular context
           When i post an activity in a context
           And someone favorites this activity
           Then this someone else can't favorite twice this activity
        """
        from .mockers import user_status_context
        from .mockers import subscribe_context, create_context
        username = '******'
        username_not_me = 'xavi'
        self.create_user(username)
        self.create_user(username_not_me)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username_not_me, subscribe_context)
        res = self.create_activity(username, user_status_context)
        activity_id = res.json['id']
        res = self.testapp.post('/activities/%s/favorites' % activity_id, '', oauth2Header(username_not_me), status=201)
        res = self.testapp.post('/activities/%s/favorites' % activity_id, '', oauth2Header(username_not_me), status=200)

        self.assertEqual(res.json['object']['favorites'][0]['username'], username_not_me)
        self.assertEqual(res.json['object']['favorited'], True)
        self.assertEqual(res.json['object']['favoritesCount'], 1)

    def test_unfavorite_activity(self):
        """
           Given a plain user
           and a regular context
           When i post an activity in a context
           Then someone else can remove previously favorite mark from this activity
        """
        from .mockers import user_status_context
        from .mockers import subscribe_context, create_context
        username = '******'
        username_not_me = 'xavi'
        self.create_user(username)
        self.create_user(username_not_me)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username_not_me, subscribe_context)
        res = self.create_activity(username, user_status_context)
        activity_id = res.json['id']
        res = self.testapp.post('/activities/%s/favorites' % activity_id, '', oauth2Header(username_not_me), status=201)
        res = self.testapp.delete('/activities/%s/favorites/%s' % (activity_id, username_not_me), '', oauth2Header(username_not_me), status=200)
        activity = self.testapp.get('/activities/%s' % activity_id, '', oauth2Header(username), status=200)

        self.assertEqual(res.json['object']['favorites'], [])
        self.assertEqual(res.json['object']['favorited'], False)
        self.assertEqual(res.json['object']['favoritesCount'], 0)

        self.assertEqual(activity.json['favorites'], [])
        self.assertEqual(activity.json['favorited'], False)
        self.assertEqual(activity.json['favoritesCount'], 0)

    def test_favorite_activity_by_various(self):
        """
           Given a plain user
           and a regular context
           When i post an activity in a context
           Then someone else can favorite this activity
           and i also can favorite it
        """
        from .mockers import user_status_context
        from .mockers import subscribe_context, create_context
        username = '******'
        username_not_me = 'xavi'
        self.create_user(username)
        self.create_user(username_not_me)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username_not_me, subscribe_context)
        res = self.create_activity(username, user_status_context)
        activity_id = res.json['id']
        res = self.testapp.post('/activities/%s/favorites' % activity_id, '', oauth2Header(username_not_me), status=201)
        res = self.testapp.post('/activities/%s/favorites' % activity_id, '', oauth2Header(username), status=201)

        self.assertEqual(res.json['object']['favorites'][0]['username'], username_not_me)
        self.assertEqual(res.json['object']['favorites'][1]['username'], username)
        self.assertEqual(res.json['object']['favorited'], True)
        self.assertEqual(res.json['object']['favoritesCount'], 2)

    def test_unfavorite_activity_get_other_favorites(self):
        """
           Given a plain user
           and a regular context
           When i post an activity in a context
           And varius users favorite it
           And someone unfavorite it
           Then someone who unfavorite this activity
           and the rest of favorites remains
        """
        from .mockers import user_status_context
        from .mockers import subscribe_context, create_context
        username = '******'
        username_not_me = 'xavi'
        self.create_user(username)
        self.create_user(username_not_me)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username_not_me, subscribe_context)
        res = self.create_activity(username, user_status_context)
        activity_id = res.json['id']
        res = self.testapp.post('/activities/%s/favorites' % activity_id, '', oauth2Header(username_not_me), status=201)
        res = self.testapp.post('/activities/%s/favorites' % activity_id, '', oauth2Header(username), status=201)
        res = self.testapp.delete('/activities/%s/favorites/%s' % (activity_id, username_not_me), '', oauth2Header(username_not_me), status=200)

        self.assertEqual(res.json['object']['favorites'][0]['username'], username)
        self.assertEqual(res.json['object']['favorited'], False)
        self.assertEqual(res.json['object']['favoritesCount'], 1)
Example #18
0
class MessagesACLTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        self.conf_dir = os.path.dirname(os.path.dirname(__file__))
        self.repository = os.path.join(self.conf_dir, 'repository')
        self.app = loadapp('config:tests.ini', relative_to=self.conf_dir)
        self.app.registry.max_store.drop_collection('users')
        self.app.registry.max_store.drop_collection('activity')
        self.app.registry.max_store.drop_collection('contexts')
        self.app.registry.max_store.drop_collection('security')
        self.app.registry.max_store.drop_collection('conversations')
        self.app.registry.max_store.drop_collection('messages')
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    def tearDown(self):
        shutil.rmtree(self.repository, ignore_errors=True)

    def test_add_message_to_conversation(self):
        """
            Given i'm a regular user
            And I'm a participant in the conversation
            When i try to add a message to a conversation
            Then i succeed
        """
        from max.tests.mockers import group_message as creation_message
        from max.tests.mockers import message2

        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'

        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        res = self.testapp.post('/conversations', json.dumps(creation_message), oauth2Header(sender), status=201)
        conversation_id = res.json['contexts'][0]['id']

        self.testapp.post('/conversations/{}/messages'.format(conversation_id), json.dumps(message2), oauth2Header(recipient2), status=201)

    def test_add_message_to_conversation_not_participant(self):
        """
            Given i'm a regular user
            And i'm not a participant in the conversation
            When i try to add a message to a conversation
            Then i get a Forbidden Exception
        """
        from max.tests.mockers import message
        from max.tests.mockers import message2

        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'

        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        conversation_id = res.json['contexts'][0]['id']

        self.testapp.post('/conversations/{}/messages'.format(conversation_id), json.dumps(message2), oauth2Header(recipient2), status=403)

    def test_add_message_to_conversation_impersonating(self):
        """
            Given i'm a regular user
            When i try to add a message to a conversation
            And i'm impersonating as another user
            Then i get a Forbidden Exception
        """
        from max.tests.mockers import group_message as creation_message
        from max.tests.mockers import message4

        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'

        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        res = self.testapp.post('/conversations', json.dumps(creation_message), oauth2Header(sender), status=201)
        conversation_id = res.json['contexts'][0]['id']

        self.testapp.post('/conversations/{}/messages'.format(conversation_id), json.dumps(message4), oauth2Header(recipient2), status=403)

    def test_add_message_to_conversation_as_owner_impersonating(self):
        """
            Given i'm a regular user
            And i'm the owner of a conversation
            When i try to add a message to a conversation
            And i'm impersonating as another user
            Then i get a Forbidden Exception
        """
        from max.tests.mockers import message
        from max.tests.mockers import message4

        sender = 'messi'
        recipient = 'xavi'

        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        conversation_id = res.json['contexts'][0]['id']

        self.testapp.post('/conversations/{}/messages'.format(conversation_id), json.dumps(message4), oauth2Header(sender), status=403)

    def test_add_message_to_conversation_as_manager_impersonating(self):
        """
            Given i'm a Manager
            When i try to add a message to a conversation
            And i'm impersonating as another user
            Then i succeed
        """
        from max.tests.mockers import message
        from max.tests.mockers import message4

        sender = 'messi'
        recipient = 'xavi'

        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        conversation_id = res.json['contexts'][0]['id']

        self.testapp.post('/conversations/{}/messages'.format(conversation_id), json.dumps(message4), oauth2Header(test_manager), status=201)

    # Get conversation messages list tests

    def test_get_messages_as_manager(self):
        """
            Given i'm a Manager
            When i try to list a conversation's messages
            Then i succeed
        """
        from max.tests.mockers import message
        sender = 'messi'
        recipient = 'xavi'

        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = res.json['contexts'][0]['id']

        self.testapp.get('/conversations/{}/messages'.format(cid), '', oauth2Header(test_manager), status=200)

    def test_get_messages_as_participant(self):
        """
            Given i'm a regular user
            And i'm a conversation participant
            When i try to list a conversation's messages
            Then i succeed
        """
        from max.tests.mockers import message
        sender = 'messi'
        recipient = 'xavi'

        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = res.json['contexts'][0]['id']

        self.testapp.get('/conversations/{}/messages'.format(cid), '', oauth2Header(recipient), status=200)

    def test_get_messages_as_non_participant(self):
        """
            Given i'm a regular user
            And i'm not a conversation participant
            When i try to list a conversation's messages
            Then i get a Forbidden Exception
        """
        from max.tests.mockers import message
        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'

        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = res.json['contexts'][0]['id']

        self.testapp.get('/conversations/{}/messages'.format(cid), '', oauth2Header(recipient2), status=403)

    # Get message attachment tests

    def test_get_message_image_as_manager(self):
        """
            Given i'm a Manager
            When i try to view a message image attachment
            Then i succeed
        """
        from max.tests.mockers import message
        from max.tests.mockers import message_with_image
        sender = 'messi'
        recipient = 'xavi'

        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = res.json['contexts'][0]['id']

        thefile = open(os.path.join(self.conf_dir, "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'image/png')]

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])
        message_id = self.testapp.post('/conversations/%s/messages' % cid, dict(json_data=json.dumps(message_with_image)), oauth2Header(sender), upload_files=files, status=201).json['id']
        self.testapp.get('/messages/%s/image' % (message_id), headers=oauth2Header(test_manager), status=200)

    def test_get_message_image_as_participant(self):
        """
            Given i'm a regular user
            And i'm a conversation participant
            When i try to view a message image attachment
            Then i succeed
        """
        from max.tests.mockers import message
        from max.tests.mockers import message_with_image
        sender = 'messi'
        recipient = 'xavi'

        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = res.json['contexts'][0]['id']

        thefile = open(os.path.join(self.conf_dir, "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'image/png')]

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])
        message_id = self.testapp.post('/conversations/%s/messages' % cid, dict(json_data=json.dumps(message_with_image)), oauth2Header(sender), upload_files=files, status=201).json['id']
        self.testapp.get('/messages/%s/image' % (message_id), headers=oauth2Header(recipient), status=200)

    def test_get_message_image_as_non_participant(self):
        """
            Given i'm a regular user
            And i'm not a conversation participant
            When i try to view a message image attachment
            Then i get a Forbidden Exception
        """
        from max.tests.mockers import message
        from max.tests.mockers import message_with_image
        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'

        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = res.json['contexts'][0]['id']

        thefile = open(os.path.join(self.conf_dir, "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'image/png')]

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])
        message_id = self.testapp.post('/conversations/%s/messages' % cid, dict(json_data=json.dumps(message_with_image)), oauth2Header(sender), upload_files=files, status=201).json['id']
        self.testapp.get('/messages/%s/image' % (message_id), headers=oauth2Header(recipient2), status=403)

    def test_get_message_file_as_manager(self):
        """
            Given i'm a Manager
            When i try to view a file attachment
            Then i succeed
        """
        from max.tests.mockers import message
        from max.tests.mockers import message_with_file
        sender = 'messi'
        recipient = 'xavi'

        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = res.json['contexts'][0]['id']

        thefile = open(os.path.join(self.conf_dir, "map.pdf"), "rb")
        files = [('file', 'map.pdf', thefile.read(), 'application/pdf')]

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])
        message_id = self.testapp.post('/conversations/%s/messages' % cid, dict(json_data=json.dumps(message_with_file)), oauth2Header(sender), upload_files=files, status=201).json['id']
        self.testapp.get('/messages/%s/file/download' % (message_id), headers=oauth2Header(test_manager), status=200)

    def test_get_message_file_as_participant(self):
        """
            Given i'm a regular user
            And i'm a conversation participant
            When i try to view a file attachment
            Then i succeed
        """
        from max.tests.mockers import message
        from max.tests.mockers import message_with_file
        sender = 'messi'
        recipient = 'xavi'

        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = res.json['contexts'][0]['id']

        thefile = open(os.path.join(self.conf_dir, "map.pdf"), "rb")
        files = [('file', 'map.pdf', thefile.read(), 'application/pdf')]

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])
        message_id = self.testapp.post('/conversations/%s/messages' % cid, dict(json_data=json.dumps(message_with_file)), oauth2Header(sender), upload_files=files, status=201).json['id']
        self.testapp.get('/messages/%s/file/download' % (message_id), headers=oauth2Header(recipient), status=200)

    def test_get_message_file_as_non_participant(self):
        """
            Given i'm nota regular user
            And i'm not a conversation participant
            When i try to view a file attachment
            Then i get a Forbidden Exception
        """
        from max.tests.mockers import message
        from max.tests.mockers import message_with_file
        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'

        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = res.json['contexts'][0]['id']

        thefile = open(os.path.join(self.conf_dir, "map.pdf"), "rb")
        files = [('file', 'map.pdf', thefile.read(), 'application/pdf')]

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])
        message_id = self.testapp.post('/conversations/%s/messages' % cid, dict(json_data=json.dumps(message_with_file)), oauth2Header(sender), upload_files=files, status=201).json['id']
        self.testapp.get('/messages/%s/file/download' % (message_id), headers=oauth2Header(recipient2), status=403)
Example #19
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    def test_maintenance_keywords(self):
        from .mockers import user_status
        username = '******'
        self.create_user(username, displayName='Lionel messi')
        self.create_activity(username, user_status)

        # Hard modify keywords directly on mongodb to simulate bad keywords
        activities = self.exec_mongo_query('activity', 'find', {})
        activity = activities[0]
        del activity['_keywords']
        activity['object']['_keywords'] = []
        self.exec_mongo_query('activity', 'update', {'_id': activities[0]['_id']}, activity)

        self.testapp.post('/admin/maintenance/keywords', "", oauth2Header(test_manager), status=200)
        res = self.testapp.get('/activities/%s' % activity['_id'], "", oauth2Header(username), status=200)

        expected_keywords = [u'canvi', u'creaci\xf3', u'estatus', u'lionel', u'messi', u'testejant']
        response_keywords = res.json['keywords']
        response_keywords.sort()
        self.assertListEqual(expected_keywords, response_keywords)

    def test_maintenance_dates(self):
        from .mockers import user_status, user_comment
        username = '******'
        self.create_user(username, displayName='Lionel messi')
        res = self.create_activity(username, user_status)
        self.testapp.post('/activities/%s/comments' % str(res.json['id']), json.dumps(user_comment), oauth2Header(username), status=201)
        res = self.testapp.post('/activities/%s/comments' % str(res.json['id']), json.dumps(user_comment), oauth2Header(username), status=201)

        # Hard modify keywords directly on mongodb to simulate bad keywords
        activities = self.exec_mongo_query('activity', 'find', {'verb': 'post'})
        activity = activities[0]

        # simulate ancient commented field with wrong date
        activity['commented'] = activity['published']
        del activity['lastComment']
        self.exec_mongo_query('activity', 'update', {'_id': activities[0]['_id']}, activity)

        self.testapp.post('/admin/maintenance/dates', "", oauth2Header(test_manager), status=200)
        res = self.testapp.get('/activities/%s' % activity['_id'], "", oauth2Header(username), status=200)

        self.assertEqual(res.json['lastComment'], res.json['replies'][-1]['id'])

    def test_maintenance_subscriptions(self):
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context
        from hashlib import sha1

        username = '******'
        self.create_user(username)
        self.create_context(create_context, permissions=dict(read='subscribed', write='subscribed', subscribe='restricted', invite='restricted'))
        chash = sha1(create_context['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)

        # Hard modify context directly on mongo to simulate changed permissions, displayName and tags
        contexts = self.exec_mongo_query('contexts', 'find', {'hash': chash})
        context = contexts[0]
        context['permissions']['write'] = 'restricted'
        context['displayName'] = 'Changed Name'
        context['tags'].append('new tag')
        self.exec_mongo_query('contexts', 'update', {'_id': context['_id']}, context)
        self.testapp.post('/admin/maintenance/subscriptions', "", oauth2Header(test_manager), status=200)

        # Check user subscription is updated
        res = self.testapp.get('/people/{}'.format(username), "", oauth2Header(username), status=200)
        self.assertEqual(res.json['subscribedTo'][0]['displayName'], 'Changed Name')
        self.assertListEqual(res.json['subscribedTo'][0]['tags'], ['Assignatura', 'new tag'])
        self.assertListEqual(res.json['subscribedTo'][0]['permissions'], ['read'])

        # Check user activity is updated
        res = self.testapp.get('/people/{}/timeline'.format(username), "", oauth2Header(username), status=200)
        self.assertEqual(res.json[0]['contexts'][0]['displayName'], 'Changed Name')
        self.assertListEqual(res.json[0]['contexts'][0]['tags'], ['Assignatura', 'new tag'])

    def test_maintenance_conversations(self):
        from .mockers import group_message as message

        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'
        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)

        # Hard modify group conversation directly on mongo to simulate changed permissions, displayName and tags
        conversations = self.exec_mongo_query('conversations', 'find', {})
        conversation = conversations[0]
        conversation['permissions']['write'] = 'restricted'
        conversation['displayName'] = 'Changed Name'
        conversation['tags'] = []
        conversation['participants'] = ['messi', 'xavi', 'shakira']  # Simulate ol'times structure
        self.exec_mongo_query('conversations', 'update', {'_id': conversation['_id']}, conversation)

        # Hard Put a displayName on a user
        users = self.exec_mongo_query('users', 'find', {'username': '******'})
        user = users[0]
        user['displayName'] = 'Lionel Messi'
        self.exec_mongo_query('users', 'update', {'_id': user['_id']}, user)

        self.testapp.post('/admin/maintenance/conversations', "", oauth2Header(test_manager), status=200)

        # Check user subscription is updated
        res = self.testapp.get('/people/{}'.format(sender), "", oauth2Header(sender), status=200)
        self.assertEqual(res.json['talkingIn'][0]['displayName'], 'Changed Name')
        self.assertEqual(res.json['talkingIn'][0]['participants'][0]['username'], 'messi')
        self.assertEqual(res.json['talkingIn'][0]['participants'][1]['username'], 'xavi')
        self.assertEqual(res.json['talkingIn'][0]['participants'][2]['username'], 'shakira')
        self.assertListEqual(res.json['talkingIn'][0]['permissions'], ['read', 'unsubscribe'])
        self.assertListEqual(res.json['talkingIn'][0]['tags'], ['group'])
        conversation_id = res.json['talkingIn'][0]['id']

        # Check context participants are updated
        res = self.testapp.get('/conversations/{}'.format(conversation_id), "", oauth2Header(sender), status=200)
        self.assertEqual(res.json['participants'][0]['displayName'], 'Lionel Messi')

        # Check user activity is updated
        res = self.testapp.get('/conversations/{}/messages'.format(conversation_id), "", oauth2Header(sender), status=200)
        self.assertEqual(res.json[0]['contexts'][0]['displayName'], 'Changed Name')

    def test_maintenance_conversations_group_one_participant(self):
        from .mockers import group_message as message

        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'
        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        conversation_id = str(res.json['contexts'][0]['id'])

        self.testapp.delete('/people/{}/conversations/{}'.format(recipient, conversation_id), '', oauth2Header(recipient), status=204)
        self.testapp.delete('/people/{}/conversations/{}'.format(recipient2, conversation_id), '', oauth2Header(recipient2), status=204)

        self.testapp.post('/admin/maintenance/conversations', "", oauth2Header(test_manager), status=200)

        res = self.testapp.get('/conversations/{}'.format(conversation_id), '', oauth2Header(sender), status=200)
        self.assertEqual(len(res.json['participants']), 1)
        self.assertIn('archive', res.json['tags'])

    def test_maintenance_two_people_conversations(self):
        from .mockers import message as creation_message

        sender = 'messi'
        recipient = 'xavi'
        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(creation_message), oauth2Header(sender), status=201)
        conversation_id = str(res.json['contexts'][0]['id'])

        self.testapp.post('/admin/maintenance/conversations', "", oauth2Header(test_manager), status=200)

        res = self.testapp.get('/conversations/{}'.format(conversation_id), '', oauth2Header(sender), status=200)
        self.assertEqual(len(res.json['participants']), 2)
        self.assertNotIn('single', res.json['tags'])

    def test_maintenance_two_people_conversations_one_leave_conversation(self):
        from .mockers import message as creation_message

        sender = 'messi'
        recipient = 'xavi'
        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(creation_message), oauth2Header(sender), status=201)
        conversation_id = str(res.json['contexts'][0]['id'])
        self.testapp.delete('/people/{}/conversations/{}'.format(recipient, conversation_id), '', oauth2Header(recipient), status=204)

        self.testapp.post('/admin/maintenance/conversations', "", oauth2Header(test_manager), status=200)

        res = self.testapp.get('/conversations/{}'.format(conversation_id), '', oauth2Header(sender), status=200)
        self.assertEqual(len(res.json['participants']), 2)
        self.assertIn('single', res.json['tags'])

    def test_maintenance_two_people_conversations_one_user_deleted(self):
        from .mockers import message as creation_message

        sender = 'messi'
        recipient = 'xavi'
        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(creation_message), oauth2Header(sender), status=201)
        conversation_id = str(res.json['contexts'][0]['id'])
        self.testapp.delete('/people/{}'.format(recipient), headers=oauth2Header(test_manager), status=204)

        self.testapp.post('/admin/maintenance/conversations', "", oauth2Header(test_manager), status=200)

        res = self.testapp.get('/conversations/{}'.format(conversation_id), '', oauth2Header(sender), status=200)
        self.assertEqual(len(res.json['participants']), 2)
        self.assertIn('archive', res.json['tags'])

    def test_maintenance_two_people_conversations_tagged_archived(self):
        from .mockers import message as creation_message

        sender = 'messi'
        recipient = 'xavi'
        self.create_user(sender)
        self.create_user(recipient)

        res = self.testapp.post('/conversations', json.dumps(creation_message), oauth2Header(sender), status=201)
        conversation_id = str(res.json['contexts'][0]['id'])

        # Hard modify two people conversation directly on mongo to simulate archive in tags
        conversations = self.exec_mongo_query('conversations', 'find', {})
        conversation = conversations[0]
        conversation['tags'] = ['archive']
        self.exec_mongo_query('conversations', 'update', {'_id': conversation['_id']}, conversation)

        self.testapp.post('/admin/maintenance/conversations', "", oauth2Header(test_manager), status=200)

        res = self.testapp.get('/conversations/{}'.format(conversation_id), '', oauth2Header(sender), status=200)
        self.assertEqual(len(res.json['participants']), 2)
        self.assertNotIn('single', res.json['tags'])

    def test_maintenance_users(self):
        username = '******'
        self.create_user(username)

        # Hard modify user directly on mongo to simulate wrong owner and check is wrong
        self.exec_mongo_query('users', 'update', {'username': username}, {'$set': {'_owner': 'test_manager'}})
        res = self.testapp.get('/people/{}'.format(username), "", oauth2Header(test_manager), status=200)
        self.assertEqual(res.json['owner'], 'test_manager')

        self.testapp.post('/admin/maintenance/users', "", oauth2Header(test_manager), status=200)
        res = self.testapp.get('/people/{}'.format(username), "", oauth2Header(test_manager), status=200)
        self.assertEqual(res.json['owner'], username)

    def test_maintenance_tokens(self):
        username = '******'
        self.create_user(username)

        # Hard modify user directly on mongo to simulate old style tokens
        self.exec_mongo_query('users', 'update', {'username': username}, {'$set': {'iosDevices': ['token1', 'token2'], 'androidDevices': ['token3', 'token4']}})
        user = self.exec_mongo_query('users', 'find', {'username': username})[0]
        ios = self.testapp.get('/people/{}/tokens/platforms/{}'.format(username, 'ios'), "", oauth2Header(username), status=200)
        android = self.testapp.get('/people/{}/tokens/platforms/{}'.format(username, 'android'), "", oauth2Header(username), status=200)

        self.assertEqual(ios.json, [])
        self.assertEqual(android.json, [])
        self.assertIn('iosDevices', user)
        self.assertIn('androidDevices', user)

        self.testapp.post('/admin/maintenance/tokens', "", oauth2Header(test_manager), status=200)

        user = self.exec_mongo_query('users', 'find', {'username': username})[0]
        ios = self.testapp.get('/people/{}/tokens/platforms/{}'.format(username, 'ios'), "", oauth2Header(username), status=200)
        android = self.testapp.get('/people/{}/tokens/platforms/{}'.format(username, 'android'), "", oauth2Header(username), status=200)

        migrated_ios_tokens = [a['token'] for a in ios.json]
        migrated_android_tokens = [a['token'] for a in android.json]
        self.assertItemsEqual(migrated_ios_tokens, ['token1', 'token2'])
        self.assertItemsEqual(migrated_android_tokens, ['token3', 'token4'])
        self.assertNotIn('iosDevices', user)
        self.assertNotIn('androidDevices', user)
Example #20
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    def tearDown(self):
        import pyramid.testing
        pyramid.testing.tearDown()

    # BEGIN TESTS

    def test_add_device_token_ios(self):
        username = '******'
        token = {'platform': 'ios', 'token': '12345678901234567890123456789012'}
        self.create_user(username)
        res = self.testapp.post('/tokens', json.dumps(token), oauth2Header(username), status=201)
        result = json.loads(res.text)
        self.assertEqual(result.get('token', ''), token['token'])
        self.assertEqual(result.get('platform', ''), token['platform'])

    def test_add_device_token_android(self):
        username = '******'
        self.create_user(username)
        token = {'platform': 'android', 'token': '12345678901234567890123456789012klhsdflajshdfkjashdfoq'}
        res = self.testapp.post('/tokens', json.dumps(token), oauth2Header(username), status=201)
        result = json.loads(res.text)
        self.assertEqual(result.get('token', ''), token['token'])
        self.assertEqual(result.get('platform', ''), token['platform'])

    def test_add_device_invalid_platform(self):
        username = '******'
        token = {'platform': 'blackberry', 'token': '12345678901234567890123456789012klhsdflajshdfkjashdfoq'}
        self.create_user(username)
        self.testapp.post('/tokens', json.dumps(token), oauth2Header(username), status=400)

    def test_delete_device_token(self):
        username = '******'
        token = {'platform': 'ios', 'token': '12345678901234567890123456789012'}

        self.create_user(username)
        self.testapp.post('/tokens', json.dumps(token), oauth2Header(username), status=201)
        self.testapp.delete('/tokens/%s' % (token['token']), "", oauth2Header(username), status=204)

    def test_add_duplicated_token(self):
        """
            Given i'm a regular user

        """
        sender = 'messi'
        recipient = 'xavi'
        self.create_user(sender)
        self.create_user(recipient)

        token = {'platform': 'ios', 'token': '12345678901234567890123456789012'}

        self.testapp.post('/tokens', json.dumps(token), oauth2Header(sender), status=201)
        sender_tokens = self.testapp.get('/people/{}/tokens/platforms/{}'.format(sender, token['platform']), "", headers=oauth2Header(sender), status=200).json

        self.assertEqual(len(sender_tokens), 1)
        self.testapp.post('/tokens', json.dumps(token), oauth2Header(recipient), status=201)

        sender_tokens = self.testapp.get('/people/{}/tokens/platforms/{}'.format(sender, token['platform']), "", headers=oauth2Header(sender), status=200).json
        recipient_tokens = self.testapp.get('/people/{}/tokens/platforms/{}'.format(recipient, token['platform']), "", headers=oauth2Header(recipient), status=200).json

        self.assertEqual(len(sender_tokens), 0)
        self.assertEqual(len(recipient_tokens), 1)

    def test_get_pushtokens_for_given_conversations(self):
        """ doctest .. http:get:: /conversations/{id}/tokens """
        from .mockers import message
        sender = 'messi'
        recipient = 'xavi'
        self.create_user(sender)
        self.create_user(recipient)

        platform = 'ios'
        token_sender = '12345678901234567890123456789012'
        token_recipient = '12345678901234567890123456789013'
        self.testapp.post('/people/%s/device/%s/%s' % (sender, platform, token_sender), "", oauth2Header(sender), status=201)
        self.testapp.post('/people/%s/device/%s/%s' % (recipient, platform, token_recipient), "", oauth2Header(recipient), status=201)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        conversation_id = res.json['contexts'][0]['id']

        res = self.testapp.get('/conversations/%s/tokens' % (conversation_id), '', oauth2Header(test_manager), status=200)
        self.assertEqual(res.json[0]['platform'], u'ios')
        self.assertEqual(res.json[0]['token'], u'12345678901234567890123456789013')
        self.assertEqual(res.json[0]['username'], u'xavi')

        self.assertEqual(res.json[1]['platform'], u'ios')
        self.assertEqual(res.json[1]['token'], u'12345678901234567890123456789012')
        self.assertEqual(res.json[1]['username'], u'messi')
        self.assertEqual(len(res.json), 2)

    def test_get_pushtokens_for_given_context(self):
        """
        """
        from .mockers import create_context, subscribe_context
        username = '******'
        username2 = 'xavi'
        self.create_user(username)
        self.create_user(username2)

        platform = 'ios'
        token_1 = '12345678901234567890123456789012'
        token_2 = '12345678901234567890123456789013'
        self.testapp.post('/people/%s/device/%s/%s' % (username, platform, token_1), "", oauth2Header(username), status=201)
        self.testapp.post('/people/%s/device/%s/%s' % (username2, platform, token_2), "", oauth2Header(username2), status=201)

        url_hash = self.create_context(create_context).json['hash']
        self.admin_subscribe_user_to_context(username, subscribe_context)

        res = self.testapp.get('/contexts/%s/tokens' % (url_hash), '', oauth2Header(test_manager), status=200)
        self.assertEqual(res.json[0]['platform'], u'ios')
        self.assertEqual(res.json[0]['token'], u'12345678901234567890123456789012')
        self.assertEqual(res.json[0]['username'], u'messi')
        self.assertEqual(len(res.json), 1)
Example #21
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # BEGIN TESTS

    def test_create_context(self):
        """ doctests .. http:post:: /contexts"""
        from .mockers import create_context
        new_context = dict(create_context)
        self.testapp.post('/contexts', json.dumps(new_context), oauth2Header(test_manager), status=201)

    def test_create_context_creator_is_admin(self):
        """
            Given a admin user
            When I create a context
            Then the creator of the context is the admin user
        """
        from .mockers import create_context
        res = self.testapp.post('/contexts', json.dumps(create_context), oauth2Header(test_manager), status=201)
        self.assertEqual(res.json['creator'], test_manager)

    def test_create_context_default_fields(self):
        """
            Given an admin user
            When I create a context
            Then non-required fields with defaults are set
        """
        from .mockers import create_context
        res = self.testapp.post('/contexts', json.dumps(create_context), oauth2Header(test_manager), status=201)
        self.assertIn('permissions', res.json)
        self.assertIn('tags', res.json)
        self.assertIn('objectType', res.json)
        self.assertEqual(res.json['objectType'], 'context')

    def test_post_activity_with_public_context(self):
        """ Post an activity to a context which allows everyone to read and write
        """
        from .mockers import subscribe_context, create_context
        from .mockers import user_status_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        res = self.create_activity(username, user_status_context)

        result = json.loads(res.text)
        self.assertEqual(result.get('actor', None).get('username', None), 'messi')
        self.assertEqual(result.get('object', None).get('objectType', None), 'note')
        self.assertEqual(result.get('contexts', None)[0]['url'], subscribe_context['object']['url'])

    def test_post_activity_with_private_read_write_context(self):
        """ Post an activity to a context which needs the user to be subscribed to read and write
            and we have previously subscribed the user.
        """
        from .mockers import subscribe_context, create_context
        from .mockers import user_status_context
        from hashlib import sha1

        username = '******'
        self.create_user(username)
        url_hash = sha1(create_context['url']).hexdigest()

        context_permissions = dict(read='subscribed', write='subscribed', subscribe='restricted', invite='restricted')
        self.create_context(create_context, permissions=context_permissions)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        res = self.create_activity(username, user_status_context)

        result = json.loads(res.text)
        self.assertEqual(result.get('actor', None).get('username', None), 'messi')
        self.assertEqual(result.get('object', None).get('objectType', None), 'note')
        self.assertEqual(result.get('contexts', None)[0]['url'], subscribe_context['object']['url'])
        return url_hash, username, user_status_context

    def test_post_activity_with_private_read_context(self):
        """ Try to post an activity to a context which needs the user to be subscribed to read
            but needs to explicitly give write permission on the user to post and we have previously
            subscribed the user but not given write permission.
        """
        from .mockers import subscribe_context, create_context
        from .mockers import user_status_context
        username = '******'
        self.create_user(username)
        context_permissions = dict(read='subscribed', write='restricted', subscribe='restricted', invite='restricted')
        self.create_context(create_context, permissions=context_permissions)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context, expect=403)

    def test_add_public_context(self):
        from hashlib import sha1
        from .mockers import create_context
        res = self.testapp.post('/contexts', json.dumps(create_context), oauth2Header(test_manager), status=201)
        result = json.loads(res.text)
        url_hash = sha1(create_context['url']).hexdigest()
        self.assertEqual(result.get('hash', None), url_hash)

    def test_add_invalid_context(self):
        from .mockers import create_invalid_context
        self.create_context(create_invalid_context, expect=400)

    def test_add_uri_context_without_displayName(self):
        """
            Add a Uri context without a displayName and check that the default displayName is set
            with the url from the uri object
        """
        from .mockers import create_context_without_displayname
        res = self.create_context(create_context_without_displayname, expect=201)
        result = json.loads(res.text)
        self.assertEqual(result.get('displayName', None), create_context_without_displayname['url'])

    def test_add_public_context_with_all_params(self):
        from hashlib import sha1
        from .mockers import create_context_full
        res = self.testapp.post('/contexts', json.dumps(create_context_full), oauth2Header(test_manager), status=201)
        result = json.loads(res.text)
        url_hash = sha1(create_context_full['url']).hexdigest()
        self.assertEqual(result.get('hash', None), url_hash)
        self.assertEqual(result.get('displayName', None), create_context_full['displayName'])
        self.assertEqual(result.get('twitterHashtag', None), create_context_full['twitterHashtag'])
        self.assertEqual(result.get('twitterUsername', None), create_context_full['twitterUsername'])

    def test_context_exists(self):
        """ doctest .. http:get:: /contexts/{hash} """
        from hashlib import sha1
        from .mockers import create_context
        url_hash = sha1(create_context['url']).hexdigest()
        self.create_context(create_context)
        res = self.testapp.get('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(result.get('hash', None), url_hash)

    def test_context_informs_all_permissions(self):
        """ doctest .. http:get:: /contexts/{hash} """
        from hashlib import sha1
        from .mockers import create_context
        from max import DEFAULT_CONTEXT_PERMISSIONS
        url_hash = sha1(create_context['url']).hexdigest()
        self.create_context(create_context)
        res = self.testapp.get('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(result.get('hash', None), url_hash)
        self.assertItemsEqual(result['permissions'].keys(), DEFAULT_CONTEXT_PERMISSIONS.keys())

    def test_create_context_that_already_exists(self):
        """ doctest .. http:get:: /contexts/{hash} """
        from hashlib import sha1
        from .mockers import create_context
        url_hash = sha1(create_context['url']).hexdigest()
        self.testapp.post('/contexts', json.dumps(create_context), oauth2Header(test_manager), status=201)
        res = self.testapp.post('/contexts', json.dumps(create_context), oauth2Header(test_manager), status=200)
        self.assertEqual(res.json.get('hash', None), url_hash)

    def test_modify_context(self):
        """ doctest .. http:put:: /contexts/{hash} """
        from hashlib import sha1
        from .mockers import create_context

        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterHashtag": "assignatura1"}), oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(result.get('hash', None), url_hash)
        self.assertEqual(result.get('twitterHashtag', None), 'assignatura1')

    def test_modify_context_with_owner(self):
        """ doctest .. http:put:: /contexts/{hash} """
        from hashlib import sha1
        from .mockers import create_context

        mindundi = 'messi'
        self.create_user(mindundi)
        self.create_context(create_context, owner=mindundi)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterHashtag": "assignatura1"}), oauth2Header(mindundi), status=200)
        result = json.loads(res.text)
        self.assertEqual(result.get('hash', None), url_hash)
        self.assertEqual(result.get('twitterHashtag', None), 'assignatura1')

    def test_modify_context_forbidden(self):
        """ doctest .. http:put:: /contexts/{hash} """
        from hashlib import sha1
        from .mockers import create_context

        mindundi = 'messi'
        self.create_user(mindundi)
        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterHashtag": "assignatura1"}), oauth2Header(mindundi), status=403)

    def test_modify_inexistent_context(self):
        """ doctest .. http:put:: /contexts/{hash} """

        url_hash = '0000000000000'
        self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterHashtag": "assignatura1"}), oauth2Header(test_manager), status=404)

    @httpretty.activate
    @patch('tweepy.API', MockTweepyAPI)
    def test_modify_context_with_twitter_username(self):
        from hashlib import sha1
        from .mockers import create_context

        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterHashtag": "assignatura1", "twitterUsername": "******"}), oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(result.get('hash', None), url_hash)
        self.assertEqual(result.get('twitterHashtag', None), 'assignatura1')
        self.assertEqual(result.get('twitterUsername', None), 'maxupcnet')
        self.assertEqual(result.get('twitterUsernameId', None), '526326641')

    def test_get_context_tags(self):
        from hashlib import sha1
        from .mockers import create_context
        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.get('/contexts/%s/tags' % url_hash, "", oauth2Header(test_manager), status=200)
        self.assertEqual(res.json, ['Assignatura'])

    def test_update_context_tags_updates_existing_tags(self):
        from hashlib import sha1
        from .mockers import create_context
        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.put('/contexts/%s/tags' % url_hash, json.dumps(['prova']), oauth2Header(test_manager), status=200)
        self.assertEqual(res.json, ['Assignatura', 'prova'])

    def test_update_context_tags_updates_existing_activites_tags(self):
        from hashlib import sha1
        from .mockers import create_context, subscribe_context, user_status_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)
        self.testapp.put('/contexts/%s/tags' % url_hash, json.dumps(['prova']), oauth2Header(test_manager), status=200)
        res = self.testapp.get('/contexts/%s/activities' % url_hash, "", oauth2Header(username), status=200)
        self.assertEqual(res.json[0]['contexts'][0]['tags'], ['Assignatura', 'prova'])

    def test_update_context_tags_updates_existing_subscription_tags(self):
        from hashlib import sha1
        from .mockers import create_context, subscribe_context, user_status_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)
        self.testapp.put('/contexts/%s/tags' % url_hash, json.dumps(['prova']), oauth2Header(test_manager), status=200)
        res = self.testapp.get('/people/%s' % username, "", oauth2Header(username), status=200)
        self.assertEqual(res.json['subscribedTo'][0]['tags'], ['Assignatura', 'prova'])

    def test_clear_context_tags(self):
        from hashlib import sha1
        from .mockers import create_context
        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.delete('/contexts/%s/tags' % url_hash, "", oauth2Header(test_manager), status=200)
        self.assertEqual(res.json, [])

    def test_remove_context_tag(self):
        from hashlib import sha1
        from .mockers import create_context
        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        self.testapp.put('/contexts/%s/tags' % url_hash, json.dumps(['prova']), oauth2Header(test_manager), status=200)
        self.testapp.delete('/contexts/%s/tags/%s' % (url_hash, 'Assignatura'), "", oauth2Header(test_manager), status=204)

    def test_modify_context_displayName_updates_subscription(self):
        from hashlib import sha1
        from .mockers import create_context, subscribe_context

        username = '******'
        self.create_user(username)
        self.create_context(create_context, permissions=dict(read='subscribed', write='restricted', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context, expect=201)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"displayName": "New Name"}), oauth2Header(test_manager), status=200)
        res = self.testapp.get('/people/%s/subscriptions' % username, '', oauth2Header(username), status=200)
        self.assertEqual(res.json[0]['displayName'], 'New Name')

    def test_modify_context_unsetting_property(self):
        from hashlib import sha1
        from .mockers import create_context

        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        self.modify_context(create_context['url'], {"twitterHashtag": "assignatura1", "twitterUsername": "******"})
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterHashtag": "", "twitterUsername": ""}), oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(result.get('hash', None), url_hash)
        self.assertEqual(result.get('twitterHashtag', None), None)
        self.assertEqual(result.get('twitterUsername', None), None)
        self.assertEqual(result.get('twitterUsernameId', None), None)

    def test_delete_context(self):
        """ doctest .. http:delete:: /contexts/{hash} """
        from hashlib import sha1
        from .mockers import create_context
        url_hash = sha1(create_context['url']).hexdigest()
        self.create_context(create_context)
        self.testapp.delete('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=204)

    def test_deleted_context_is_really_deleted(self):
        from hashlib import sha1
        from .mockers import create_context
        url_hash = sha1(create_context['url']).hexdigest()
        self.create_context(create_context)
        self.testapp.delete('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=204)
        res = self.testapp.get('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=404)
        result = json.loads(res.text)
        self.assertEqual(result.get('error', None), 'ObjectNotFound')

    def test_delete_inexistent_context(self):
        """ doctest .. http:delete:: /contexts/{hash} """
        url_hash = '00000000000000'
        self.testapp.delete('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=404)

    def test_delete_only_deleted_specified_context(self):
        from hashlib import sha1
        from .mockers import create_context, create_contextA
        self.create_context(create_context)
        self.create_context(create_contextA)

        url_hash = sha1(create_context['url']).hexdigest()
        url_hashA = sha1(create_contextA['url']).hexdigest()
        self.testapp.delete('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=204)
        res = self.testapp.get('/contexts/%s' % url_hashA, "", oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(result.get('hash', None), url_hashA)

    def test_delete_context_removes_subscription_from_user(self):
        """
        """
        from hashlib import sha1
        from .mockers import subscribe_context, subscribe_contextA
        from .mockers import create_context, create_contextA
        from .mockers import user_status_context, user_status_contextA
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.create_context(create_contextA)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username, subscribe_contextA)
        self.create_activity(username, user_status_context)
        self.create_activity(username, user_status_contextA)

        url_hash = sha1(create_context['url']).hexdigest()
        self.testapp.delete('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=204)

        res = self.testapp.get('/people/%s' % username, "", oauth2Header(username))
        result = json.loads(res.text)
        self.assertEqual(result.get('username', None), 'messi')
        self.assertEqual(len(result.get('subscribedTo', [])), 1)
        self.assertEqual(result.get('subscribedTo', [])[0]['url'], subscribe_contextA['object']['url'])

    def test_user_cannot_see_activity_from_deleted_context(self):
        """
        """
        from hashlib import sha1
        from .mockers import subscribe_context
        from .mockers import create_context
        from .mockers import user_status_context
        from .mockers import context_query
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)

        url_hash = sha1(create_context['url']).hexdigest()
        self.testapp.delete('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=204)
        self.testapp.get('/contexts/%s/activities' % (context_query['context']), '', oauth2Header(username), status=404)

    def test_user_cannot_see_own_activity_from_deleted_context_in_timeline(self):
        """
        """
        from hashlib import sha1
        from .mockers import subscribe_context
        from .mockers import create_context
        from .mockers import user_status_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)

        url_hash = sha1(create_context['url']).hexdigest()
        self.testapp.delete('/contexts/%s' % url_hash, "", oauth2Header(test_manager), status=204)
        res = self.testapp.get('/people/%s/timeline' % username, {}, oauth2Header(username), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 0)

    def test_add_private_rw_context(self):
        from hashlib import sha1
        from .mockers import create_context_private_rw
        res = self.testapp.post('/contexts', json.dumps(create_context_private_rw), oauth2Header(test_manager), status=201)
        result = json.loads(res.text)
        url_hash = sha1(create_context_private_rw['url']).hexdigest()
        self.assertEqual(result.get('hash', None), url_hash)
        self.assertEqual(result.get('permissions', None), create_context_private_rw['permissions'])

    def test_add_private_r_context(self):
        from hashlib import sha1
        from .mockers import create_context_private_r
        res = self.testapp.post('/contexts', json.dumps(create_context_private_r), oauth2Header(test_manager), status=201)
        result = json.loads(res.text)
        url_hash = sha1(create_context_private_r['url']).hexdigest()
        self.assertEqual(result.get('hash', None), url_hash)
        self.assertEqual(result.get('permissions', None), create_context_private_r['permissions'])

    def test_check_permissions_on_subscribed_rw_context(self):
        from .mockers import create_context_private_rw, subscribe_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context_private_rw)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        res = self.testapp.get('/people/%s' % username, "", oauth2Header(username))
        result = json.loads(res.text)
        self.assertEqual(len(result.get('subscribedTo', [])), 1)
        self.assertEqual(result.get('subscribedTo', {})[0]['url'], subscribe_context['object']['url'])
        self.assertEqual('read' in result.get('subscribedTo', {})[0]['permissions'], True)
        self.assertEqual('write' in result.get('subscribedTo', {})[0]['permissions'], True)

    def test_check_permissions_on_subscribed_write_restricted_context(self):
        from .mockers import create_context_private_r, subscribe_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context_private_r)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        res = self.testapp.get('/people/%s' % username, "", oauth2Header(username))
        result = json.loads(res.text)
        self.assertEqual(len(result.get('subscribedTo', [])), 1)
        self.assertEqual(result.get('subscribedTo', {})[0]['url'], subscribe_context['object']['url'])
        self.assertEqual('read' in result.get('subscribedTo', {})[0]['permissions'], True)
        self.assertEqual('write' not in result.get('subscribedTo', {})[0]['permissions'], True)

    def test_post_on_subscribed_write_restricted_context_without_write_permission(self):
        from .mockers import create_context_private_r, subscribe_context, user_status_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context_private_r)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        res = self.create_activity(username, user_status_context, expect=403)

    def test_post_on_subscribed_rw_context(self):
        from .mockers import create_context_private_rw, subscribe_context, user_status_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context_private_rw)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        res = self.create_activity(username, user_status_context)
        result = json.loads(res.text)
        self.assertEqual(result.get('actor', None).get('username', None), 'messi')
        self.assertEqual(result.get('object', None).get('objectType', None), 'note')
        self.assertEqual(result.get('contexts', None)[0]['url'], user_status_context['contexts'][0]['url'])

    def test_grant_write_permission_on_write_restricted_context(self):
        """ doctest .. http:put:: /contexts/{hash}/permissions/{username}/{permission} """
        from .mockers import create_context_private_r, subscribe_context
        from hashlib import sha1
        username = '******'
        self.create_user(username)
        self.create_context(create_context_private_r)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        chash = sha1(create_context_private_r['url']).hexdigest()
        permission = 'write'
        res = self.testapp.put('/contexts/%s/permissions/%s/%s' % (chash, username, permission), "", oauth2Header(test_manager), status=201)
        result = json.loads(res.text)
        self.assertEqual('read' in result['permissions'], True)
        self.assertEqual('write' in result['permissions'], True)

    def test_revoke_write_permission_on_write_restricted_context(self):
        """ doctest .. http:delete:: /contexts/{hash}/permissions/{username}/{permission} """
        from .mockers import create_context_private_r, subscribe_context
        from hashlib import sha1
        username = '******'
        self.create_user(username)
        self.create_context(create_context_private_r)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        chash = sha1(create_context_private_r['url']).hexdigest()
        permission = 'write'
        res = self.testapp.put('/contexts/%s/permissions/%s/%s' % (chash, username, permission), "", oauth2Header(test_manager), status=201)
        res = self.testapp.delete('/contexts/%s/permissions/%s/%s' % (chash, username, permission), "", oauth2Header(test_manager), status=201)
        result = json.loads(res.text)
        self.assertEqual('read' in result['permissions'], True)
        self.assertEqual('write' not in result['permissions'], True)

    def test_grant_write_permission_on_non_subscribed_context(self):
        from .mockers import create_context_private_r
        from hashlib import sha1
        username = '******'
        self.create_user(username)
        self.create_context(create_context_private_r)
        chash = sha1(create_context_private_r['url']).hexdigest()
        permission = 'write'
        self.testapp.put('/contexts/%s/permissions/%s/%s' % (chash, username, permission), "", oauth2Header(test_manager), status=404)

    def test_grant_invalid_permission_on_subscribed_context(self):
        from .mockers import create_context_private_r, subscribe_context
        from hashlib import sha1
        username = '******'
        self.create_user(username)
        self.create_context(create_context_private_r)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        chash = sha1(create_context_private_r['url']).hexdigest()
        permission = 'badpermission'
        res = self.testapp.put('/contexts/%s/permissions/%s/%s' % (chash, username, permission), "", oauth2Header(test_manager), status=400)
        result = json.loads(res.text)
        self.assertEqual(result.get('error', None), 'InvalidPermission')

    def test_reset_user_subscription_to_default_permissions(self):
        from .mockers import create_context_private_r, subscribe_context
        from hashlib import sha1
        username = '******'
        self.create_user(username)
        self.create_context(create_context_private_r)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        chash = sha1(create_context_private_r['url']).hexdigest()
        permission = 'write'
        self.testapp.put('/contexts/%s/permissions/%s/%s' % (chash, username, permission), "", oauth2Header(test_manager), status=201)
        res = self.testapp.post('/contexts/%s/permissions/%s/defaults' % (chash, username), "", oauth2Header(test_manager), status=200)

        result = json.loads(res.text)
        self.assertEqual('read' in result['permissions'], True)
        self.assertEqual('write' in result['permissions'], False)

    def test_get_context_subscriptions(self):
        from .mockers import create_contextA, subscribe_contextA
        from .mockers import create_context_private_r, subscribe_context
        from hashlib import sha1
        username = '******'
        self.create_user(username)
        self.create_context(create_contextA)
        self.create_context(create_context_private_r)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(username, subscribe_contextA)
        chash = sha1(create_context_private_r['url']).hexdigest()
        res = self.testapp.get('/contexts/%s/subscriptions' % (chash), "", oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(result[0].get('username', ''), 'messi')
        self.assertEqual(result[0].get('hash', ''), chash)

    def test_create_context_with_upload_url(self):
        """ """
        from .mockers import create_context_with_uploadurl
        new_context = dict(create_context_with_uploadurl)
        res = self.testapp.post('/contexts', json.dumps(new_context), oauth2Header(test_manager), status=201)
        self.assertTrue(res.json.get('uploadURL'))
Example #22
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security_single)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    def test_get_security(self):
        res = self.testapp.get('/admin/security', "", oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(result.get('roles', None).get('Manager')[0], 'test_manager')

    def test_security_add_user_to_role(self):
        username = '******'
        self.create_user(username)
        res = self.testapp.post('/admin/security/roles/%s/users/%s' % ('Manager', username), "", oauth2Header(test_manager), status=201)
        self.assertItemsEqual(['messi', 'test_manager'], res.json)

    def test_security_add_user_to_non_allowed_role(self):
        username = '******'
        self.create_user(username)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('WrongRole', username), "", oauth2Header(test_manager), status=400)

    def test_security_remove_user_from_non_allowed_role(self):
        username = '******'
        self.create_user(username)
        self.testapp.delete('/admin/security/roles/%s/users/%s' % ('WrongRole', username), "", oauth2Header(test_manager), status=400)

    def test_security_add_user_to_role_already_has_role(self):
        res = self.testapp.post('/admin/security/roles/%s/users/%s' % ('Manager', 'test_manager'), "", oauth2Header(test_manager), status=200)
        self.assertListEqual(['test_manager'], res.json)

    def test_security_remove_user_from_role(self):
        username = '******'
        self.create_user(username)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('Manager', username), "", oauth2Header(test_manager), status=201)
        self.testapp.delete('/admin/security/roles/%s/users/%s' % ('Manager', username), "", oauth2Header(test_manager), status=204)

    def test_security_remove_user_from_role_user_not_in_role(self):
        username = '******'
        self.create_user(username)
        self.testapp.delete('/admin/security/roles/%s/users/%s' % ('Manager', username), "", oauth2Header(test_manager), status=404)

    def test_security_add_user_to_role_check_security_reloaded(self):
        test_manager2 = 'messi'
        self.create_user(test_manager2)
        self.testapp.get('/activities', "", oauth2Header(test_manager2), status=403)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('Manager', test_manager2), "", oauth2Header(test_manager), status=201)
        self.testapp.get('/activities', "", oauth2Header(test_manager2), status=200)

    def test_security_remove_user_from_role_check_security_reloaded(self):
        test_manager2 = 'messi'
        self.create_user(test_manager2)
        self.testapp.post('/admin/security/roles/%s/users/%s' % ('Manager', test_manager2), "", oauth2Header(test_manager), status=201)
        self.testapp.get('/activities', "", oauth2Header(test_manager2), status=200)
        self.testapp.delete('/admin/security/roles/%s/users/%s' % ('Manager', test_manager2), "", oauth2Header(test_manager), status=204)
        self.testapp.get('/activities', "", oauth2Header(test_manager2), status=403)
Example #23
0
class ActivitiesACLTests(unittest.TestCase, MaxTestBase):
    def setUp(self):
        conf_dir = os.path.dirname(os.path.dirname(__file__))

        self.app = loadapp("config:tests.ini", relative_to=conf_dir)
        self.app.registry.max_store.drop_collection("users")
        self.app.registry.max_store.drop_collection("activity")
        self.app.registry.max_store.drop_collection("contexts")
        self.app.registry.max_store.drop_collection("security")
        self.app.registry.max_store.drop_collection("conversations")
        self.app.registry.max_store.drop_collection("messages")
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch("requests.post", new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # Add comment to activity tests

    def test_comment_activity_as_manager(self):
        """
            Given i'm a Manager user
            When i try to post a comment on a contextless activity
            I succeed
        """
        from max.tests.mockers import user_status as activity
        from max.tests.mockers import user_comment as comment

        username = "******"
        self.create_user(username)
        activity_id = self.create_activity(username, activity).json["id"]
        self.comment_activity(test_manager, activity_id, comment, expect=201)

    def test_comment_others_activity_as_user(self):
        """
            Given i'm a regular user
            When i try to post a comment on a contextless activity
            I succeed
        """
        from max.tests.mockers import user_status as activity
        from max.tests.mockers import user_comment as comment

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        activity_id = self.create_activity(username, activity).json["id"]
        self.comment_activity(other, activity_id, comment, expect=201)

    def test_comment_others_activity_as_owner(self):
        """
            Given i'm the owner of the activity
            When i try to post a comment on a contextless activity i own
            I succeed
        """
        from max.tests.mockers import user_status as activity
        from max.tests.mockers import user_comment as comment

        username = "******"
        self.create_user(username)
        activity_id = self.create_activity(username, activity).json["id"]
        self.comment_activity(username, activity_id, comment, expect=201)

    # Add comment to contexted activity tests

    def test_comment_context_activity_as_manager(self):
        """
            Given i'm a Manager user
            When i try to post a comment on a contexted activity
            I succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        self.comment_activity(test_manager, activity_id, comment, expect=201)

    def test_comment_onw_context_activity_as_user(self):
        """
            Given i'm a regular user
            When i try to post a comment on a contexted activity that i own
            And I have permission to write on the context
            Then i succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        self.create_user(username)
        self.create_context(create_context, permissions={"write": "subscribed"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        self.comment_activity(username, activity_id, comment, expect=201)

    def test_comment_others_context_activity_as_user(self):
        """
            Given i'm a regular user
            When i try to post a comment on a someone else's contexted activity
            And I have permission to write on the context
            Then i succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={"write": "subscribed"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(other, subscribe_context)
        activity_id = self.create_activity(other, activity).json["id"]
        self.comment_activity(username, activity_id, comment, expect=201)

    def test_comment_others_context_activity_as_context_owner(self):
        """
            Given i'm the owner of a context
            When i try to post a comment on a contexted activity
            And I have permission to write on the context
            Then i succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, owner=username, permissions={"write": "subscribed"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(other, subscribe_context)
        activity_id = self.create_activity(other, activity).json["id"]
        self.comment_activity(username, activity_id, comment, expect=201)

    def test_comment_others_context_activity_as_context_owner_no_write(self):
        """
            Given i'm the owner of a context
            When i try to post a comment on a contexted activity
            And I don't have permission to write on the context
            Then i get a Forbidden Exception
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        self.create_user(username)
        url_hash = self.create_context(create_context, owner=username, permissions={"write": "subscribed"}).json["hash"]
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        self.revoke_permission(url_hash, username, "write")
        self.comment_activity(username, activity_id, comment, expect=403)

    def test_comment_others_context_activity_as_user_no_write(self):
        """
            Given i'm a regular user
            When i try to post a comment on a contexted activity
            And I don't have permission to write on the context
            Then i get a Forbidden Exception
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        self.create_user(username)
        url_hash = self.create_context(create_context, permissions={"write": "subscribed"}).json["hash"]
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        self.revoke_permission(url_hash, username, "write")
        self.comment_activity(username, activity_id, comment, expect=403)

    # Delete activity comment tests

    def test_delete_comment_activity_as_manager(self):
        """
            Given i'm a Manager user
            When i try to delete a comment from a contextless activity
            I succeed
        """
        from max.tests.mockers import user_status as activity
        from max.tests.mockers import user_comment as comment

        username = "******"
        self.create_user(username)
        activity_id = self.create_activity(username, activity).json["id"]
        comment_id = self.comment_activity(username, activity_id, comment).json["id"]
        self.delete_activity_comment(test_manager, activity_id, comment_id, expect=204)

    def test_delete_comment_activity_as_comment_owner(self):
        """
            Given i'm a regular user
            When i try to delete a comment from a contextless activity
            and im the owner of the comment
            I succeed
        """
        from max.tests.mockers import user_status as activity
        from max.tests.mockers import user_comment as comment

        username = "******"
        self.create_user(username)
        activity_id = self.create_activity(username, activity).json["id"]
        comment_id = self.comment_activity(username, activity_id, comment).json["id"]
        self.delete_activity_comment(username, activity_id, comment_id, expect=204)

    def test_delete_others_comment_activity_as_activity_owner(self):
        """
            Given i'm the Owner of an activity
            When i try to delete a comment from a the activivyt
            And i'm not the owner of the comment
            I succeed
        """
        from max.tests.mockers import user_status as activity
        from max.tests.mockers import user_comment as comment

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        activity_id = self.create_activity(username, activity).json["id"]
        comment_id = self.comment_activity(other, activity_id, comment).json["id"]
        self.delete_activity_comment(username, activity_id, comment_id, expect=204)

    def test_delete_others_comment_activity(self):
        """
            Given i'm a regular user
            When i try to delete a comment from a contextless activity
            and i'm not the owner of the comment
            And i'm not the owner of the activity
            I get a Forbidden exception
        """
        from max.tests.mockers import user_status as activity
        from max.tests.mockers import user_comment as comment

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        activity_id = self.create_activity(other, activity).json["id"]
        comment_id = self.comment_activity(other, activity_id, comment).json["id"]
        self.delete_activity_comment(username, activity_id, comment_id, expect=403)

    # Delete contexted activity comment tests

    def test_delete_context_comment_activity_as_manager(self):
        """
            Given i'm a Manager user
            When i try to delete a comment from a contexted activity
            I succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        self.create_user(username)
        self.create_context(create_context, permissions={"write": "subscribed"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        comment_id = self.comment_activity(username, activity_id, comment).json["id"]
        self.delete_activity_comment(test_manager, activity_id, comment_id, expect=204)

    def test_delete_context_comment_activity_as_comment_owner(self):
        """
            Given i'm a regular user
            When i try to delete a comment from a contexted activity
            and im the owner of the comment
            I succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        self.create_user(username)
        self.create_context(create_context, owner=username, permissions={"write": "subscribed"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        comment_id = self.comment_activity(username, activity_id, comment).json["id"]
        self.delete_activity_comment(username, activity_id, comment_id, expect=204)

    def test_delete_context_others_comment_activity_as_activity_owner(self):
        """
            Given i'm a regular user
            When i try to delete a comment from a contexted activity
            And i'm not the owner of the comment
            And i'm the owner of the activity
            I succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={"write": "subscribed"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(other, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        comment_id = self.comment_activity(other, activity_id, comment).json["id"]
        self.delete_activity_comment(username, activity_id, comment_id, expect=204)

    def test_delete_context_others_comment_activity_with_delete_permission(self):
        """
            Given i'm a regular user
            When i try to delete a comment from a contexted activity
            And i'm not the owner of the activity
            And i'm not the owner of the comment
            And i have delete permission on my context subscription
            I succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        chash = self.create_context(create_context, permissions={"write": "subscribed", "delete": "restricted"}).json[
            "hash"
        ]
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(other, subscribe_context)
        activity_id = self.create_activity(other, activity).json["id"]
        comment_id = self.comment_activity(other, activity_id, comment).json["id"]
        self.grant_permission(chash, username, "delete")
        self.delete_activity_comment(username, activity_id, comment_id, expect=204)

    def test_delete_context_comment_activity_as_context_owner(self):
        """
            Given i'm a Owner of a context
            When i try to delete a comment from that context
            and i'm not the owner of the activity
            and i'm not the owner of the comment
            and i don't have explicit delete permission
            I get a Forbidden Exception
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, owner=username, permissions={"write": "subscribed", "delete": "restricted"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(other, subscribe_context)
        activity_id = self.create_activity(other, activity).json["id"]
        comment_id = self.comment_activity(other, activity_id, comment).json["id"]
        self.delete_activity_comment(username, activity_id, comment_id, expect=403)

    def test_delete_context_others_comment_activity(self):
        """
            Given i'm a regular user
            When i try to delete a comment from a contexted activity
            and i'm not the owner of the activity
            and i'm not the owner of the comment
            I get a Forbidden exception
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import user_comment as comment
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={"write": "subscribed", "delete": "restricted"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(other, subscribe_context)
        activity_id = self.create_activity(other, activity).json["id"]
        comment_id = self.comment_activity(other, activity_id, comment).json["id"]
        self.delete_activity_comment(username, activity_id, comment_id, expect=403)

    # Get all user comments tests

    def test_get_all_user_comments(self):
        """
            Given i'm a regular user
            When i try to get all the comments i wrote anywhere
            I succeed
        """
        username = "******"
        self.create_user(username)
        self.testapp.get("/people/{}/comments".format(username), "", headers=oauth2Header(username), status=200)

    def test_get_all_other_user_comments_as_manager(self):
        """
            Given i'm a Manager user
            When i try to get all the comments someone else wrote
            I succeed
        """
        username = "******"
        self.create_user(username)
        self.testapp.get("/people/{}/comments".format(username), "", headers=oauth2Header(test_manager), status=200)

    def test_get_all_other_user_comments(self):
        """
            Given i'm a regular user
            When i try to get all the comments someone else wrote
            I get a Forbidden exception
        """
        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.testapp.get("/people/{}/comments".format(username), "", headers=oauth2Header(other), status=403)

    # Get all activity comments tests

    def test_get_all_activity_comments_as_manager(self):
        """
            Given i'm a Manager user
            When i try to get all the comments posted on a contextless activity
            I succeed
        """
        from max.tests.mockers import user_status as activity

        username = "******"
        self.create_user(username)
        activity_id = self.create_activity(username, activity).json["id"]
        self.testapp.get(
            "/activities/{}/comments".format(activity_id), "", headers=oauth2Header(test_manager), status=200
        )

    def test_get_all_activity_comments_as_activity_owner(self):
        """
            Given i'm the Owner of a contextless activity
            When i try to get all the comments posted on the activity
            I succeed
        """
        from max.tests.mockers import user_status as activity

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        activity_id = self.create_activity(username, activity).json["id"]
        self.testapp.get("/activities/{}/comments".format(activity_id), "", headers=oauth2Header(username), status=200)

    def test_get_all_activity_comments(self):
        """
            Given i'm a regular user
            When i try to get all the comments from a contextless activity
            And i don't own that activity
            I succeed
        """
        from max.tests.mockers import user_status as activity

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        activity_id = self.create_activity(username, activity).json["id"]
        self.testapp.get("/activities/{}/comments".format(activity_id), "", headers=oauth2Header(other), status=200)

    # Get all contexted activity comments tests

    def test_get_all_contexted_activity_comments_as_manager(self):
        """
            Given i'm a Manager user
            When i try to get all the comments posted on a contexted activity
            I succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        self.create_user(username)
        self.create_context(create_context, permissions={"write": "subscribed", "delete": "restricted"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        self.testapp.get(
            "/activities/{}/comments".format(activity_id), "", headers=oauth2Header(test_manager), status=200
        )

    def test_get_all_contexted_activity_comments_as_activity_owner(self):
        """
            Given i'm the Owner of a contextless activity
            When i try to get all the comments posted on the activity
            I succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={"write": "subscribed", "read": "subscribed"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(other, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        self.testapp.get("/activities/{}/comments".format(activity_id), "", headers=oauth2Header(username), status=200)

    def test_get_all_contexted_activity_comments(self):
        """
            Given i'm a regular user
            When i try to get all the comments from a contexted activity
            And i don't own the activity
            And i'm subscribed to the context
            And i have read permission on the context
            I succeed
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={"write": "subscribed", "read": "subscribed"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(other, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        self.testapp.get("/activities/{}/comments".format(activity_id), "", headers=oauth2Header(other), status=200)

    def test_get_all_contexted_activity_comments_non_subscribed(self):
        """
            Given i'm a regular user
            When i try to get all the comments from a contexted activity
            And i'm not subscribed to the context
            I get a Forbidden exception
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={"write": "subscribed", "read": "subscribed"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        self.testapp.get("/activities/{}/comments".format(activity_id), "", headers=oauth2Header(other), status=403)

    def test_get_all_contexted_activity_comments_no_read_permission(self):
        """
            Given i'm a regular user
            When i try to get all the comments from a contexted activity
            And i'm subscribed to the context
            And i don't have read permission
            I get a Forbidden exception
        """
        from max.tests.mockers import user_status_context as activity
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        other = "penny"
        self.create_user(username)
        self.create_user(other)
        self.create_context(create_context, permissions={"write": "subscribed", "read": "restricted"})
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.admin_subscribe_user_to_context(other, subscribe_context)
        activity_id = self.create_activity(username, activity).json["id"]
        self.testapp.get("/activities/{}/comments".format(activity_id), "", headers=oauth2Header(other), status=403)

    # Get all context comments tests

    def test_get_all_context_comments_as_manager(self):
        """
            Given i'm a Manager user
            When i try to get all the comments posted on context activities
            I succeed
        """
        from max.tests.mockers import create_context

        chash = self.create_context(create_context).json["hash"]
        self.testapp.get("/contexts/{}/comments".format(chash), "", headers=oauth2Header(test_manager), status=200)

    def test_get_all_context_comments_as_context_owner(self):
        """
            Given i'm the Owner of a contex
            When i try to get all the comments posted on context activities
            And i'm not subscribed on that context
            I get a Forbidden Exception
        """
        from max.tests.mockers import create_context

        username = "******"
        self.create_user(username)
        chash = self.create_context(create_context, owner=username).json["hash"]
        self.testapp.get("/contexts/{}/comments".format(chash), "", headers=oauth2Header(username), status=403)

    def test_get_all_context_comments(self):
        """
            Given i'm a regular user
            When i try to get all the comments posted on context activities
            And i'm subscribed to the context
            And i have read permission on the context
            I succeed
        """
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        self.create_user(username)
        chash = self.create_context(create_context, permissions={"write": "subscribed", "read": "subscribed"}).json[
            "hash"
        ]
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.testapp.get("/contexts/{}/comments".format(chash), "", headers=oauth2Header(username), status=200)

    def test_get_all_context_comments_non_subscribed(self):
        """
            Given i'm a regular user
            When i try to get all the comments posted on context activities
            And i'm not subscribed to the context
            I get a Forbidden exception
        """
        from max.tests.mockers import create_context

        username = "******"
        self.create_user(username)
        chash = self.create_context(create_context, permissions={"write": "subscribed", "read": "subscribed"}).json[
            "hash"
        ]
        self.testapp.get("/contexts/{}/comments".format(chash), "", headers=oauth2Header(username), status=403)

    def test_get_all_context_comments_no_read_permission(self):
        """
            Given i'm a regular user
            When i try to get all the comments posted on context activities
            And i'm subscribed to the context
            And i don't have read permission
            I get a Forbidden exception
        """
        from max.tests.mockers import create_context, subscribe_context

        username = "******"
        self.create_user(username)
        chash = self.create_context(create_context, permissions={"write": "subscribed", "read": "restricted"}).json[
            "hash"
        ]
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.testapp.get("/contexts/{}/comments".format(chash), "", headers=oauth2Header(username), status=403)

    # Get all global comments tests

    def test_get_all_comments(self):
        """
            Given i'm a regular user
            When i try to get all the comments
            I get a Forbidden exception
        """
        username = "******"
        self.create_user(username)
        self.testapp.get("/activities/comments", "", headers=oauth2Header(username), status=403)

    def test_get_all_comments_as_manager(self):
        """
            Given i'm a Manager user
            When i try to get all the comments
            I succeed
        """
        username = "******"
        self.create_user(username)
        self.testapp.get("/activities/comments", "", headers=oauth2Header(test_manager), status=200)
Example #24
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # BEGIN TESTS

    def test_add_public_context_with_valid_parameters_that_needs_formating(self):
        """
            Test formatters acting correctly by testing the extraction of the "@" and "#"
            on receiving a twitter @username and #hashtag containing extra chars (@,# and trailing/leading whitespace)
        """
        from .mockers import create_context_full

        new_context = dict(create_context_full)
        new_context['twitterUsername'] = '******' % create_context_full['twitterUsername']
        new_context['twitterHashtag'] = '  #%s' % create_context_full['twitterHashtag']
        res = self.testapp.post('/contexts', json.dumps(new_context), oauth2Header(test_manager), status=201)
        result = json.loads(res.text)
        self.assertEqual(result.get('twitterUsername', None), create_context_full['twitterUsername'])
        self.assertEqual(result.get('twitterHashtag', None), create_context_full['twitterHashtag'])

    def test_modify_public_context_with_valid_parameters_that_need_formating(self):
        """
            Test validation failure on receiving a invalid twitter username
        """
        from .mockers import create_context_full
        from hashlib import sha1

        res = self.testapp.post('/contexts', json.dumps(create_context_full), oauth2Header(test_manager), status=201)
        url_hash = sha1(create_context_full['url']).hexdigest()
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"twitterUsername": "******", "twitterHashtag": "#atenea"}), oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(result.get('twitterUsername', None), 'maxupcnet')
        self.assertEqual(result.get('twitterHashtag', None), 'atenea')

    def test_add_public_context_with_bad_twitter_username(self):
        """
            Test validation failure on receiving a invalid twitter username
        """
        from .mockers import create_context_full
        bad_context = dict(create_context_full)
        bad_context['twitterUsername'] = '******'
        res = self.testapp.post('/contexts', json.dumps(bad_context), oauth2Header(test_manager), status=400)
        result = json.loads(res.text)
        self.assertEqual(result.get('error', None), 'ValidationError')

    def test_add_public_context_with_bad_hashtag(self):
        """
            Test validation failure on receiving a invalid twitter hashtag
        """

        from .mockers import create_context_full
        bad_context = dict(create_context_full)
        bad_context['twitterHashtag'] = '##badhashtag'
        res = self.testapp.post('/contexts', json.dumps(bad_context), oauth2Header(test_manager), status=400)
        result = json.loads(res.text)
        self.assertEqual(result.get('error', None), 'ValidationError')
Example #25
0
class PeopleACLTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(os.path.dirname(__file__))

        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.app.registry.max_store.drop_collection('users')
        self.app.registry.max_store.drop_collection('activity')
        self.app.registry.max_store.drop_collection('contexts')
        self.app.registry.max_store.drop_collection('security')
        self.app.registry.max_store.drop_collection('conversations')
        self.app.registry.max_store.drop_collection('messages')
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

    # Add people tests

    def test_create_person_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to create a person
            I succeed
        """
        username = '******'
        self.testapp.post('/people', json.dumps({"username": username}), headers=oauth2Header(test_manager), status=201)

    def test_create_person_as_non_manager(self):
        """
            Given i'm user that doesn't have the Manager role
            When i try to create a person
            I get a Forbidden exception
        """
        username = '******'
        other = 'penny'
        self.testapp.post('/people', json.dumps({"username": other}), headers=oauth2Header(username), status=403)

    def test_create_person_as_oneself(self):
        """
            Given i'm user that doesn't have the Manager role
            When i try to create a person
            I succeed
        """
        username = '******'
        self.testapp.post('/people', json.dumps({"username": username}), headers=oauth2Header(username), status=201)

    # View profile tests

    def test_get_person_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to view a user profile
            I succeed
        """
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        self.testapp.get('/people/{}'.format(username), "", headers=oauth2Header(test_manager), status=200)

    def test_get_person_as_non_manager(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to view a user profile
            I succeed
        """
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        self.testapp.get('/people/{}'.format(test_manager), "", headers=oauth2Header(username), status=200)

    # Get all people

    def test_get_all_people_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to get all people
            I succeed
        """
        self.create_user(test_manager)
        self.testapp.get('/people', "", headers=oauth2Header(test_manager), status=200)

    def test_get_all_people_as_non_manager(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to get a visible people listing
            I suceed
        """
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        self.testapp.get('/people', "", headers=oauth2Header(username), status=200)

    # Modify user tests

    def test_modify_person_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to modify a user profile
            I succeed
        """
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        self.testapp.put('/people/{}'.format(username), "", headers=oauth2Header(test_manager), status=200)

    def test_modify_person_as_non_manager_neither_owner(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to modify a user profile
            And that person is not me
            I get a Forbidden Exception
        """
        username = '******'
        other = 'penny'

        self.create_user(test_manager)
        self.create_user(username)
        self.create_user(other)
        self.testapp.put('/people/{}'.format(other), "", headers=oauth2Header(username), status=403)

    def test_modify_person_as_owner(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to modify my own profile
            I succeed
        """
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        self.testapp.put('/people/{}'.format(username), "", headers=oauth2Header(username), status=200)

    # Delete user tests

    def test_delete_person_as_manager(self):
        """
            Given i'm a user that has the Manager role
            When i try to delete a user
            I succeed
        """
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        self.testapp.delete('/people/{}'.format(username), headers=oauth2Header(test_manager), status=204)

    def test_delete_person_as_non_manager_neither_owner(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to delete a user
            I get a Forbidden Exception
        """
        username = '******'
        other = 'penny'

        self.create_user(test_manager)
        self.create_user(username)
        self.create_user(other)
        self.testapp.delete('/people/{}'.format(other), headers=oauth2Header(username), status=403)

    def test_delete_person_as_owner(self):
        """
            Given i'm a user that doesn't have the Manager role
            When i try to delete myself
            I get a Forbidden Exception
        """
        username = '******'

        self.create_user(test_manager)
        self.create_user(username)
        self.testapp.delete('/people/{}'.format(username), headers=oauth2Header(username), status=403)
Example #26
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # BEGIN TESTS

    def test_get_activities_order_sorted_by_last_comment_publish_date(self):
        """
            Given a plain user
            When I post activities on a context
            and I comment on an old activity
            Then in the comment-sorted activities, the commented activity becomes the first
        """
        from .mockers import user_comment
        from .mockers import user_status_context
        from .mockers import subscribe_context, create_context
        from .mockers import context_query

        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity_0_id = self.create_activity(username, user_status_context).json['id']
        activity_1_id = self.create_activity(username, user_status_context, note='Second').json['id']
        activity_2_id = self.create_activity(username, user_status_context, note='Third').json['id']
        res = self.testapp.post('/activities/%s/comments' % str(activity_1_id), json.dumps(user_comment), oauth2Header(username), status=201)

        res = self.testapp.get('/contexts/%s/activities?sort=published' % (context_query['context']), '', oauth2Header(username), status=200)

        self.assertEqual(len(res.json), 3)
        self.assertEqual(res.json[0].get('id', None), activity_2_id)
        self.assertEqual(res.json[1].get('id', None), activity_1_id)
        self.assertEqual(res.json[2].get('id', None), activity_0_id)

    def test_timeline_order_sorted_by_last_comment_publish_date(self):
        """
            Given a plain user
            When I post activities
            and I comment on an old activity
            Then in the comment-sorted timeline, the commented activity becomes the first
        """
        from .mockers import user_status, user_comment
        username = '******'
        self.create_user(username)
        activity_ids = []
        # Create 7 activities to overpass limit of 5
        for i in range(7):
            activity_ids.append(self.create_activity(username, user_status, note=str(i)).json['id'])
        res = self.testapp.post('/activities/%s/comments' % str(activity_ids[0]), json.dumps(user_comment), oauth2Header(username), status=201)
        # Get first 5 results
        res = self.testapp.get('/people/%s/timeline?sort=published&priority=comments&limit=5' % username, "", oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 5)

        self.assertEqual(res.json[0].get('id', None), activity_ids[0])
        self.assertEqual(res.json[1].get('id', None), activity_ids[6])
        self.assertEqual(res.json[2].get('id', None), activity_ids[5])
        self.assertEqual(res.json[3].get('id', None), activity_ids[4])
        self.assertEqual(res.json[4].get('id', None), activity_ids[3])

        # get next 2 results
        res = self.testapp.get('/people/%s/timeline?sort=published&priority=comments&limit=5&before=%s' % (username, activity_ids[3]), "", oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 2)

        self.assertEqual(res.json[0].get('id', None), activity_ids[2])
        self.assertEqual(res.json[1].get('id', None), activity_ids[1])

    def test_timeline_order_sorted_by_last_comment_publish_date_when_delete_comment(self):
        """
            Given a plain user
            When I post activities
            and I comment on an old activity
            and I delete comment on an old activity
            Then in the comment-sorted timeline
        """
        from .mockers import user_status, user_comment
        username = '******'
        self.create_user(username)
        activity_ids = []
        # Create 7 activities to overpass limit of 5
        for i in range(7):
            activity_ids.append(self.create_activity(username, user_status, note=str(i)).json['id'])
        res = self.testapp.post('/activities/%s/comments' % str(activity_ids[0]), json.dumps(user_comment), oauth2Header(username), status=201)
        comment_id = res.json['id']

        # Delete comment
        res = self.testapp.delete('/activities/%s/comments/%s' % (str(activity_ids[0]), comment_id), '', oauth2Header(username), status=204)

        # Get first 5 results
        res = self.testapp.get('/people/%s/timeline?sort=published&priority=comments&limit=5' % username, "", oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 5)
        self.assertEqual(res.json[0].get('id', None), activity_ids[6])
        self.assertEqual(res.json[1].get('id', None), activity_ids[5])
        self.assertEqual(res.json[2].get('id', None), activity_ids[4])
        self.assertEqual(res.json[3].get('id', None), activity_ids[3])
        self.assertEqual(res.json[4].get('id', None), activity_ids[2])

        # get next 2 results
        res = self.testapp.get('/people/%s/timeline?sort=published&priority=comments&limit=5&before=%s' % (username, activity_ids[3]), "", oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 3)

        self.assertEqual(res.json[0].get('id', None), activity_ids[2])
        self.assertEqual(res.json[1].get('id', None), activity_ids[1])
        self.assertEqual(res.json[2].get('id', None), activity_ids[0])

    def test_timeline_order_sorted_by_last_comment_publish_date_when_delete_one_comment(self):
        """
            Given a plain user
            When I post activities
            and I comment on an old activity
            and I delete comment on an old activity
            Then in the comment-sorted timeline
        """
        from .mockers import user_status, user_comment
        username = '******'
        self.create_user(username)
        activity_ids = []
        # Create 7 activities to overpass limit of 5
        for i in range(7):
            activity_ids.append(self.create_activity(username, user_status, note=str(i)).json['id'])
        res = self.testapp.post('/activities/%s/comments' % str(activity_ids[0]), json.dumps(user_comment), oauth2Header(username), status=201)
        comment_id = res.json['id']
        self.testapp.post('/activities/%s/comments' % str(activity_ids[0]), json.dumps(user_comment), oauth2Header(username), status=201)
        self.testapp.post('/activities/%s/comments' % str(activity_ids[0]), json.dumps(user_comment), oauth2Header(username), status=201)

        # Delete comment
        res = self.testapp.delete('/activities/%s/comments/%s' % (str(activity_ids[0]), comment_id), '', oauth2Header(username), status=204)

        # Get first 5 results
        res = self.testapp.get('/people/%s/timeline?sort=published&priority=comments&limit=5' % username, "", oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 5)
        self.assertEqual(res.json[0].get('id', None), activity_ids[0])
        self.assertEqual(res.json[1].get('id', None), activity_ids[6])
        self.assertEqual(res.json[2].get('id', None), activity_ids[5])
        self.assertEqual(res.json[3].get('id', None), activity_ids[4])
        self.assertEqual(res.json[4].get('id', None), activity_ids[3])

        # get next 2 results
        res = self.testapp.get('/people/%s/timeline?sort=published&priority=comments&limit=5&before=%s' % (username, activity_ids[3]), "", oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 2)

        self.assertEqual(res.json[0].get('id', None), activity_ids[2])
        self.assertEqual(res.json[1].get('id', None), activity_ids[1])

    def test_timeline_order_sorted_by_activity_publish_date(self):
        """
            Given a plain user
            When I post activities
            and I comment on an old activity
            Then in the activities-sorted timeline, the order equals the activity order
        """
        from .mockers import user_status, user_comment
        username = '******'
        self.create_user(username)
        activity_0_id = self.create_activity(username, user_status).json['id']
        activity_1_id = self.create_activity(username, user_status, note="second").json['id']
        activity_2_id = self.create_activity(username, user_status, note="third").json['id']
        res = self.testapp.post('/activities/%s/comments' % str(activity_1_id), json.dumps(user_comment), oauth2Header(username), status=201)

        res = self.testapp.get('/people/%s/timeline?sort=published' % username, "", oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 3)
        self.assertEqual(res.json[0].get('id', None), activity_2_id)
        self.assertEqual(res.json[1].get('id', None), activity_1_id)
        self.assertEqual(res.json[2].get('id', None), activity_0_id)
Example #27
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # BEGIN TESTS
    def test_get_all_users_admin(self):
        username = '******'
        self.create_user(username)
        res = self.testapp.get('/people', "", oauth2Header(test_manager))

        self.assertEqual(len(res.json), 2)
        self.assertEqual(res.json[0].get('username'), 'test_manager')
        self.assertEqual(res.json[1].get('username'), 'messi')

    def test_admin_post_activity_without_context(self):
        from .mockers import user_status
        username = '******'
        self.create_user(username)
        res = self.testapp.post('/people/%s/activities' % username, json.dumps(user_status), oauth2Header(test_manager))
        result = json.loads(res.text)
        self.assertEqual(result.get('actor', None).get('username', None), 'messi')
        self.assertEqual(result.get('object', None).get('objectType', None), 'note')
        self.assertEqual(result.get('contexts', None), None)

    def test_admin_post_activity_with_context(self):
        """ doctest .. http:post:: /people/{username}/activities """
        from .mockers import subscribe_context
        from .mockers import user_status_context
        from .mockers import create_context

        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        res = self.testapp.post('/people/%s/activities' % username, json.dumps(user_status_context), oauth2Header(test_manager))
        result = json.loads(res.text)
        self.assertEqual(result.get('actor', None).get('username', None), 'messi')
        self.assertEqual(result.get('object', None).get('objectType', None), 'note')
        self.assertEqual(result.get('contexts', None)[0]['url'], subscribe_context['object']['url'])

    def test_admin_post_activity_with_context_as_actor(self):
        """ doctest .. http:post:: /contexts/{hash}/activities """
        from .mockers import subscribe_context
        from .mockers import user_status_as_context
        from .mockers import create_context
        from hashlib import sha1
        self.create_context(create_context)
        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.post('/contexts/%s/activities' % url_hash, json.dumps(user_status_as_context), oauth2Header(test_manager), status=201)
        result = json.loads(res.text)
        self.assertEqual(result.get('actor', None).get('hash', None), url_hash)
        self.assertEqual(result.get('object', None).get('objectType', None), 'note')
        self.assertEqual(result.get('contexts', None)[0]['url'], subscribe_context['object']['url'])

    def test_get_other_activities(self):
        from .mockers import user_status_context
        from .mockers import subscribe_context, create_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)
        self.testapp.get('/people/%s/activities' % (username), '', oauth2Header(test_manager), status=200)

    def test_delete_user(self):
        username = '******'
        self.create_user(username)
        self.testapp.delete('/people/%s' % username, '', oauth2Header(test_manager), status=204)

    def test_delete_all_conversations(self):
        from .mockers import group_message as message
        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'

        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)

        self.testapp.delete('/conversations', '', oauth2Header(test_manager), status=204)

        conversations = self.testapp.get('/conversations', '', oauth2Header(sender), status=200)
        self.assertEqual(len(conversations.json), 0)

        user_data = self.testapp.get('/people/{}'.format(sender), '', oauth2Header(sender), status=200)
        self.assertEqual(len(user_data.json['talkingIn']), 0)

    def test_delete_inexistent_user(self):
        username = '******'
        username2 = 'xavi'
        self.create_user(username)
        self.testapp.delete('/people/%s' % username2, '', oauth2Header(test_manager), status=400)

    def test_admin_delete_inexistent_activity(self):
        fake_id = '519200000000000000000000'
        self.testapp.delete('/activities/%s' % (fake_id), '', oauth2Header(test_manager), status=404)

    def test_admin_get_people_activities_by_context(self):
        """
        """
        from .mockers import user_status
        from .mockers import context_query
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context

        username = '******'
        self.create_user(username)
        self.create_context(create_context, permissions=dict(read='subscribed', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        self.create_activity(username, user_status_context)
        self.create_activity(username, user_status)

        res = self.testapp.get('/people/%s/activities' % username, context_query, oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 1)

    def test_admin_get_all_activities_by_context(self):
        """




        XXX This test was here to test the Manager endpoint that didn't search for recursive activities
        now this is unified so this feature will have to be refactored to a preset or parameter to
        disable recursivity.

        The test now is fixed to pass with correct acitivity count asserts




        """
        from .mockers import user_status
        from .mockers import subscribe_context, subscribe_contextA
        from .mockers import create_context, create_contextA
        from .mockers import user_status_context, user_status_contextA

        from hashlib import sha1

        username = '******'
        self.create_user(username)
        self.create_context(create_context, permissions=dict(read='subscribed', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        url_hash = sha1(create_context['url']).hexdigest()

        self.create_context(create_contextA, permissions=dict(read='subscribed', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_contextA)
        url_hashA = sha1(create_contextA['url']).hexdigest()

        self.create_activity(username, user_status_context)
        self.create_activity(username, user_status_contextA)
        self.create_activity(username, user_status)

        res = self.testapp.get('/contexts/%s/activities' % url_hash, {}, oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 2)

        res = self.testapp.get('/contexts/%s/activities' % url_hashA, {}, oauth2Header(test_manager), status=200)
        result = json.loads(res.text)
        self.assertEqual(len(result), 1)

    # def test_admin_post_activity_with_unauthorized_context_type_as_actor(self):
    #     from .mockers import create_unauthorized_context
    #     from hashlib import sha1

    #     result = self.create_context(create_invalid_context, expect=201)
        # url_hash = sha1(create_invalid_context['object']['url']).hexdigest()
        # res = self.testapp.post('/contexts/%s/activities' % url_hash, json.dumps(user_status_context), oauth2Header(test_manager))
        # result = json.loads(res.text)
        # self.assertEqual(result.get('actor', None).get('hash', None), url_hash)
        # self.assertEqual(result.get('object', None).get('objectType', None), 'note')
        # self.assertEqual(result.get('contexts', None)[0], subscribe_context['object'])

    def test_get_users_twitter_enabled(self):
        """ Doctest .. http:get:: /people """
        username = '******'
        username2 = 'xavi'
        self.create_user(username)
        self.create_user(username2)
        self.modify_user(username, {"twitterUsername": "******"})
        res = self.testapp.get('/people', {"twitter_enabled": True}, oauth2Header(test_manager), status=200)

        self.assertEqual(len(res.json), 1)
        self.assertIn('twitterUsername', res.json[0])

    def test_get_context_twitter_enabled(self):
        from .mockers import create_context, create_contextA
        self.create_context(create_context)
        self.create_context(create_contextA)
        self.modify_context(create_context['url'], {"twitterHashtag": "assignatura1", "twitterUsername": "******"})

        res = self.testapp.get('/contexts', {"twitter_enabled": True}, oauth2Header(test_manager), status=200)

        self.assertEqual(len(res.json), 1)

    def test_rename_context_url(self):
        from .mockers import create_context
        from .mockers import subscribe_context, user_status_context
        from hashlib import sha1

        username = '******'
        self.create_user(username)
        self.create_context(create_context, permissions=dict(read='subscribed', write='subscribed', subscribe='restricted', invite='restricted'))
        self.admin_subscribe_user_to_context(username, subscribe_context)
        activity = self.create_activity(username, user_status_context)

        url_hash = sha1(create_context['url']).hexdigest()
        res = self.testapp.put('/contexts/%s' % url_hash, json.dumps({"url": "http://new.url"}), oauth2Header(test_manager), status=200)

        # Test context is updated
        new_url_hash = sha1('http://new.url').hexdigest()
        res = self.testapp.get('/contexts/%s' % new_url_hash, "", oauth2Header(test_manager), status=200)
        self.assertEqual(res.json['url'], 'http://new.url')
        self.assertEqual(res.json['hash'], new_url_hash)

        # Test user subscription is updated
        res = self.testapp.get('/people/%s' % username, "", oauth2Header(test_manager), status=200)
        self.assertEqual(res.json['subscribedTo'][0]['url'], 'http://new.url')
        self.assertEqual(res.json['subscribedTo'][0]['hash'], new_url_hash)

        # Test user original subscription activity is updated
        subscription_activity = self.exec_mongo_query('activity', 'find', {'object.hash': new_url_hash, 'object.url': "http://new.url", 'actor.username': username})
        self.assertNotEqual(subscription_activity, [])
        self.assertEqual(subscription_activity[0]['object']['hash'], new_url_hash)
        self.assertEqual(subscription_activity[0]['object']['url'], 'http://new.url')

        # Test user activity is updated
        res = self.testapp.get('/activities/%s' % activity.json['id'], "", oauth2Header(test_manager), status=200)
        self.assertEqual(res.json['contexts'][0]['url'], 'http://new.url')
        self.assertEqual(res.json['contexts'][0]['hash'], new_url_hash)
Example #28
0
class DeprecationTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)

        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # Test deprecated Add people

    def test_deprecated_request_create_user(self):
        """
            Given a request to the deprecated POST /people/{username}
            When the request is processed
            Then the request is rewrited as POST /people
            And the username is now in the body
            And the displayName is preserved in the body
        """
        res = self.testapp.post('/people/sheldon', json.dumps({"displayName": 'Sheldon'}), headers=oauth2Header(test_manager), status=201)

        rewrited_request = res.request
        rewrited_request_url = urlparse.urlparse(rewrited_request.url).path

        self.assertEqual(rewrited_request_url, '/people')
        self.assertEqual(res.json['username'], 'sheldon')
        self.assertEqual(res.json['displayName'], 'Sheldon')

    # Test deprecated subscribe user

    def test_deprecated_subscribe_user(self):
        """
            Given a request to the deprecated POST /people/{username}/subscriptions
            When the request is processed
            Then the request is rewrited as POST /contexts/{hash}/subscriptions
            And the actor now is in the body
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)
        res = self.create_context(create_context)
        context_hash = res.json['hash']

        res = self.testapp.post('/people/%s/subscriptions' % username, json.dumps(subscribe_context), oauth2Header(test_manager), status=201)

        rewrited_request = res.request
        rewrited_request_url = urlparse.urlparse(rewrited_request.url).path

        self.assertEqual(rewrited_request_url, '/contexts/{}/subscriptions'.format(context_hash))
        self.assertEqual(res.json['actor']['username'], 'sheldon')
        self.assertEqual(res.json['actor']['objectType'], 'person')

    # Test deprecated unsubscribe user

    def test_deprecated_unsubscribe_user(self):
        """
            Given a request to the deprecated DELETE /people/{username}/subscriptions
            When the request is processed
            Then the request is rewrited as DELETE /contexts/{hash}/subscriptions
            And the actor now is in the body
        """
        from max.tests.mockers import create_context, subscribe_context
        username = '******'

        self.create_user(username)
        res = self.create_context(create_context)
        context_hash = res.json['hash']

        self.admin_subscribe_user_to_context(username, subscribe_context)
        res = self.testapp.delete('/people/%s/subscriptions/%s' % (username, context_hash), "", oauth2Header(test_manager), status=204)

        rewrited_request = res.request
        rewrited_request_url = urlparse.urlparse(rewrited_request.url).path

        self.assertEqual(rewrited_request_url, '/contexts/{}/subscriptions/{}'.format(context_hash, username))

    # Test deprecated create context activity

    def test_deprecated_user_post_activity_to_context(self):
        """
            Given a request to the deprecated POST /people/{username}/activities
            And the request has a "contexts" parameter
            When the request is processed
            Then the request is rewrited as POST /contexts/{hash}/activities
            And the actor is in the body
            and object is preserved in the body
        """
        from max.tests.mockers import create_context, subscribe_context
        from max.tests.mockers import user_status_context as activity

        username = '******'

        self.create_user(username)
        res = self.create_context(create_context)
        context_hash = res.json['hash']
        self.admin_subscribe_user_to_context(username, subscribe_context)

        res = self.testapp.post('/people/%s/activities' % username, json.dumps(activity), oauth2Header(username), status=201)

        rewrited_request = res.request
        rewrited_request_url = urlparse.urlparse(rewrited_request.url).path

        self.assertEqual(rewrited_request_url, '/contexts/{}/activities'.format(context_hash))
        self.assertEqual(res.json['actor']['username'], 'sheldon')
        self.assertEqual(res.json['actor']['objectType'], 'person')
        self.assertIn('object', res.json)

    def test_deprecated_user_post_activity_to_context_without_context(self):
        """
            Given a request to the deprecated POST /people/{username}/activities
            And the request doesn't have a "contexts" parameter
            When the request is processed
            Then the request remains untouched
        """
        from max.tests.mockers import create_context, subscribe_context
        from max.tests.mockers import user_status as activity

        username = '******'

        self.create_user(username)
        res = self.create_context(create_context)
        context_hash = res.json['hash']
        self.admin_subscribe_user_to_context(username, subscribe_context)

        res = self.testapp.post('/people/sheldon/activities', json.dumps(activity), oauth2Header(username), status=201)

        rewrited_request = res.request
        rewrited_request_url = urlparse.urlparse(rewrited_request.url).path

        self.assertEqual(rewrited_request_url, '/people/sheldon/activities'.format(context_hash))
        self.assertNotIn('contexts', res.json)

    # Test depreacted join conversation

    def test_deprecated_join_conversation(self):
        """
            Given a request to the deprecated POST /people/{user}/conversations/{id}
            When the request is processed
            Then the request is rewrited as DELETE /conversations/{id}/participants
            And the actor is in the body
        """
        from max.tests.mockers import group_message as message
        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'
        recipient3 = 'melendi'
        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)
        self.create_user(recipient3)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])

        res = self.testapp.post('/people/{}/conversations/{}'.format(recipient3, cid), '', oauth2Header(test_manager), status=201)

        rewrited_request = res.request
        rewrited_request_url = urlparse.urlparse(rewrited_request.url).path

        self.assertEqual(rewrited_request_url, '/conversations/{}/participants'.format(cid))
        self.assertEqual(res.json['actor']['username'], recipient3)
        self.assertEqual(res.json['actor']['objectType'], 'person')

    def test_deprecated_leave_conversation(self):
        """
            Given a request to the deprecated DELETE /people/{user}/conversations/{id}
            When the request is processed
            Then the request is rewrited as DELETE /conversations/{id}/participants/{username}
            And the url parameters are remapped
        """
        from max.tests.mockers import group_message as message
        sender = 'messi'
        recipient = 'xavi'
        recipient2 = 'shakira'
        self.create_user(sender)
        self.create_user(recipient)
        self.create_user(recipient2)

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])

        res = self.testapp.delete('/people/{}/conversations/{}'.format(recipient2, cid), '', oauth2Header(test_manager), status=204)

        rewrited_request = res.request
        rewrited_request_url = urlparse.urlparse(rewrited_request.url).path

        self.assertEqual(rewrited_request_url, '/conversations/{}/participants/{}'.format(cid, recipient2))

    def test_deprecated_add_token(self):
        """
            Given a request to the deprecated POST /people/{user}/device/{platform}/{token}
            When the request is processed
            Then the request is rewrited as POST /tokens
            And the token is injected in the request body
            And the platform is injected in the reqeust body
            And the response contains a Person instead of a Token
        """
        username = '******'
        self.create_user(username)
        token = '000000000000000000'
        platform = 'ios'

        res = self.testapp.post('/people/{}/device/{}/{}'.format(username, platform, token), '', headers=oauth2Header(username), status=201)

        rewrited_request = res.request
        rewrited_request_url = urlparse.urlparse(rewrited_request.url).path

        self.assertEqual(rewrited_request_url, '/tokens')
        self.assertEqual(res.json['username'], username)
        self.assertEqual(res.json['objectType'], 'person')

    def test_deprecated_delete_token(self):
        """
            Given a request to the deprecated DELETE /people/{user}/device/{platform}/{token}
            When the request is processed
            Then the request is rewrited as DELETE /tokens/{token}
            And the token is injected in the body
            And the platform is injected in the body
        """
        username = '******'
        self.create_user(username)
        token = '000000000000000000'
        platform = 'ios'

        self.testapp.post('/people/{}/device/{}/{}'.format(username, platform, token), '', headers=oauth2Header(username), status=201)
        res = self.testapp.delete('/people/{}/device/{}/{}'.format(username, platform, token), '', headers=oauth2Header(username), status=204)

        rewrited_request = res.request
        rewrited_request_url = urlparse.urlparse(rewrited_request.url).path

        self.assertEqual(rewrited_request_url, '/tokens/{}'.format(token))

    def test_deprecated_sortBy_parameter(self):
        """
            Given a plain user
            When I query ativities using old sortBy parameter
            I get the expected result

            THIS TEST IS A DUPLICATE OF max.tests.test_timeline_order_sorted_by_last_comment_publish_date
            ONLY TO TEST THE TRANSLATION OF THE SORTBY PARAMETER

        """
        from .mockers import user_status, user_comment
        username = '******'
        self.create_user(username)
        activity_ids = []
        # Create 7 activities to overpass limit of 5
        for i in range(7):
            activity_ids.append(self.create_activity(username, user_status, note=str(i)).json['id'])
        res = self.testapp.post('/activities/%s/comments' % str(activity_ids[0]), json.dumps(user_comment), oauth2Header(username), status=201)
        # Get first 5 results
        res = self.testapp.get('/people/%s/timeline?sortBy=comments&limit=5' % username, "", oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 5)

        self.assertEqual(res.json[0].get('id', None), activity_ids[0])
        self.assertEqual(res.json[1].get('id', None), activity_ids[6])
        self.assertEqual(res.json[2].get('id', None), activity_ids[5])
        self.assertEqual(res.json[3].get('id', None), activity_ids[4])
        self.assertEqual(res.json[4].get('id', None), activity_ids[3])

        # get next 2 results
        res = self.testapp.get('/people/%s/timeline?sortBy=comments&limit=5&before=%s' % (username, activity_ids[3]), "", oauth2Header(username), status=200)
        self.assertEqual(len(res.json), 2)

        self.assertEqual(res.json[0].get('id', None), activity_ids[2])
        self.assertEqual(res.json[1].get('id', None), activity_ids[1])
Example #29
0
class FunctionalTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(__file__)
        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.reset_database(self.app)
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    def tearDown(self):
        import pyramid.testing
        shutil.rmtree(self.app.registry.settings['file_repository'], ignore_errors=True)
        pyramid.testing.tearDown()

    # BEGIN TESTS

    def test_create_image_activity(self):
        """
            Given a plain user
            When I post an image activity
            And I am authenticated as myself
            Then the image activity is created correctly
        """
        from .mockers import user_image_activity as activity
        username = '******'
        self.create_user(username)
        thefile = open(os.path.join(os.path.dirname(__file__), "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'image/png')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)
        res = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200)
        response = res.json

        self.assertEqual(response[0]['object'].get('fullURL'), u'/activities/{}/image/full'.format(response[0]['id']))
        self.assertEqual(response[0]['object'].get('thumbURL'), u'/activities/{}/image/thumb'.format(response[0]['id']))

    def test_create_file_activity(self):
        """
            Given a plain user
            When I post a file activity
            And I am authenticated as myself
            Then the file activity is created correctly
        """
        from .mockers import user_file_activity as activity
        username = '******'
        self.create_user(username)
        thefile = open(os.path.join(os.path.dirname(__file__), "map.pdf"), "rb")
        files = [('file', 'map.pdf', thefile.read(), 'application/pdf')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)

        res = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200)
        response = res.json
        self.assertEqual(response[0]['object'].get('fullURL'), u'/activities/{}/file/download'.format(response[0]['id']))

    def test_create_image_activity_with_context(self):
        """
            Given a plain user
            When I post an image activity to a context with no uploadURL
            And I am authenticated as myself
            Then the image activity is created correctly
        """
        from .mockers import user_image_activity_with_context as activity
        from .mockers import subscribe_context, create_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)

        thefile = open(os.path.join(os.path.dirname(__file__), "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'image/png')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)

        res = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200)
        response = res.json
        self.assertEqual(response[0]['object'].get('fullURL'), u'/activities/{}/image/full'.format(response[0]['id']))
        self.assertEqual(response[0]['object'].get('thumbURL'), u'/activities/{}/image/thumb'.format(response[0]['id']))

    def test_create_file_activity_with_context(self):
        """
            Given a plain user
            When I post an file activity to a context with no uploadURL
            And I am authenticated as myself
            Then the file activity is created correctly
        """
        from .mockers import user_file_activity_with_context as activity
        from .mockers import subscribe_context, create_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)

        thefile = open(os.path.join(os.path.dirname(__file__), "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'application/pdf')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)

        res = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200)
        response = res.json
        self.assertEqual(response[0]['object'].get('fullURL'), u'/activities/{}/file/download'.format(response[0]['id']))

    def test_create_image_activity_with_context_with_uploadurl(self):
        """
            Given a plain user
            When I post an image activity to a context with uploadURL
            And I am authenticated as myself
            Then the image activity is created correctly
        """
        from .mockers import user_image_activity_with_context_with_uploadurl as activity
        from .mockers import subscribe_context_with_uploadurl, create_context_with_uploadurl
        username = '******'
        self.create_user(username)
        self.create_context(create_context_with_uploadurl)
        self.admin_subscribe_user_to_context(username, subscribe_context_with_uploadurl)

        thefile = open(os.path.join(os.path.dirname(__file__), "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'image/png')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)

        res = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200)
        response = res.json
        self.assertEqual(response[0]['object'].get('fullURL'), u'http://localhost:8181/theimage')
        self.assertEqual(response[0]['object'].get('thumbURL'), u'http://localhost:8181/theimage/thumb')

    def test_create_file_activity_with_context_with_uploadurl(self):
        """
            Given a plain user
            When I post an file activity to a context with uploadURL
            And I am authenticated as myself
            Then the file activity is created correctly
        """
        from .mockers import user_file_activity_with_context_with_uploadurl as activity
        from .mockers import subscribe_context_with_uploadurl, create_context_with_uploadurl
        username = '******'
        self.create_user(username)
        self.create_context(create_context_with_uploadurl)
        self.admin_subscribe_user_to_context(username, subscribe_context_with_uploadurl)

        thefile = open(os.path.join(os.path.dirname(__file__), "map.pdf"), "rb")
        files = [('file', 'map.pdf', thefile.read(), 'application/pdf')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)

        res = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200)
        response = res.json
        self.assertEqual(response[0]['object'].get('fullURL'), u'http://localhost:8181/theimage')

    def test_post_message_with_image_to_an_already_existing_conversation(self):
        from .mockers import message, message_with_image
        sender = 'messi'
        recipient = 'xavi'
        self.create_user(sender)
        self.create_user(recipient)

        thefile = open(os.path.join(os.path.dirname(__file__), "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'image/png')]

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])
        self.testapp.post('/conversations/%s/messages' % cid, dict(json_data=json.dumps(message_with_image)), oauth2Header(sender), upload_files=files, status=201)

        res = self.testapp.get('/conversations/%s/messages' % cid, "", oauth2Header(sender), status=200)
        result = json.loads(res.text)

        self.assertEqual(len(result), 2)
        self.assertEqual(result[0].get("contexts", None)[0].get("id", None), cid)
        self.assertEqual(result[0].get("contexts", None)[0].get("objectType", None), "conversation")
        self.assertEqual(result[0].get("objectType", None), "message")
        self.assertEqual(result[1]['object'].get('fullURL'), u'/messages/{}/image/full'.format(result[1]['id']))
        self.assertEqual(result[1]['object'].get('thumbURL'), u'/messages/{}/image/thumb'.format(result[1]['id']))

        full_url = result[1]['object'].get('fullURL')
        res = self.testapp.get(full_url, '', oauth2Header(sender), status=200)

    def test_post_message_with_file_to_an_already_existing_conversation(self):
        from .mockers import message, message_with_file
        sender = 'messi'
        recipient = 'xavi'
        self.create_user(sender)
        self.create_user(recipient)

        thefile = open(os.path.join(os.path.dirname(__file__), "map.pdf"), "rb")
        files = [('file', 'map.pdf', thefile.read(), 'application/pdf')]

        res = self.testapp.post('/conversations', json.dumps(message), oauth2Header(sender), status=201)
        cid = str(res.json['contexts'][0]['id'])
        self.testapp.post('/conversations/%s/messages' % cid, dict(json_data=json.dumps(message_with_file)), oauth2Header(sender), upload_files=files, status=201)

        res = self.testapp.get('/conversations/%s/messages' % cid, "", oauth2Header(sender), status=200)
        result = json.loads(res.text)

        self.assertEqual(len(result), 2)
        self.assertEqual(result[0].get("contexts", None)[0].get("id", None), cid)
        self.assertEqual(result[0].get("contexts", None)[0].get("objectType", None), "conversation")
        self.assertEqual(result[0].get("objectType", None), "message")
        self.assertEqual(result[1]['object'].get('fullURL'), u'/messages/{}/file/download'.format(result[1]['id']))

    def test_get_image_activity_file_with_context(self):
        """
            Given a plain user
            When I post an image activity to a context with no uploadURL
            And I am authenticated as myself
            Then the image activity is created correctly
        """
        from .mockers import user_image_activity_with_context as activity
        from .mockers import subscribe_context, create_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)

        thefile = open(os.path.join(os.path.dirname(__file__), "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'image/png')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)

        res = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200)
        response = res.json

        res = self.testapp.get('/activities/{}/image/full'.format(response[0]['id']), '', oauth2Header(username), status=200)
        self.assertEqual(len(res.body), 20492)
        self.assertEqual(res.content_type, u'image/png')

    def test_get_file_activity_file_with_context(self):
        """
            Given a plain user
            When I post an file activity to a context with no uploadURL
            And I am authenticated as myself
            Then the file activity is created correctly
            And I can retrieve it with the endpoint
        """
        from .mockers import user_file_activity_with_context as activity
        from .mockers import subscribe_context, create_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)

        thefile = open(os.path.join(os.path.dirname(__file__), "map.pdf"), "rb")
        files = [('file', 'map.pdf', thefile.read(), 'application/pdf')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)

        res = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200)
        response = res.json

        res = self.testapp.get('/activities/{}/file/download'.format(response[0]['id']), '', oauth2Header(username), status=200)

        self.assertEqual(len(res.body), 34981)
        self.assertEqual(res.content_type, u'application/pdf')

    def test_get_file_activity_file_with_context_not_allowed_user(self):
        """
            Given a file activity created by me in a context
            When an user non subscribed to this context tries to retrieve it
            Then the user cannot acces the file activity
        """
        from .mockers import user_file_activity_with_context as activity
        from .mockers import subscribe_context, create_context
        username = '******'
        username2 = 'thor'
        self.create_user(username)
        self.create_user(username2)
        self.create_context(create_context, permissions={'read': 'subscribed'})
        self.admin_subscribe_user_to_context(username, subscribe_context)

        thefile = open(os.path.join(os.path.dirname(__file__), "map.pdf"), "rb")
        files = [('file', 'map.pdf', thefile.read(), 'application/pdf')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)

        activity_id = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200).json[0]['id']

        self.testapp.get('/activities/{}/file/download'.format(activity_id), '', oauth2Header(username2), status=403)

    def test_get_thumb_image_activity_file_with_context(self):
        """
            Given a plain user
            When I post an image activity to a context with no uploadURL
            And I am authenticated as myself
            Then the image activity is created correctly
        """
        from .mockers import user_image_activity_with_context as activity
        from .mockers import subscribe_context, create_context
        username = '******'
        self.create_user(username)
        self.create_context(create_context)
        self.admin_subscribe_user_to_context(username, subscribe_context)

        thefile = open(os.path.join(os.path.dirname(__file__), "avatar.png"), "rb")
        files = [('file', 'avatar.png', thefile.read(), 'image/png')]

        res = self.testapp.post('/people/{}/activities'.format(username), dict(json_data=json.dumps(activity)), oauth2Header(username), upload_files=files, status=201)

        res = self.testapp.get('/people/{}/activities'.format(username), '', oauth2Header(username), status=200)
        response = res.json

        res = self.testapp.get('/activities/{}/image/thumb'.format(response[0]['id']), '', oauth2Header(username), status=200)

        # Give a margin of size of 10 bytes, sometimes readed image
        # size differs by two bytes, who knows why ...
        self.assertLessEqual(abs(len(res.body) - 2966), 10)

        self.assertEqual(res.content_type, u'image/jpeg')
Example #30
0
class TokenACLTests(unittest.TestCase, MaxTestBase):

    def setUp(self):
        conf_dir = os.path.dirname(os.path.dirname(__file__))

        self.app = loadapp('config:tests.ini', relative_to=conf_dir)
        self.app.registry.max_store.drop_collection('users')
        self.app.registry.max_store.drop_collection('activity')
        self.app.registry.max_store.drop_collection('contexts')
        self.app.registry.max_store.drop_collection('security')
        self.app.registry.max_store.drop_collection('conversations')
        self.app.registry.max_store.drop_collection('messages')
        self.app.registry.max_store.drop_collection('tokens')
        self.app.registry.max_store.security.insert(test_default_security)
        self.patched_post = patch('requests.post', new=partial(mock_post, self))
        self.patched_post.start()
        self.testapp = MaxTestApp(self)

        self.create_user(test_manager)

    # Add new token test

    def test_add_token(self):
        """
            Given i'm a regular user
            When i try to add a device token
            I succeed
        """
        from max.tests.mockers import token

        username = '******'
        self.create_user(username)

        self.testapp.post('/tokens', json.dumps(token), headers=oauth2Header(username), status=201)

    def test_add_token_impersonated(self):
        """
            Given i'm a Manager user
            When i try to add a device token to someone else
            I succeed
        """
        from max.tests.mockers import token

        username = '******'
        self.create_user(username)

        self.testapp.post('/tokens', json.dumps(impersonate_payload(token, username)), headers=oauth2Header(test_manager), status=201)

    def test_add_token_impersonated_no_privileges(self):
        """
            Given i'm a regular user
            When i try to add a device token to someone else
            And i'm impersonated as the other user
            I get a Forbidden Exception
        """
        from max.tests.mockers import token

        username = '******'
        username2 = 'penny'
        self.create_user(username)
        self.create_user(username2)

        self.testapp.post('/tokens', json.dumps(impersonate_payload(token, username)), headers=oauth2Header(username2), status=403)

    # Get all tokens tests

    def test_get_user_tokens(self):
        """
            Given i'm a regular user
            When i try to get al my tokens
            I succeed
        """
        username = '******'
        self.create_user(username)
        self.testapp.get('/people/{}/tokens'.format(username), '', headers=oauth2Header(username), status=200)

    def test_get_user_tokens_as_manager(self):
        """
            Given i'm a regular user
            When i try to get al my tokens
            I succeed
        """
        username = '******'
        self.create_user(username)
        self.testapp.get('/people/{}/tokens'.format(username), '', headers=oauth2Header(test_manager), status=200)

    def test_get_user_tokens_as_other(self):
        """
            Given i'm a regular user
            When i try to get al my tokens
            I get a Forbidden Exception
        """
        username = '******'
        other = 'penny'
        self.create_user(username)
        self.create_user(other)

        self.testapp.get('/people/{}/tokens'.format(username), '', headers=oauth2Header(other), status=403)

    # Get all tokens by platform tests

    def test_get_user_platform_tokens(self):
        """
            Given i'm a regular user
            When i try to get al my tokens
            I succeed
        """
        username = '******'
        self.create_user(username)
        self.testapp.get('/people/{}/tokens/platforms/{}'.format(username, 'ios'), '', headers=oauth2Header(username), status=200)

    def test_get_user_platform_tokens_as_manager(self):
        """
            Given i'm a regular user
            When i try to get al my tokens
            I succeed
        """
        username = '******'
        self.create_user(username)
        self.testapp.get('/people/{}/tokens/platforms/{}'.format(username, 'ios'), '', headers=oauth2Header(test_manager), status=200)

    def test_get_user_platform_tokens_as_other(self):
        """
            Given i'm a regular user
            When i try to get al my tokens
            I get a Forbidden Exception
        """
        username = '******'
        other = 'penny'
        self.create_user(username)
        self.create_user(other)

        self.testapp.get('/people/{}/tokens/platforms/{}'.format(username, 'ios'), '', headers=oauth2Header(other), status=403)

    # Delete token test

    def test_delete_token(self):
        """
            Given i'm a regular user
            When i try to add delete a device token
            I succeed
        """
        from max.tests.mockers import token

        username = '******'
        self.create_user(username)

        self.testapp.post('/tokens', json.dumps(token), headers=oauth2Header(username), status=201)
        self.testapp.delete('/tokens/{}'.format(token['token']), '', headers=oauth2Header(username), status=204)

    def test_delete_ohers_token(self):
        """
            Given i'm a regular user
            When i try to delete someone else's device token
            I get a Forbidden Exception
        """
        from max.tests.mockers import token

        username = '******'
        username2 = 'penny'
        self.create_user(username)
        self.create_user(username2)

        self.testapp.post('/tokens', json.dumps(token), headers=oauth2Header(username), status=201)
        self.testapp.delete('/tokens/{}'.format(token['token']), '', headers=oauth2Header(username2), status=403)

    def test_delete_token_impersonated(self):
        """
            Given i'm a Manager user
            When i try to delete someone else's device token
            I succeed
        """
        from max.tests.mockers import token

        username = '******'
        self.create_user(username)

        self.testapp.post('/tokens', json.dumps(token), headers=oauth2Header(username), status=201)
        self.testapp.delete('/tokens/{}'.format(token['token']), json.dumps(impersonate_payload({}, test_manager)), headers=oauth2Header(username), status=204)

    def test_delete_token_impersonated_no_privileges(self):
        """
            Given i'm a regular user
            When i try to delete someone else's device token
            And i'm impersonating as the other user
            I get a Forbidden Exception
        """
        from max.tests.mockers import token

        username = '******'
        username2 = 'penny'
        self.create_user(username)
        self.create_user(username2)

        self.testapp.post('/tokens', json.dumps(token), headers=oauth2Header(username), status=201)
        self.testapp.delete('/tokens/{}'.format(token['token']), json.dumps(impersonate_payload({}, username2)), headers=oauth2Header(username), status=204)

    # Delete all user tokens tests

    def test_delete_user_tokens(self):
        """
            Given i'm a regular user
            When i try to delete all my tokens
            I succeed
        """
        username = '******'
        self.create_user(username)

        self.testapp.delete('/people/{}/tokens'.format(username), '', headers=oauth2Header(username), status=204)

    def test_delete_user_tokens_impersonated(self):
        """
            Given i'm a Manager user
            When i try to delete another user tokens
            I succeed
        """
        username = '******'
        self.create_user(username)

        self.testapp.delete('/people/{}/tokens'.format(username), '', headers=oauth2Header(test_manager), status=204)

    def test_delete_user_tokens_impersonated_no_privileges(self):
        """
            Given i'm a regular user
            When i try to delete another user tokens
            I succeed
        """
        username = '******'
        username2 = 'penny'
        self.create_user(username)
        self.create_user(username2)

        self.testapp.delete('/people/{}/tokens'.format(username), '', headers=oauth2Header(username2), status=403)

    # Delete all user tokens by platform tests

    def test_delete_user_tokens_by_platform(self):
        """
            Given i'm a regular user
            When i try to delete all my tokens by platform
            I succeed
        """
        username = '******'
        self.create_user(username)

        self.testapp.delete('/people/{}/tokens/platforms/{}'.format(username, 'ios'), '', headers=oauth2Header(username), status=204)

    def test_delete_user_tokens_by_platform_impersonated(self):
        """
            Given i'm a Manager user
            When i try to delete another user tokens by platform
            I succeed
        """
        username = '******'
        self.create_user(username)

        self.testapp.delete('/people/{}/tokens/platforms/{}'.format(username, 'ios'), '', headers=oauth2Header(test_manager), status=204)

    def test_delete_user_tokens_by_platform_impersonated_no_privileges(self):
        """
            Given i'm a regular user
            When i try to delete another user tokens by platform
            I succeed
        """
        username = '******'
        username2 = 'penny'
        self.create_user(username)
        self.create_user(username2)

        self.testapp.delete('/people/{}/tokens/platforms/{}'.format(username, 'ios'), '', headers=oauth2Header(username2), status=403)

    # Get conversation user's tokens tests

    def test_get_conversation_tokens_as_manager(self):
        """
            Given i'm a Manager user
            When i try to list all tokens of users of a conversation
            I succeed
        """
        from max.tests.mockers import message

        username = '******'
        username2 = 'xavi'
        self.create_user(username)
        self.create_user(username2)
        chash = self.testapp.post('/conversations', json.dumps(message), oauth2Header(username), status=201).json['id']
        self.testapp.get('/conversations/{}/tokens'.format(chash), '', headers=oauth2Header(test_manager), status=200)

    def test_get_conversation_tokens_as_anyone_else(self):
        """
            Given i'm a regular user
            When i try to list all tokens of users of a conversation
            I get a Forbidden Exception
        """
        from max.tests.mockers import message

        username = '******'
        username2 = 'xavi'
        self.create_user(username)
        self.create_user(username2)
        chash = self.testapp.post('/conversations', json.dumps(message), oauth2Header(username), status=201).json['id']
        self.testapp.get('/conversations/{}/tokens'.format(chash), '', headers=oauth2Header(username), status=403)

    # Get context user's tokens tests

    def test_get_context_tokens_as_manager(self):
        """
            Given i'm a Manager user
            When i try to list all tokens of users subscribed to a context
            I succeed
        """
        from max.tests.mockers import create_context

        chash = self.create_context(create_context).json['hash']

        self.testapp.get('/contexts/{}/tokens'.format(chash), '', headers=oauth2Header(test_manager), status=200)

    def test_get_context_tokens_as_anyone_else(self):
        """
            Given i'm a regular user
            When i try to list all tokens of users subscribed to a context
            I get a Forbidden Exception
        """
        from max.tests.mockers import create_context

        username = '******'
        self.create_user(username)
        chash = self.create_context(create_context).json['hash']

        self.testapp.get('/contexts/{}/tokens'.format(chash), '', headers=oauth2Header(username), status=403)