')
def entity_detailed_view(viewcode, type, pid):
"""Display entity view (local or remote).
@@ -44,6 +44,8 @@ def entity_detailed_view(viewcode, type, pid):
:param: pid: Resource PID.
:returns: The html rendering of the resource.
"""
+ if type not in ['local', 'remote']:
+ abort(404)
entity_class = LocalEntity if type == 'local' else RemoteEntity
if not (record := entity_class.get_record_by_pid(pid)):
abort(404, _('Entity not found.'))
diff --git a/rero_ils/modules/ext.py b/rero_ils/modules/ext.py
index cddd0d56db..c189bd12ec 100644
--- a/rero_ils/modules/ext.py
+++ b/rero_ils/modules/ext.py
@@ -37,7 +37,6 @@
from invenio_records.signals import after_record_insert, after_record_update, \
before_record_update
from invenio_records_rest.errors import JSONSchemaValidationError
-from invenio_userprofiles.signals import after_profile_update
from jsonschema.exceptions import ValidationError
from rero_ils.filter import address_block, empty_data, format_date_filter, \
@@ -75,8 +74,7 @@
enrich_patron_transaction_data
from rero_ils.modules.patrons.api import current_librarian, current_patrons
from rero_ils.modules.patrons.listener import \
- create_subscription_patron_transaction, enrich_patron_data, \
- update_from_profile
+ create_subscription_patron_transaction, enrich_patron_data
from rero_ils.modules.permissions import LibraryNeed, OrganisationNeed, \
OwnerNeed
from rero_ils.modules.sru.views import SRUDocumentsSearch
@@ -311,9 +309,6 @@ def register_signals(self, app):
oaiharvest_finished.connect(publish_harvested_records, weak=False)
- # invenio-userprofiles signal
- after_profile_update.connect(update_from_profile)
-
# store the username in the session
user_logged_in.connect(set_user_name)
user_logged_out.connect(remove_user_name)
diff --git a/rero_ils/modules/holdings/api.py b/rero_ils/modules/holdings/api.py
index 4b83f13725..ec69d78257 100644
--- a/rero_ils/modules/holdings/api.py
+++ b/rero_ils/modules/holdings/api.py
@@ -27,7 +27,7 @@
from dateutil.relativedelta import relativedelta
from elasticsearch_dsl import Q
from flask import current_app
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from invenio_records_rest.utils import obj_or_import_string
from jinja2 import Environment
diff --git a/rero_ils/modules/ill_requests/api.py b/rero_ils/modules/ill_requests/api.py
index e34ad38ac6..bdbd3ce35c 100644
--- a/rero_ils/modules/ill_requests/api.py
+++ b/rero_ils/modules/ill_requests/api.py
@@ -24,7 +24,7 @@
from dateutil.relativedelta import *
from elasticsearch_dsl.query import Q
from flask import current_app
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from rero_ils.modules.api import IlsRecord, IlsRecordsIndexer, IlsRecordsSearch
from rero_ils.modules.fetchers import id_fetcher
diff --git a/rero_ils/modules/ill_requests/forms.py b/rero_ils/modules/ill_requests/forms.py
index 11a7430a21..ff8df103e4 100644
--- a/rero_ils/modules/ill_requests/forms.py
+++ b/rero_ils/modules/ill_requests/forms.py
@@ -17,8 +17,8 @@
"""Forms definitions about ILL request in public view."""
-from flask_babelex import gettext as _
-from flask_babelex import lazy_gettext
+from flask_babel import gettext as _
+from flask_babel import lazy_gettext
from flask_wtf import FlaskForm
from wtforms import FormField, IntegerField, RadioField, SelectField, \
StringField, TextAreaField, validators
@@ -118,7 +118,7 @@ class Meta:
render_kw={'placeholder': 'https://...'}
)
- def validate(self):
+ def validate(self, **kwargs):
"""Custom validation for this form."""
if self.url.data:
self.origin.validators = [
@@ -129,7 +129,7 @@ def validate(self):
validators.DataRequired(),
validators.URL(require_tld=False)
]
- return super().validate()
+ return super().validate(kwargs)
class ILLRequestForm(FlaskForm):
@@ -165,9 +165,9 @@ class ILLRequestForm(FlaskForm):
]
)
- def validate(self):
+ def validate(self, **kwargs):
"""Add custom validation on the form."""
- form_validate = super().validate()
+ form_validate = super().validate(kwargs)
# if 'copy' is set to True, then 'pages' is required field
custom_validate = True
diff --git a/rero_ils/modules/ill_requests/views.py b/rero_ils/modules/ill_requests/views.py
index 37bc0a12d6..c3477838b5 100644
--- a/rero_ils/modules/ill_requests/views.py
+++ b/rero_ils/modules/ill_requests/views.py
@@ -21,7 +21,7 @@
from flask import Blueprint, current_app, flash, redirect, render_template, \
request, url_for
-from flask_babelex import gettext as _
+from flask_babel import lazy_gettext as _
from rero_ils.modules.documents.api import Document
from rero_ils.modules.documents.views import create_title_text
diff --git a/rero_ils/modules/indexer_utils.py b/rero_ils/modules/indexer_utils.py
index c90e0d368a..b75fd3a3d6 100644
--- a/rero_ils/modules/indexer_utils.py
+++ b/rero_ils/modules/indexer_utils.py
@@ -28,11 +28,11 @@
def record_to_index(record):
"""Get index/doc_type given a record.
- It tries to extract from `record['$schema']` the index and doc_type.
+ It tries to extract from `record['$schema']` the index.
If it fails, return the default values.
:param record: The record object.
- :return: Tuple (index, doc_type).
+ :return: index.
"""
index_names = current_search.mappings.keys()
schema = record.get('$schema', '')
@@ -43,10 +43,8 @@ def record_to_index(record):
if re.search(r'/mef/', schema):
schema = re.sub(r'/mef/', '/remote_entities/', schema)
schema = re.sub(r'mef-contribution', 'remote_entity', schema)
- index, doc_type = schema_to_index(schema, index_names=index_names)
- if index and doc_type:
- return index, doc_type
+ if index := schema_to_index(schema, index_names=index_names):
+ return index
else:
- return (current_app.config['INDEXER_DEFAULT_INDEX'],
- current_app.config['INDEXER_DEFAULT_DOC_TYPE'])
+ return current_app.config['INDEXER_DEFAULT_INDEX']
diff --git a/rero_ils/modules/item_types/api.py b/rero_ils/modules/item_types/api.py
index 18718fe504..25df8d8c3f 100644
--- a/rero_ils/modules/item_types/api.py
+++ b/rero_ils/modules/item_types/api.py
@@ -23,7 +23,7 @@
from functools import partial
from elasticsearch_dsl import Q
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from .models import ItemTypeIdentifier, ItemTypeMetadata
from ..api import IlsRecord, IlsRecordsIndexer, IlsRecordsSearch
diff --git a/rero_ils/modules/items/api/circulation.py b/rero_ils/modules/items/api/circulation.py
index 9c6e8659cc..5e51796fd6 100644
--- a/rero_ils/modules/items/api/circulation.py
+++ b/rero_ils/modules/items/api/circulation.py
@@ -22,7 +22,7 @@
from datetime import datetime
from flask import current_app
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from invenio_circulation.api import get_loan_for_item
from invenio_circulation.errors import ItemNotAvailableError, \
NoValidTransitionAvailableError
diff --git a/rero_ils/modules/items/api/record.py b/rero_ils/modules/items/api/record.py
index f00b618d7b..e032ff56d6 100644
--- a/rero_ils/modules/items/api/record.py
+++ b/rero_ils/modules/items/api/record.py
@@ -21,7 +21,7 @@
import pytz
from elasticsearch_dsl.query import Q
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from rero_ils.modules.api import IlsRecord
from rero_ils.modules.holdings.models import HoldingTypes
diff --git a/rero_ils/modules/libraries/api.py b/rero_ils/modules/libraries/api.py
index 33aa81e481..4c3f894490 100644
--- a/rero_ils/modules/libraries/api.py
+++ b/rero_ils/modules/libraries/api.py
@@ -25,7 +25,7 @@
from dateutil import parser
from dateutil.rrule import FREQNAMES, rrule
from elasticsearch_dsl import Q
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from rero_ils.modules.api import IlsRecord, IlsRecordsIndexer, IlsRecordsSearch
from rero_ils.modules.fetchers import id_fetcher
diff --git a/rero_ils/modules/loans/api.py b/rero_ils/modules/loans/api.py
index ce6440ffed..dedad7311d 100644
--- a/rero_ils/modules/loans/api.py
+++ b/rero_ils/modules/loans/api.py
@@ -25,7 +25,7 @@
from dateutil.relativedelta import relativedelta
from elasticsearch_dsl import A, Q
from flask import current_app
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from invenio_circulation.errors import MissingRequiredParameterError
from invenio_circulation.pidstore.fetchers import loan_pid_fetcher
from invenio_circulation.pidstore.minters import loan_pid_minter
@@ -999,7 +999,7 @@ def can_anonymize(cls, loan_data=None, patron=None):
patron = patron or Patron.get_record_by_pid(patron_pid)
keep_history = True
if patron:
- keep_history = patron.user.profile.keep_history
+ keep_history = patron.user.user_profile.get('keep_history', True)
else:
msg = f'Can not anonymize loan: {loan_data.get("pid")} ' \
f'no patron: {loan_data.get("patron_pid")}'
diff --git a/rero_ils/modules/local_fields/api.py b/rero_ils/modules/local_fields/api.py
index da944efaf4..d403078270 100644
--- a/rero_ils/modules/local_fields/api.py
+++ b/rero_ils/modules/local_fields/api.py
@@ -21,7 +21,7 @@
from functools import partial
from elasticsearch_dsl import Q
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from .models import LocalFieldIdentifier, LocalFieldMetadata
from ..api import IlsRecord, IlsRecordsIndexer, IlsRecordsSearch
diff --git a/rero_ils/modules/locations/api.py b/rero_ils/modules/locations/api.py
index 4952de952c..9c6b48764f 100644
--- a/rero_ils/modules/locations/api.py
+++ b/rero_ils/modules/locations/api.py
@@ -20,7 +20,7 @@
from functools import partial
from elasticsearch_dsl.query import Q
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from rero_ils.modules.api import IlsRecord, IlsRecordsIndexer, IlsRecordsSearch
from rero_ils.modules.fetchers import id_fetcher
diff --git a/rero_ils/modules/operation_logs/logs/api.py b/rero_ils/modules/operation_logs/logs/api.py
index f4822f5121..d147b37c56 100644
--- a/rero_ils/modules/operation_logs/logs/api.py
+++ b/rero_ils/modules/operation_logs/logs/api.py
@@ -45,8 +45,9 @@ def _get_patron_data(cls, patron):
'name': patron.formatted_name,
'type': patron_type['name'] if patron_type else None,
'age': patron.age,
- 'postal_code': patron.user.profile.postal_code,
- 'gender': patron.user.profile.gender or 'no_information',
+ 'postal_code': patron.user.user_profile.get(
+ 'postal_code', 'no_information'),
+ 'gender': patron.user.user_profile.get('gender', 'no_information'),
'pid': patron.pid,
'hashed_pid': hashed_pid
}
diff --git a/rero_ils/modules/patron_transactions/extensions.py b/rero_ils/modules/patron_transactions/extensions.py
index 52c10af721..d2fd7ed8da 100644
--- a/rero_ils/modules/patron_transactions/extensions.py
+++ b/rero_ils/modules/patron_transactions/extensions.py
@@ -18,7 +18,7 @@
"""Patron transactions record extensions."""
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from invenio_records.extensions import RecordExtension
from rero_ils.modules.patron_transaction_events.api import \
diff --git a/rero_ils/modules/patron_transactions/utils.py b/rero_ils/modules/patron_transactions/utils.py
index bb8e29f8ce..8cfacdde03 100644
--- a/rero_ils/modules/patron_transactions/utils.py
+++ b/rero_ils/modules/patron_transactions/utils.py
@@ -19,7 +19,7 @@
"""Utility functions about PatronTransactions."""
from datetime import datetime, timezone
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from .api import PatronTransaction, PatronTransactionsSearch
from ..utils import get_ref_for_pid
diff --git a/rero_ils/modules/patron_types/api.py b/rero_ils/modules/patron_types/api.py
index 0af556556e..5844dd8f38 100644
--- a/rero_ils/modules/patron_types/api.py
+++ b/rero_ils/modules/patron_types/api.py
@@ -23,7 +23,7 @@
from functools import partial
from elasticsearch_dsl import Q
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from .models import PatronTypeIdentifier, PatronTypeMetadata
from ..api import IlsRecord, IlsRecordsIndexer, IlsRecordsSearch
diff --git a/rero_ils/modules/patrons/api.py b/rero_ils/modules/patrons/api.py
index 6f5691ad5c..b9564bbcfc 100644
--- a/rero_ils/modules/patrons/api.py
+++ b/rero_ils/modules/patrons/api.py
@@ -23,8 +23,8 @@
from elasticsearch_dsl import Q
from flask import current_app
-from flask_babelex import gettext as _
-from flask_babelex import ngettext
+from flask_babel import gettext as _
+from flask_babel import ngettext
from flask_login import current_user
from invenio_circulation.proxies import current_circulation
from invenio_db import db
@@ -48,7 +48,6 @@
from rero_ils.modules.users.models import UserRole
from rero_ils.modules.utils import extracted_data_from_ref, \
get_patron_from_arguments, get_ref_for_pid, sorted_pids
-from rero_ils.utils import create_user_from_data
from .extensions import UserDataExtension
from .models import CommunicationChannel, PatronIdentifier, PatronMetadata
@@ -66,24 +65,6 @@
if UserRole.PATRON in patron.get('roles', [])
])
-
-def create_patron_from_data(data, delete_pid=False, dbcommit=False,
- reindex=False):
- """Create a patron and a user from a data dict.
-
- :param data - dictionary representing a library user
- :param dbcommit - commit the changes in the db after the creation
- :param reindex - index the record after the creation
- :returns: - A `Patron` instance
- """
- data = create_user_from_data(data)
- return Patron.create(
- data=data,
- delete_pid=delete_pid,
- dbcommit=dbcommit,
- reindex=reindex)
-
-
# provider
PatronProvider = type(
'PatronProvider',
@@ -520,9 +501,12 @@ def set_keep_history(self, keep_history, dbcommit=True, reindex=True):
:param dbcommit - commit the changes
:param reindex - index the changes
"""
- self.user.profile.keep_history = keep_history
+ user = self._get_user_by_user_id(self.get('user_id'))
+ profile = user.user_profile
+ profile['keep_history'] = keep_history
+ user.user_profile = profile
+ db.session.merge(user)
if dbcommit:
- db.session.merge(self.user)
db.session.commit()
if reindex:
self.reindex()
@@ -748,10 +732,10 @@ def is_expired(self):
@property
def formatted_name(self):
"""Return the best possible human-readable patron name."""
- profile = self.user.profile
+ profile = self.user.user_profile
name_parts = [
- profile.last_name.strip(),
- profile.first_name.strip()
+ profile.get('last_name', '').strip(),
+ profile.get('first_name', '').strip()
]
return ', '.join(filter(None, name_parts))
@@ -880,7 +864,8 @@ def age(self):
:returns: Age of the patron as ``int``
"""
- birth_date = self.user.profile.birth_date
+ birth_date = self.user.user_profile['birth_date']
+ birth_date = datetime.strptime(birth_date, '%Y-%m-%d')
today = date.today()
return today.year - birth_date.year - (
(today.month, today.day) < (birth_date.month, birth_date.day))
diff --git a/rero_ils/modules/patrons/cli.py b/rero_ils/modules/patrons/cli.py
index ae4edbf462..ae9ea9a8d9 100644
--- a/rero_ils/modules/patrons/cli.py
+++ b/rero_ils/modules/patrons/cli.py
@@ -23,13 +23,10 @@
import os
import sys
import traceback
-from datetime import datetime
import click
from flask import current_app
from flask.cli import with_appcontext
-from flask_security.confirmable import confirm_user
-from invenio_accounts.ext import hash_password
from invenio_db import db
from invenio_jsonschemas.proxies import current_jsonschemas
from jsonmerge import Merger
@@ -38,8 +35,9 @@
from werkzeug.local import LocalProxy
from rero_ils.modules.patrons.models import CommunicationChannel
+from rero_ils.modules.users.api import User
-from .api import User, create_patron_from_data
+from .utils import create_patron_from_data
from ..patrons.api import Patron, PatronProvider
from ..providers import append_fixtures_new_identifiers
from ..utils import JsonWriter, get_schema_for_resource, read_json_record
@@ -83,34 +81,7 @@ def import_users(infile, append, verbose, password, lazy, dont_stop_on_error,
pids = []
error_records = []
for count, patron_data in enumerate(data, 1):
- password = patron_data.get('password', password)
- username = patron_data['username']
- if password:
- patron_data.pop('password', None)
- if verbose:
- user_record = User.get_by_username(username)
- if not user_record:
- click.secho('{count: <8} Creating user: {username}'.format(
- count=count,
- username=username
- )
- )
- else:
- user = user_record.user
- for field in profile_fields:
- value = patron_data.get(field)
- if value is not None:
- if field == 'birth_date':
- value = datetime.strptime(value, '%Y-%m-%d')
- setattr(user.profile, field, value)
- db.session.merge(user)
- db.session.commit()
- click.secho('{count: <8} User updated: {username}'.format(
- count=count,
- username=username
- ),
- fg='yellow'
- )
+
try:
# patron creation
patron = None
@@ -120,22 +91,14 @@ def import_users(infile, append, verbose, password, lazy, dont_stop_on_error,
if not patron:
patron = create_patron_from_data(
data=patron_data,
- dbcommit=False,
- reindex=False
+ dbcommit=True,
+ reindex=True
)
- user = patron.user
- user.password = hash_password(password)
- user.active = True
- db.session.merge(user)
- db.session.commit()
- confirm_user(user)
- patron.reindex()
pids.append(patron.pid)
else:
# remove profile fields from patron record
- for field in profile_fields:
- patron_data.pop(field, None)
- patron.update(data=patron_data, dbcommit=True, reindex=True)
+ patron.update(
+ data=User.remove_fields(data), dbcommit=True, reindex=True)
if verbose:
click.secho('{count: <8} Patron updated: {username}'
.format(count=count, username=username),
diff --git a/rero_ils/modules/patrons/listener.py b/rero_ils/modules/patrons/listener.py
index d5b09ab398..4506334dba 100644
--- a/rero_ils/modules/patrons/listener.py
+++ b/rero_ils/modules/patrons/listener.py
@@ -65,14 +65,14 @@ def create_subscription_patron_transaction(sender, record=None, **kwargs):
record.add_subscription(ptty, start_date, end_date)
-def update_from_profile(sender, profile=None, **kwargs):
+def update_from_profile(sender, user, **kwargs):
"""Update the patron linked with the user profile data.
:param profile - the rero user profile
"""
- for patron in Patron.get_patrons_by_user(profile.user):
+ for patron in Patron.get_patrons_by_user(user):
patron.reindex()
if patron.is_patron:
from ..loans.api import anonymize_loans
- if not profile.keep_history:
+ if not user.user_profile.get('keep_history', True):
anonymize_loans(patron=patron, dbcommit=True, reindex=True)
diff --git a/rero_ils/modules/patrons/schemas/json.py b/rero_ils/modules/patrons/schemas/json.py
index 32765284f6..9f5535cada 100644
--- a/rero_ils/modules/patrons/schemas/json.py
+++ b/rero_ils/modules/patrons/schemas/json.py
@@ -85,7 +85,8 @@ def remove_user_data(self, data, many, **kwargs):
:return Data cleared from user profile information.
"""
data = data if many else [data]
- profile_fields = set(User.profile_fields + ['username', 'email'])
+ profile_fields = set(
+ User.profile_fields + ['username', 'email', 'password'])
for record in data:
for field in profile_fields:
record.pop(field, None)
diff --git a/rero_ils/modules/patrons/tasks.py b/rero_ils/modules/patrons/tasks.py
index 35d9afcf0d..6d2c26f5d9 100644
--- a/rero_ils/modules/patrons/tasks.py
+++ b/rero_ils/modules/patrons/tasks.py
@@ -24,6 +24,8 @@
from celery import shared_task
from flask import current_app
+from rero_ils.modules.users.api import User
+
from .api import Patron
from ..patron_types.api import PatronType
from ..utils import add_years, set_timestamp
@@ -56,7 +58,7 @@ def is_obsolete(subscription, end_date=None):
# `create_subscription_patron_transaction`. This listener will
# create a new subscription if needed
patron.update(
- Patron.remove_user_data(patron.dumps()),
+ User.remove_fields(patron.dumps()),
dbcommit=True,
reindex=True
)
diff --git a/rero_ils/modules/patrons/utils.py b/rero_ils/modules/patrons/utils.py
index 613959ab31..79367bb5ee 100644
--- a/rero_ils/modules/patrons/utils.py
+++ b/rero_ils/modules/patrons/utils.py
@@ -20,6 +20,8 @@
from flask_login import current_user
from marshmallow import ValidationError
+from rero_ils.modules.users.api import User
+
def user_has_patron(user=current_user):
"""Test if user has a patron."""
@@ -68,3 +70,40 @@ def validate_role_changes(user, changes, raise_exc=True):
return False
# No problems were detected
return True
+
+
+def create_user_from_data(data, send_email=False):
+ """Create a user and set the profile fields from a data.
+
+ :param data: A dict containing a mix of patron and user data.
+ :param send_email - send the reset password email to the user
+ :returns: The modified dict.
+ """
+ user = User.get_by_username(data.get('username'))
+ if not user:
+ user = User.create(data, send_email)
+ user_id = user.id
+ else:
+ user_id = user.user.id
+ data['user_id'] = user_id
+
+ return User.remove_fields(data)
+
+
+def create_patron_from_data(
+ data, dbcommit=True, reindex=True, send_email=False
+):
+ """Create a patron and a user from a data dict.
+
+ :param data - dictionary representing a library user
+ :param send_email - send the reset password email to the user
+ :returns: - A `Patron` instance
+ """
+ from .api import Patron
+ data = create_user_from_data(data, send_email)
+ ptrn = Patron.create(
+ data=data,
+ delete_pid=False,
+ dbcommit=dbcommit,
+ reindex=reindex)
+ return ptrn
diff --git a/rero_ils/modules/patrons/views.py b/rero_ils/modules/patrons/views.py
index 23e9ae6a7e..0fd6e4794e 100644
--- a/rero_ils/modules/patrons/views.py
+++ b/rero_ils/modules/patrons/views.py
@@ -25,9 +25,9 @@
from flask import Blueprint, abort, current_app, jsonify, render_template
from flask import request as flask_request
-from flask_babelex import format_currency
-from flask_babelex import gettext as _
-from flask_babelex import lazy_gettext
+from flask_babel import format_currency
+from flask_babel import lazy_gettext
+from flask_babel import lazy_gettext as _
from flask_breadcrumbs import register_breadcrumb
from flask_login import current_user, login_required
from flask_menu import register_menu
@@ -361,7 +361,7 @@ def get_institution_code(institution):
# Birthdate
if 'birthdate' in token_scopes:
- data['birthdate'] = current_user.profile.birth_date.isoformat()
+ data['birthdate'] = current_user.user_profile.get('birth_date')
# Patron types
if 'patron_types' in token_scopes:
diff --git a/rero_ils/modules/selfcheck/admin.py b/rero_ils/modules/selfcheck/admin.py
index 81834f7c69..44bbbdbb10 100644
--- a/rero_ils/modules/selfcheck/admin.py
+++ b/rero_ils/modules/selfcheck/admin.py
@@ -20,7 +20,7 @@
from flask_admin.contrib.sqla import ModelView
from flask_admin.form.fields import DateTimeField
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from werkzeug.local import LocalProxy
from wtforms.fields import SelectField
from wtforms.validators import DataRequired
diff --git a/rero_ils/modules/selfcheck/api.py b/rero_ils/modules/selfcheck/api.py
index ede88a2b1e..d8536b94cb 100644
--- a/rero_ils/modules/selfcheck/api.py
+++ b/rero_ils/modules/selfcheck/api.py
@@ -21,7 +21,7 @@
from datetime import datetime, timezone
from flask import current_app
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from invenio_circulation.errors import CirculationException, \
ItemNotAvailableError
@@ -96,7 +96,7 @@ def authorize_patron(barcode, password, **kwargs):
if patron and patron.is_patron:
# User email is an optional field. When User hasn't email address,
# we take his username as login.
- user_login = patron.user.email or patron.user.profile.username
+ user_login = patron.user.email or patron.user.username
return authorize_selfckeck_user(user_login, password)
return False
diff --git a/rero_ils/modules/selfcheck/utils.py b/rero_ils/modules/selfcheck/utils.py
index 623da0b478..3efe3550a6 100644
--- a/rero_ils/modules/selfcheck/utils.py
+++ b/rero_ils/modules/selfcheck/utils.py
@@ -86,11 +86,11 @@ def format_patron_address(patron):
city=address.get('city')
)
else:
- profile = patron.user.profile
+ profile = patron.user.user_profile
formated_address = '{street}, {postal_code} {city}'.format(
- street=profile.street.strip(),
- postal_code=profile.postal_code.strip(),
- city=profile.city.strip()
+ street=profile['street'].strip(),
+ postal_code=profile['postal_code'].strip(),
+ city=profile['city'].strip()
)
# Should never append, but can be imported from an old system
return formated_address.replace(r'\n', ' ').replace(r'\r', ' ')\
diff --git a/rero_ils/modules/stats/views.py b/rero_ils/modules/stats/views.py
index f85da079a3..3d2ef23132 100644
--- a/rero_ils/modules/stats/views.py
+++ b/rero_ils/modules/stats/views.py
@@ -161,7 +161,7 @@ def stats_librarian_queries(record_pid):
# JINJA FILTERS ===============================================================
-@jinja2.contextfilter
+@jinja2.pass_context
@blueprint.app_template_filter()
def yearmonthfilter(context, value, format="%Y-%m-%dT%H:%M:%S"):
"""Convert datetime in local timezone.
@@ -177,7 +177,7 @@ def yearmonthfilter(context, value, format="%Y-%m-%dT%H:%M:%S"):
return f"{month_name} {value.year}"
-@jinja2.contextfilter
+@jinja2.pass_context
@blueprint.app_template_filter()
def stringtodatetime(context, value, format="%Y-%m-%dT%H:%M:%S"):
"""Convert string to datetime.
@@ -188,7 +188,7 @@ def stringtodatetime(context, value, format="%Y-%m-%dT%H:%M:%S"):
return datetime.datetime.strptime(value, format)
-@jinja2.contextfilter
+@jinja2.pass_context
@blueprint.app_template_filter()
def sort_dict_by_key(context, dictionary):
"""Sort dict by dict of keys.
@@ -200,7 +200,7 @@ def sort_dict_by_key(context, dictionary):
return StatCSVSerializer.sort_dict_by_key(dictionary)
-@jinja2.contextfilter
+@jinja2.pass_context
@blueprint.app_template_filter()
def sort_dict_by_library(context, dictionary):
"""Sort dict by library name.
@@ -212,7 +212,7 @@ def sort_dict_by_library(context, dictionary):
return sorted(dictionary, key=lambda v: v['library']['name'])
-@jinja2.contextfilter
+@jinja2.pass_context
@blueprint.app_template_filter()
def process_data(context, value):
"""Process data.
diff --git a/rero_ils/modules/tasks.py b/rero_ils/modules/tasks.py
index d0d458864a..3e68250c09 100644
--- a/rero_ils/modules/tasks.py
+++ b/rero_ils/modules/tasks.py
@@ -26,14 +26,14 @@
@shared_task(ignore_result=True)
-def process_bulk_queue(version_type=None, queue=None, es_bulk_kwargs=None,
+def process_bulk_queue(version_type=None, queue=None, search_bulk_kwargs=None,
stats_only=True):
"""Process bulk indexing queue.
:param str version_type: Elasticsearch version type.
:param Queue queue: Queue to use.
:param str routing_key: Routing key to use.
- :param dict es_bulk_kwargs: Passed to
+ :param dict search_bulk_kwargs: Passed to
:func:`elasticsearch:elasticsearch.helpers.bulk`.
:param boolean stats_only: if `True` only report number of
successful/failed operations instead of just number of
@@ -52,7 +52,7 @@ def process_bulk_queue(version_type=None, queue=None, es_bulk_kwargs=None,
routing_key=queue
)
return indexer.process_bulk_queue(
- es_bulk_kwargs=es_bulk_kwargs, stats_only=stats_only)
+ search_bulk_kwargs=search_bulk_kwargs, stats_only=stats_only)
@shared_task(ignore_result=True)
diff --git a/rero_ils/modules/templates/schemas/json.py b/rero_ils/modules/templates/schemas/json.py
index 92849a1bec..66d7bf54ca 100644
--- a/rero_ils/modules/templates/schemas/json.py
+++ b/rero_ils/modules/templates/schemas/json.py
@@ -19,7 +19,7 @@
"""Marshmallow schema for JSON representation of `Template` resources."""
from functools import partial
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from invenio_records_rest.schemas import StrictKeysMixin
from invenio_records_rest.schemas.fields import GenFunction, SanitizedUnicode
from marshmallow import ValidationError, fields, validates, validates_schema
diff --git a/rero_ils/modules/users/api.py b/rero_ils/modules/users/api.py
index fd63f4c6dc..c5a297d6e4 100644
--- a/rero_ils/modules/users/api.py
+++ b/rero_ils/modules/users/api.py
@@ -18,23 +18,20 @@
"""API for manipulating users."""
-from datetime import datetime
from flask import current_app, url_for
-from flask_babelex import lazy_gettext as _
+from flask_babel import lazy_gettext as _
from flask_login import current_user
from flask_security.confirmable import confirm_user
from flask_security.recoverable import send_reset_password_instructions
-from invenio_accounts.ext import hash_password
+from flask_security.utils import hash_password
from invenio_accounts.models import User as BaseUser
from invenio_db import db
from invenio_jsonschemas import current_jsonschemas
-from invenio_records.validators import PartialDraft4Validator
from invenio_records_rest.utils import obj_or_import_string
-from invenio_userprofiles.models import UserProfile
+from jsonschema import Draft4Validator
from jsonschema.exceptions import ValidationError
from sqlalchemy import func
-from sqlalchemy.orm.exc import NoResultFound
from werkzeug.local import LocalProxy
from ..api import ils_record_format_checker
@@ -86,9 +83,12 @@ class User(object):
profile_fields = [
'first_name', 'last_name', 'street', 'postal_code', 'gender',
- 'city', 'birth_date', 'username', 'home_phone', 'business_phone',
+ 'city', 'birth_date', 'home_phone', 'business_phone',
'mobile_phone', 'other_phone', 'keep_history', 'country'
]
+ user_fields = [
+ 'email', 'username', 'password'
+ ]
def __init__(self, user):
"""User class initializer."""
@@ -100,37 +100,34 @@ def id(self):
return self.user.id
@classmethod
- def create(cls, data, **kwargs):
+ def create(cls, data, send_email=True, **kwargs):
"""User record creation.
:param cls - class object
:param data - dictionary representing a user record
+ :param send_email - send the reset password email to the user
"""
with db.session.begin_nested():
- email = data.pop('email', None)
- data.pop('roles', None)
# Generate password if not present
- password = data.pop('password', None)
- if not password:
- password = password_generator()
- cls._validate(data=data)
+ profile = {
+ k: v for k, v in data.items()
+ if k in cls.profile_fields
+ }
+ if profile:
+ cls._validate(profile)
+ password = data.get('password', password_generator())
+ cls._validate_password(password=password)
user = BaseUser(
+ username=data.get('username'),
password=hash_password(password),
- profile=data, active=True)
+ user_profile=profile, active=True)
db.session.add(user)
- profile = user.profile
- for field in cls.profile_fields:
- value = data.get(field)
- if value is not None:
- if field == 'birth_date':
- value = datetime.strptime(value, '%Y-%m-%d')
- setattr(profile, field, value)
# send the reset password notification for new users
- if email:
+ if email := data.get('email'):
user.email = email
db.session.merge(user)
db.session.commit()
- if user.email:
+ if data.get('email') and send_email:
send_reset_password_instructions(user)
confirm_user(user)
return cls(user)
@@ -141,49 +138,40 @@ def update(self, data):
:param data - dictionary representing a user record to update
"""
from ..patrons.listener import update_from_profile
- data.pop('roles', None)
- self._validate(data=data)
- email = data.pop('email', None)
- password = data.pop('password', None)
+ profile = {k: v for k, v in data.items() if k in self.profile_fields}
+ if profile:
+ self._validate(profile)
+ if password := data.get('password'):
+ self._validate_password(password=password)
+
user = self.user
with db.session.begin_nested():
- if user.profile is None:
- user.profile = UserProfile(user_id=user.id)
- profile = user.profile
- for field in self.profile_fields:
- if field == 'birth_date':
- setattr(
- profile, field,
- datetime.strptime(data.get(field), '%Y-%m-%d'))
- else:
- setattr(profile, field, data.get(field, ''))
if password:
user.password = hash_password(password)
-
- if email and email != user.email:
+ user.username = data.get('username')
+ if email := data.get('email'):
user.email = email
- # remove the email from user data
- elif not email and user.email:
- user.email = None
+ else:
+ user._email = None
+ user.user_profile = profile
db.session.merge(user)
db.session.commit()
confirm_user(user)
- update_from_profile('user', self.user.profile)
+ update_from_profile('user', self.user)
return self
@classmethod
def _validate(cls, data, **kwargs):
"""Validate user record against schema."""
- if 'password' in data:
- cls._validate_password(data['password'])
- default_user_schema = get_schema_for_resource('user')
- if schema := data.pop('$schema', default_user_schema):
- _records_state.validate(
- data,
- schema,
- format_checker=ils_record_format_checker,
- cls=PartialDraft4Validator
- )
+ schema = get_schema_for_resource('user')
+ data['$schema'] = schema
+ _records_state.validate(
+ data,
+ schema,
+ format_checker=ils_record_format_checker,
+ cls=Draft4Validator
+ )
+ data.pop('$schema')
return data
@classmethod
@@ -194,6 +182,17 @@ def _validate_password(cls, password):
except PasswordValidatorException as e:
raise ValidationError(str(e)) from e
+ @classmethod
+ @property
+ def fields(cls):
+ """Validate password."""
+ return cls.profile_fields + cls.user_fields
+
+ @classmethod
+ def remove_fields(cls, data):
+ """."""
+ return {k: v for k, v in data.items() if k not in cls.fields}
+
@classmethod
def get_record(cls, user_id):
"""Get a user by a user_id.
@@ -225,14 +224,11 @@ def dumps_metadata(self, dump_patron: bool = False) -> dict:
metadata = {
'roles': [r.name for r in self.user.roles]
}
- if self.user.profile:
- for field in self.profile_fields:
- if value := getattr(self.user.profile, field):
- if field == 'birth_date':
- value = datetime.strftime(value, '%Y-%m-%d')
- metadata[field] = value
+ metadata.update(self.user.user_profile)
if self.user.email:
metadata['email'] = self.user.email
+ if self.user.username:
+ metadata['username'] = self.user.username
if dump_patron:
for patron in Patron.get_patrons_by_user(self.user):
metadata.setdefault('patrons', []).append({
@@ -251,11 +247,8 @@ def get_by_username(cls, username):
:param username - the user name
:return: the user record
"""
- try:
- profile = UserProfile.get_by_username(username)
- return cls(profile.user)
- except NoResultFound:
- return None
+ if base_user := BaseUser.query.filter_by(username=username).first():
+ return cls(base_user)
@classmethod
def get_by_email(cls, email):
diff --git a/rero_ils/modules/users/jsonschemas/users/user-v0.0.1.json b/rero_ils/modules/users/jsonschemas/users/user-v0.0.1.json
index 6f89e145b6..986302e455 100644
--- a/rero_ils/modules/users/jsonschemas/users/user-v0.0.1.json
+++ b/rero_ils/modules/users/jsonschemas/users/user-v0.0.1.json
@@ -7,7 +7,6 @@
"propertiesOrder": [
"first_name",
"last_name",
- "username",
"email",
"password",
"street",
@@ -26,8 +25,7 @@
"$schema",
"first_name",
"last_name",
- "birth_date",
- "username"
+ "birth_date"
],
"properties": {
"$schema": {
@@ -105,24 +103,6 @@
]
}
},
- "username": {
- "title": "Username",
- "description": "Login username for the web interface.",
- "type": "string",
- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9-_]{2}[a-zA-Z0-9-_]*$",
- "minLength": 3,
- "maxLength": 255,
- "widget": {
- "formlyConfig": {
- "validation": {
- "messages": {
- "patternMessage": "Username must start with a letter or a number, be at least three characters long and only contain alphanumeric characters, dashes and underscores.",
- "uniqueUsernameMessage": "This username is already taken."
- }
- }
- }
- }
- },
"street": {
"title": "Street",
"description": "Street and number of the address.",
diff --git a/rero_ils/modules/users/schemas.py b/rero_ils/modules/users/schemas.py
new file mode 100644
index 0000000000..1100eaa153
--- /dev/null
+++ b/rero_ils/modules/users/schemas.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+#
+# RERO ILS
+# Copyright (C) 2019-2022 RERO
+# Copyright (C) 2019-2022 UCLouvain
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, version 3 of the License.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+
+"""Models for RERO-ILS users."""
+from marshmallow import Schema, fields
+
+
+class UserProfile(Schema):
+ """A custom user profile schema."""
+
+ last_name = fields.String()
+ """Last name of person."""
+
+ first_name = fields.String()
+ """First name of person."""
+
+ gender = fields.String()
+ """Gender of person."""
+
+ birth_date = fields.Date()
+ """Birth date of person."""
+
+ street = fields.String()
+ """Street address of person."""
+
+ postal_code = fields.String()
+ """Postal code address of person."""
+
+ city = fields.String()
+ """City address of person."""
+
+ country = fields.String()
+ """Country address of person."""
+
+ home_phone = fields.String()
+ """Home phone number of person."""
+
+ business_phone = fields.String()
+ """Business phone number of person."""
+
+ mobile_phone = fields.String()
+ """Mobile phone number of person."""
+
+ other_phone = fields.String()
+ """Other phone number of person."""
+
+ keep_history = fields.Boolean()
+ """Boolean stating to keep loan history or not."""
diff --git a/rero_ils/modules/utils.py b/rero_ils/modules/utils.py
index 33f61ca259..dec7edf9c3 100644
--- a/rero_ils/modules/utils.py
+++ b/rero_ils/modules/utils.py
@@ -38,8 +38,8 @@
import sqlalchemy
from dateutil import parser
from flask import current_app, session
-from flask_babelex import gettext as _
-from flask_babelex import ngettext
+from flask_babel import gettext as _
+from flask_babel import ngettext
from flask_login import current_user
from invenio_accounts.models import Role
from invenio_cache import current_cache
diff --git a/rero_ils/modules/vendors/api.py b/rero_ils/modules/vendors/api.py
index 6930716a7f..f868c7cc26 100644
--- a/rero_ils/modules/vendors/api.py
+++ b/rero_ils/modules/vendors/api.py
@@ -20,7 +20,7 @@
from functools import partial
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from rero_ils.modules.acquisition.acq_invoices.api import \
AcquisitionInvoicesSearch
diff --git a/rero_ils/modules/views.py b/rero_ils/modules/views.py
index 37323af36e..3eae3e3671 100644
--- a/rero_ils/modules/views.py
+++ b/rero_ils/modules/views.py
@@ -25,7 +25,6 @@
import requests
from flask import Blueprint, abort, current_app, jsonify, make_response, \
request
-from flask_babelex import get_domain
from rero_ils.modules.utils import cached, get_all_roles
@@ -153,15 +152,15 @@ def translations(ln):
:param ln: language ISO 639-1 Code (two chars).
"""
- domain = get_domain()
- paths = domain.paths
+ babel = current_app.extensions['babel']
+ paths = babel.default_directories
try:
path = next(p for p in paths if p.find('rero_ils') > -1)
except StopIteration:
current_app.logger.error(f'translations for {ln} does not exist')
abort(404)
- po_file_name = f'{path}/{ln}/LC_MESSAGES/{domain.domain}.po'
+ po_file_name = f'{path}/{ln}/LC_MESSAGES/{babel.default_domain}.po'
if not os.path.isfile(po_file_name):
abort(404)
try:
diff --git a/rero_ils/theme/menus.py b/rero_ils/theme/menus.py
index 4b6000001f..e7e30be4b0 100644
--- a/rero_ils/theme/menus.py
+++ b/rero_ils/theme/menus.py
@@ -20,7 +20,7 @@
from functools import partial
from flask import current_app, request, session
-from flask_babelex import gettext as _
+from flask_babel import lazy_gettext as _
from flask_login import current_user
from flask_menu import current_menu
from invenio_i18n.ext import current_i18n
diff --git a/rero_ils/theme/templates/security/email/reset_instructions.html b/rero_ils/theme/templates/security/email/reset_instructions.html
index 0b73c9b4d2..4e8a0c6a9b 100644
--- a/rero_ils/theme/templates/security/email/reset_instructions.html
+++ b/rero_ils/theme/templates/security/email/reset_instructions.html
@@ -18,8 +18,8 @@
#}
-{%- if user.profile.first_name and user.profile.last_name %}
-{{ _('Dear') }} {{ user.profile.first_name }} {{ user.profile.last_name }},
+{%- if user.user_profile.first_name and user.user_profile.last_name %}
+{{ _('Dear') }} {{ user.user_profile.first_name }} {{ user.user_profile.last_name }},
{%- else %}
{{ _('Dear patron') }},
{%- endif %}
diff --git a/rero_ils/theme/templates/security/email/reset_instructions.txt b/rero_ils/theme/templates/security/email/reset_instructions.txt
index 9797724663..9156455cd6 100644
--- a/rero_ils/theme/templates/security/email/reset_instructions.txt
+++ b/rero_ils/theme/templates/security/email/reset_instructions.txt
@@ -1,6 +1,6 @@
-{%- if user.profile.first_name and user.profile.last_name %}
-{{ _('Dear') }} {{ user.profile.first_name }} {{ user.profile.last_name }},
+{%- if user.user_profile.first_name and user.user_profile.last_name %}
+{{ _('Dear') }} {{ user.user_profile.first_name }} {{ user.user_profile.last_name }},
{%- else %}
{{ _('Dear patron') }},
{%- endif %}
diff --git a/rero_ils/theme/templates/security/email/reset_notice.html b/rero_ils/theme/templates/security/email/reset_notice.html
index 7b0a331027..4774d290a1 100644
--- a/rero_ils/theme/templates/security/email/reset_notice.html
+++ b/rero_ils/theme/templates/security/email/reset_notice.html
@@ -18,8 +18,8 @@
#}
-{%- if user.profile.first_name and user.profile.last_name %}
-{{ _('Dear') }} {{ user.profile.first_name }} {{ user.profile.last_name }},
+{%- if user.user_profile.first_name and user.user_profile.last_name %}
+{{ _('Dear') }} {{ user.user_profile.first_name }} {{ user.user_profile.last_name }},
{%- else %}
{{ _('Dear patron') }},
{%- endif %}
diff --git a/rero_ils/theme/templates/security/email/reset_notice.txt b/rero_ils/theme/templates/security/email/reset_notice.txt
index 138266d4a1..baabb28f33 100644
--- a/rero_ils/theme/templates/security/email/reset_notice.txt
+++ b/rero_ils/theme/templates/security/email/reset_notice.txt
@@ -1,5 +1,5 @@
-{%- if user.profile.first_name and user.profile.last_name %}
-{{ _('Dear') }} {{ user.profile.first_name }} {{ user.profile.last_name }},
+{%- if user.user_profile.first_name and user.user_profile.last_name %}
+{{ _('Dear') }} {{ user.user_profile.first_name }} {{ user.user_profile.last_name }},
{%- else %}
{{ _('Dear patron') }},
{%- endif %}
diff --git a/rero_ils/utils.py b/rero_ils/utils.py
index 2acbc55823..d6d1c7124f 100644
--- a/rero_ils/utils.py
+++ b/rero_ils/utils.py
@@ -17,20 +17,12 @@
"""Utilities functions for rero-ils."""
-from copy import deepcopy
-from datetime import datetime
import iso639
from flask import current_app
-from flask_babelex import gettext
-from flask_security.confirmable import confirm_user
-from invenio_accounts.ext import hash_password
-from invenio_accounts.models import User as BaseUser
-from invenio_db import db
+from flask_babel import gettext
from invenio_i18n.ext import current_i18n
-from rero_ils.modules.utils import password_generator
-
def unique_list(data):
"""Unicity of list."""
@@ -39,8 +31,7 @@ def unique_list(data):
def get_current_language():
"""Return the current selected locale."""
- loc = current_i18n.locale
- return loc.language
+ return current_i18n.locale.language
def get_i18n_supported_languages():
@@ -69,62 +60,6 @@ def remove_empties_from_dict(a_dict):
return new_dict or None
-def create_user_from_data(data):
- """Create a user and set the profile fields from a data.
-
- :param data: A dict containing a mix of patron and user data.
- :returns: The modified dict.
- """
- from .modules.users.api import User
- data = deepcopy(data)
- profile_fields = [
- 'first_name', 'last_name', 'street', 'postal_code', 'gender',
- 'city', 'birth_date', 'username', 'home_phone', 'business_phone',
- 'mobile_phone', 'other_phone', 'keep_history', 'country', 'email',
- 'password'
- ]
- user = User.get_by_username(data.get('username'))
- if not user:
- with db.session.begin_nested():
- # create the user
- password = data.get('password')
- if not password:
- length = current_app.config.get(
- 'RERO_ILS_PASSWORD_MIN_LENGTH', 8)
- special_char = current_app.config.get(
- 'RERO_ILS_PASSWORD_SPECIAL_CHAR')
- password = password_generator(
- length=length, special_char=special_char)
- password = hash_password(password)
- user = BaseUser(password=password, profile=dict(), active=True)
- db.session.add(user)
- # set the user fields
- if data.get('email') is not None:
- user.email = data['email']
- profile = user.profile
- # set the profile
- for field in profile_fields:
- value = data.get(field)
- if value is not None:
- if field == 'birth_date':
- value = datetime.strptime(value, '%Y-%m-%d')
- setattr(profile, field, value)
- db.session.merge(user)
- db.session.commit()
- confirm_user(user)
- user_id = user.id
- else:
- user_id = user.user.id
- # remove the user fields from the data
- for field in profile_fields:
- try:
- del data[field]
- except KeyError:
- pass
- data['user_id'] = user_id
- return data
-
-
def language_iso639_2to1(lang):
"""Convert a bibliographic language to alpha2.
diff --git a/scripts/setup b/scripts/setup
index 77d6db7c6b..b771812ef1 100755
--- a/scripts/setup
+++ b/scripts/setup
@@ -653,6 +653,10 @@ eval ${PREFIX} invenio reroils stats collect librarian
eval ${PREFIX} invenio reroils stats report collect-all month
eval ${PREFIX} invenio reroils stats report collect-all year
+info_msg "Initialize wiki search"
+eval ${PREFIX} invenio flask_wiki init-index
+eval ${PREFIX} invenio flask_wiki index
+
date
success_msg "Perfect ${PROGRAM}! See you soon…"
exit 0
diff --git a/scripts/test b/scripts/test
index 51fbd3d0e0..22f6703efa 100755
--- a/scripts/test
+++ b/scripts/test
@@ -67,35 +67,25 @@ if [[ -z "${VIRTUAL_ENV}" ]]; then
fi
function pretests () {
-# +============================+===========+==========================+==========+
-# | flask | 1.1.4 | <2.2.5 | 55261 |
-# | flask-security | 3.0.0 | <3.1.0 | 45183 |
-# | flask-security | 3.0.0 | >0 | 44501 |
-# | pillow | 9.5.0 | <10.0.1 | 61489 |
-# | sqlalchemy | 1.3.24 | <2.0.0b1 | 51668 |
-# | sqlalchemy-utils | 0.35.0 | >=0.27.0 | 42194 |
-# | wtforms | 2.3.3 | <3.0.0a1 | 42852 |
-# | werkzeug | 1.0.1 | <2.2.3 | 53325 |
-# | werkzeug | 1.0.1 | <2.2.3 | 53326 |
-# | celery | 5.1.2 | <5.2.0 | 42498 |
-# | celery | 5.1.2 | <5.2.2 | 43738 |
-# | click | 7.1.2 | <8.0.0 | 47833 |
-# | cryptography | 39.0.2 | <41.0.0 | 59062 |
-# | cryptography | 39.0.2 | <41.0.2 | 59473 |
-# | cryptography | 39.0.2 | >=0.8,<41.0.3 | 60224 |
-# | cryptography | 39.0.2 | >=0.8,<41.0.3 | 60225 |
-# | cryptography | 39.0.2 | >=0.8,<41.0.3 | 60223 |
-# | py | 1.11.0 | <=1.11.0 | 51457 |
-# | safety | 1.10.3 | <2.2.0 | 51358 |
-# | sentry-sdk | 1.6.0 | <1.14.0 | 53812 |
-# | flask-caching | 2.1.0 | <=2.1.0 | 40459 |
-# | pillow | 9.5.0 | <10.0.0 | 62156 |
-# | werkzeug | 1.0.1 | <2.3.8 | 62019 |
-# | cryptography | 39.0.2 | <41.0.4 | 62451 |
-# | cryptography | 39.0.2 | <41.0.5 | 62452 |
-# | cryptography | 39.0.2 | >=3.1,<41.0.6 | 62556 |
-# +==============================================================================+
- safety check -i 40459 -i 45183 -i 44501 -i 51668 -i 42194 -i 42852 -i 53325 -i 53326 -i 54456 -i 42498 -i 43738 -i 47833 -i 51457 -i 51358 -i 59473 -i 55261 -i 53812 -i 59956 -i 59062 -i 59473 -i 60224 -i 60225 -i 60223 -i 61489 -i 62019 -i 62156 -i 62451 -i 62452 -i 62556
+ # -> Vulnerability found in flask-caching version 2.0.1
+ # Vulnerability ID: 40459
+ # -> Vulnerability found in sqlalchemy version 1.4.50
+ # Vulnerability ID: 51668
+ # -> Vulnerability found in sqlalchemy-utils version 0.38.3
+ # Vulnerability ID: 42194
+ # -> Vulnerability found in wtforms version 2.3.3
+ # Vulnerability ID: 42852
+ # -> Vulnerability found in werkzeug version 2.2.3
+ # Vulnerability ID: 62019
+ # -> Vulnerability found in py version 1.11.0
+ # Vulnerability ID: 51457
+ info_msg "Check vulnerabilities:"
+ safety_exceptions="-i 40459 -i 51668 -i 42194 -i 42852 -i 62019 -i 51457"
+ msg=$(safety check -o text ${safety_exceptions}) || {
+ echo "Safety vulnerabilites found for packages:" $(safety check -o bare ${safety_exceptions})
+ echo "Run:" "safety check -o screen ${safety_exceptions} | grep -i vulnerability" "for more details"
+ exit 1
+ }
info_msg "Check json:"
invenio reroils utils check_json tests/data rero_ils/modules data
info_msg "Check license:"
diff --git a/tests/api/circulation/test_actions_views_checkin.py b/tests/api/circulation/test_actions_views_checkin.py
index 5facaed5fa..9f7ca3bbea 100644
--- a/tests/api/circulation/test_actions_views_checkin.py
+++ b/tests/api/circulation/test_actions_views_checkin.py
@@ -19,7 +19,7 @@
from datetime import date, datetime, timedelta, timezone
from flask import url_for
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from invenio_accounts.testutils import login_user_via_session
from utils import get_json, postdata
@@ -128,7 +128,6 @@ def test_checkin_overdue_item(
item_on_loan_martigny_patron_and_loan_on_loan):
"""Test a checkin for an overdue item with incremental fees."""
- login_user_via_session(client, librarian_martigny.user)
item, patron, loan = item_on_loan_martigny_patron_and_loan_on_loan
# Update the circulation policy corresponding to the loan
@@ -155,6 +154,7 @@ def test_checkin_overdue_item(
# Check overdues preview API and check result
url = url_for('api_loan.preview_loan_overdue', loan_pid=loan.pid)
+ login_user_via_session(client, librarian_martigny.user)
res = client.get(url)
data = get_json(res)
assert res.status_code == 200
diff --git a/tests/api/circulation/test_actions_views_extend_loan_request.py b/tests/api/circulation/test_actions_views_extend_loan_request.py
index dc78e20b31..958c2fc230 100644
--- a/tests/api/circulation/test_actions_views_extend_loan_request.py
+++ b/tests/api/circulation/test_actions_views_extend_loan_request.py
@@ -79,7 +79,6 @@ def test_extend_loan(
item_on_loan_martigny_patron_and_loan_on_loan,
yesterday):
"""Test frontend extend action."""
- login_user_via_session(client, librarian_martigny.user)
item, patron, loan = item_on_loan_martigny_patron_and_loan_on_loan
# Update loan `end_date` to play with "extend" function without problem
loan['end_date'] = loan['start_date']
@@ -98,6 +97,7 @@ def test_extend_loan(
transaction_location_pid=loc_public_martigny.pid
)
+ login_user_via_session(client, librarian_martigny.user)
res, _ = postdata(client, 'api_item.extend_loan', params)
assert res.status_code == 403
diff --git a/tests/api/conftest.py b/tests/api/conftest.py
index 52be5d9dad..c30e220ab7 100644
--- a/tests/api/conftest.py
+++ b/tests/api/conftest.py
@@ -23,7 +23,7 @@
from datetime import datetime
import pytest
-from invenio_accounts.ext import hash_password
+from flask_security.utils import hash_password
from invenio_accounts.models import User
from utils import flush_index
@@ -42,12 +42,14 @@ def user_with_profile(db, default_user_password):
active=True,
)
db.session.add(user)
- profile = user.profile
- profile.birth_date = datetime(1990, 1, 1)
- profile.first_name = 'User'
- profile.last_name = 'With Profile'
- profile.city = 'Nowhere'
+ profile = dict(
+ birth_date=datetime(1990, 1, 1),
+ first_name='User',
+ last_name='With Profile',
+ city='Nowhere'
+ )
profile.username = 'user_with_profile'
+ user.user_profile = profile
db.session.merge(user)
db.session.commit()
return user
diff --git a/tests/api/items/test_items_rest.py b/tests/api/items/test_items_rest.py
index 340875163d..c033e08874 100644
--- a/tests/api/items/test_items_rest.py
+++ b/tests/api/items/test_items_rest.py
@@ -908,7 +908,6 @@ def test_requested_loans_to_validate(
item_type_standard_martigny, item2_lib_martigny, json_header,
item_type_missing_martigny, patron_sion, circulation_policies):
"""Test requested loans to validate."""
- login_user_via_session(client, librarian_martigny.user)
holding_pid = item2_lib_martigny.holding_pid
holding = Holding.get_record_by_pid(holding_pid)
@@ -933,6 +932,7 @@ def test_requested_loans_to_validate(
library_pid = librarian_martigny.replace_refs()['libraries'][0]['pid']
+ login_user_via_session(client, librarian_martigny.user)
res, _ = postdata(
client,
'api_item.librarian_request',
diff --git a/tests/api/items/test_items_serializer.py b/tests/api/items/test_items_serializer.py
index fab7f8de89..6f471364ac 100644
--- a/tests/api/items/test_items_serializer.py
+++ b/tests/api/items/test_items_serializer.py
@@ -25,7 +25,6 @@
def test_serializers(
client,
- db,
item_lib_martigny, # on shelf
document,
item_lib_fully, # on loan
@@ -122,11 +121,6 @@ def test_serializers(
data = get_csv(response)
assert data
- document['provisionActivity'][0]['type'] = 'bf:Publication'
- db.session.rollback()
- # restore initial item on Elasticsearch
- item.reindex()
-
# with temporary_item_type
item_type = item_type_on_site_martigny
circulation = [
@@ -143,13 +137,8 @@ def test_serializers(
}
item.commit()
item.reindex()
-
list_url = url_for('invenio_records_rest.item_list', q=f'pid:{item.pid}')
response = client.get(list_url, headers=rero_json_header)
data = response.json['hits']['hits']
assert circulation == \
data[0]['metadata']['item_type']['circulation_information']
-
- db.session.rollback()
- item_type.reindex()
- item.reindex()
diff --git a/tests/api/loans/test_loans_rest.py b/tests/api/loans/test_loans_rest.py
index bfe80232dd..d1a649f9c8 100644
--- a/tests/api/loans/test_loans_rest.py
+++ b/tests/api/loans/test_loans_rest.py
@@ -528,8 +528,6 @@ def test_timezone_due_date(client, librarian_martigny,
circ_policy_short_martigny,
lib_martigny):
"""Test that timezone affects due date regarding library location."""
- # Login to perform action
- login_user_via_session(client, librarian_martigny.user)
# Close the library all days. Except Monday.
del lib_martigny['exception_dates']
@@ -596,6 +594,8 @@ def test_timezone_due_date(client, librarian_martigny,
dbcommit=True,
reindex=True
)
+ # Login to perform action
+ login_user_via_session(client, librarian_martigny.user)
# Checkout the item
res, data = postdata(
diff --git a/tests/api/loans/test_loans_rest_views.py b/tests/api/loans/test_loans_rest_views.py
index be5ab23f81..3f18e54ad1 100644
--- a/tests/api/loans/test_loans_rest_views.py
+++ b/tests/api/loans/test_loans_rest_views.py
@@ -30,7 +30,6 @@ def test_loan_can_extend(client, patron_martigny, item_lib_martigny,
loc_public_martigny, librarian_martigny,
circulation_policies, json_header):
"""Test is loan can extend."""
- login_user(client, patron_martigny)
params = {
'patron_pid': patron_martigny.pid,
'transaction_location_pid': loc_public_martigny.pid,
@@ -43,6 +42,7 @@ def test_loan_can_extend(client, patron_martigny, item_lib_martigny,
list_url = url_for(
'api_loan.can_extend', loan_pid=loan.pid)
+ login_user(client, patron_martigny)
response = client.get(list_url, headers=json_header)
assert response.status_code == 200
assert get_json(response) == {
diff --git a/tests/api/notifications/test_notifications_rest.py b/tests/api/notifications/test_notifications_rest.py
index f0cdc13633..3a24993298 100644
--- a/tests/api/notifications/test_notifications_rest.py
+++ b/tests/api/notifications/test_notifications_rest.py
@@ -784,11 +784,11 @@ def test_request_notifications_temp_item_type(
):
"""Test request notifications with item type with negative availability."""
mailbox.clear()
- login_user_via_session(client, librarian_martigny.user)
item_lib_martigny['temporary_item_type'] = {
- '$ref': get_ref_for_pid('itty', item_type_missing_martigny.pid)
+ '$ref': get_ref_for_pid('itty', item_type_missing_martigny.pid)
}
item_lib_martigny.update(item_lib_martigny, dbcommit=True, reindex=True)
+ login_user_via_session(client, librarian_martigny.user)
res, data = postdata(
client,
diff --git a/tests/api/operation_logs/test_operation_logs_rest.py b/tests/api/operation_logs/test_operation_logs_rest.py
index 7fd3144fc3..f15ca22e38 100644
--- a/tests/api/operation_logs/test_operation_logs_rest.py
+++ b/tests/api/operation_logs/test_operation_logs_rest.py
@@ -105,7 +105,6 @@ def test_operation_log_on_item(
item_lib_martigny
):
"""Test operation log on Item."""
- login_user_via_session(client, librarian_martigny.user)
# Get the operation log index
fake_data = {'date': datetime.now().isoformat()}
@@ -119,6 +118,7 @@ def test_operation_log_on_item(
q = f'record.type:item AND record.value:{item.pid}'
es_url = url_for('invenio_records_rest.oplg_list', q=q, sort='mostrecent')
+ login_user_via_session(client, librarian_martigny.user)
res = client.get(es_url)
data = get_json(res)
assert data['hits']['total']['value'] == 1
diff --git a/tests/api/patrons/test_patrons_marshmallow.py b/tests/api/patrons/test_patrons_marshmallow.py
index 2656fab1f1..9adc188374 100644
--- a/tests/api/patrons/test_patrons_marshmallow.py
+++ b/tests/api/patrons/test_patrons_marshmallow.py
@@ -24,8 +24,8 @@
from utils import postdata
from rero_ils.modules.patrons.api import Patron
+from rero_ils.modules.patrons.utils import create_user_from_data
from rero_ils.modules.users.models import UserRole
-from rero_ils.utils import create_user_from_data
def test_patrons_marshmallow_loaders(
@@ -38,6 +38,8 @@ def test_patrons_marshmallow_loaders(
# Using 'console' commands, no matter connected user, all operations are
# allowed on a Patron, even changes any roles.
user_data = create_user_from_data(system_librarian_martigny_data_tmp)
+ from rero_ils.modules.users.api import User
+ user_data = User.remove_fields(user_data)
patron = Patron.create(user_data, dbcommit=True, reindex=True)
assert patron and patron['roles'] == [UserRole.FULL_PERMISSIONS]
diff --git a/tests/api/patrons/test_patrons_rest.py b/tests/api/patrons/test_patrons_rest.py
index 53e37713ba..866e76efaa 100644
--- a/tests/api/patrons/test_patrons_rest.py
+++ b/tests/api/patrons/test_patrons_rest.py
@@ -32,8 +32,8 @@
from rero_ils.modules.patron_transactions.api import PatronTransaction
from rero_ils.modules.patrons.api import Patron
from rero_ils.modules.patrons.models import CommunicationChannel
+from rero_ils.modules.patrons.utils import create_user_from_data
from rero_ils.modules.utils import extracted_data_from_ref, get_ref_for_pid
-from rero_ils.utils import create_user_from_data
def test_patrons_shortcuts(
diff --git a/tests/api/stats/conftest.py b/tests/api/stats/conftest.py
index 12e17bf7b5..07914145c4 100644
--- a/tests/api/stats/conftest.py
+++ b/tests/api/stats/conftest.py
@@ -62,7 +62,7 @@ def stats_librarian(item_lib_martigny, item_lib_fully, item_lib_sion):
@pytest.fixture(scope='module')
-def stats_report_martigny(stats_cfg_martigny):
+def stats_report_martigny(stats_cfg_martigny, item_lib_martigny):
"""Stats fixture for librarian."""
stat_report = StatsReport(stats_cfg_martigny)
values = stat_report.collect()
diff --git a/tests/api/test_serializers.py b/tests/api/test_serializers.py
index 0a817fdf46..ae8fec2b66 100644
--- a/tests/api/test_serializers.py
+++ b/tests/api/test_serializers.py
@@ -38,7 +38,6 @@ def test_operation_logs_serializers(
lib_martigny_data
):
"""Test serializers for operation logs."""
- login_user(client, patron_martigny)
params = {
'patron_pid': patron_martigny.pid,
'transaction_location_pid': loc_public_martigny.pid,
@@ -51,6 +50,7 @@ def test_operation_logs_serializers(
# Force update ES index
flush_index(OperationLogsSearch.Meta.index)
list_url = url_for('invenio_records_rest.oplg_list')
+ login_user(client, patron_martigny)
response = client.get(list_url, headers=rero_json_header)
assert response.status_code == 200
data = get_json(response)
@@ -132,7 +132,6 @@ def test_loans_serializers(
circulation_policies
):
"""Test serializers for loans."""
- login_user(client, patron_martigny)
# create somes loans on same item with different state
params = {
'patron_pid': patron_martigny.pid,
@@ -162,6 +161,7 @@ def test_loans_serializers(
params=params, copy_item=True)
list_url = url_for('invenio_records_rest.loanid_list')
+ login_user(client, patron_martigny)
response = client.get(list_url, headers=rero_json_header)
assert response.status_code == 200
data = get_json(response)
diff --git a/tests/api/test_translations.py b/tests/api/test_translations.py
index a77d4886a7..bf0c57b091 100644
--- a/tests/api/test_translations.py
+++ b/tests/api/test_translations.py
@@ -16,7 +16,6 @@
# along with this program. If not, see .
"""Test translations API."""
-import mock
from flask import url_for
from utils import get_json
@@ -46,17 +45,13 @@ def test_translations_exceptions(client, app):
# ... class FakeDomain(object):
# ... paths = []
#
- magic_mock = mock.MagicMock(return_value=type(
- 'FakeDomain', (object,), dict(paths=[])
- ))
- with mock.patch('rero_ils.modules.views.get_domain', magic_mock):
- res = client.get(
- url_for(
- 'api_blueprint.translations',
- ln='dummy_language'
- )
+ res = client.get(
+ url_for(
+ 'api_blueprint.translations',
+ ln='dummy_language'
)
- assert res.status_code == 404
+ )
+ assert res.status_code == 404
res = client.get(
url_for(
diff --git a/tests/api/test_user_authentication.py b/tests/api/test_user_authentication.py
index 7aa3b1c480..b6cbb5d2f4 100644
--- a/tests/api/test_user_authentication.py
+++ b/tests/api/test_user_authentication.py
@@ -19,7 +19,7 @@
import re
from flask import url_for
-from flask_babelex import gettext
+from flask_babel import gettext
from flask_security.recoverable import send_password_reset_notice
from invenio_accounts.testutils import login_user_via_session
from utils import get_json, postdata
diff --git a/tests/api/users/test_users_rest.py b/tests/api/users/test_users_rest.py
index 791af0079f..53d80b7c9d 100644
--- a/tests/api/users/test_users_rest.py
+++ b/tests/api/users/test_users_rest.py
@@ -41,18 +41,7 @@ def test_users_post_put(client, user_data_tmp, librarian_martigny,
assert res.status_code == 401
login_user_via_session(client, librarian_martigny.user)
-
- # test invalid create
- user_data_tmp['toto'] = 'toto'
- res, data = postdata(
- client,
- 'api_users.users_list',
- user_data_tmp
- )
- assert res.status_code == 400
-
# test with invalid password
- user_data_tmp.pop('toto')
user_data_tmp['first_name'] = 1
user_data_tmp['password'] = '12345'
res, data = postdata(
diff --git a/tests/conftest.py b/tests/conftest.py
index f6c4f255da..e32c6266ae 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -27,7 +27,7 @@
from dotenv import load_dotenv
pytest_plugins = (
- # 'celery.contrib.pytest',
+ 'celery.contrib.pytest',
'fixtures.circulation',
'fixtures.metadata',
'fixtures.organisations',
@@ -39,7 +39,7 @@
@pytest.fixture(scope='module')
-def es(appctx):
+def search(appctx):
"""Setup and teardown all registered Elasticsearch indices.
Scope: module
diff --git a/tests/data/data.json b/tests/data/data.json
index 94cf02f374..47d6d94936 100644
--- a/tests/data/data.json
+++ b/tests/data/data.json
@@ -5187,7 +5187,6 @@
"first_name": "John",
"last_name": "Smith",
"birth_date": "1974-03-21",
- "username": "smith_john",
"street": "1600 Donald Trump Avenue NW",
"postal_code": "20500",
"city": "Washington, D.C.",
diff --git a/tests/ui/acq_accounts/test_acq_accounts_jsonresolver.py b/tests/ui/acq_accounts/test_acq_accounts_jsonresolver.py
index c3aacc6320..7756f42865 100644
--- a/tests/ui/acq_accounts/test_acq_accounts_jsonresolver.py
+++ b/tests/ui/acq_accounts/test_acq_accounts_jsonresolver.py
@@ -34,11 +34,11 @@ def test_acq_accounts_jsonresolver(acq_account_fiction_martigny):
# deleted record
acq_account_fiction_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'acq_account': {'$ref': 'https://bib.rero.ch/api/acq_accounts/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/acq_accounts/test_acq_accounts_mapping.py b/tests/ui/acq_accounts/test_acq_accounts_mapping.py
index c864d4f3ba..3fd0c871f0 100644
--- a/tests/ui/acq_accounts/test_acq_accounts_mapping.py
+++ b/tests/ui/acq_accounts/test_acq_accounts_mapping.py
@@ -22,7 +22,7 @@
AcqAccountsSearch
-def test_acq_accounts_es_mapping(es, db, acq_account_fiction_martigny_data,
+def test_acq_accounts_es_mapping(search, db, acq_account_fiction_martigny_data,
budget_2020_martigny, lib_martigny):
"""Test acquisition account elasticsearch mapping."""
search = AcqAccountsSearch()
diff --git a/tests/ui/acq_invoices/test_acq_invoices_jsonresolver.py b/tests/ui/acq_invoices/test_acq_invoices_jsonresolver.py
index 2272277522..a1d3ad3de6 100644
--- a/tests/ui/acq_invoices/test_acq_invoices_jsonresolver.py
+++ b/tests/ui/acq_invoices/test_acq_invoices_jsonresolver.py
@@ -33,11 +33,11 @@ def test_acq_invoices_jsonresolver(acq_invoice_fiction_martigny):
# deleted record
acq_invoice_fiction_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'acq_invoice': {'$ref': 'https://bib.rero.ch/api/acq_invoices/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/acq_order_lines/test_acq_order_lines_jsonresolver.py b/tests/ui/acq_order_lines/test_acq_order_lines_jsonresolver.py
index 64cde10dbd..33d78db057 100644
--- a/tests/ui/acq_order_lines/test_acq_order_lines_jsonresolver.py
+++ b/tests/ui/acq_order_lines/test_acq_order_lines_jsonresolver.py
@@ -36,7 +36,7 @@ def test_acq_order_lines_jsonresolver(
# deleted record
acq_order_line_fiction_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
@@ -45,4 +45,4 @@ def test_acq_order_lines_jsonresolver(
}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/acq_orders/test_acq_orders_jsonresolver.py b/tests/ui/acq_orders/test_acq_orders_jsonresolver.py
index 896a8573f7..95951030ab 100644
--- a/tests/ui/acq_orders/test_acq_orders_jsonresolver.py
+++ b/tests/ui/acq_orders/test_acq_orders_jsonresolver.py
@@ -33,11 +33,11 @@ def test_acq_orders_jsonresolver(acq_order_fiction_martigny):
# deleted record
acq_order_fiction_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'acq_order': {'$ref': 'https://bib.rero.ch/api/acq_orders/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/acq_orders/test_acq_orders_mapping.py b/tests/ui/acq_orders/test_acq_orders_mapping.py
index 6b346ee2ce..2d6dc393f3 100644
--- a/tests/ui/acq_orders/test_acq_orders_mapping.py
+++ b/tests/ui/acq_orders/test_acq_orders_mapping.py
@@ -22,7 +22,7 @@
AcqOrdersSearch
-def test_acq_orders_es_mapping(es, db, lib_martigny, vendor_martigny,
+def test_acq_orders_es_mapping(search, db, lib_martigny, vendor_martigny,
acq_order_fiction_martigny_data):
"""Test acquisition orders elasticsearch mapping."""
search = AcqOrdersSearch()
diff --git a/tests/ui/acq_receipt_lines/test_acq_receipt_lines_jsonresolver.py b/tests/ui/acq_receipt_lines/test_acq_receipt_lines_jsonresolver.py
index eb1ad7f601..6e8083675d 100644
--- a/tests/ui/acq_receipt_lines/test_acq_receipt_lines_jsonresolver.py
+++ b/tests/ui/acq_receipt_lines/test_acq_receipt_lines_jsonresolver.py
@@ -33,10 +33,10 @@ def test_acq_receipt_lines_jsonresolver(acq_receipt_line_1_fiction_martigny):
# deleted record
acq_receipt_line_1_fiction_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
data = {'$ref': 'https://bib.rero.ch/api/acq_receipt_lines/n_e'}
rec = Record.create({'acq_receipt_line': data})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/acq_receipt_lines/test_acq_receipt_lines_mapping.py b/tests/ui/acq_receipt_lines/test_acq_receipt_lines_mapping.py
index b2990ec8d6..9c0ab13f65 100644
--- a/tests/ui/acq_receipt_lines/test_acq_receipt_lines_mapping.py
+++ b/tests/ui/acq_receipt_lines/test_acq_receipt_lines_mapping.py
@@ -23,10 +23,11 @@
AcqReceiptLine, AcqReceiptLinesSearch
-def test_acq_receipt_lines_es_mapping(es, db, lib_martigny, vendor_martigny,
- acq_receipt_line_1_fiction_martigny,
- acq_receipt_line_1_fiction_martigny_data
- ):
+def test_acq_receipt_lines_es_mapping(
+ search, db, lib_martigny, vendor_martigny,
+ acq_receipt_line_1_fiction_martigny,
+ acq_receipt_line_1_fiction_martigny_data
+):
"""Test acquisition receipt lines elasticsearch mapping."""
search = AcqReceiptLinesSearch()
mapping = get_mapping(search.Meta.index)
diff --git a/tests/ui/acq_receipts/test_acq_receipts_jsonresolver.py b/tests/ui/acq_receipts/test_acq_receipts_jsonresolver.py
index 779beced36..75c1246b59 100644
--- a/tests/ui/acq_receipts/test_acq_receipts_jsonresolver.py
+++ b/tests/ui/acq_receipts/test_acq_receipts_jsonresolver.py
@@ -33,10 +33,10 @@ def test_acq_receipts_jsonresolver(acq_receipt_fiction_martigny):
# deleted record
acq_receipt_fiction_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
data = {'$ref': 'https://bib.rero.ch/api/acq_receipts/n_e'}
rec = Record.create({'acq_receipt': data})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/acq_receipts/test_acq_receipts_mapping.py b/tests/ui/acq_receipts/test_acq_receipts_mapping.py
index 51879ccc95..dfe1099239 100644
--- a/tests/ui/acq_receipts/test_acq_receipts_mapping.py
+++ b/tests/ui/acq_receipts/test_acq_receipts_mapping.py
@@ -23,7 +23,7 @@
AcqReceiptsSearch
-def test_acq_receipts_es_mapping(es, db, lib_martigny, vendor_martigny,
+def test_acq_receipts_es_mapping(search, db, lib_martigny, vendor_martigny,
acq_order_fiction_martigny,
acq_account_fiction_martigny,
acq_receipt_fiction_martigny_data):
diff --git a/tests/ui/budgets/test_budgets_jsonresolver.py b/tests/ui/budgets/test_budgets_jsonresolver.py
index 662487468e..4144d62481 100644
--- a/tests/ui/budgets/test_budgets_jsonresolver.py
+++ b/tests/ui/budgets/test_budgets_jsonresolver.py
@@ -34,11 +34,11 @@ def test_budgets_jsonresolver(budget_2017_martigny):
# deleted record
budget_2017_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'budget': {'$ref': 'https://bib.rero.ch/api/budgets/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/budgets/test_budgets_mapping.py b/tests/ui/budgets/test_budgets_mapping.py
index f72c57fdc0..a4ebd9acae 100644
--- a/tests/ui/budgets/test_budgets_mapping.py
+++ b/tests/ui/budgets/test_budgets_mapping.py
@@ -21,7 +21,9 @@
from rero_ils.modules.acquisition.budgets.api import Budget, BudgetsSearch
-def test_budgets_es_mapping(es, db, org_martigny, budget_2017_martigny_data):
+def test_budgets_es_mapping(
+ search, db, org_martigny, budget_2017_martigny_data
+):
"""Test acquisition budget elasticsearch mapping."""
search = BudgetsSearch()
mapping = get_mapping(search.Meta.index)
diff --git a/tests/ui/collections/test_collections_mapping.py b/tests/ui/collections/test_collections_mapping.py
index 24e1bf6fef..98a959ca29 100644
--- a/tests/ui/collections/test_collections_mapping.py
+++ b/tests/ui/collections/test_collections_mapping.py
@@ -21,7 +21,7 @@
from rero_ils.modules.collections.api import Collection, CollectionsSearch
-def test_collections_es_mapping(es, db, org_martigny, coll_martigny_1_data,
+def test_collections_es_mapping(search, db, org_martigny, coll_martigny_1_data,
item_lib_martigny, item2_lib_martigny):
"""Test collections elasticsearch mapping."""
search = CollectionsSearch()
diff --git a/tests/ui/conftest.py b/tests/ui/conftest.py
index 91585a0621..67bdaa2bf8 100644
--- a/tests/ui/conftest.py
+++ b/tests/ui/conftest.py
@@ -17,11 +17,8 @@
"""Common pytest fixtures and plugins."""
-
-from datetime import datetime
-
import pytest
-from invenio_accounts.ext import hash_password
+from flask_security.utils import hash_password
from invenio_accounts.models import User
from invenio_search import current_search_client
@@ -30,20 +27,20 @@
def user_with_profile(db, default_user_password):
"""Create a simple invenio user with a profile."""
with db.session.begin_nested():
+ profile = dict(
+ birth_date='1990-01-01',
+ first_name='User',
+ last_name='With Profile',
+ city='Nowhere'
+ )
user = User(
email='user_with_profile@test.com',
+ username='user_with_profile',
password=hash_password(default_user_password),
- profile={},
+ user_profile=profile,
active=True,
)
db.session.add(user)
- profile = user.profile
- profile.birth_date = datetime(1990, 1, 1)
- profile.first_name = 'User'
- profile.last_name = 'With Profile'
- profile.city = 'Nowhere'
- profile.username = 'user_with_profile'
- db.session.merge(user)
db.session.commit()
user.password_plaintext = default_user_password
return user
@@ -53,19 +50,19 @@ def user_with_profile(db, default_user_password):
def user_without_email(db, default_user_password):
"""Create a simple invenio user without email."""
with db.session.begin_nested():
+ profile = dict(
+ birth_date='1990-01-01',
+ first_name='User',
+ last_name='With Profile',
+ city='Nowhere'
+ )
user = User(
password=hash_password(default_user_password),
- profile={},
+ user_profile=profile,
+ username='user_without_email',
active=True,
)
db.session.add(user)
- profile = user.profile
- profile.birth_date = datetime(1990, 1, 1)
- profile.first_name = 'User'
- profile.last_name = 'With Profile'
- profile.city = 'Nowhere'
- profile.username = 'user_without_email'
- db.session.merge(user)
db.session.commit()
user.password_plaintext = default_user_password
return user
diff --git a/tests/ui/documents/test_documents_api.py b/tests/ui/documents/test_documents_api.py
index 2ac96c389f..7e119a7ff4 100644
--- a/tests/ui/documents/test_documents_api.py
+++ b/tests/ui/documents/test_documents_api.py
@@ -355,6 +355,11 @@ def test_document_indexing(document, export_document):
]
assert record.partOf[0].document.title == parent_titles.pop()
+ # check updated created should exists
+ record = next(s.source(['_updated', '_created']).scan())
+ assert record._updated
+ assert record._created
+
# restore initial data
document['title'].pop(-1)
document['title'][0]['mainTitle'][1]['value'] = orig_title
diff --git a/tests/ui/documents/test_documents_jsonresolver.py b/tests/ui/documents/test_documents_jsonresolver.py
index 330320d714..b8b28a8a83 100644
--- a/tests/ui/documents/test_documents_jsonresolver.py
+++ b/tests/ui/documents/test_documents_jsonresolver.py
@@ -32,11 +32,11 @@ def test_documents_jsonresolver(document):
# deleted record
document.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'document': {'$ref': 'https://bib.rero.ch/api/documents/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/documents/test_documents_mapping.py b/tests/ui/documents/test_documents_mapping.py
index 9f9bb5ebc0..e5ad3c458c 100644
--- a/tests/ui/documents/test_documents_mapping.py
+++ b/tests/ui/documents/test_documents_mapping.py
@@ -27,9 +27,11 @@
@mock.patch('requests.Session.get')
-def test_document_es_mapping(mock_contributions_mef_get, es, db, org_martigny,
- document_data_ref, item_lib_martigny,
- entity_person_response_data):
+def test_document_es_mapping(
+ mock_contributions_mef_get, search, db, org_martigny,
+ document_data_ref, item_lib_martigny,
+ entity_person_response_data
+):
"""Test document elasticsearch mapping."""
search = DocumentsSearch()
mapping = get_mapping(search.Meta.index)
diff --git a/tests/ui/entities/local_entities/test_local_entities_jsonresolver.py b/tests/ui/entities/local_entities/test_local_entities_jsonresolver.py
index f233f37f61..2e272d16e4 100644
--- a/tests/ui/entities/local_entities/test_local_entities_jsonresolver.py
+++ b/tests/ui/entities/local_entities/test_local_entities_jsonresolver.py
@@ -37,11 +37,11 @@ def test_local_entities_jsonresolver(local_entity_person2):
# deleted record
local_entity_person2.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'local_entity': {'$ref': 'https://bib.rero.ch/api/local_entities/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/holdings/test_holdings_api.py b/tests/ui/holdings/test_holdings_api.py
index 0e136928c4..0ddb8bc724 100644
--- a/tests/ui/holdings/test_holdings_api.py
+++ b/tests/ui/holdings/test_holdings_api.py
@@ -32,7 +32,7 @@
delete_standard_holdings_having_no_items
-def test_holding_create(db, es, document, org_martigny,
+def test_holding_create(db, search, document, org_martigny,
loc_public_martigny, item_type_standard_martigny,
holding_lib_martigny_data):
"""Test holding creation."""
diff --git a/tests/ui/holdings/test_holdings_jsonresolver.py b/tests/ui/holdings/test_holdings_jsonresolver.py
index 42b987e608..10fc5fa885 100644
--- a/tests/ui/holdings/test_holdings_jsonresolver.py
+++ b/tests/ui/holdings/test_holdings_jsonresolver.py
@@ -35,11 +35,11 @@ def test_holdings_jsonresolver(holding_lib_martigny):
# deleted record
holding_lib_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'holding': {'$ref': 'https://bib.rero.ch/api/holdings/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/holdings/test_holdings_mapping.py b/tests/ui/holdings/test_holdings_mapping.py
index 8ca1852727..7267013358 100644
--- a/tests/ui/holdings/test_holdings_mapping.py
+++ b/tests/ui/holdings/test_holdings_mapping.py
@@ -21,7 +21,7 @@
from rero_ils.modules.holdings.api import Holding, HoldingsSearch
-def test_holding_es_mapping(es, db, loc_public_martigny,
+def test_holding_es_mapping(search, db, loc_public_martigny,
item_type_standard_martigny,
document, holding_lib_martigny_data):
"""Test holding elasticsearch mapping."""
diff --git a/tests/ui/ill_requests/test_ill_requests_jsonresolver.py b/tests/ui/ill_requests/test_ill_requests_jsonresolver.py
index 23e5e9f20d..352286fed8 100644
--- a/tests/ui/ill_requests/test_ill_requests_jsonresolver.py
+++ b/tests/ui/ill_requests/test_ill_requests_jsonresolver.py
@@ -34,11 +34,11 @@ def test_ill_requests_jsonresolver(ill_request_martigny):
# deleted record
ill_request_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'ill_request': {'$ref': 'https://bib.rero.ch/api/ill_requests/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/item_types/test_item_types_jsonresolver.py b/tests/ui/item_types/test_item_types_jsonresolver.py
index eea297df5d..93c0435106 100644
--- a/tests/ui/item_types/test_item_types_jsonresolver.py
+++ b/tests/ui/item_types/test_item_types_jsonresolver.py
@@ -34,11 +34,11 @@ def test_item_types_jsonresolver(item_type_standard_martigny):
# deleted record
item_type_standard_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'item_type': {'$ref': 'https://bib.rero.ch/api/item_types/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/item_types/test_item_types_mapping.py b/tests/ui/item_types/test_item_types_mapping.py
index 1f2d54e2f4..6f6e95075f 100644
--- a/tests/ui/item_types/test_item_types_mapping.py
+++ b/tests/ui/item_types/test_item_types_mapping.py
@@ -24,7 +24,7 @@
from rero_ils.modules.item_types.api import ItemType, ItemTypesSearch
-def test_item_type_es_mapping(es, db, org_martigny, item_type_data_tmp):
+def test_item_type_es_mapping(search, db, org_martigny, item_type_data_tmp):
"""Test item type elasticsearch mapping."""
search = ItemTypesSearch()
mapping = get_mapping(search.Meta.index)
diff --git a/tests/ui/items/test_items_jsonresolver.py b/tests/ui/items/test_items_jsonresolver.py
index 85632c7730..ee1531c0af 100644
--- a/tests/ui/items/test_items_jsonresolver.py
+++ b/tests/ui/items/test_items_jsonresolver.py
@@ -32,11 +32,11 @@ def test_items_jsonresolver(item_lib_martigny):
# deleted record
item_lib_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'item': {'$ref': 'https://bib.rero.ch/api/items/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/libraries/test_libraries_jsonresolver.py b/tests/ui/libraries/test_libraries_jsonresolver.py
index dc30c6c481..b3aa884433 100644
--- a/tests/ui/libraries/test_libraries_jsonresolver.py
+++ b/tests/ui/libraries/test_libraries_jsonresolver.py
@@ -33,11 +33,11 @@ def test_libraries_jsonresolver(lib_martigny):
# deleted record
library.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'library': {'$ref': 'https://bib.rero.ch/api/libraries/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/libraries/test_libraries_mapping.py b/tests/ui/libraries/test_libraries_mapping.py
index 0c064fd4f5..1ecaac7146 100644
--- a/tests/ui/libraries/test_libraries_mapping.py
+++ b/tests/ui/libraries/test_libraries_mapping.py
@@ -22,7 +22,7 @@
from rero_ils.modules.libraries.api import LibrariesSearch, Library
-def test_library_es_mapping(es, db, lib_martigny_data, org_martigny):
+def test_library_es_mapping(search, db, lib_martigny_data, org_martigny):
"""Test library elasticsearch mapping."""
search = LibrariesSearch()
mapping = get_mapping(search.Meta.index)
diff --git a/tests/ui/loans/test_loans_jsonresolver.py b/tests/ui/loans/test_loans_jsonresolver.py
index 16c715e22e..8cb45f2631 100644
--- a/tests/ui/loans/test_loans_jsonresolver.py
+++ b/tests/ui/loans/test_loans_jsonresolver.py
@@ -32,11 +32,11 @@ def test_loans_jsonresolver(loan_pending_martigny):
# deleted record
loan_pending_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'loan': {'$ref': 'https://bib.rero.ch/api/loans/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/local_fields/test_local_fields_jsonresolver.py b/tests/ui/local_fields/test_local_fields_jsonresolver.py
index 71f7f374f5..bda88b0eb3 100644
--- a/tests/ui/local_fields/test_local_fields_jsonresolver.py
+++ b/tests/ui/local_fields/test_local_fields_jsonresolver.py
@@ -35,11 +35,11 @@ def test_local_field_jsonresolver(local_field_martigny):
# deleted record
local_field.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'local_fields': {'$ref': 'https://bib.rero.ch/api/local_fields/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/locations/test_locations_jsonresolver.py b/tests/ui/locations/test_locations_jsonresolver.py
index 3b7fd72916..f38c76f9ac 100644
--- a/tests/ui/locations/test_locations_jsonresolver.py
+++ b/tests/ui/locations/test_locations_jsonresolver.py
@@ -32,11 +32,11 @@ def test_locations_jsonresolver(loc_public_martigny):
# deleted record
loc_public_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'location': {'$ref': 'https://bib.rero.ch/api/locations/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/locations/test_locations_mapping.py b/tests/ui/locations/test_locations_mapping.py
index c459f36132..efa5b00eb9 100644
--- a/tests/ui/locations/test_locations_mapping.py
+++ b/tests/ui/locations/test_locations_mapping.py
@@ -22,7 +22,7 @@
from rero_ils.modules.locations.api import Location, LocationsSearch
-def test_location_es_mapping(es, db, loc_public_martigny_data,
+def test_location_es_mapping(search, db, loc_public_martigny_data,
lib_martigny, org_martigny):
"""Test library elasticsearch mapping."""
search = LocationsSearch()
diff --git a/tests/ui/organisations/test_organisations_jsonresolver.py b/tests/ui/organisations/test_organisations_jsonresolver.py
index c3b9e8f0f0..6bbb5c62fc 100644
--- a/tests/ui/organisations/test_organisations_jsonresolver.py
+++ b/tests/ui/organisations/test_organisations_jsonresolver.py
@@ -34,11 +34,11 @@ def test_organisations_jsonresolver(app, organisation_temp):
# deleted record
organisation_temp.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'organisation': {'$ref': 'https://bib.rero.ch/api/organisations/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/patron_transaction_events/test_patron_transaction_events_jsonresolver.py b/tests/ui/patron_transaction_events/test_patron_transaction_events_jsonresolver.py
index 91b25d45ff..036b14b33f 100644
--- a/tests/ui/patron_transaction_events/test_patron_transaction_events_jsonresolver.py
+++ b/tests/ui/patron_transaction_events/test_patron_transaction_events_jsonresolver.py
@@ -38,7 +38,7 @@ def test_patron_transaction_event_jsonresolver(
# deleted record
patron_transaction_overdue_event_saxon.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create(
@@ -48,4 +48,4 @@ def test_patron_transaction_event_jsonresolver(
'https://bib.rero.ch/api/patron_transaction_events/n_e'}}
)
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/patron_transactions/test_patron_transactions_jsonresolver.py b/tests/ui/patron_transactions/test_patron_transactions_jsonresolver.py
index 48bb19c90d..7be124de9b 100644
--- a/tests/ui/patron_transactions/test_patron_transactions_jsonresolver.py
+++ b/tests/ui/patron_transactions/test_patron_transactions_jsonresolver.py
@@ -40,7 +40,7 @@ def test_patron_transaction_jsonresolver(patron_transaction_overdue_martigny):
# deleted record
patron_transaction_overdue_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create(
@@ -49,4 +49,4 @@ def test_patron_transaction_jsonresolver(patron_transaction_overdue_martigny):
'$ref': 'https://bib.rero.ch/api/patron_transactions/n_e'}}
)
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/patron_types/test_patron_types_jsonresolver.py b/tests/ui/patron_types/test_patron_types_jsonresolver.py
index b2d61df6a3..95b26c9fbe 100644
--- a/tests/ui/patron_types/test_patron_types_jsonresolver.py
+++ b/tests/ui/patron_types/test_patron_types_jsonresolver.py
@@ -34,11 +34,11 @@ def test_patron_types_jsonresolver(app, patron_type_tmp):
# deleted record
patron_type_tmp.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'patron_type': {'$ref': 'https://bib.rero.ch/api/patron_types/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/patrons/test_patrons_api.py b/tests/ui/patrons/test_patrons_api.py
index d699be295f..dac76d5134 100644
--- a/tests/ui/patrons/test_patrons_api.py
+++ b/tests/ui/patrons/test_patrons_api.py
@@ -28,8 +28,8 @@
from rero_ils.modules.patrons.api import Patron, PatronsSearch, \
patron_id_fetcher
from rero_ils.modules.patrons.models import CommunicationChannel
+from rero_ils.modules.patrons.utils import create_user_from_data
from rero_ils.modules.users.models import UserRole
-from rero_ils.utils import create_user_from_data
def test_patron_extended_validation(app, patron_martigny,
@@ -157,9 +157,10 @@ def test_patron_create(app, roles, lib_martigny, librarian_martigny_data_tmp,
user = User.query.filter_by(id=ptrn.get('user_id')).first()
assert user and user.active
for field in ['first_name', 'last_name', 'street', 'postal_code', 'city',
- 'username', 'home_phone']:
- assert getattr(user.profile, field) == l_martigny_data_tmp.get(field)
- assert user.profile.birth_date.strftime('%Y-%m-%d') == \
+ 'home_phone']:
+ assert user.user_profile.get(field) == l_martigny_data_tmp.get(field)
+ assert user.username == l_martigny_data_tmp.get('username')
+ assert user.user_profile.get('birth_date') == \
l_martigny_data_tmp.get('birth_date')
user_roles = [r.name for r in user.roles]
assert set(user_roles) == set(ptrn.get('roles'))
@@ -237,6 +238,8 @@ def test_patron_create_without_email(app, roles, patron_type_children_martigny,
patron_martigny_data_tmp = \
create_user_from_data(patron_martigny_data_tmp)
+ from rero_ils.modules.users.api import User
+ patron_martigny_data_tmp = User.remove_fields(patron_martigny_data_tmp)
# communication channel require at least one email
patron_martigny_data_tmp['patron']['communication_channel'] = 'email'
diff --git a/tests/ui/patrons/test_patrons_jsonresolver.py b/tests/ui/patrons/test_patrons_jsonresolver.py
index 26bf172f12..f25afe4e9d 100644
--- a/tests/ui/patrons/test_patrons_jsonresolver.py
+++ b/tests/ui/patrons/test_patrons_jsonresolver.py
@@ -34,11 +34,11 @@ def test_patrons_jsonresolver(system_librarian_martigny):
# deleted record
system_librarian_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'patron': {'$ref': 'https://bib.rero.ch/api/patrons/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/patrons/test_patrons_mapping.py b/tests/ui/patrons/test_patrons_mapping.py
index ed50849bb8..ac438f3d24 100644
--- a/tests/ui/patrons/test_patrons_mapping.py
+++ b/tests/ui/patrons/test_patrons_mapping.py
@@ -23,7 +23,7 @@
def test_patron_es_mapping(
- roles, es, lib_martigny, librarian_martigny_data_tmp):
+ roles, search, lib_martigny, librarian_martigny_data_tmp):
"""Test patron elasticsearch mapping."""
search = PatronsSearch()
mapping = get_mapping(search.Meta.index)
diff --git a/tests/ui/stats/test_stats_report_n_patrons.py b/tests/ui/stats/test_stats_report_n_patrons.py
index 96a574d379..c8b8cb9df1 100644
--- a/tests/ui/stats/test_stats_report_n_patrons.py
+++ b/tests/ui/stats/test_stats_report_n_patrons.py
@@ -55,7 +55,7 @@ def patch_creation_date(patron, date):
}
assert StatsReport(cfg).collect() == [[0]]
- from rero_ils.modules.patrons.api import create_patron_from_data
+ from rero_ils.modules.patrons.utils import create_patron_from_data
patron_martigny = create_patron_from_data(
data={k: v for k, v in patron_martigny_data.items() if k != 'pid'},
diff --git a/tests/ui/stats_cfg/test_stats_cfg_jsonresolver.py b/tests/ui/stats_cfg/test_stats_cfg_jsonresolver.py
index 1b078434e8..2e4fa4c324 100644
--- a/tests/ui/stats_cfg/test_stats_cfg_jsonresolver.py
+++ b/tests/ui/stats_cfg/test_stats_cfg_jsonresolver.py
@@ -34,11 +34,11 @@ def test_stats_cfg_jsonresolver(stats_cfg_martigny):
# deleted record
stats_cfg_martigny.delete()
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
'stats_cfg': {'$ref': 'https://bib.rero.ch/api/stats_cfg/n_e'}
})
with pytest.raises(JsonRefError):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
diff --git a/tests/ui/templates/test_templates_api.py b/tests/ui/templates/test_templates_api.py
index 474af24970..c118af7ba8 100644
--- a/tests/ui/templates/test_templates_api.py
+++ b/tests/ui/templates/test_templates_api.py
@@ -27,7 +27,7 @@
from rero_ils.modules.utils import get_ref_for_pid
-def test_template_create(db, es, templ_doc_public_martigny_data,
+def test_template_create(db, search, templ_doc_public_martigny_data,
org_martigny, system_librarian_martigny):
"""Test template creation."""
templ_doc_public_martigny_data['toto'] = 'toto'
diff --git a/tests/ui/templates/test_templates_mapping.py b/tests/ui/templates/test_templates_mapping.py
index ca979ec6b3..aee9699473 100644
--- a/tests/ui/templates/test_templates_mapping.py
+++ b/tests/ui/templates/test_templates_mapping.py
@@ -22,7 +22,7 @@
from rero_ils.modules.templates.api import Template, TemplatesSearch
-def test_template_es_mapping(es, db, templ_doc_public_martigny_data,
+def test_template_es_mapping(search, db, templ_doc_public_martigny_data,
org_martigny, system_librarian_martigny,
librarian_martigny):
"""Test template elasticsearch mapping."""
diff --git a/tests/ui/test_indexer_utils.py b/tests/ui/test_indexer_utils.py
index adcf30fe30..72c69e9958 100644
--- a/tests/ui/test_indexer_utils.py
+++ b/tests/ui/test_indexer_utils.py
@@ -59,23 +59,23 @@ def test_record_to_index(app):
assert record_to_index({
'$schema': 'https://bib.rero.ch/schemas/'
'documents/document-v0.0.1.json'
- }) == ('documents-document-v0.0.1', '_doc')
+ }) == 'documents-document-v0.0.1'
assert record_to_index({
'$schema': 'https://bib.rero.ch/schemas/'
'documents/document-v0.0.1.json'
- }) == ('documents-document-v0.0.1', '_doc')
+ }) == 'documents-document-v0.0.1'
# for mef-mef-contributions
assert record_to_index({
'$schema': 'https://mef.rero.ch/schemas/'
'mef/mef-contribution-v0.0.1.json'
- }) == ('remote_entities-remote_entity-v0.0.1', '_doc')
+ }) == 'remote_entities-remote_entity-v0.0.1'
# for others
assert record_to_index({
'$schema': 'https://bib.rero.ch/schemas/'
'organisations/organisation-v0.0.1.json'
- }) == ('organisations-organisation-v0.0.1', '_doc')
+ }) == 'organisations-organisation-v0.0.1'
def test_get_resource_from_ES(document):
diff --git a/tests/ui/users/test_forms.py b/tests/ui/users/test_forms.py
index d06c980b9d..46919d41f2 100644
--- a/tests/ui/users/test_forms.py
+++ b/tests/ui/users/test_forms.py
@@ -97,7 +97,7 @@ def test_register_form(client, app):
}
res = client.post(url_for('security.register'), data=form_data)
assert res.status_code == 302
- assert res.location == 'http://localhost/'
+ assert res.location == '/'
form_data = {
'email': 'foo@bar.com',
@@ -106,11 +106,12 @@ def test_register_form(client, app):
}
res = client.post(url_for('security.register'), data=form_data)
assert res.status_code == 302
- assert res.location == 'http://localhost/'
+ assert res.location == '/'
@mock.patch('flask_security.views.reset_password_token_status',
- mock.MagicMock(return_value=[False, False, {}]))
+ mock.MagicMock(
+ return_value=[False, False, {'email': 'foo@foo.com'}]))
@mock.patch('flask_security.views.update_password',
mock.MagicMock())
def test_reset_password_form(client, app):
diff --git a/tests/ui/users/test_schema.py b/tests/ui/users/test_schema.py
new file mode 100644
index 0000000000..c966e5ccb1
--- /dev/null
+++ b/tests/ui/users/test_schema.py
@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+#
+# RERO ILS
+# Copyright (C) 2023 RERO
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, version 3 of the License.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+
+"""Tests Schema for users."""
+import pytest
+from invenio_accounts.models import User
+
+
+def test_custom_schema(app):
+ """Test register form."""
+ user = User(email="admin@inveniosoftware.org")
+ user.user_profile = {
+ "first_name": "Louis",
+ "last_name": "Roduit",
+ "gender": "male",
+ "birth_date": "1947-06-07",
+ "street": "Avenue Leopold-Robert, 13",
+ "postal_code": "1920",
+ "city": "Martigny",
+ "country": "sz",
+ "home_phone": "+41324993156",
+ "business_phone": "+41324993156",
+ "mobile_phone": "+41324993156",
+ "other_phone": "+41324993156",
+ }
+ assert user
+ with pytest.raises(ValueError):
+ user.user_profile = {
+ "username": "admin",
+ }
diff --git a/tests/ui/vendors/test_vendors_jsonresolver.py b/tests/ui/vendors/test_vendors_jsonresolver.py
index 5731c6aea4..8e327636db 100644
--- a/tests/ui/vendors/test_vendors_jsonresolver.py
+++ b/tests/ui/vendors/test_vendors_jsonresolver.py
@@ -34,7 +34,7 @@ def test_vendors_jsonresolver(app, vendor_martigny):
# deleted record
vendor_martigny.delete()
with pytest.raises(Exception):
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
# non existing record
rec = Record.create({
@@ -42,5 +42,5 @@ def test_vendors_jsonresolver(app, vendor_martigny):
})
with pytest.raises(JsonRefError) as error:
- rec.replace_refs().dumps()
+ type(rec)(rec.replace_refs()).dumps()
assert 'PIDDoesNotExistError' in str(error)
diff --git a/tests/ui/vendors/test_vendors_mapping.py b/tests/ui/vendors/test_vendors_mapping.py
index 8268bd967a..94f564e21f 100644
--- a/tests/ui/vendors/test_vendors_mapping.py
+++ b/tests/ui/vendors/test_vendors_mapping.py
@@ -21,7 +21,7 @@
from rero_ils.modules.vendors.api import Vendor, VendorsSearch
-def test_budgets_es_mapping(es, db, org_martigny, vendor_martigny_data):
+def test_budgets_es_mapping(search, db, org_martigny, vendor_martigny_data):
"""Test vendors elasticsearch mapping."""
search = VendorsSearch()
mapping = get_mapping(search.Meta.index)
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index fc3cb5c2fb..de6923bc0f 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -38,169 +38,169 @@ def create_app():
@pytest.fixture()
-def circ_policy_schema(monkeypatch):
+def circ_policy_schema():
"""Circ policy Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.circ_policies.jsonschemas',
'circ_policies/circ_policy-v0.0.1.json',
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def template_schema(monkeypatch):
+def template_schema():
"""Template Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.templates.jsonschemas',
'templates/template-v0.0.1.json',
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def notification_schema(monkeypatch):
+def notification_schema():
"""Notifications Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.notifications.jsonschemas',
'/notifications/notification-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def item_type_schema(monkeypatch):
+def item_type_schema():
"""Item type Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.item_types.jsonschemas',
'/item_types/item_type-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def acq_account_schema(monkeypatch):
+def acq_account_schema():
"""Acq account Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.acquisition.acq_accounts.jsonschemas',
'/acq_accounts/acq_account-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def acq_order_schema(monkeypatch):
+def acq_order_schema():
"""Acq order Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.acquisition.acq_orders.jsonschemas',
'/acq_orders/acq_order-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def acq_order_line_schema(monkeypatch):
+def acq_order_line_schema():
"""Acq order line Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.acquisition.acq_order_lines.jsonschemas',
'/acq_order_lines/acq_order_line-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def acq_receipt_line_schema(monkeypatch):
+def acq_receipt_line_schema():
"""Acq receipt line Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.acquisition.acq_receipt_lines.jsonschemas',
'/acq_receipt_lines/acq_receipt_line-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def budget_schema(monkeypatch):
+def budget_schema():
"""Budget Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.acquisition.budgets.jsonschemas',
'/budgets/budget-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def library_schema(monkeypatch):
+def library_schema():
"""Library Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.libraries.jsonschemas',
'libraries/library-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def local_fields_schema(monkeypatch):
+def local_fields_schema():
"""Local fields Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.local_fields.jsonschemas',
'local_fields/local_field-v0.0.1.json')
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def location_schema(monkeypatch):
+def location_schema():
"""Location Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.locations.jsonschemas',
'locations/location-v0.0.1.json')
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def patron_transaction_schema(monkeypatch):
+def patron_transaction_schema():
"""Patron transaction Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.patron_transactions.jsonschemas',
'patron_transactions/patron_transaction-v0.0.1.json')
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def patron_transaction_event_schema(monkeypatch):
+def patron_transaction_event_schema():
"""Patron transaction event Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.patron_transaction_events.jsonschemas',
'patron_transaction_events/patron_transaction_event-v0.0.1.json')
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def organisation_schema(monkeypatch):
+def organisation_schema():
"""Organisation Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.organisations.jsonschemas',
'organisations/organisation-v0.0.1.json',
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def patron_type_schema(monkeypatch):
+def patron_type_schema():
"""Patron type Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.patron_types.jsonschemas',
'/patron_types/patron_type-v0.0.1.json',
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def patron_schema(monkeypatch):
+def patron_schema():
"""Patron Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.patrons.jsonschemas',
'/patrons/patron-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture(scope="function")
@@ -213,90 +213,90 @@ def patron_martigny_data_tmp_with_id(patron_martigny_data_tmp):
@pytest.fixture()
-def remote_entities_schema(monkeypatch):
+def remote_entities_schema():
"""Remote entity Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.entities.remote_entities.jsonschemas',
'/remote_entities/remote_entity-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def local_entities_schema(monkeypatch):
+def local_entities_schema():
"""Local entity Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.entities.local_entities.jsonschemas',
'/local_entities/local_entity-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def document_schema(monkeypatch):
+def document_schema():
"""Jsonschema for documents."""
schema_in_bytes = resource_string(
'rero_ils.modules.documents.jsonschemas',
'documents/document-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def item_schema(monkeypatch):
+def item_schema():
"""Item Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.items.jsonschemas',
'items/item-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def user_schema(monkeypatch):
+def user_schema():
"""User Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.users.jsonschemas',
'users/user-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def holding_schema(monkeypatch):
+def holding_schema():
"""Holdings Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.holdings.jsonschemas',
'/holdings/holding-v0.0.1.json')
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def ill_request_schema(monkeypatch):
+def ill_request_schema():
"""ILL requests JSONSchema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.ill_requests.jsonschemas',
'/ill_requests/ill_request-v0.0.1.json')
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def operation_log_schema(monkeypatch):
+def operation_log_schema():
"""Operation log Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.operation_logs.jsonschemas',
'operation_logs/operation_log-v0.0.1.json'
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
-def vendors_schema(monkeypatch):
+def vendors_schema():
"""Local fields Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.vendors.jsonschemas',
'vendors/vendor-v0.0.1.json')
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
@pytest.fixture()
@@ -564,10 +564,10 @@ def mef_record_with_idref_gnd_rero(mef_record_with_idref_gnd_rero_data):
@pytest.fixture()
-def stats_cfg_schema(monkeypatch):
+def stats_cfg_schema():
"""Template Jsonschema for records."""
schema_in_bytes = resource_string(
'rero_ils.modules.stats_cfg.jsonschemas',
'stats_cfg/stat_cfg-v0.0.1.json',
)
- return get_schema(monkeypatch, schema_in_bytes)
+ return get_schema(schema_in_bytes)
diff --git a/tests/unit/documents/test_documents_dojson.py b/tests/unit/documents/test_documents_dojson.py
index 0ec5d82d4a..a1d9c41dc3 100644
--- a/tests/unit/documents/test_documents_dojson.py
+++ b/tests/unit/documents/test_documents_dojson.py
@@ -5448,7 +5448,7 @@ def test_marc21_to_identified_by_from_035():
@mock.patch('requests.Session.get')
-def test_marc21_to_electronicLocator_from_856(mock_cover_get):
+def test_marc21_to_electronicLocator_from_856(mock_cover_get, app):
"""Test dojson electronicLocator from 856."""
marc21xml = """
@@ -5475,7 +5475,7 @@ def test_marc21_to_electronicLocator_from_856(mock_cover_get):
{
'url': 'http://reader.digitale-s.de/r/d/XXX.html',
'type': 'versionOfResource',
- 'content': 'fullText',
+ 'content': 'full text',
'public_note': 'Vol. 1'
}
]
@@ -5597,7 +5597,7 @@ def test_marc21_to_identified_by_from_930():
@mock.patch('requests.Session.get')
-def test_get_mef_link(mock_get, capsys):
+def test_get_mef_link(mock_get, capsys, app):
"""Test get mef contribution link"""
mock_get.return_value = mock_response(json_data={
diff --git a/tests/unit/documents/test_documents_dojson_dc.py b/tests/unit/documents/test_documents_dojson_dc.py
index 8189e3fef1..fc0990f4f7 100644
--- a/tests/unit/documents/test_documents_dojson_dc.py
+++ b/tests/unit/documents/test_documents_dojson_dc.py
@@ -19,7 +19,7 @@
from __future__ import absolute_import, print_function
-from flask_babelex import gettext as _
+from flask_babel import gettext as _
from rero_ils.modules.documents.dojson.contrib.jsontodc import dublincore
diff --git a/tests/unit/test_patrons_jsonschema.py b/tests/unit/test_patrons_jsonschema.py
index 076ac9c535..dfad8ea750 100644
--- a/tests/unit/test_patrons_jsonschema.py
+++ b/tests/unit/test_patrons_jsonschema.py
@@ -121,14 +121,14 @@ def test_additional_email(app, patron_martigny):
user = patron_martigny.user
original_user_email = user.email
- user.email = None
+ user._email = None
patron_martigny['patron']['communication_channel'] = 'email'
with pytest.raises(ValidationError) as e:
Patron.validate(patron_martigny)
assert 'At least one email should be defined for an email ' \
'communication channel' in str(e)
- user.email = original_user_email
+ user._email = original_user_email
def test_phone(patron_schema, patron_martigny_data_tmp_with_id):
diff --git a/tests/unit/test_users_jsonschema.py b/tests/unit/test_users_jsonschema.py
index 9ce0f7745b..bbded3746d 100644
--- a/tests/unit/test_users_jsonschema.py
+++ b/tests/unit/test_users_jsonschema.py
@@ -40,7 +40,6 @@ def test_user_all_jsonschema_keys_values(
{'key': 'last_name', 'value': 25},
{'key': 'birth_date', 'value': 25},
{'key': 'gender', 'value': 25},
- {'key': 'username', 'value': 25},
{'key': 'street', 'value': 25},
{'key': 'postal_code', 'value': 25},
{'key': 'city', 'value': 25},
diff --git a/tests/utils.py b/tests/utils.py
index 85118349f2..c4d962c935 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -22,7 +22,6 @@
from datetime import datetime, timedelta, timezone
import jsonref
-import requests
import xmltodict
from flask import url_for
from invenio_accounts.testutils import login_user_via_session, \
@@ -49,8 +48,8 @@
from rero_ils.modules.locations.api import Location
from rero_ils.modules.organisations.api import Organisation
from rero_ils.modules.patron_types.api import PatronType
-from rero_ils.modules.patrons.api import Patron, PatronsSearch, \
- create_patron_from_data
+from rero_ils.modules.patrons.api import Patron, PatronsSearch
+from rero_ils.modules.patrons.utils import create_patron_from_data
from rero_ils.modules.selfcheck.models import SelfcheckTerminal
@@ -246,27 +245,9 @@ def check_timezone_date(timezone, date, expected=None):
assert tocheck_date.hour == hour, error_msg
-def mocked_requests_get(*args, **kwargs):
+def jsonloader(uri, **kwargs):
"""This method will be used by the mock to replace requests.get."""
- class MockResponse:
- """Mock response class.
-
- This class will get a json schema directly from the source file.
- Examples:
- https://bib.rero.ch/schemas/documents/document-v0.0.1.json ->
- rero_ils.modules.documents.jsonschemas.document-v0.0.1.json
- https://bib.rero.ch/schemas/common/languages-v0.0.1.json ->
- rero_ils.jsonschemas.common.languages-v0.0.1.json
- """
-
- def __init__(self, json_data, status_code):
- self.json_data = json_data
- self.status_code = status_code
-
- def json(self):
- return self.json_data
-
- ref_split = args[0].split('/')
+ ref_split = uri.split('/')
# TODO: find a better way to determine name and path.
if ref_split[-2] == 'common':
path = 'rero_ils.jsonschemas'
@@ -288,32 +269,25 @@ def json(self):
)
schema_in_bytes = resource_string(path, name)
- if not schema_in_bytes:
- return MockResponse({}, 404)
schema = json.loads(schema_in_bytes.decode('utf8'))
- if not schema:
- return MockResponse({}, 404)
- return MockResponse(schema, 200)
+ return schema
-def get_schema(monkeypatch, schema_in_bytes):
+def get_schema(schema_in_bytes):
"""Get json schema and replace $refs.
For the resolving of the $ref we have to catch the request.get and
get the referenced json schema directly from the resource.
- :param monkeypatch: https://docs.pytest.org/en/stable/monkeypatch.html
:schema_in_bytes: schema in bytes.
:returns: resolved json schema.
"""
- # apply the monkeypatch for requests.get to mocked_requests_get
- monkeypatch.setattr(requests, "get", mocked_requests_get)
- schema = jsonref.loads(schema_in_bytes.decode('utf8'))
+ schema = jsonref.loads(schema_in_bytes.decode('utf8'), loader=jsonloader)
# Replace all remaining $refs
- while schema != jsonref.loads(jsonref.dumps(schema)):
- schema = jsonref.loads(jsonref.dumps(schema))
+ while schema != jsonref.loads(jsonref.dumps(schema), loader=jsonloader):
+ schema = jsonref.loads(jsonref.dumps(schema), loader=jsonloader)
return schema
@@ -403,11 +377,7 @@ def create_patron(data):
:param data: - A dict containing a mix of user and patron data.
:returns: - A freshly created Patron instance.
"""
- ptrn = create_patron_from_data(
- data=data,
- delete_pid=False,
- dbcommit=True,
- reindex=True)
+ ptrn = create_patron_from_data(data=data)
flush_index(PatronsSearch.Meta.index)
return ptrn