Exemple #1
0
class PageController(BaseUIController, SharableMixin,
                     UsesStoredWorkflowMixin, UsesVisualizationMixin, UsesItemRatings):

    _page_list = PageListGrid()
    _all_published_list = PageAllPublishedGrid()
    _history_selection_grid = HistorySelectionGrid()
    _workflow_selection_grid = WorkflowSelectionGrid()
    _datasets_selection_grid = HistoryDatasetAssociationSelectionGrid()
    _page_selection_grid = PageSelectionGrid()
    _visualization_selection_grid = VisualizationSelectionGrid()

    def __init__(self, app):
        super(PageController, self).__init__(app)
        self.page_manager = PageManager(app)
        self.history_manager = HistoryManager(app)
        self.history_serializer = HistorySerializer(self.app)
        self.hda_manager = HDAManager(app)

    @web.expose
    @web.json
    @web.require_login()
    def list(self, trans, *args, **kwargs):
        """ List user's pages. """
        # Handle operation
        if 'operation' in kwargs and 'id' in kwargs:
            session = trans.sa_session
            operation = kwargs['operation'].lower()
            ids = util.listify(kwargs['id'])
            for id in ids:
                item = session.query(model.Page).get(self.decode_id(id))
                if operation == "delete":
                    item.deleted = True
            session.flush()

        # Build grid dictionary.
        grid = self._page_list(trans, *args, **kwargs)
        grid['shared_by_others'] = self._get_shared(trans)
        return grid

    @web.expose
    @web.json
    def list_published(self, trans, *args, **kwargs):
        grid = self._all_published_list(trans, *args, **kwargs)
        grid['shared_by_others'] = self._get_shared(trans)
        return grid

    def _get_shared(self, trans):
        """Identify shared pages"""
        shared_by_others = trans.sa_session \
            .query(model.PageUserShareAssociation) \
            .filter_by(user=trans.get_user()) \
            .join(model.Page.table) \
            .filter(model.Page.deleted == false()) \
            .order_by(desc(model.Page.update_time)) \
            .all()
        return [{'username' : p.page.user.username,
                 'slug'     : p.page.slug,
                 'title'    : p.page.title} for p in shared_by_others]

    @web.legacy_expose_api
    @web.require_login("create pages")
    def create(self, trans, payload=None, **kwd):
        """
        Create a new page.
        """
        if trans.request.method == 'GET':
            return {
                'title'  : 'Create a new page',
                'inputs' : [{
                    'name'      : 'title',
                    'label'     : 'Name'
                }, {
                    'name'      : 'slug',
                    'label'     : 'Identifier',
                    'help'      : 'A unique identifier that will be used for public links to this page. This field can only contain lowercase letters, numbers, and dashes (-).'
                }, {
                    'name'      : 'annotation',
                    'label'     : 'Annotation',
                    'help'      : 'A description of the page. The annotation is shown alongside published pages.'
                }, {
                    'name'      : 'content_format',
                    'label'     : 'Content Format',
                    'type'      : 'select',
                    'options'   : [('HTML', 'html'), ('Markdown', 'markdown')],
                    'help'      : 'Use the traditional rich HTML editor or the newer experimental Markdown editor to create the page content. The HTML editor has several known bugs, is unmaintained and pages created with it will be read-only in future releases of Galaxy.'
                }]
            }
        else:
            try:
                page = self.page_manager.create(trans, payload)
            except exceptions.MessageException as e:
                return self.message_exception(trans, unicodify(e))
            return {'message': 'Page \'%s\' successfully created.' % page.title, 'status': 'success'}

    @web.legacy_expose_api
    @web.require_login("edit pages")
    def edit(self, trans, payload=None, **kwd):
        """
        Edit a page's attributes.
        """
        id = kwd.get('id')
        if not id:
            return self.message_exception(trans, 'No page id received for editing.')
        decoded_id = self.decode_id(id)
        user = trans.get_user()
        p = trans.sa_session.query(model.Page).get(decoded_id)
        if trans.request.method == 'GET':
            if p.slug is None:
                self.create_item_slug(trans.sa_session, p)
            return {
                'title'  : 'Edit page attributes',
                'inputs' : [{
                    'name'      : 'title',
                    'label'     : 'Name',
                    'value'     : p.title
                }, {
                    'name'      : 'slug',
                    'label'     : 'Identifier',
                    'value'     : p.slug,
                    'help'      : 'A unique identifier that will be used for public links to this page. This field can only contain lowercase letters, numbers, and dashes (-).'
                }, {
                    'name'      : 'annotation',
                    'label'     : 'Annotation',
                    'value'     : self.get_item_annotation_str(trans.sa_session, user, p),
                    'help'      : 'A description of the page. The annotation is shown alongside published pages.'
                }]
            }
        else:
            p_title = payload.get('title')
            p_slug = payload.get('slug')
            p_annotation = payload.get('annotation')
            if not p_title:
                return self.message_exception(trans, 'Please provide a page name is required.')
            elif not p_slug:
                return self.message_exception(trans, 'Please provide a unique identifier.')
            elif not self._is_valid_slug(p_slug):
                return self.message_exception(trans, 'Page identifier can only contain lowercase letters, numbers, and dashes (-).')
            elif p_slug != p.slug and trans.sa_session.query(model.Page).filter_by(user=p.user, slug=p_slug, deleted=False).first():
                return self.message_exception(trans, 'Page id must be unique.')
            else:
                p.title = p_title
                p.slug = p_slug
                if p_annotation:
                    p_annotation = sanitize_html(p_annotation)
                    self.add_item_annotation(trans.sa_session, user, p, p_annotation)
                trans.sa_session.add(p)
                trans.sa_session.flush()
            return {'message': 'Attributes of \'%s\' successfully saved.' % p.title, 'status': 'success'}

    @web.expose
    @web.require_login("edit pages")
    def edit_content(self, trans, id):
        """
        Render the main page editor interface.
        """
        id = self.decode_id(id)
        page = trans.sa_session.query(model.Page).get(id)
        assert page.user == trans.user
        return trans.fill_template("page/editor.mako", page=page)

    @web.expose
    @web.require_login("use Galaxy pages")
    def share(self, trans, id, email="", use_panels=False):
        """ Handle sharing with an individual user. """
        msg = mtype = None
        page = trans.sa_session.query(model.Page).get(self.decode_id(id))
        if email:
            other = trans.sa_session.query(model.User) \
                                    .filter(and_(model.User.table.c.email == email,
                                                 model.User.table.c.deleted == false())) \
                                    .first()
            if not other:
                mtype = "error"
                msg = ("User '%s' does not exist" % escape(email))
            elif other == trans.get_user():
                mtype = "error"
                msg = ("You cannot share a page with yourself")
            elif trans.sa_session.query(model.PageUserShareAssociation) \
                    .filter_by(user=other, page=page).count() > 0:
                mtype = "error"
                msg = ("Page already shared with '%s'" % escape(email))
            else:
                share = model.PageUserShareAssociation()
                share.page = page
                share.user = other
                session = trans.sa_session
                session.add(share)
                self.create_item_slug(session, page)
                session.flush()
                page_title = escape(page.title)
                other_email = escape(other.email)
                trans.set_message("Page '%s' shared with user '%s'" % (page_title, other_email))
                return trans.response.send_redirect(url_for("/pages/sharing?id=%s" % id))
        return trans.fill_template("/ind_share_base.mako",
                                   message=msg,
                                   messagetype=mtype,
                                   item=page,
                                   email=email,
                                   use_panels=use_panels)

    @web.expose
    @web.require_login()
    def display(self, trans, id):
        id = self.decode_id(id)
        page = trans.sa_session.query(model.Page).get(id)
        if not page:
            raise web.httpexceptions.HTTPNotFound()
        return self.display_by_username_and_slug(trans, page.user.username, page.slug)

    @web.expose
    def display_by_username_and_slug(self, trans, username, slug):
        """ Display page based on a username and slug. """

        # Get page.
        session = trans.sa_session
        user = session.query(model.User).filter_by(username=username).first()
        page = trans.sa_session.query(model.Page).filter_by(user=user, slug=slug, deleted=False).first()
        if page is None:
            raise web.httpexceptions.HTTPNotFound()
        # Security check raises error if user cannot access page.
        self.security_check(trans, page, False, True)

        latest_revision = page.latest_revision
        if latest_revision.content_format == "html":
            # Process page content.
            processor = PageContentProcessor(trans, self._get_embed_html)
            processor.feed(page.latest_revision.content)
            # Output is string, so convert to unicode for display.
            page_content = unicodify(processor.output(), 'utf-8')
            template = "page/display.mako"
        else:
            page_content = trans.security.encode_id(page.id)
            template = "page/display_markdown.mako"

        # Get rating data.
        user_item_rating = 0
        if trans.get_user():
            user_item_rating = self.get_user_item_rating(trans.sa_session, trans.get_user(), page)
            if user_item_rating:
                user_item_rating = user_item_rating.rating
            else:
                user_item_rating = 0
        ave_item_rating, num_ratings = self.get_ave_item_rating_data(trans.sa_session, page)

        return trans.fill_template_mako(template, item=page,
                                        item_data=page_content,
                                        user_item_rating=user_item_rating,
                                        ave_item_rating=ave_item_rating,
                                        num_ratings=num_ratings,
                                        content_only=True)

    @web.expose
    @web.require_login("use Galaxy pages")
    def set_accessible_async(self, trans, id=None, accessible=False):
        """ Set page's importable attribute and slug. """
        page = self.get_page(trans, id)

        # Only set if importable value would change; this prevents a change in the update_time unless attribute really changed.
        importable = accessible in ['True', 'true', 't', 'T']
        if page.importable != importable:
            if importable:
                self._make_item_accessible(trans.sa_session, page)
            else:
                page.importable = importable
            trans.sa_session.flush()
        return

    @web.expose
    @web.require_login("rate items")
    @web.json
    def rate_async(self, trans, id, rating):
        """ Rate a page asynchronously and return updated community data. """

        page = self.get_page(trans, id, check_ownership=False, check_accessible=True)
        if not page:
            return trans.show_error_message("The specified page does not exist.")

        # Rate page.
        self.rate_item(trans.sa_session, trans.get_user(), page, rating)

        return self.get_ave_item_rating_data(trans.sa_session, page)

    @web.expose
    def get_embed_html_async(self, trans, id):
        """ Returns HTML for embedding a workflow in a page. """

        # TODO: user should be able to embed any item he has access to. see display_by_username_and_slug for security code.
        page = self.get_page(trans, id)
        if page:
            return "Embedded Page '%s'" % page.title

    @web.expose
    @web.json
    @web.require_login("use Galaxy pages")
    def get_name_and_link_async(self, trans, id=None):
        """ Returns page's name and link. """
        page = self.get_page(trans, id)

        if self.create_item_slug(trans.sa_session, page):
            trans.sa_session.flush()
        return_dict = {"name": page.title, "link": url_for(controller='page',
                                                           action="display_by_username_and_slug",
                                                           username=page.user.username,
                                                           slug=page.slug)}
        return return_dict

    @web.expose
    @web.json
    @web.require_login("select a history from saved histories")
    def list_histories_for_selection(self, trans, **kwargs):
        """ Returns HTML that enables a user to select one or more histories. """
        return self._history_selection_grid(trans, **kwargs)

    @web.expose
    @web.json
    @web.require_login("select a workflow from saved workflows")
    def list_workflows_for_selection(self, trans, **kwargs):
        """ Returns HTML that enables a user to select one or more workflows. """
        return self._workflow_selection_grid(trans, **kwargs)

    @web.expose
    @web.json
    @web.require_login("select a visualization from saved visualizations")
    def list_visualizations_for_selection(self, trans, **kwargs):
        """ Returns HTML that enables a user to select one or more visualizations. """
        return self._visualization_selection_grid(trans, **kwargs)

    @web.expose
    @web.json
    @web.require_login("select a page from saved pages")
    def list_pages_for_selection(self, trans, **kwargs):
        """ Returns HTML that enables a user to select one or more pages. """
        return self._page_selection_grid(trans, **kwargs)

    @web.expose
    @web.json
    @web.require_login("select a dataset from saved datasets")
    def list_datasets_for_selection(self, trans, **kwargs):
        """ Returns HTML that enables a user to select one or more datasets. """
        return self._datasets_selection_grid(trans, **kwargs)

    @web.expose
    def get_editor_iframe(self, trans):
        """ Returns the document for the page editor's iframe. """
        return trans.fill_template("page/wymiframe.mako")

    def get_page(self, trans, id, check_ownership=True, check_accessible=False):
        """Get a page from the database by id."""
        # Load history from database
        id = self.decode_id(id)
        page = trans.sa_session.query(model.Page).get(id)
        if not page:
            error("Page not found")
        else:
            return self.security_check(trans, page, check_ownership, check_accessible)

    def get_item(self, trans, id):
        return self.get_page(trans, id)

    def _get_embedded_history_html(self, trans, decoded_id):
        """
        Returns html suitable for embedding in another page.
        """
        # histories embedded in pages are set to importable when embedded, check for access here
        history = self.history_manager.get_accessible(decoded_id, trans.user, current_history=trans.history)

        # create ownership flag for template, dictify models
        # note: adding original annotation since this is published - get_dict returns user-based annos
        user_is_owner = trans.user == history.user
        history.annotation = self.get_item_annotation_str(trans.sa_session, history.user, history)

        # include all datasets: hidden, deleted, and purged
        history_dictionary = self.history_serializer.serialize_to_view(
            history, view='detailed', user=trans.user, trans=trans
        )
        contents = self.history_serializer.serialize_contents(history, 'contents', trans=trans, user=trans.user)
        history_dictionary['annotation'] = history.annotation

        filled = trans.fill_template("history/embed.mako",
                                     item=history,
                                     user_is_owner=user_is_owner,
                                     history_dict=history_dictionary,
                                     content_dicts=contents)
        return filled

    def _get_embedded_visualization_html(self, trans, encoded_id):
        """
        Returns html suitable for embedding visualizations in another page.
        """
        visualization = self.get_visualization(trans, encoded_id, False, True)
        visualization.annotation = self.get_item_annotation_str(trans.sa_session, visualization.user, visualization)
        if not visualization:
            return None

        # Fork to template based on visualization.type (registry or builtin).
        if((trans.app.visualizations_registry and visualization.type in trans.app.visualizations_registry.plugins) and
                (visualization.type not in trans.app.visualizations_registry.BUILT_IN_VISUALIZATIONS)):
            # if a registry visualization, load a version into an iframe :(
            # TODO: simplest path from A to B but not optimal - will be difficult to do reg visualizations any other way
            # TODO: this will load the visualization twice (once above, once when the iframe src calls 'saved')
            encoded_visualization_id = trans.security.encode_id(visualization.id)
            return trans.fill_template('visualization/embed_in_frame.mako',
                                       item=visualization,
                                       encoded_visualization_id=encoded_visualization_id,
                                       content_only=True)

        return trans.fill_template("visualization/embed.mako", item=visualization, item_data=None)

    def _get_embed_html(self, trans, item_class, item_id):
        """ Returns HTML for embedding an item in a page. """
        item_class = self.get_class(item_class)
        encoded_id, decoded_id = get_page_identifiers(item_id, trans.app)
        if item_class == model.History:
            return self._get_embedded_history_html(trans, decoded_id)

        elif item_class == model.HistoryDatasetAssociation:
            dataset = self.hda_manager.get_accessible(decoded_id, trans.user)
            dataset = self.hda_manager.error_if_uploading(dataset)

            dataset.annotation = self.get_item_annotation_str(trans.sa_session, dataset.history.user, dataset)
            if dataset:
                data = self.hda_manager.text_data(dataset)
                return trans.fill_template("dataset/embed.mako", item=dataset, item_data=data)

        elif item_class == model.StoredWorkflow:
            workflow = self.get_stored_workflow(trans, encoded_id, False, True)
            workflow.annotation = self.get_item_annotation_str(trans.sa_session, workflow.user, workflow)
            if workflow:
                self.get_stored_workflow_steps(trans, workflow)
                return trans.fill_template("workflow/embed.mako", item=workflow, item_data=workflow.latest_workflow.steps)

        elif item_class == model.Visualization:
            return self._get_embedded_visualization_html(trans, encoded_id)

        elif item_class == model.Page:
            pass
