def setUp(self):
     """
     Sets up the testing environment;
     creates a `UserController`
     """
     self.init(user_role=model.ROLE_ADMINISTRATOR)
     self.user_c = UserController()
Example #2
0
 def transactional_setup_method(self):
     """
     Sets up the testing environment;
     creates a `UserController`
     """
     self.init(user_role=ROLE_ADMINISTRATOR)
     self.user_c = UserController()
 def setUp(self):
     """
     Sets up the testing environment;
     creates a `UserController`
     """
     self.init(user_role=model.ROLE_ADMINISTRATOR)
     self.user_c = UserController()
 def transactional_setup_method(self):
     """
     Sets up the testing environment;
     creates a `UserController`
     """
     self.init(user_role=model.ROLE_ADMINISTRATOR)
     self.user_c = UserController()
Example #5
0
def init_cherrypy(arguments=None):
    #### Mount static folders from modules marked for introspection
    arguments = arguments or []
    CONFIGUER = TvbProfile.current.web.CHERRYPY_CONFIGURATION
    for module in arguments:
        module_inst = importlib.import_module(str(module))
        module_path = os.path.dirname(os.path.abspath(module_inst.__file__))
        CONFIGUER["/static_" + str(module)] = {'tools.staticdir.on': True,
                                               'tools.staticdir.dir': '.',
                                               'tools.staticdir.root': module_path}

    #### Mount controllers, and specify the root URL for them.
    cherrypy.tree.mount(BaseController(), "/", config=CONFIGUER)
    cherrypy.tree.mount(UserController(), "/user/", config=CONFIGUER)
    cherrypy.tree.mount(ProjectController(), "/project/", config=CONFIGUER)
    cherrypy.tree.mount(FigureController(), "/project/figure/", config=CONFIGUER)
    cherrypy.tree.mount(FlowController(), "/flow/", config=CONFIGUER)
    cherrypy.tree.mount(SettingsController(), "/settings/", config=CONFIGUER)
    cherrypy.tree.mount(HelpController(), "/help/", config=CONFIGUER)
    cherrypy.tree.mount(SimulatorController(), "/burst/", config=CONFIGUER)
    cherrypy.tree.mount(ParameterExplorationController(), "/burst/explore/", config=CONFIGUER)
    cherrypy.tree.mount(DynamicModelController(), "/burst/dynamic/", config=CONFIGUER)
    cherrypy.tree.mount(SpatioTemporalController(), "/spatial/", config=CONFIGUER)
    cherrypy.tree.mount(RegionsModelParametersController(), "/burst/modelparameters/regions/", config=CONFIGUER)
    cherrypy.tree.mount(SurfaceModelParametersController(), "/spatial/modelparameters/surface/", config=CONFIGUER)
    cherrypy.tree.mount(RegionStimulusController(), "/spatial/stimulus/region/", config=CONFIGUER)
    cherrypy.tree.mount(SurfaceStimulusController(), "/spatial/stimulus/surface/", config=CONFIGUER)
    cherrypy.tree.mount(LocalConnectivityController(), "/spatial/localconnectivity/", config=CONFIGUER)
    cherrypy.tree.mount(NoiseConfigurationController(), "/burst/noise/", config=CONFIGUER)
    cherrypy.tree.mount(HPCController(), "/hpc/", config=CONFIGUER)

    cherrypy.config.update(CONFIGUER)

    # ----------------- Register additional request handlers -----------------
    # This tool checks for MAX upload size
    cherrypy.tools.upload = Tool('on_start_resource', RequestHandler.check_upload_size)
    # This tools clean up files on disk (mainly after export)
    cherrypy.tools.cleanup = Tool('on_end_request', RequestHandler.clean_files_on_disk)
    # ----------------- End register additional request handlers ----------------

    # Register housekeeping job
    if TvbProfile.current.hpc.IS_HPC_RUN and TvbProfile.current.hpc.CAN_RUN_HPC:
        cherrypy.engine.housekeeper = cherrypy.process.plugins.BackgroundTask(
            TvbProfile.current.hpc.BACKGROUND_JOB_INTERVAL, HPCOperationService.check_operations_job)
        cherrypy.engine.housekeeper.start()

    # HTTP Server is fired now ######
    cherrypy.engine.start()
Example #6
0
 def __init__(self):
     UserController.__init__(self)
     self.settingsservice = SettingsService()
