def test_attach_tags_to_record_pass(self):
        """Successfully attach tags to a record."""
        from invenio_records.models import Record
        # first create a record
        test_record = Record(
            creation_date=datetime.now(),
            modification_date=datetime.now()
        )
        test_record_info = dict(
            name="test_record"
        )
        test_record.additional_info = test_record_info
        db.session.add(test_record)
        db.session.commit()
        # attach tags to the record
        tag_data = dict(
            tags=["ROOT", "PHYSICS"]
        )
        answer = self.post(
            'recordlisttagresource',
            user_id=self.user_a.id,
            data=tag_data,
            urlargs=dict(record_id=test_record.id),
        )
        # answer.json is a list of TagRepresentation objects
        ordered_created_tags = []
        for tag_representation in answer.json:
            ordered_tag_repr = OrderedDict(
                sorted(tag_representation.items(), key=lambda t: t[0])
            )
            ordered_created_tags.append(ordered_tag_repr)
        # now query DB
        get_answer = self.get(
            'recordlisttagresource',
            user_id=self.user_a.id,
            urlargs=dict(record_id=test_record.id),
        )
        ordered_retrieved_tags = []
        for retrieved_tag_repr in get_answer.json:
            ordered_retrieved_tag_repr = OrderedDict(
                sorted(retrieved_tag_repr.items(), key=lambda t: t[0])
            )
            ordered_retrieved_tags.append(ordered_retrieved_tag_repr)

        self.assertEqual(ordered_created_tags, ordered_retrieved_tags)
        self.delete(
            'taglistresource',
            user_id=self.user_a.id,
            code=204
        )
        # delete the created record
        db.session.delete(test_record)
        db.session.commit()
예제 #2
0
    def create_records(self, rng):
        """Place records with specific IDs to the database."""
        from invenio_records.api import Record as Rec
        from invenio_records.models import Record

        for i in rng:
            rec = Record(id=i)
            db.session.add(rec)
            rec = Rec.create({
                'recid': i,
                'collections': {'primary': 'HEP'},
                'title': 'Record ' + str(i)
            })
            rec.commit()

        db.session.flush()
예제 #3
0
def search_unit(query, f, m, wl=None):
    """Return hitset of recIDs found that were created during 'query'."""
    from invenio.ext.sqlalchemy import db
    from invenio_records.models import Record

    return intbitset(db.session.query(Record.id).filter(
        *Record.filter_time_interval(query)).all())
예제 #4
0
def search_unit(query, f, m, wl=None):
    """Return hitset of recIDs found that were modified during 'query'."""
    from invenio.ext.sqlalchemy import db
    from invenio_records.models import Record

    return intbitset(db.session.query(Record.id).filter(
        *Record.filter_time_interval(query, 'm')).all())
예제 #5
0
 def create(cls, master_id, eliot_task_id, rule_name):
     from invenio_records.models import Record
     self = cls(master_id)
     self.status = StatusMaster.booting
     self.all_recids = Record.allids()  # `create` is a good time for this.
     self._rule_name = rule_name
     super(RedisMaster, self).create(eliot_task_id)
     return self
예제 #6
0
    def create_new_pid(self, pid_value):
        """
        Creates a new row inside the ``Record`` table.

        If ``pid_value`` is not ``None`` will be use as ``id`` to create this
        new row.
        """
        if pid_value is not None:
            record = Record(id=int(pid_value))
        else:
            record = Record()
        try:
            db.session.add(record)
            db.session.commit()
        except SQLAlchemyError:
            db.session.rollback()
            raise ValueError("Duplicate value for %s" % (pid_value, ))
        return str(record.id)
예제 #7
0
    def test_detailed_records(self):
        """Test visiting each detailed record returns 200"""
        from invenio_records.models import Record

        self.login('admin', 'admin')  # To also check restricted records
        for recid in Record.allids():
            response = self.client.get("/record/{recid}".format(recid=recid))
            if response.status_code != 200:
                raise Exception(response, recid)
예제 #8
0
    def create(cls, master_id, eliot_task_id, rule_name):
        from invenio_records.models import Record

        self = cls(master_id)
        self.status = StatusMaster.booting
        self.all_recids = Record.allids()  # `create` is a good time for this.
        self._rule_name = rule_name
        super(RedisMaster, self).create(eliot_task_id)
        return self