class HistoryManagerTestCase( BaseTestCase ):

    def set_up_managers( self ):
        super( HistoryManagerTestCase, self ).set_up_managers()
        self.history_mgr = HistoryManager( self.app )

    def test_base( self ):
        user2 = self.user_mgr.create( self.trans, **user2_data )
        user3 = self.user_mgr.create( self.trans, **user3_data )

        self.log( "should be able to create a new history" )
        history1 = self.history_mgr.create( self.trans, name='history1', user=user2 )
        self.assertIsInstance( history1, model.History )
        self.assertEqual( history1.name, 'history1' )
        self.assertEqual( history1.user, user2 )
        self.assertEqual( history1, self.trans.sa_session.query( model.History ).get( history1.id ) )
        self.assertEqual( history1,
            self.trans.sa_session.query( model.History ).filter( model.History.name == 'history1' ).one() )
        self.assertEqual( history1,
            self.trans.sa_session.query( model.History ).filter( model.History.user == user2 ).one() )

        self.log( "should be able to copy a history" )
        history2 = self.history_mgr.copy( self.trans, history1, user=user3 )
        self.assertIsInstance( history2, model.History )
        self.assertEqual( history2.user, user3 )
        self.assertEqual( history2, self.trans.sa_session.query( model.History ).get( history2.id ) )
        self.assertEqual( history2.name, history1.name )
        self.assertNotEqual( history2, history1 )

        self.log( "should be able to query" )
        histories = self.trans.sa_session.query( model.History ).all()
        self.assertEqual( self.history_mgr.one( self.trans, filters=( model.History.id == history1.id ) ), history1 )
        self.assertEqual( self.history_mgr.list( self.trans ), histories )
        self.assertEqual( self.history_mgr.by_id( self.trans, history1.id ), history1 )
        self.assertEqual( self.history_mgr.by_ids( self.trans, [ history2.id, history1.id ] ), [ history2, history1 ] )

        self.log( "should be able to limit and offset" )
        self.assertEqual( self.history_mgr.list( self.trans, limit=1 ), histories[0:1] )
        self.assertEqual( self.history_mgr.list( self.trans, offset=1 ), histories[1:] )
        self.assertEqual( self.history_mgr.list( self.trans, limit=1, offset=1 ), histories[1:2] )

        self.assertEqual( self.history_mgr.list( self.trans, limit=0 ), [] )
        self.assertEqual( self.history_mgr.list( self.trans, offset=3 ), [] )

        self.log( "should be able to order" )
        history3 = self.history_mgr.create( self.trans, name="history3", user=user2 )
        name_first_then_time = ( model.History.name, sqlalchemy.desc( model.History.create_time ) )
        self.assertEqual( self.history_mgr.list( self.trans, order_by=name_first_then_time ),
            [ history2, history1, history3 ] )

    def test_has_user( self ):
        owner = self.user_mgr.create( self.trans, **user2_data )
        non_owner = self.user_mgr.create( self.trans, **user3_data )

        item1 = self.history_mgr.create( self.trans, user=owner )
        item2 = self.history_mgr.create( self.trans, user=owner )
        item3 = self.history_mgr.create( self.trans, user=non_owner )

        self.log( "should be able to list items by user" )
        user_histories = self.history_mgr.by_user( self.trans, owner )
        self.assertEqual( user_histories, [ item1, item2 ] )

    def test_ownable( self ):
        owner = self.user_mgr.create( self.trans, **user2_data )
        non_owner = self.user_mgr.create( self.trans, **user3_data )

        item1 = self.history_mgr.create( self.trans, user=owner )

        self.log( "should be able to poll whether a given user owns an item" )
        self.assertTrue(  self.history_mgr.is_owner( self.trans, item1, owner ) )
        self.assertFalse( self.history_mgr.is_owner( self.trans, item1, non_owner ) )

        self.log( "should raise an error when checking ownership with non-owner" )
        self.assertRaises( exceptions.ItemOwnershipException,
            self.history_mgr.error_unless_owner, self.trans, item1, non_owner )
        self.assertRaises( exceptions.ItemOwnershipException,
            self.history_mgr.get_owned, self.trans, item1.id, non_owner )

        self.log( "should not raise an error when checking ownership with owner" )
        self.assertEqual( self.history_mgr.error_unless_owner( self.trans, item1, owner ), item1 )
        self.assertEqual( self.history_mgr.get_owned( self.trans, item1.id, owner ), item1 )

        self.log( "should not raise an error when checking ownership with admin" )
        self.assertTrue( self.history_mgr.is_owner( self.trans, item1, self.admin_user ) )
        self.assertEqual( self.history_mgr.error_unless_owner( self.trans, item1, self.admin_user ), item1 )
        self.assertEqual( self.history_mgr.get_owned( self.trans, item1.id, self.admin_user ), item1 )

    def test_accessible( self ):
        owner = self.user_mgr.create( self.trans, **user2_data )
        item1 = self.history_mgr.create( self.trans, user=owner )

        non_owner = self.user_mgr.create( self.trans, **user3_data )

        self.log( "should be inaccessible by default except to owner" )
        self.assertTrue( self.history_mgr.is_accessible( self.trans, item1, owner ) )
        self.assertTrue( self.history_mgr.is_accessible( self.trans, item1, self.admin_user ) )
        self.assertFalse( self.history_mgr.is_accessible( self.trans, item1, non_owner ) )

        self.log( "should raise an error when checking accessibility with non-owner" )
        self.assertRaises( exceptions.ItemAccessibilityException,
            self.history_mgr.error_unless_accessible, self.trans, item1, non_owner )
        self.assertRaises( exceptions.ItemAccessibilityException,
            self.history_mgr.get_accessible, self.trans, item1.id, non_owner )

        self.log( "should not raise an error when checking ownership with owner" )
        self.assertEqual( self.history_mgr.error_unless_accessible( self.trans, item1, owner ), item1 )
        self.assertEqual( self.history_mgr.get_accessible( self.trans, item1.id, owner ), item1 )

        self.log( "should not raise an error when checking ownership with admin" )
        self.assertTrue( self.history_mgr.is_accessible( self.trans, item1, self.admin_user ) )
        self.assertEqual( self.history_mgr.error_unless_accessible( self.trans, item1, self.admin_user ), item1 )
        self.assertEqual( self.history_mgr.get_accessible( self.trans, item1.id, self.admin_user ), item1 )

    def test_importable( self ):
        owner = self.user_mgr.create( self.trans, **user2_data )
        self.trans.set_user( owner )
        non_owner = self.user_mgr.create( self.trans, **user3_data )

        item1 = self.history_mgr.create( self.trans, user=owner )

        self.log( "should not be importable by default" )
        self.assertFalse( item1.importable )
        self.assertIsNone( item1.slug )

        self.log( "should be able to make importable (accessible by link) to all users" )
        accessible = self.history_mgr.make_importable( self.trans, item1 )
        self.assertEqual( accessible, item1 )
        self.assertIsNotNone( accessible.slug )
        self.assertTrue( accessible.importable )

        for user in self.user_mgr.list( self.trans ):
            self.assertTrue( self.history_mgr.is_accessible( self.trans, accessible, user ) )

        self.log( "should be able to make non-importable/inaccessible again" )
        inaccessible = self.history_mgr.make_non_importable( self.trans, accessible )
        self.assertEqual( inaccessible, accessible )
        self.assertIsNotNone( inaccessible.slug )
        self.assertFalse( inaccessible.importable )

        self.assertTrue( self.history_mgr.is_accessible( self.trans, inaccessible, owner ) )
        self.assertFalse( self.history_mgr.is_accessible( self.trans, inaccessible, non_owner ) )
        self.assertTrue( self.history_mgr.is_accessible( self.trans, inaccessible, self.admin_user ) )

    def test_published( self ):
        owner = self.user_mgr.create( self.trans, **user2_data )
        self.trans.set_user( owner )
        non_owner = self.user_mgr.create( self.trans, **user3_data )

        item1 = self.history_mgr.create( self.trans, user=owner )

        self.log( "should not be published by default" )
        self.assertFalse( item1.published )
        self.assertIsNone( item1.slug )

        self.log( "should be able to publish (listed publicly) to all users" )
        published = self.history_mgr.publish( self.trans, item1 )
        self.assertEqual( published, item1 )
        self.assertTrue( published.published )
        # note: publishing sets importable to true as well
        self.assertTrue( published.importable )
        self.assertIsNotNone( published.slug )

        for user in self.user_mgr.list( self.trans ):
            self.assertTrue( self.history_mgr.is_accessible( self.trans, published, user ) )

        self.log( "should be able to make non-importable/inaccessible again" )
        unpublished = self.history_mgr.unpublish( self.trans, published )
        self.assertEqual( unpublished, published )
        self.assertFalse( unpublished.published )
        # note: unpublishing does not make non-importable, you must explicitly do that separately
        self.assertTrue( published.importable )
        self.history_mgr.make_non_importable( self.trans, unpublished )
        self.assertFalse( published.importable )
        # note: slug still remains after unpublishing
        self.assertIsNotNone( unpublished.slug )

        self.assertTrue( self.history_mgr.is_accessible( self.trans, unpublished, owner ) )
        self.assertFalse( self.history_mgr.is_accessible( self.trans, unpublished, non_owner ) )
        self.assertTrue( self.history_mgr.is_accessible( self.trans, unpublished, self.admin_user ) )

    def test_sharable( self ):
        owner = self.user_mgr.create( self.trans, **user2_data )
        self.trans.set_user( owner )
        item1 = self.history_mgr.create( self.trans, user=owner )

        non_owner = self.user_mgr.create( self.trans, **user3_data )
        #third_party = self.user_mgr.create( self.trans, **user4_data )

        self.log( "should be unshared by default" )
        self.assertEqual( self.history_mgr.get_share_assocs( self.trans, item1 ), [] )
        self.assertEqual( item1.slug, None )

        self.log( "should be able to share with specific users" )
        share_assoc = self.history_mgr.share_with( self.trans, item1, non_owner )
        self.assertIsInstance( share_assoc, model.HistoryUserShareAssociation )
        self.assertTrue( self.history_mgr.is_accessible( self.trans, item1, non_owner ) )
        self.assertEqual(
            len( self.history_mgr.get_share_assocs( self.trans, item1 ) ), 1 )
        self.assertEqual(
            len( self.history_mgr.get_share_assocs( self.trans, item1, user=non_owner ) ), 1 )
        self.assertIsInstance( item1.slug, basestring )

        self.log( "should be able to unshare with specific users" )
        share_assoc = self.history_mgr.unshare_with( self.trans, item1, non_owner )
        self.assertIsInstance( share_assoc, model.HistoryUserShareAssociation )
        self.assertFalse( self.history_mgr.is_accessible( self.trans, item1, non_owner ) )
        self.assertEqual( self.history_mgr.get_share_assocs( self.trans, item1 ), [] )
        self.assertEqual(
            self.history_mgr.get_share_assocs( self.trans, item1, user=non_owner ), [] )

    #TODO: test slug formation

    def test_anon( self ):
        anon_user = None
        self.trans.set_user( anon_user )

        self.log( "should not allow access and owner for anon user on a history by another anon user (None)" )
        anon_history1 = self.history_mgr.create( self.trans, user=None )
        self.assertFalse( self.history_mgr.is_owner( self.trans, anon_history1, anon_user ) )
        self.assertFalse( self.history_mgr.is_accessible( self.trans, anon_history1, anon_user ) )

        self.log( "should allow access and owner for anon user on a history if it's the session's current history" )
        anon_history2 = self.history_mgr.create( self.trans, user=anon_user )
        self.trans.set_history( anon_history2 )
        self.assertTrue( self.history_mgr.is_owner( self.trans, anon_history2, anon_user ) )
        self.assertTrue( self.history_mgr.is_accessible( self.trans, anon_history2, anon_user ) )

        self.log( "should not allow owner or access for anon user on someone elses history" )
        owner = self.user_mgr.create( self.trans, **user2_data )
        someone_elses = self.history_mgr.create( self.trans, user=owner )
        self.assertFalse( self.history_mgr.is_owner( self.trans, someone_elses, anon_user ) )
        self.assertFalse( self.history_mgr.is_accessible( self.trans, someone_elses, anon_user ) )

        self.log( "should allow access for anon user if the history is published or importable" )
        self.history_mgr.make_importable( self.trans, someone_elses )
        self.assertTrue( self.history_mgr.is_accessible( self.trans, someone_elses, anon_user ) )
        self.history_mgr.publish( self.trans, someone_elses )
        self.assertTrue( self.history_mgr.is_accessible( self.trans, someone_elses, anon_user ) )

    def test_delete_and_purge( self ):
        user2 = self.user_mgr.create( self.trans, **user2_data )
        self.trans.set_user( user2 )

        history1 = self.history_mgr.create( self.trans, name='history1', user=user2 )
        self.trans.set_history( history1 )

        self.assertFalse( history1.deleted )

        self.history_mgr.delete( self.trans, history1 )
        self.assertTrue( history1.deleted )

        self.history_mgr.undelete( self.trans, history1 )
        self.assertFalse( history1.deleted )

        history2 = self.history_mgr.create( self.trans, name='history2', user=user2 )
        self.history_mgr.purge( self.trans, history1 )
        self.assertTrue( history1.purged )

    def test_histories( self ):
        user2 = self.user_mgr.create( self.trans, **user2_data )
        self.trans.set_user( user2 )

        history1 = self.history_mgr.create( self.trans, name='history1', user=user2 )
        self.trans.set_history( history1 )
        history2 = self.history_mgr.create( self.trans, name='history2', user=user2 )

        self.log( "should be able to set or get the current history for a user" )
        self.assertEqual( self.history_mgr.get_current( self.trans ), history1 )
        self.assertEqual( self.history_mgr.set_current( self.trans, history2 ), history2 )
        self.assertEqual( self.history_mgr.get_current( self.trans ), history2 )
        self.assertEqual( self.history_mgr.set_current_by_id( self.trans, history1.id ), history1 )
        self.assertEqual( self.history_mgr.get_current( self.trans ), history1 )