class UsersControllerTest(BaseTransactionalControllerTest):
    """Unit test for UserController"""
    
    def setUp(self):
        """
        Sets up the testing environment;
        creates a `UserController`
        """
        self.init(user_role=model.ROLE_ADMINISTRATOR)
        self.user_c = UserController()


    def tearDown(self):
        """ Cleans the testing environment """
        self.cleanup()

    
    def test_index_valid_post(self):
        """
        Tests for a valid redirect on user login
        """
        user = model.User('valid_user', md5('valid_pass').hexdigest(), '*****@*****.**', True, 'CLINICIAN')
        dao.store_entity(user)
        login_data = {'username': '******', 'password': '******'}
        cherrypy.request.method = "POST"
        self._expect_redirect('/user/profile', self.user_c.index, **login_data)
    
    
    def test_profile_logout(self):
        """
        Simulate a logout and make sure we are redirected to the logout page.
        """
        cherrypy.request.method = "POST"
        self._expect_redirect('/user/logout', self.user_c.profile, logout=True)
        
        
    def test_profile_no_settings(self):
        """
        Delete the dummy tvb settings file and make sure we are redirected to the settings page.
        """
        os.remove(TvbProfile.current.TVB_CONFIG_FILE)
        TvbProfile.current.manager.stored_settings = None
        self._expect_redirect('/settings/settings', self.user_c.profile)

        
    def test_profile_get(self):
        """
        Simulate a GET request and make sure all required information for the user profile
        page are returned.
        """
        cherrypy.request.method = "GET"
        template_dict = self.user_c.profile()
        self._check_default_attributes(template_dict, {}, {})
        self.assertEqual(template_dict[common.KEY_USER].id, self.test_user.id)
        
    
    def test_profile_edit(self):
        """
        Simulate a edit of the email and check that data is actually changed.
        """
        edited_data = {'email': u'*****@*****.**'}
        cherrypy.request.method = "POST"
        self.user_c.profile(save=True, **edited_data)
        user = dao.get_user_by_id(self.test_user.id)
        self.assertEqual('*****@*****.**', user.email)
        
        
    def test_logout(self):
        """
        Test that a logout removes the user from session.
        """
        cherrypy.request.config = {'tools.sessions.name': 'session_id'}
        cherrypy.serving.response.cookie['session_id'] = 1
        self._expect_redirect('/user', self.user_c.logout)
        self.assertTrue(common.KEY_USER not in cherrypy.session, "User should be removed after logout.")
        
    
    def test_switch_online_help(self):
        """
        Test the switchOnlineHelp method and make sure it adds corresponding entry to UserPreferences.
        """
        self._expect_redirect('/user/profile', self.user_c.switchOnlineHelp)
        self.assertFalse(utils.string2bool(self.test_user.preferences[UserPreferences.ONLINE_HELP_ACTIVE]),
                         "Online help should be switched to False.")
        
        
    def test_register_cancel(self):
        """
        Test cancel on registration page.
        """
        self._expect_redirect('/user', self.user_c.register, cancel=True)
            
    
    def test_register_post_valid(self):
        """
        Test with valid data and check user is created.
        """
        cherrypy.request.method = "POST"
        data = dict(username="******",
                    password="******",
                    password2="pass",
                    email="*****@*****.**",
                    comment="This is some dummy comment",
                    role="CLINICIAN")
        self._expect_redirect('/user', self.user_c.register, **data)
        stored_user = dao.get_user_by_name('registered_user')
        self.assertTrue(stored_user is not None, "New user should be saved.")
        
        
    def test_register_post_invalid_data(self):
        """
        Check that errors field from template is filled in case invalid data is submitted.
        """
        cherrypy.request.method = "POST"
        # Data invalid missing username
        data = dict(password="******",
                    password2="pass",
                    email="*****@*****.**",
                    comment="This is some dummy comment",
                    role="CLINICIAN")
        template_dict = self.user_c.register(**data)
        self.assertTrue(template_dict[common.KEY_ERRORS] != {}, "Errors should contain some data.")
        
        
    def test_create_new_cancel(self):
        """
        Test that a cancel brings you back to usermanagement.
        """
        self._expect_redirect('/user/usermanagement', self.user_c.create_new, cancel=True)
    
    
    def test_create_new_valid_post(self):
        """
        Test that a valid create new post will actually create a new user in database.
        """
        data = dict(username="******",
                    password="******",
                    password2="pass",
                    email="*****@*****.**",
                    comment="This is some dummy comment",
                    role="CLINICIAN")
        cherrypy.request.method = "POST"
        self._expect_redirect('/user/usermanagement', self.user_c.create_new, **data)
        created_user = dao.get_user_by_name("registered_user")
        self.assertTrue(created_user is not None, "Should have a new user created.")
        
    
    def test_usermanagement_no_access(self):
        """
        Since we need to be admin to access this, we should get redirect to /tvb.
        """
        self.test_user.role = "TEST"
        self._expect_redirect('/tvb', self.user_c.usermanagement)
        self.assertEqual(cherrypy.session[common.KEY_MESSAGE_TYPE], common.TYPE_ERROR)
        
    
    def test_usermanagement_cancel(self):
        """
        Test that a cancel redirects us to a corresponding page.
        """
        self.test_user.role = "ADMINISTRATOR"
        self.test_user = dao.store_entity(self.test_user)
        cherrypy.session[common.KEY_USER] = self.test_user
        self._expect_redirect('/user/profile', self.user_c.usermanagement, cancel=True)
        
        
    def test_usermanagement_post_valid(self):
        """
        Create a valid post and check that user is created.
        """
        self.test_user.role = "ADMINISTRATOR"
        self.test_user = dao.store_entity(self.test_user)
        cherrypy.session[common.KEY_USER] = self.test_user
        TestFactory.create_user(username="******")
        TestFactory.create_user(username="******", validated=False)
        user_before_delete = dao.get_user_by_name("to_be_deleted")
        self.assertTrue(user_before_delete is not None)
        user_before_validation = dao.get_user_by_name("to_validate")
        self.assertFalse(user_before_validation.validated)
        data = {"delete_%i" % user_before_delete.id: True,
                "role_%i" % user_before_validation.id: "ADMINISTRATOR",
                "validate_%i" % user_before_validation.id: True}
        self.user_c.usermanagement(do_persist=True, **data)
        user_after_delete = dao.get_user_by_id(user_before_delete.id)
        self.assertTrue(user_after_delete is None, "User should be deleted.")
        user_after_validation = dao.get_user_by_id(user_before_validation.id)
        self.assertTrue(user_after_validation.validated, "User should be validated now.")
        self.assertTrue(user_after_validation.role == "ADMINISTRATOR", "Role has not changed.")
        
        
    def test_recoverpassword_cancel(self):
        """
        Test that cancel redirects to user page.
        """
        cherrypy.request.method = "POST"
        self._expect_redirect('/user', self.user_c.recoverpassword, cancel=True)
    
    
    def test_recoverpassword_valid_post(self):
        """
        Test a valid password recovery.
        """
        cherrypy.request.method = "POST"
        data = {"email": self.test_user.email,
                "username": ""}
        self._expect_redirect("/user", self.user_c.recoverpassword, **data)
        self.assertTrue(cherrypy.session[common.KEY_MESSAGE_TYPE] == common.TYPE_INFO,
                        "Info message informing successfull reset should be present")
        
        
    def test_validate_valid(self):
        """
        Pass a valid user and test that it is actually validate.
        """
        self.test_user.role = "ADMINISTRATOR"
        self.test_user = dao.store_entity(self.test_user)
        cherrypy.session[common.KEY_USER] = self.test_user
        TestFactory.create_user(username="******", validated=False)
        user_before_validation = dao.get_user_by_name("to_validate")
        self.assertFalse(user_before_validation.validated)
        self._expect_redirect('/tvb', self.user_c.validate, user_before_validation.username)
        user_after_validation = dao.get_user_by_id(user_before_validation.id)
        self.assertTrue(user_after_validation.validated, "User should be validated.")
        self.assertTrue(cherrypy.session[common.KEY_MESSAGE_TYPE] == common.TYPE_INFO)
        
        
    def test_validate_invalid(self):
        """
        Pass a valid user and test that it is actually validate.
        """
        unexisting = dao.get_user_by_name("should-not-exist")
        self.assertTrue(unexisting is None, "This user should not exist")
        self._expect_redirect('/tvb', self.user_c.validate, "should-not-exist")
        self.assertTrue(cherrypy.session[common.KEY_MESSAGE_TYPE] == common.TYPE_ERROR)
    
    
    def _check_default_attributes(self, template_dict, data, errors):
        """
        Check that all the defaults are present in the template dictionary.
        """
        self.assertEqual(template_dict[common.KEY_LINK_ANALYZE], '/flow/step/2')
        self.assertEqual(template_dict[common.KEY_BACK_PAGE], False)
        self.assertEqual(template_dict[common.KEY_LINK_CONNECTIVITY_TAB], '/flow/step_connectivity')
        self.assertEqual(template_dict[common.KEY_CURRENT_TAB], 'nav-user')
        self.assertEqual(template_dict[common.KEY_FORM_DATA], data)
        self.assertEqual(template_dict[common.KEY_ERRORS], errors)
        self.assertEqual(template_dict[common.KEY_INCLUDE_TOOLTIP], True)
 def __init__(self):
     UserController.__init__(self)
     self.settingsservice = SettingsService()