예제 #9
0
 def test_detailed_records(self):
     """Test visiting each detailed record returns 200"""
     from invenio_records.models import Record
     failing_recids = []
     for recid in Record.allids():
         try:
             if self.client.get("/record/{recid}".format(recid=recid)).status_code != 200:
                 failing_recids.append(recid)
         except Exception:
             failing_recids.append(recid)
     self.failIf(failing_recids)
    def test_attach_tags_to_record_pass(self):
        """Successfully attach tags to a record."""
        from invenio_records.models import Record
        # first create a record
        test_record = Record(creation_date=datetime.now(),
                             modification_date=datetime.now())
        test_record_info = dict(name="test_record")
        test_record.additional_info = test_record_info
        db.session.add(test_record)
        db.session.commit()
        # attach tags to the record
        tag_data = dict(tags=["ROOT", "PHYSICS"])
        answer = self.post(
            'recordlisttagresource',
            user_id=self.user_a.id,
            data=tag_data,
            urlargs=dict(record_id=test_record.id),
        )
        # answer.json is a list of TagRepresentation objects
        ordered_created_tags = []
        for tag_representation in answer.json:
            ordered_tag_repr = OrderedDict(
                sorted(tag_representation.items(), key=lambda t: t[0]))
            ordered_created_tags.append(ordered_tag_repr)
        # now query DB
        get_answer = self.get(
            'recordlisttagresource',
            user_id=self.user_a.id,
            urlargs=dict(record_id=test_record.id),
        )
        ordered_retrieved_tags = []
        for retrieved_tag_repr in get_answer.json:
            ordered_retrieved_tag_repr = OrderedDict(
                sorted(retrieved_tag_repr.items(), key=lambda t: t[0]))
            ordered_retrieved_tags.append(ordered_retrieved_tag_repr)

        self.assertEqual(ordered_created_tags, ordered_retrieved_tags)
        self.delete('taglistresource', user_id=self.user_a.id, code=204)
        # delete the created record
        db.session.delete(test_record)
        db.session.commit()
예제 #11
0
    def __init__(self, master_id, eliot_task_id=None, rule_name=None):
        """Initialize a lock handle for a certain master.

        ..note::
            Registers the master with redis if it does not already exist.

        :type master_id: str
        """
        from invenio_records.models import Record
        super(RedisMaster, self).__init__(master_id, eliot_task_id)

        if not RedisMaster._already_instnatiated(master_id):
            self.all_recids = Record.allids()  # __init__ is a good time for this.
            self.status = StatusMaster.booting
            self._rule_name = rule_name
예제 #12
0
def search_unit(query, f, m, wl=None):
    """Search for records with given citation count.

    Query usually looks like '10->23'.
    """
    from invenio_records.models import Record
    from invenio.legacy.bibrank.citation_searcher import (
        get_records_with_num_cites)
    numstr = '"{}"'.format(query)
    #this is sort of stupid but since we may need to
    #get the records that do _not_ have cites, we have to
    #know the ids of all records, too
    #but this is needed only if bsu_p is 0 or 0 or 0->0
    allrecs = intbitset()
    if query == 0 or query == "0" or \
       query.startswith("0->") or query.endswith("->0"):
        allrecs = Record.allids()
    return get_records_with_num_cites(numstr, allrecs)
예제 #13
0
def search_unit(query, f, m, wl=None):
    """Search for records with given citation count excluding self-cites.

    Query usually looks like '10->23'.
    """
    from invenio_records.models import Record
    from invenio.legacy.bibrank.citation_searcher import (
        get_records_with_num_cites
    )
    numstr = '"{}"'.format(query)
    # this is sort of stupid but since we may need to
    # get the records that do _not_ have cites, we have to
    # know the ids of all records, too
    # but this is needed only if bsu_p is 0 or 0 or 0->0
    allrecs = intbitset()
    if query == 0 or query == "0" or \
       query.startswith("0->") or query.endswith("->0"):
        allrecs = Record.allids()
    return get_records_with_num_cites(numstr, allrecs, exclude_selfcites=True)
 def test_detach_tags_from_record_pass(self):
     """Successfully detach tag from record."""
     from invenio_records.models import Record
     # first create a record
     test_record = Record(creation_date=datetime.now(),
                          modification_date=datetime.now())
     db.session.add(test_record)
     db.session.commit()
     # create some tags
     tags_list = ["HighEnergyPhysics", "Higgs", "ROOT"]
     # attach the tags to the record
     tags_data = dict(tags=tags_list, )
     self.post(
         'recordlisttagresource',
         user_id=self.user_a.id,
         data=tags_data,
         urlargs=dict(record_id=test_record.id),
     )
     # detach tags from record and delete them
     self.delete('taglistresource', user_id=self.user_a.id, code=204)
     # delete record
     db.session.delete(test_record)
     db.session.commit()
 def test_detach_tags_from_record_fails(self):
     """Fail to detach tag from record."""
     from invenio_records.models import Record
     # first create a record
     test_record = Record(creation_date=datetime.now(),
                          modification_date=datetime.now())
     db.session.add(test_record)
     db.session.commit()
     # create a tag
     data = dict(name='HighEnergyPhysics', )
     self.post(
         'taglistresource',
         user_id=self.user_a.id,
         data=data,
         code=201,
     )
     # try to detach tag that is not attached to record
     detach_answer = self.delete(
         'recordtagresource',
         urlargs=dict(record_id=test_record.id,
                      tag_name=data[data.keys()[0]]),
         user_id=self.user_a.id,
     )
     ordered_detach_answer = OrderedDict(
         sorted(detach_answer.json.items(), key=lambda t: t[0]))
     expected_result = dict(
         message=("Tag '{0} is not attached to record with id={1}".format(
             data[data.keys()[0]], test_record.id)),
         status=400)
     ordered_expected_result = OrderedDict(
         sorted(expected_result.items(), key=lambda t: t[0]))
     self.assertEqual(ordered_detach_answer, ordered_expected_result)
     # delete tag
     self.delete('taglistresource', user_id=self.user_a.id, code=204)
     # delete record
     db.session.delete(test_record)
     db.session.commit()