Exemple #3
0
class HistoryManagerTestCase(BaseTestCase):

    def set_up_managers(self):
        super(HistoryManagerTestCase, self).set_up_managers()
        self.history_manager = HistoryManager(self.app)
        self.hda_manager = hdas.HDAManager(self.app)

    def add_hda_to_history(self, history, **kwargs):
        dataset = self.hda_manager.dataset_manager.create()
        hda = self.hda_manager.create(history=history, dataset=dataset, **kwargs)
        return hda

    def test_base(self):
        user2 = self.user_manager.create(**user2_data)
        user3 = self.user_manager.create(**user3_data)

        self.log("should be able to create a new history")
        history1 = self.history_manager.create(name='history1', user=user2)
        self.assertIsInstance(history1, model.History)
        self.assertEqual(history1.name, 'history1')
        self.assertEqual(history1.user, user2)
        self.assertEqual(history1, self.trans.sa_session.query(model.History).get(history1.id))
        self.assertEqual(history1,
            self.trans.sa_session.query(model.History).filter(model.History.name == 'history1').one())
        self.assertEqual(history1,
            self.trans.sa_session.query(model.History).filter(model.History.user == user2).one())

        history2 = self.history_manager.copy(history1, user=user3)

        self.log("should be able to query")
        histories = self.trans.sa_session.query(model.History).all()
        self.assertEqual(self.history_manager.one(filters=(model.History.id == history1.id)), history1)
        self.assertEqual(self.history_manager.list(), histories)
        self.assertEqual(self.history_manager.by_id(history1.id), history1)
        self.assertEqual(self.history_manager.by_ids([history2.id, history1.id]), [history2, history1])

        self.log("should be able to limit and offset")
        self.assertEqual(self.history_manager.list(limit=1), histories[0:1])
        self.assertEqual(self.history_manager.list(offset=1), histories[1:])
        self.assertEqual(self.history_manager.list(limit=1, offset=1), histories[1:2])

        self.assertEqual(self.history_manager.list(limit=0), [])
        self.assertEqual(self.history_manager.list(offset=3), [])

        self.log("should be able to order")
        history3 = self.history_manager.create(name="history3", user=user2)
        name_first_then_time = (model.History.name, sqlalchemy.desc(model.History.create_time))
        self.assertEqual(self.history_manager.list(order_by=name_first_then_time),
            [history2, history1, history3])

    def test_copy(self):
        user2 = self.user_manager.create(**user2_data)
        user3 = self.user_manager.create(**user3_data)

        self.log("should be able to copy a history (and it's hdas)")
        history1 = self.history_manager.create(name='history1', user=user2)
        tags = [u'tag-one']
        annotation = u'history annotation'
        self.history_manager.set_tags(history1, tags, user=user2)
        self.history_manager.annotate(history1, annotation, user=user2)

        hda = self.add_hda_to_history(history1, name='wat')
        hda_tags = [u'tag-one', u'tag-two']
        hda_annotation = u'annotation'
        self.hda_manager.set_tags(hda, hda_tags, user=user2)
        self.hda_manager.annotate(hda, hda_annotation, user=user2)

        history2 = self.history_manager.copy(history1, user=user3)
        self.assertIsInstance(history2, model.History)
        self.assertEqual(history2.user, user3)
        self.assertEqual(history2, self.trans.sa_session.query(model.History).get(history2.id))
        self.assertEqual(history2.name, history1.name)
        self.assertNotEqual(history2, history1)

        copied_hda = history2.datasets[0]
        copied_hda_tags = self.hda_manager.get_tags(copied_hda)
        self.assertEqual(sorted(hda_tags), sorted(copied_hda_tags))
        copied_hda_annotation = self.hda_manager.annotation(copied_hda)
        self.assertEqual(hda_annotation, copied_hda_annotation)

    def test_has_user(self):
        owner = self.user_manager.create(**user2_data)
        non_owner = self.user_manager.create(**user3_data)

        item1 = self.history_manager.create(user=owner)
        item2 = self.history_manager.create(user=owner)
        self.history_manager.create(user=non_owner)

        self.log("should be able to list items by user")
        user_histories = self.history_manager.by_user(owner)
        self.assertEqual(user_histories, [item1, item2])

    def test_ownable(self):
        owner = self.user_manager.create(**user2_data)
        non_owner = self.user_manager.create(**user3_data)

        item1 = self.history_manager.create(user=owner)

        self.log("should be able to poll whether a given user owns an item")
        self.assertTrue(self.history_manager.is_owner(item1, owner))
        self.assertFalse(self.history_manager.is_owner(item1, non_owner))

        self.log("should raise an error when checking ownership with non-owner")
        self.assertRaises(exceptions.ItemOwnershipException,
            self.history_manager.error_unless_owner, item1, non_owner)
        self.assertRaises(exceptions.ItemOwnershipException,
            self.history_manager.get_owned, item1.id, non_owner)

        self.log("should not raise an error when checking ownership with owner")
        self.assertEqual(self.history_manager.error_unless_owner(item1, owner), item1)
        self.assertEqual(self.history_manager.get_owned(item1.id, owner), item1)

        self.log("should not raise an error when checking ownership with admin")
        self.assertTrue(self.history_manager.is_owner(item1, self.admin_user))
        self.assertEqual(self.history_manager.error_unless_owner(item1, self.admin_user), item1)
        self.assertEqual(self.history_manager.get_owned(item1.id, self.admin_user), item1)

    def test_accessible(self):
        owner = self.user_manager.create(**user2_data)
        item1 = self.history_manager.create(user=owner)

        non_owner = self.user_manager.create(**user3_data)

        self.log("should be inaccessible by default except to owner")
        self.assertTrue(self.history_manager.is_accessible(item1, owner))
        self.assertTrue(self.history_manager.is_accessible(item1, self.admin_user))
        self.assertFalse(self.history_manager.is_accessible(item1, non_owner))

        self.log("should raise an error when checking accessibility with non-owner")
        self.assertRaises(exceptions.ItemAccessibilityException,
            self.history_manager.error_unless_accessible, item1, non_owner)
        self.assertRaises(exceptions.ItemAccessibilityException,
            self.history_manager.get_accessible, item1.id, non_owner)

        self.log("should not raise an error when checking ownership with owner")
        self.assertEqual(self.history_manager.error_unless_accessible(item1, owner), item1)
        self.assertEqual(self.history_manager.get_accessible(item1.id, owner), item1)

        self.log("should not raise an error when checking ownership with admin")
        self.assertTrue(self.history_manager.is_accessible(item1, self.admin_user))
        self.assertEqual(self.history_manager.error_unless_accessible(item1, self.admin_user), item1)
        self.assertEqual(self.history_manager.get_accessible(item1.id, self.admin_user), item1)

    def test_importable(self):
        owner = self.user_manager.create(**user2_data)
        self.trans.set_user(owner)
        non_owner = self.user_manager.create(**user3_data)

        item1 = self.history_manager.create(user=owner)

        self.log("should not be importable by default")
        self.assertFalse(item1.importable)
        self.assertIsNone(item1.slug)

        self.log("should be able to make importable (accessible by link) to all users")
        accessible = self.history_manager.make_importable(item1)
        self.assertEqual(accessible, item1)
        self.assertIsNotNone(accessible.slug)
        self.assertTrue(accessible.importable)

        for user in self.user_manager.list():
            self.assertTrue(self.history_manager.is_accessible(accessible, user))

        self.log("should be able to make non-importable/inaccessible again")
        inaccessible = self.history_manager.make_non_importable(accessible)
        self.assertEqual(inaccessible, accessible)
        self.assertIsNotNone(inaccessible.slug)
        self.assertFalse(inaccessible.importable)

        self.assertTrue(self.history_manager.is_accessible(inaccessible, owner))
        self.assertFalse(self.history_manager.is_accessible(inaccessible, non_owner))
        self.assertTrue(self.history_manager.is_accessible(inaccessible, self.admin_user))

    def test_published(self):
        owner = self.user_manager.create(**user2_data)
        self.trans.set_user(owner)
        non_owner = self.user_manager.create(**user3_data)

        item1 = self.history_manager.create(user=owner)

        self.log("should not be published by default")
        self.assertFalse(item1.published)
        self.assertIsNone(item1.slug)

        self.log("should be able to publish (listed publicly) to all users")
        published = self.history_manager.publish(item1)
        self.assertEqual(published, item1)
        self.assertTrue(published.published)
        # note: publishing sets importable to true as well
        self.assertTrue(published.importable)
        self.assertIsNotNone(published.slug)

        for user in self.user_manager.list():
            self.assertTrue(self.history_manager.is_accessible(published, user))

        self.log("should be able to make non-importable/inaccessible again")
        unpublished = self.history_manager.unpublish(published)
        self.assertEqual(unpublished, published)
        self.assertFalse(unpublished.published)
        # note: unpublishing does not make non-importable, you must explicitly do that separately
        self.assertTrue(published.importable)
        self.history_manager.make_non_importable(unpublished)
        self.assertFalse(published.importable)
        # note: slug still remains after unpublishing
        self.assertIsNotNone(unpublished.slug)

        self.assertTrue(self.history_manager.is_accessible(unpublished, owner))
        self.assertFalse(self.history_manager.is_accessible(unpublished, non_owner))
        self.assertTrue(self.history_manager.is_accessible(unpublished, self.admin_user))

    def test_sharable(self):
        owner = self.user_manager.create(**user2_data)
        self.trans.set_user(owner)
        item1 = self.history_manager.create(user=owner)

        non_owner = self.user_manager.create(**user3_data)
        # third_party = self.user_manager.create( **user4_data )

        self.log("should be unshared by default")
        self.assertEqual(self.history_manager.get_share_assocs(item1), [])
        self.assertEqual(item1.slug, None)

        self.log("should be able to share with specific users")
        share_assoc = self.history_manager.share_with(item1, non_owner)
        self.assertIsInstance(share_assoc, model.HistoryUserShareAssociation)
        self.assertTrue(self.history_manager.is_accessible(item1, non_owner))
        self.assertEqual(
            len(self.history_manager.get_share_assocs(item1)), 1)
        self.assertEqual(
            len(self.history_manager.get_share_assocs(item1, user=non_owner)), 1)
        self.assertIsInstance(item1.slug, string_types)

        self.log("should be able to unshare with specific users")
        share_assoc = self.history_manager.unshare_with(item1, non_owner)
        self.assertIsInstance(share_assoc, model.HistoryUserShareAssociation)
        self.assertFalse(self.history_manager.is_accessible(item1, non_owner))
        self.assertEqual(self.history_manager.get_share_assocs(item1), [])
        self.assertEqual(
            self.history_manager.get_share_assocs(item1, user=non_owner), [])

    # TODO: test slug formation

    def test_anon(self):
        anon_user = None
        self.trans.set_user(anon_user)

        self.log("should not allow access and owner for anon user on a history by another anon user (None)")
        anon_history1 = self.history_manager.create(user=None)
        # do not set the trans.history!
        self.assertFalse(self.history_manager.is_owner(anon_history1, anon_user, current_history=self.trans.history))
        self.assertFalse(self.history_manager.is_accessible(anon_history1, anon_user, current_history=self.trans.history))

        self.log("should allow access and owner for anon user on a history if it's the session's current history")
        anon_history2 = self.history_manager.create(user=anon_user)
        self.trans.set_history(anon_history2)
        self.assertTrue(self.history_manager.is_owner(anon_history2, anon_user, current_history=self.trans.history))
        self.assertTrue(self.history_manager.is_accessible(anon_history2, anon_user, current_history=self.trans.history))

        self.log("should not allow owner or access for anon user on someone elses history")
        owner = self.user_manager.create(**user2_data)
        someone_elses = self.history_manager.create(user=owner)
        self.assertFalse(self.history_manager.is_owner(someone_elses, anon_user, current_history=self.trans.history))
        self.assertFalse(self.history_manager.is_accessible(someone_elses, anon_user, current_history=self.trans.history))

        self.log("should allow access for anon user if the history is published or importable")
        self.history_manager.make_importable(someone_elses)
        self.assertTrue(self.history_manager.is_accessible(someone_elses, anon_user, current_history=self.trans.history))
        self.history_manager.publish(someone_elses)
        self.assertTrue(self.history_manager.is_accessible(someone_elses, anon_user, current_history=self.trans.history))

    def test_delete_and_purge(self):
        user2 = self.user_manager.create(**user2_data)
        self.trans.set_user(user2)

        history1 = self.history_manager.create(name='history1', user=user2)
        self.trans.set_history(history1)

        self.log("should allow deletion and undeletion")
        self.assertFalse(history1.deleted)

        self.history_manager.delete(history1)
        self.assertTrue(history1.deleted)

        self.history_manager.undelete(history1)
        self.assertFalse(history1.deleted)

        self.log("should allow purging")
        history2 = self.history_manager.create(name='history2', user=user2)
        self.history_manager.purge(history2)
        self.assertTrue(history2.deleted)
        self.assertTrue(history2.purged)

    def test_current(self):
        user2 = self.user_manager.create(**user2_data)
        self.trans.set_user(user2)

        history1 = self.history_manager.create(name='history1', user=user2)
        self.trans.set_history(history1)
        history2 = self.history_manager.create(name='history2', user=user2)

        self.log("should be able to set or get the current history for a user")
        self.assertEqual(self.history_manager.get_current(self.trans), history1)
        self.assertEqual(self.history_manager.set_current(self.trans, history2), history2)
        self.assertEqual(self.history_manager.get_current(self.trans), history2)
        self.assertEqual(self.history_manager.set_current_by_id(self.trans, history1.id), history1)
        self.assertEqual(self.history_manager.get_current(self.trans), history1)

    def test_most_recently_used(self):
        user2 = self.user_manager.create(**user2_data)
        self.trans.set_user(user2)

        history1 = self.history_manager.create(name='history1', user=user2)
        self.trans.set_history(history1)
        history2 = self.history_manager.create(name='history2', user=user2)

        self.log("should be able to get the most recently used (updated) history for a given user")
        self.assertEqual(self.history_manager.most_recent(user2), history2)
        self.history_manager.update(history1, {'name': 'new name'})
        self.assertEqual(self.history_manager.most_recent(user2), history1)

    def test_rating(self):
        user2 = self.user_manager.create(**user2_data)
        manager = self.history_manager
        item = manager.create(name='history1', user=user2)

        self.log("should properly handle no ratings")
        self.assertEqual(manager.rating(item, user2), None)
        self.assertEqual(manager.ratings(item), [])
        self.assertEqual(manager.ratings_avg(item), 0)
        self.assertEqual(manager.ratings_count(item), 0)

        self.log("should allow rating by user")
        manager.rate(item, user2, 5)
        self.assertEqual(manager.rating(item, user2), 5)
        self.assertEqual(manager.ratings(item), [5])
        self.assertEqual(manager.ratings_avg(item), 5)
        self.assertEqual(manager.ratings_count(item), 1)

        self.log("should allow updating")
        manager.rate(item, user2, 4)
        self.assertEqual(manager.rating(item, user2), 4)
        self.assertEqual(manager.ratings(item), [4])
        self.assertEqual(manager.ratings_avg(item), 4)
        self.assertEqual(manager.ratings_count(item), 1)

        self.log("should reflect multiple reviews")
        user3 = self.user_manager.create(**user3_data)
        self.assertEqual(manager.rating(item, user3), None)
        manager.rate(item, user3, 1)
        self.assertEqual(manager.rating(item, user3), 1)
        self.assertEqual(manager.ratings(item), [4, 1])
        self.assertEqual(manager.ratings_avg(item), 2.5)
        self.assertEqual(manager.ratings_count(item), 2)