class TestUsersController(BaseTransactionalControllerTest):
    """Unit test for UserController"""

    def transactional_setup_method(self):
        """
        Sets up the testing environment;
        creates a `UserController`
        """
        self.clean_database()
        self.init(user_role=ROLE_ADMINISTRATOR)
        self.user_c = UserController()

    def transactional_teardown_method(self):
        """ Cleans the testing environment """
        self.cleanup()
        self.clean_database()

    def test_index_valid_post(self):
        """
        Tests for a valid redirect on user login
        """
        user = User('valid_user', 'name', hash_password('valid_pass'), '*****@*****.**', True, 'CLINICIAN')
        dao.store_entity(user)
        login_data = {'username': '******', 'password': '******'}
        cherrypy.request.method = "POST"
        self._expect_redirect('/user/profile', self.user_c.index, **login_data)

    def test_profile_logout(self):
        """
        Simulate a logout and make sure we are redirected to the logout page.
        """
        cherrypy.request.method = "POST"
        self._expect_redirect('/user/logout', self.user_c.profile, logout=True)

    def test_profile_no_settings(self):
        """
        Delete the dummy tvb settings file and make sure we are redirected to the settings page.
        """
        os.remove(TvbProfile.current.TVB_CONFIG_FILE)
        TvbProfile.current.manager.stored_settings = None
        self._expect_redirect('/settings/settings', self.user_c.profile)

    def test_profile_get(self):
        """
        Simulate a GET request and make sure all required information for the user profile
        page are returned.
        """
        cherrypy.request.method = "GET"
        template_dict = self.user_c.profile()
        self._check_default_attributes(template_dict, {}, {})
        assert template_dict[common.KEY_USER].id == self.test_user.id

    def test_profile_edit(self):
        """
        Simulate a edit of the email and check that data is actually changed.
        """
        edited_data = {'email': '*****@*****.**'}
        cherrypy.request.method = "POST"
        self.user_c.profile(save=True, **edited_data)
        user = dao.get_user_by_id(self.test_user.id)
        assert '*****@*****.**' == user.email

    def test_logout(self):
        """
        Test that a logout removes the user from session.
        """
        cherrypy.request.config = {'tools.sessions.name': 'session_id'}
        cherrypy.serving.response.cookie['session_id'] = 1
        self._expect_redirect('/user', self.user_c.logout)
        assert common.KEY_USER not in cherrypy.session, "User should be removed after logout."

    def test_switch_online_help(self):
        """
        Test the switch_online_help method and make sure it adds corresponding entry to UserPreferences.
        """
        self._expect_redirect('/user/profile', self.user_c.switch_online_help)
        assert not string2bool(self.test_user.preferences[UserPreferences.ONLINE_HELP_ACTIVE]), \
            "Online help should be switched to False."

    def test_register_cancel(self):
        """
        Test cancel on registration page.
        """
        self._expect_redirect('/user', self.user_c.register, cancel=True)

    def test_register_post_valid(self):
        """
        Test with valid data and check user is created.
        """
        cherrypy.request.method = "POST"
        data = dict(username="******",
                    display_name="display_name",
                    password="******",
                    password2="pass",
                    email="*****@*****.**",
                    comment="This is some dummy comment",
                    role="CLINICIAN")
        self._expect_redirect('/user', self.user_c.register, **data)
        stored_user = dao.get_user_by_name('registered_user')
        assert stored_user is not None, "New user should be saved."

    def test_register_post_invalid_data(self):
        """
        Check that errors field from template is filled in case invalid data is submitted.
        """
        cherrypy.request.method = "POST"
        # Data invalid missing username
        data = dict(password="******",
                    password2="pass",
                    email="*****@*****.**",
                    comment="This is some dummy comment",
                    role="CLINICIAN")
        template_dict = self.user_c.register(**data)
        assert template_dict[common.KEY_ERRORS] != {}, "Errors should contain some data."

    def test_create_new_cancel(self):
        """
        Test that a cancel brings you back to usermanagement.
        """
        self._expect_redirect('/user/usermanagement', self.user_c.create_new, cancel=True)

    def test_create_new_valid_post(self):
        """
        Test that a valid create new post will actually create a new user in database.
        """
        data = dict(username="******",
                    display_name="display_name",
                    password="******",
                    password2="pass",
                    email="*****@*****.**",
                    comment="This is some dummy comment",
                    role="CLINICIAN")
        cherrypy.request.method = "POST"
        self._expect_redirect('/user/usermanagement', self.user_c.create_new, **data)
        created_user = dao.get_user_by_name("registered_user")
        assert created_user is not None, "Should have a new user created."

    def test_usermanagement_no_access(self):
        """
        Since we need to be admin to access this, we should get redirect to /tvb.
        """
        self.test_user.role = "TEST"
        self._expect_redirect('/tvb', self.user_c.usermanagement)
        assert cherrypy.session[common.KEY_MESSAGE_TYPE] == common.TYPE_ERROR

    def test_usermanagement_cancel(self):
        """
        Test that a cancel redirects us to a corresponding page.
        """
        self.test_user.role = "ADMINISTRATOR"
        self.test_user = dao.store_entity(self.test_user)
        cherrypy.session[common.KEY_USER] = self.test_user
        self._expect_redirect('/user/profile', self.user_c.usermanagement, cancel=True)

    def test_usermanagement_post_valid(self):
        """
        Create a valid post and check that user is created.
        """
        self.test_user.role = "ADMINISTRATOR"
        self.test_user = dao.store_entity(self.test_user)
        cherrypy.session[common.KEY_USER] = self.test_user
        TestFactory.create_user(username="******")
        TestFactory.create_user(username="******", validated=False)
        user_before_delete = dao.get_user_by_name("to_be_deleted")
        assert user_before_delete is not None
        user_before_validation = dao.get_user_by_name("to_validate")
        assert not user_before_validation.validated
        data = {"delete_%i" % user_before_delete.id: True,
                "role_%i" % user_before_validation.id: "ADMINISTRATOR",
                "validate_%i" % user_before_validation.id: True}
        self.user_c.usermanagement(do_persist=True, **data)
        user_after_delete = dao.get_user_by_id(user_before_delete.id)
        assert user_after_delete is None, "User should be deleted."
        user_after_validation = dao.get_user_by_id(user_before_validation.id)
        assert user_after_validation.validated, "User should be validated now."
        assert user_after_validation.role == "ADMINISTRATOR", "Role has not changed."

    def test_recoverpassword_cancel(self):
        """
        Test that cancel redirects to user page.
        """
        cherrypy.request.method = "POST"
        self._expect_redirect('/user', self.user_c.recoverpassword, cancel=True)

    def test_recoverpassword_valid_post(self):
        """
        Test a valid password recovery.
        """
        cherrypy.request.method = "POST"
        data = {"email": self.test_user.email,
                "username": self.test_user.username,
                }
        self._expect_redirect("/user", self.user_c.recoverpassword, **data)
        assert cherrypy.session[common.KEY_MESSAGE_TYPE] == common.TYPE_INFO, \
            "Info message informing successfull reset should be present"

    def test_validate_valid(self):
        """
        Pass a valid user and test that it is actually validate.
        """
        self.test_user.role = "ADMINISTRATOR"
        self.test_user = dao.store_entity(self.test_user)
        cherrypy.session[common.KEY_USER] = self.test_user
        TestFactory.create_user(username="******", validated=False)
        user_before_validation = dao.get_user_by_name("to_validate")
        assert not user_before_validation.validated
        self._expect_redirect('/tvb', self.user_c.validate, user_before_validation.username)
        user_after_validation = dao.get_user_by_id(user_before_validation.id)
        assert user_after_validation.validated, "User should be validated."
        assert cherrypy.session[common.KEY_MESSAGE_TYPE] == common.TYPE_INFO

    def test_validate_invalid(self):
        """
        Pass a valid user and test that it is actually validate.
        """
        unexisting = dao.get_user_by_name("should-not-exist")
        assert unexisting is None, "This user should not exist"
        self._expect_redirect('/tvb', self.user_c.validate, "should-not-exist")
        assert cherrypy.session[common.KEY_MESSAGE_TYPE] == common.TYPE_ERROR

    def _check_default_attributes(self, template_dict, data, errors):
        """
        Check that all the defaults are present in the template dictionary.
        """
        assert template_dict[common.KEY_LINK_ANALYZE] == '/flow/step_analyzers'
        assert template_dict[common.KEY_BACK_PAGE] == False
        assert template_dict[common.KEY_LINK_CONNECTIVITY_TAB] == '/flow/step_connectivity'
        assert template_dict[common.KEY_CURRENT_TAB] == 'nav-user'
        assert template_dict[common.KEY_FORM_DATA] == data
        assert template_dict[common.KEY_ERRORS] == errors
        assert template_dict[common.KEY_INCLUDE_TOOLTIP] is True