Exemple #4
0
class HistoryManagerTestCase(BaseTestCase):
    def set_up_managers(self):
        super(HistoryManagerTestCase, self).set_up_managers()
        self.history_mgr = HistoryManager(self.app)

    def test_base(self):
        user2 = self.user_mgr.create(self.trans, **user2_data)
        user3 = self.user_mgr.create(self.trans, **user3_data)

        self.log("should be able to create a new history")
        history1 = self.history_mgr.create(self.trans,
                                           name='history1',
                                           user=user2)
        self.assertIsInstance(history1, model.History)
        self.assertEqual(history1.name, 'history1')
        self.assertEqual(history1.user, user2)
        self.assertEqual(
            history1,
            self.trans.sa_session.query(model.History).get(history1.id))
        self.assertEqual(
            history1,
            self.trans.sa_session.query(
                model.History).filter(model.History.name == 'history1').one())
        self.assertEqual(
            history1,
            self.trans.sa_session.query(
                model.History).filter(model.History.user == user2).one())

        self.log("should be able to copy a history")
        history2 = self.history_mgr.copy(self.trans, history1, user=user3)
        self.assertIsInstance(history2, model.History)
        self.assertEqual(history2.user, user3)
        self.assertEqual(
            history2,
            self.trans.sa_session.query(model.History).get(history2.id))
        self.assertEqual(history2.name, history1.name)
        self.assertNotEqual(history2, history1)

        self.log("should be able to query")
        histories = self.trans.sa_session.query(model.History).all()
        self.assertEqual(
            self.history_mgr.one(self.trans,
                                 filters=(model.History.id == history1.id)),
            history1)
        self.assertEqual(self.history_mgr.list(self.trans), histories)
        self.assertEqual(self.history_mgr.by_id(self.trans, history1.id),
                         history1)
        self.assertEqual(
            self.history_mgr.by_ids(self.trans, [history2.id, history1.id]),
            [history2, history1])

        self.log("should be able to limit and offset")
        self.assertEqual(self.history_mgr.list(self.trans, limit=1),
                         histories[0:1])
        self.assertEqual(self.history_mgr.list(self.trans, offset=1),
                         histories[1:])
        self.assertEqual(self.history_mgr.list(self.trans, limit=1, offset=1),
                         histories[1:2])

        self.assertEqual(self.history_mgr.list(self.trans, limit=0), [])
        self.assertEqual(self.history_mgr.list(self.trans, offset=3), [])

        self.log("should be able to order")
        history3 = self.history_mgr.create(self.trans,
                                           name="history3",
                                           user=user2)
        name_first_then_time = (model.History.name,
                                sqlalchemy.desc(model.History.create_time))
        self.assertEqual(
            self.history_mgr.list(self.trans, order_by=name_first_then_time),
            [history2, history1, history3])

    def test_has_user(self):
        owner = self.user_mgr.create(self.trans, **user2_data)
        non_owner = self.user_mgr.create(self.trans, **user3_data)

        item1 = self.history_mgr.create(self.trans, user=owner)
        item2 = self.history_mgr.create(self.trans, user=owner)
        item3 = self.history_mgr.create(self.trans, user=non_owner)

        self.log("should be able to list items by user")
        user_histories = self.history_mgr.by_user(self.trans, owner)
        self.assertEqual(user_histories, [item1, item2])

        query = self.history_mgr._query_by_user(self.trans, owner)
        self.assertEqual(query.all(), user_histories)

    def test_ownable(self):
        owner = self.user_mgr.create(self.trans, **user2_data)
        non_owner = self.user_mgr.create(self.trans, **user3_data)

        item1 = self.history_mgr.create(self.trans, user=owner)

        self.log("should be able to poll whether a given user owns an item")
        self.assertTrue(self.history_mgr.is_owner(self.trans, item1, owner))
        self.assertFalse(
            self.history_mgr.is_owner(self.trans, item1, non_owner))

        self.log(
            "should raise an error when checking ownership with non-owner")
        self.assertRaises(exceptions.ItemOwnershipException,
                          self.history_mgr.error_unless_owner, self.trans,
                          item1, non_owner)
        self.assertRaises(exceptions.ItemOwnershipException,
                          self.history_mgr.get_owned, self.trans, item1.id,
                          non_owner)

        self.log(
            "should not raise an error when checking ownership with owner")
        self.assertEqual(
            self.history_mgr.error_unless_owner(self.trans, item1, owner),
            item1)
        self.assertEqual(
            self.history_mgr.get_owned(self.trans, item1.id, owner), item1)

        self.log(
            "should not raise an error when checking ownership with admin")
        self.assertTrue(
            self.history_mgr.is_owner(self.trans, item1, self.admin_user))
        self.assertEqual(
            self.history_mgr.error_unless_owner(self.trans, item1,
                                                self.admin_user), item1)
        self.assertEqual(
            self.history_mgr.get_owned(self.trans, item1.id, self.admin_user),
            item1)

    def test_accessible(self):
        owner = self.user_mgr.create(self.trans, **user2_data)
        item1 = self.history_mgr.create(self.trans, user=owner)

        non_owner = self.user_mgr.create(self.trans, **user3_data)

        self.log("should be inaccessible by default except to owner")
        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, item1, owner))
        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, item1, self.admin_user))
        self.assertFalse(
            self.history_mgr.is_accessible(self.trans, item1, non_owner))

        self.log(
            "should raise an error when checking accessibility with non-owner")
        self.assertRaises(exceptions.ItemAccessibilityException,
                          self.history_mgr.error_unless_accessible, self.trans,
                          item1, non_owner)
        self.assertRaises(exceptions.ItemAccessibilityException,
                          self.history_mgr.get_accessible, self.trans,
                          item1.id, non_owner)

        self.log(
            "should not raise an error when checking ownership with owner")
        self.assertEqual(
            self.history_mgr.error_unless_accessible(self.trans, item1, owner),
            item1)
        self.assertEqual(
            self.history_mgr.get_accessible(self.trans, item1.id, owner),
            item1)

        self.log(
            "should not raise an error when checking ownership with admin")
        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, item1, self.admin_user))
        self.assertEqual(
            self.history_mgr.error_unless_accessible(self.trans, item1,
                                                     self.admin_user), item1)
        self.assertEqual(
            self.history_mgr.get_accessible(self.trans, item1.id,
                                            self.admin_user), item1)

    def test_importable(self):
        owner = self.user_mgr.create(self.trans, **user2_data)
        self.trans.set_user(owner)
        non_owner = self.user_mgr.create(self.trans, **user3_data)

        item1 = self.history_mgr.create(self.trans, user=owner)

        self.log("should not be importable by default")
        self.assertFalse(item1.importable)
        self.assertIsNone(item1.slug)

        self.log(
            "should be able to make importable (accessible by link) to all users"
        )
        accessible = self.history_mgr.make_importable(self.trans, item1)
        self.assertEqual(accessible, item1)
        self.assertIsNotNone(accessible.slug)
        self.assertTrue(accessible.importable)

        for user in self.user_mgr.list(self.trans):
            self.assertTrue(
                self.history_mgr.is_accessible(self.trans, accessible, user))

        self.log("should be able to make non-importable/inaccessible again")
        inaccessible = self.history_mgr.make_non_importable(
            self.trans, accessible)
        self.assertEqual(inaccessible, accessible)
        self.assertIsNotNone(inaccessible.slug)
        self.assertFalse(inaccessible.importable)

        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, inaccessible, owner))
        self.assertFalse(
            self.history_mgr.is_accessible(self.trans, inaccessible,
                                           non_owner))
        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, inaccessible,
                                           self.admin_user))

    def test_published(self):
        owner = self.user_mgr.create(self.trans, **user2_data)
        self.trans.set_user(owner)
        non_owner = self.user_mgr.create(self.trans, **user3_data)

        item1 = self.history_mgr.create(self.trans, user=owner)

        self.log("should not be published by default")
        self.assertFalse(item1.published)
        self.assertIsNone(item1.slug)

        self.log("should be able to publish (listed publicly) to all users")
        published = self.history_mgr.publish(self.trans, item1)
        self.assertEqual(published, item1)
        self.assertTrue(published.published)
        # note: publishing sets importable to true as well
        self.assertTrue(published.importable)
        self.assertIsNotNone(published.slug)

        for user in self.user_mgr.list(self.trans):
            self.assertTrue(
                self.history_mgr.is_accessible(self.trans, published, user))

        self.log("should be able to make non-importable/inaccessible again")
        unpublished = self.history_mgr.unpublish(self.trans, published)
        self.assertEqual(unpublished, published)
        self.assertFalse(unpublished.published)
        # note: unpublishing does not make non-importable, you must explicitly do that separately
        self.assertTrue(published.importable)
        self.history_mgr.make_non_importable(self.trans, unpublished)
        self.assertFalse(published.importable)
        # note: slug still remains after unpublishing
        self.assertIsNotNone(unpublished.slug)

        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, unpublished, owner))
        self.assertFalse(
            self.history_mgr.is_accessible(self.trans, unpublished, non_owner))
        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, unpublished,
                                           self.admin_user))

    def test_sharable(self):
        owner = self.user_mgr.create(self.trans, **user2_data)
        self.trans.set_user(owner)
        item1 = self.history_mgr.create(self.trans, user=owner)

        non_owner = self.user_mgr.create(self.trans, **user3_data)
        #third_party = self.user_mgr.create( self.trans, **user4_data )

        self.log("should be unshared by default")
        self.assertEqual(self.history_mgr.get_share_assocs(self.trans, item1),
                         [])
        self.assertEqual(item1.slug, None)

        self.log("should be able to share with specific users")
        share_assoc = self.history_mgr.share_with(self.trans, item1, non_owner)
        self.assertIsInstance(share_assoc, model.HistoryUserShareAssociation)
        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, item1, non_owner))
        self.assertEqual(
            len(self.history_mgr.get_share_assocs(self.trans, item1)), 1)
        self.assertEqual(
            len(
                self.history_mgr.get_share_assocs(self.trans,
                                                  item1,
                                                  user=non_owner)), 1)
        self.assertIsInstance(item1.slug, basestring)

        self.log("should be able to unshare with specific users")
        share_assoc = self.history_mgr.unshare_with(self.trans, item1,
                                                    non_owner)
        self.assertIsInstance(share_assoc, model.HistoryUserShareAssociation)
        self.assertFalse(
            self.history_mgr.is_accessible(self.trans, item1, non_owner))
        self.assertEqual(self.history_mgr.get_share_assocs(self.trans, item1),
                         [])
        self.assertEqual(
            self.history_mgr.get_share_assocs(self.trans,
                                              item1,
                                              user=non_owner), [])

    #TODO: test slug formation

    def test_anon(self):
        anon_user = None
        self.trans.set_user(anon_user)

        self.log(
            "should not allow access and owner for anon user on a history by another anon user (None)"
        )
        anon_history1 = self.history_mgr.create(self.trans, user=None)
        self.assertFalse(
            self.history_mgr.is_owner(self.trans, anon_history1, anon_user))
        self.assertFalse(
            self.history_mgr.is_accessible(self.trans, anon_history1,
                                           anon_user))

        self.log(
            "should allow access and owner for anon user on a history if it's the session's current history"
        )
        anon_history2 = self.history_mgr.create(self.trans, user=anon_user)
        self.trans.set_history(anon_history2)
        self.assertTrue(
            self.history_mgr.is_owner(self.trans, anon_history2, anon_user))
        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, anon_history2,
                                           anon_user))

        self.log(
            "should not allow owner or access for anon user on someone elses history"
        )
        owner = self.user_mgr.create(self.trans, **user2_data)
        someone_elses = self.history_mgr.create(self.trans, user=owner)
        self.assertFalse(
            self.history_mgr.is_owner(self.trans, someone_elses, anon_user))
        self.assertFalse(
            self.history_mgr.is_accessible(self.trans, someone_elses,
                                           anon_user))

        self.log(
            "should allow access for anon user if the history is published or importable"
        )
        self.history_mgr.make_importable(self.trans, someone_elses)
        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, someone_elses,
                                           anon_user))
        self.history_mgr.publish(self.trans, someone_elses)
        self.assertTrue(
            self.history_mgr.is_accessible(self.trans, someone_elses,
                                           anon_user))

    def test_delete_and_purge(self):
        user2 = self.user_mgr.create(self.trans, **user2_data)
        self.trans.set_user(user2)

        history1 = self.history_mgr.create(self.trans,
                                           name='history1',
                                           user=user2)
        self.trans.set_history(history1)

        self.assertFalse(history1.deleted)

        self.history_mgr.delete(self.trans, history1)
        self.assertTrue(history1.deleted)

        self.history_mgr.undelete(self.trans, history1)
        self.assertFalse(history1.deleted)

        history2 = self.history_mgr.create(self.trans,
                                           name='history2',
                                           user=user2)
        self.history_mgr.purge(self.trans, history1)
        self.assertTrue(history1.purged)

    def test_histories(self):
        user2 = self.user_mgr.create(self.trans, **user2_data)
        self.trans.set_user(user2)

        history1 = self.history_mgr.create(self.trans,
                                           name='history1',
                                           user=user2)
        self.trans.set_history(history1)
        history2 = self.history_mgr.create(self.trans,
                                           name='history2',
                                           user=user2)

        self.log("should be able to set or get the current history for a user")
        self.assertEqual(self.history_mgr.get_current(self.trans), history1)
        self.assertEqual(self.history_mgr.set_current(self.trans, history2),
                         history2)
        self.assertEqual(self.history_mgr.get_current(self.trans), history2)
        self.assertEqual(
            self.history_mgr.set_current_by_id(self.trans, history1.id),
            history1)
        self.assertEqual(self.history_mgr.get_current(self.trans), history1)