This commit is contained in:
Emmanuel Cazenave 2021-02-24 11:54:53 +01:00
parent 4e1862d3df
commit dc5509e16e
26 changed files with 286 additions and 190 deletions

View File

@ -15,15 +15,17 @@ from django.test.client import RequestFactory
from docbow_project.docbow.models import FileType
from docbow_project.docbow.views import inbox_view, outbox_view, send_file
def stat(seq):
return {
'min': min(seq),
'max': max(seq),
'mean': numpy.mean(seq),
'median': numpy.median(seq),
'std': numpy.std(seq),
'min': min(seq),
'max': max(seq),
'mean': numpy.mean(seq),
'median': numpy.median(seq),
'std': numpy.std(seq),
}
rf = RequestFactory()
paths = [('/inbox/', inbox_view, {}), ('/outbox/', outbox_view, {})]
filetypes = list(FileType.objects.all())
@ -34,8 +36,7 @@ data = []
for path, view, kwargs in paths:
get_request = rf.get(path)
get_request.session = {}
print 'Testing view', path, 'for all users:'
print
print('Testing view', path, 'for all users:')
seq = []
for user in User.objects.all():
get_request.user = user
@ -44,14 +45,15 @@ for path, view, kwargs in paths:
if hasattr(response, 'render'):
response.render()
str(response)
duration = time.time()-now
seq.append(duration*1000)
duration = time.time() - now
seq.append(duration * 1000)
data.append(stat(seq))
data[-1]['path'] = path
with file('vix.js', 'w') as f:
f.write('''var vix =
''')
f.write(
'''var vix =
'''
)
f.write(json.dumps(data, indent=4))
f.write(';')

View File

@ -71,9 +71,9 @@ class MailingListAdmin(admin.ModelAdmin):
actions = [actions.export_as_csv]
def get_actions(self, request):
'''Show delete actions only if user has delete rights
Show activation actions only if user has rights to change mailing lists
'''
"""Show delete actions only if user has delete rights
Show activation actions only if user has rights to change mailing lists
"""
a = super(MailingListAdmin, self).get_actions(request)
if request.user.has_perm('docbow.delete_mailinglist'):
a['delete_selected'] = self.get_action('delete_selected')

View File

@ -11,9 +11,9 @@ from django.views.decorators.cache import never_cache as old_never_cache
def no_delegate(view_func):
'''
Forbid delegated account to use this view.
'''
"""
Forbid delegated account to use this view.
"""
@wraps(view_func, assigned=available_attrs(view_func))
def f(request, *args, **kwargs):
@ -26,10 +26,10 @@ def no_delegate(view_func):
def as_delegate(view_func):
'''
Replace the effective user by the real user of the delegate for the
given view.
'''
"""
Replace the effective user by the real user of the delegate for the
given view.
"""
@wraps(view_func, assigned=available_attrs(view_func))
def f(request, *args, **kwargs):

View File

@ -49,10 +49,10 @@ class RecipientField(MultipleChoiceField):
self._set_choices(Func2Iter(self.get_recipients_choices))
def get_recipients_choices(self):
'''
Create a unique list of recipients from the list of users and the
list of mailing-lists.
'''
"""
Create a unique list of recipients from the list of users and the
list of mailing-lists.
"""
users = self.user_qs
if self.user:
users = users.exclude(pk=self.user.pk)

View File

@ -55,10 +55,10 @@ logger = logging.getLogger(__name__)
class RecipientForm(object):
'''
Base form mixin for forms containing a RecipienField, i.e. all
forms for sending documents.
'''
"""
Base form mixin for forms containing a RecipienField, i.e. all
forms for sending documents.
"""
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
@ -113,8 +113,8 @@ class ForwardingForm(RecipientForm, Form):
def max_filename_length():
'''Compute the maximum filename length from the possible maximum length of
the AttachedFile model.'''
"""Compute the maximum filename length from the possible maximum length of
the AttachedFile model."""
field = AttachedFile._meta.get_field('content')
prefix = field.generate_filename(None, '')
max_length = field.max_length
@ -206,9 +206,9 @@ class FileForm(RecipientForm, ModelForm):
return [self[name] for name, _ in self.content_fields]
def get_predefined_comments(self):
'''Return a list of predefined comments, structured as choice list for
a form field.
'''
"""Return a list of predefined comments, structured as choice list for
a form field.
"""
choices = [(content.description,) * 2 for content in Content.objects.all()]
choices.insert(0, ('---', '---'))
return choices
@ -249,8 +249,8 @@ class FileForm(RecipientForm, ModelForm):
return super(FileForm, self).save(commit=commit)
def save_attachments(self):
'''Create a new AttachedFile object for each uploaded file; and attach
them to the newly created Document object.'''
"""Create a new AttachedFile object for each uploaded file; and attach
them to the newly created Document object."""
instance = self.instance
for field, attached_file_kind in self.content_fields:
upload_id, uploaded_files = self.cleaned_data.get(field, (None, []))
@ -411,9 +411,9 @@ class AutomaticForwardingForm(ModelForm):
class ProfileForm(ModelForm):
'''User form for editing personal informations like email and mobile
phone.
'''
"""User form for editing personal informations like email and mobile
phone.
"""
class Meta:
model = DocbowProfile
@ -424,9 +424,9 @@ class ProfileForm(ModelForm):
fields += ('personal_email',)
def __init__(self, request, *args, **kwargs):
'''Initialize the form object.
Define a custom help text.
'''
"""Initialize the form object.
Define a custom help text.
"""
self.request = request
ModelForm.__init__(self, *args, **kwargs)
@ -437,11 +437,11 @@ class ProfileForm(ModelForm):
)
def clean_mobile_phone(self):
'''Validate the mobile phone number by sending a HMAC signature as a code by SMS
to the phone number.
"""Validate the mobile phone number by sending a HMAC signature as a code by SMS
to the phone number.
The HMAC code is valid for one day.
'''
The HMAC code is valid for one day.
"""
if self.cleaned_data.get('mobile_phone'):
mobile_phone = phone_normalize(self.cleaned_data['mobile_phone'])
validate_fr_be_phone(mobile_phone)

View File

@ -23,10 +23,16 @@ class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('ml_name', type=str, help='Name of the mailing list')
parser.add_argument(
"--add-list", action="append", help='add a list as a sublist', default=[],
"--add-list",
action="append",
help='add a list as a sublist',
default=[],
)
parser.add_argument(
"--remove-list", action="append", help='remove list as a sublist', default=[],
"--remove-list",
action="append",
help='remove list as a sublist',
default=[],
)
parser.add_argument("--add-user", action="append", help='add a user member', default=[])
parser.add_argument("--remove-user", action="append", help='remove a user member', default=[])

View File

@ -13,19 +13,19 @@ logger = logging.getLogger('docbow')
def get_extra():
'''Extract current remote ip and current user from the thread local storage
from the KeepUserAroundMiddleware middleware class.
'''
"""Extract current remote ip and current user from the thread local storage
from the KeepUserAroundMiddleware middleware class.
"""
k = KeepUserAroundMiddleware
return {'ip': k.get_global_ip(), 'user': k.get_global_user()}
class KeepUserAroundMiddleware(MiddlewareMixin):
'''
Store the request.user and the REMOTE_ADDR in a global thread local
variable, so that logging calls inside signals handler can know about
them.
'''
"""
Store the request.user and the REMOTE_ADDR in a global thread local
variable, so that logging calls inside signals handler can know about
them.
"""
__middleware_ctx = threading.local()
__middleware_ctx.user = NO_USER

View File

@ -232,7 +232,11 @@ class Migration(migrations.Migration):
('name', models.CharField(unique=True, max_length=128)),
('is_active', models.BooleanField(default=True, verbose_name='is active')),
],
options={'ordering': ['name'], 'verbose_name': 'File type', 'verbose_name_plural': 'File types',},
options={
'ordering': ['name'],
'verbose_name': 'File type',
'verbose_name_plural': 'File types',
},
bases=(docbow_project.docbow.models.NameNaturalKey, models.Model),
),
migrations.CreateModel(
@ -306,7 +310,11 @@ class Migration(migrations.Migration):
),
),
],
options={'ordering': ['-date'], 'verbose_name': 'Mailbox', 'verbose_name_plural': 'Mailboxes',},
options={
'ordering': ['-date'],
'verbose_name': 'Mailbox',
'verbose_name_plural': 'Mailboxes',
},
bases=(models.Model,),
),
migrations.CreateModel(
@ -367,7 +375,9 @@ class Migration(migrations.Migration):
),
),
],
options={'ordering': ('-id',),},
options={
'ordering': ('-id',),
},
bases=(models.Model,),
),
migrations.CreateModel(
@ -454,7 +464,8 @@ class Migration(migrations.Migration):
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='filetypeattachedfilekind', unique_together=set([('name', 'file_type')]),
name='filetypeattachedfilekind',
unique_together=set([('name', 'file_type')]),
),
migrations.AddField(
model_name='document',
@ -523,7 +534,10 @@ class Migration(migrations.Migration):
field=models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AlterUniqueTogether(name='delegation', unique_together=set([('by', 'to')]),),
migrations.AlterUniqueTogether(
name='delegation',
unique_together=set([('by', 'to')]),
),
migrations.AddField(
model_name='automaticforwarding',
name='filetypes',
@ -589,25 +603,39 @@ class Migration(migrations.Migration):
migrations.CreateModel(
name='DocbowGroup',
fields=[],
options={'verbose_name': 'Docbow admin group', 'proxy': True,},
options={
'verbose_name': 'Docbow admin group',
'proxy': True,
},
bases=('auth.group',),
),
migrations.CreateModel(
name='DocbowUser',
fields=[],
options={'verbose_name': 'Docbow admin user', 'proxy': True,},
options={
'verbose_name': 'Docbow admin user',
'proxy': True,
},
bases=('auth.user',),
),
migrations.CreateModel(
name='Inbox',
fields=[],
options={'verbose_name': 'Inbox', 'proxy': True, 'verbose_name_plural': 'Inboxes',},
options={
'verbose_name': 'Inbox',
'proxy': True,
'verbose_name_plural': 'Inboxes',
},
bases=('docbow.mailbox',),
),
migrations.CreateModel(
name='Outbox',
fields=[],
options={'verbose_name': 'Outbox', 'proxy': True, 'verbose_name_plural': 'Outboxes',},
options={
'verbose_name': 'Outbox',
'proxy': True,
'verbose_name_plural': 'Outboxes',
},
bases=('docbow.mailbox',),
),
]

View File

@ -12,5 +12,7 @@ class Migration(migrations.Migration):
]
operations = [
migrations.DeleteModel(name='DeletedMailbox',),
migrations.DeleteModel(
name='DeletedMailbox',
),
]

View File

@ -13,9 +13,13 @@ class Migration(migrations.Migration):
operations = [
migrations.AddField(
model_name='deleteddocument', name='soft_delete', field=models.BooleanField(default=False),
model_name='deleteddocument',
name='soft_delete',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='deleteddocument', name='soft_delete_date', field=models.DateTimeField(null=True),
model_name='deleteddocument',
name='soft_delete_date',
field=models.DateTimeField(null=True),
),
]

View File

@ -58,24 +58,24 @@ def ellipsize(text, length=50):
class GetByNameManager(Manager):
'''Manager providing a get_by_natural_key() method to retrieve object by
their name. The name field MUST be unique.'''
"""Manager providing a get_by_natural_key() method to retrieve object by
their name. The name field MUST be unique."""
def get_by_natural_key(self, name):
return self.get(name=name)
class ContentManager(Manager):
'''Manager providing a get_by_natural_key() method to retrieve object by
their description. The description field MUST be unique.'''
"""Manager providing a get_by_natural_key() method to retrieve object by
their description. The description field MUST be unique."""
def get_by_natural_key(self, description):
return self.get(description=description)
class NameNaturalKey(object):
'''Model mixin to export the name of a model as a natural key. The name
field MUST be unique.'''
"""Model mixin to export the name of a model as a natural key. The name
field MUST be unique."""
def natural_key(self):
return (self.name,)
@ -83,9 +83,9 @@ class NameNaturalKey(object):
@python_2_unicode_compatible
class FileType(NameNaturalKey, Model):
'''
A type of file that can be sent inside the application.
'''
"""
A type of file that can be sent inside the application.
"""
objects = GetByNameManager()
@ -218,9 +218,9 @@ class DocumentManager(Manager):
@python_2_unicode_compatible
class Document(Model):
'''
Represent a file sent between a user and some targets, user or groups.
'''
"""
Represent a file sent between a user and some targets, user or groups.
"""
objects = DocumentManager()
@ -270,8 +270,8 @@ class Document(Model):
filenames.short_description = _('Attached files')
def filename_links(self):
'''Returns a display string containing links to download attached
files, only usable in the admin application.'''
"""Returns a display string containing links to download attached
files, only usable in the admin application."""
links = []
qs = self.attached_files.all()
qs = qs.order_by('kind__position', 'kind__name', 'id')
@ -301,9 +301,9 @@ class Document(Model):
return sorted(list(map(username, self.to_user.all())) + list(map(force_text, self.to_list.all())))
def recipients(self):
'''Return a comma separated sorted list of display names for all
recipients.
'''
"""Return a comma separated sorted list of display names for all
recipients.
"""
return ', '.join(self.human_to())
recipients.short_description = _('Recipients')
@ -326,11 +326,11 @@ class Document(Model):
return recipients
def delivered_to(self):
'''Returns the list of user which received the document.
"""Returns the list of user which received the document.
It can differ from ``to()`` if the members of a recipient
mailing-list changed.
'''
It can differ from ``to()`` if the members of a recipient
mailing-list changed.
"""
return [m.owner for m in self.mailboxes.all() if m.outbox == False]
def timestamp(self, to=None):
@ -347,9 +347,9 @@ class Document(Model):
return self._timestamp
def post(self, forward=True):
'''Deliver the document into inbox of all active users recipients and into
outbox of the sender.
'''
"""Deliver the document into inbox of all active users recipients and into
outbox of the sender.
"""
to_with_origins = self.to_with_origin()
to = [user for user in to_with_origins.keys() if user.is_active]
# Create the timestamp
@ -407,14 +407,14 @@ class Document(Model):
return len(to)
def forward(self, new_sender, lists, users, automatic=False):
'''Forward the document to new recipients.
"""Forward the document to new recipients.
new_sender - new sender
lists - new mailing lists recipients
users - new users recipients
automatic - whether this forwarding is the result of an
automatic treatment
'''
new_sender - new sender
lists - new mailing lists recipients
users - new users recipients
automatic - whether this forwarding is the result of an
automatic treatment
"""
document = Document.objects.create(sender=new_sender, filetype=self.filetype, comment=self.comment)
document.to_user.set(users)
document.to_list.set(lists)
@ -472,10 +472,10 @@ class DeletedDocument(Model):
@python_2_unicode_compatible
class DocumentForwarded(Model):
'''Model to store tags applied to models.
"""Model to store tags applied to models.
First use will be to mark message as having been forwarded.
'''
First use will be to mark message as having been forwarded.
"""
from_document = ForeignKey(Document, related_name='document_forwarded_to', on_delete=CASCADE)
to_document = ForeignKey(Document, related_name='document_forwarded_from', on_delete=CASCADE)
@ -494,11 +494,11 @@ class DocumentForwarded(Model):
def list_to_csv(l, mapping_func=None):
'''Convert a list to a comma separated string of its unicode values.
"""Convert a list to a comma separated string of its unicode values.
A mapping_func function can be passed to transform the list prior to the
formatting.
'''
A mapping_func function can be passed to transform the list prior to the
formatting.
"""
if mapping_func:
l = map(mapping_func, l)
return u', '.join(map(force_text, l))
@ -506,10 +506,10 @@ def list_to_csv(l, mapping_func=None):
@python_2_unicode_compatible
class AutomaticForwarding(Model):
'''
Choice of sender and filetype to transfer mail automatically to a list
of recipients.
'''
"""
Choice of sender and filetype to transfer mail automatically to a list
of recipients.
"""
filetypes = ManyToManyField(
FileType,
@ -597,11 +597,11 @@ class AttachedFile(Model):
)
def filename(self):
'''Extract the original filename from generated unique filename for
storage.
"""Extract the original filename from generated unique filename for
storage.
It remove the part after the last underscore in the name.
'''
It remove the part after the last underscore in the name.
"""
filename = os.path.basename(self.content.name)
try:
prefix, true_filename = filename.split('_', 1)
@ -616,9 +616,9 @@ class AttachedFile(Model):
return ellipsize(self.name)
def link(self):
'''Returns the link for downloading the attached file in the admin
application.
'''
"""Returns the link for downloading the attached file in the admin
application.
"""
return '/admin/docbow/attachedfile/%s/download/' % self.id
def __str__(self):
@ -634,9 +634,9 @@ def is_guest(user):
@python_2_unicode_compatible
class Delegation(Model):
'''
Delegate account, managable by user themselves.
'''
"""
Delegate account, managable by user themselves.
"""
by = ForeignKey(
User,
@ -705,8 +705,8 @@ class MailingList(NameNaturalKey, Model):
verbose_name_plural = _('Mailing lists')
def recursive_members(self, sublist_traversed=None):
'''Traverse this list and all its recursive sublist and accumulate
members.'''
"""Traverse this list and all its recursive sublist and accumulate
members."""
if sublist_traversed is None:
sublist_traversed = set()
members = set()
@ -718,8 +718,8 @@ class MailingList(NameNaturalKey, Model):
return members
def recursive_members_with_origin(self, sublist_traversed=None):
'''Traverse this list and all its recursive sublist and accumulate
members and their origin.'''
"""Traverse this list and all its recursive sublist and accumulate
members and their origin."""
if sublist_traversed is None:
sublist_traversed = defaultdict(lambda: 0)
sublist_traversed[self] += 1
@ -864,17 +864,17 @@ class NotificationManager(Manager):
@python_2_unicode_compatible
class Notification(Model):
'''Asynchronous notification
create_dt - date and time of creation
document - the related document
user - the recipient of the notification
kind - the kind of notification
done - notification has been done successfully or not
failure - report of the last failure, if done is True, the notification
was successful if this is empty.
ctx - a pickled object
'''
"""Asynchronous notification
create_dt - date and time of creation
document - the related document
user - the recipient of the notification
kind - the kind of notification
done - notification has been done successfully or not
failure - report of the last failure, if done is True, the notification
was successful if this is empty.
ctx - a pickled object
"""
objects = NotificationManager()

View File

@ -96,10 +96,10 @@ class MailNotifier(BaseNotifier):
class SMSNotifier(BaseNotifier):
'''Variable in sms notification:
- document
- settings
'''
"""Variable in sms notification:
- document
- settings
"""
description = _('SMS')
key = 'sms'

View File

@ -204,7 +204,11 @@ class DelegateView(cbv.FormWithPostTarget, FormView):
delegate_username = delegate_user.username
delegation, created = models.Delegation.objects.get_or_create(by=request.user, to=delegate_user)
ctx.update(
{'to': models.all_emails(delegate_user), 'delegate': delegate_user, 'delegation': delegation,}
{
'to': models.all_emails(delegate_user),
'delegate': delegate_user,
'delegation': delegation,
}
)
messages.info(request, _('New delegation to user %s created.') % delegate_user.username)
messages.info(

View File

@ -2,26 +2,26 @@ from django.db import connection
def get_sql(sql, params):
'''
"""
Execute an SQL query and return the associated cursor.
'''
"""
cursor = connection.cursor()
cursor.execute(sql, params)
return cursor
def get_sql_count(sql, params):
'''
"""
Execute a count on SUB-SELECT and return the count.
'''
"""
cursor = get_sql('''SELECT COUNT(*) FROM (%s) AS CNT''' % sql, params)
return cursor.fetchone()[0]
def get_sql_ids(sql, params):
'''
"""
Retrieve a list of numerical ids.
'''
"""
cursor = get_sql(sql, params)
return (row[0] for row in cursor.fetchall())

View File

@ -48,7 +48,8 @@ class OutboxBaseTable(tables.Table):
verbose_name=_('official_sender_header'),
)
extra_senders = tables.TemplateColumn(
'{{ record.extra_senders_display }}', verbose_name=_('Additional senders'),
'{{ record.extra_senders_display }}',
verbose_name=_('Additional senders'),
)
recipients = tables.Column(accessor='recipients', verbose_name=_('recipients_header'), orderable=False)
real_sender = tables.TemplateColumn(
@ -148,7 +149,8 @@ class InboxBaseTable(tables.Table):
verbose_name=_('sender_header'),
)
extra_senders = tables.TemplateColumn(
'{{ record.extra_senders_display }}', verbose_name=_('Additional senders'),
'{{ record.extra_senders_display }}',
verbose_name=_('Additional senders'),
)
date = tables.TemplateColumn(
'{% load humantime %}{{ record.date|humantime }}', verbose_name=_('date_header')

View File

@ -23,8 +23,8 @@ def truncate_filename(file_name):
def clean_ldap_user(user):
'''Clean references to module in django-auth-ldap User model, allowing
pickling of the instances.'''
"""Clean references to module in django-auth-ldap User model, allowing
pickling of the instances."""
user.ldap_user = None
return user

View File

@ -312,10 +312,10 @@ def get_document_and_mark_seen(request, mailbox_id, outbox):
@login_required
@never_cache
def message_attached_file(request, mailbox_id, attached_file, outbox=False):
'''
Download attached files, verify that the user has access to the document
before, otherwise return 404.
'''
"""
Download attached files, verify that the user has access to the document
before, otherwise return 404.
"""
document = get_document_and_mark_seen(request, mailbox_id, outbox)
attached_file = get_object_or_404(AttachedFile, document=document, pk=attached_file)
request.record(
@ -571,9 +571,9 @@ from django import http
def su(request, username, redirect_url='/'):
'''Allows changing user for super-users. Super-user status is kept using a
flag on the session.
'''
"""Allows changing user for super-users. Super-user status is kept using a
flag on the session.
"""
if request.user.is_superuser or request.session.get('has_superuser_power'):
request.session.pop('related_users', None)
su_user = get_object_or_404(User, username=username)
@ -667,10 +667,10 @@ class ExtraContextMixin(object):
def get_related_users(request):
'''Compute the list of users for which we can see the mailboxes, and cache
it in the session.
"""Compute the list of users for which we can see the mailboxes, and cache
it in the session.
'''
"""
if 'related_users' not in request.session:
users = [request.user]
delegations = request.user.delegations_by.select_related('by')
@ -972,7 +972,12 @@ profile = login_required(as_delegate(profile_views.FullProfileView.as_view()))
def search_terms(request, outbox=True, limit_choices=10):
q = request.GET.get('term', '')
documents = sql.get_documents(Document.objects.all(), get_related_users(request), request.user, outbox,)
documents = sql.get_documents(
Document.objects.all(),
get_related_users(request),
request.user,
outbox,
)
search = watson.search(q, models=(documents,))
choices = []
for match in search:

View File

@ -45,9 +45,9 @@ class TextInpuWithPredefinedValues(MultiWidget):
class MultiFileInput(FileInput):
'''
FileInput field supporting the multiple attribute
'''
"""
FileInput field supporting the multiple attribute
"""
def __init__(self, attrs=None):
super(MultiFileInput, self).__init__(attrs)
@ -72,7 +72,12 @@ class JqueryFileUploadFileInput(MultiFileInput):
'jquery-plugin/js/jquery.fileupload.js',
'jquery-plugin/js/jquery.fileupload-ui.js',
)
css = {'all': ('jquery-ui/css/jquery-ui-1.8.4.css', 'jquery-plugin/css/jquery.fileupload-ui.css',)}
css = {
'all': (
'jquery-ui/css/jquery-ui-1.8.4.css',
'jquery-plugin/css/jquery.fileupload-ui.css',
)
}
def __init__(self, extensions=[], attached_file_kind=None, *args, **kwargs):
self.extensions = extensions
@ -137,11 +142,11 @@ class JqueryFileUploadInput(MultiWidget):
return [self.upload_id, None]
def value_from_datadict(self, data, files, name):
'''
If some file was submitted, that's the value,
If a regular hidden_id is present, use it to find uploaded files,
otherwise return an empty list
'''
"""
If some file was submitted, that's the value,
If a regular hidden_id is present, use it to find uploaded files,
otherwise return an empty list
"""
upload_id, file_input = super(JqueryFileUploadInput, self).value_from_datadict(data, files, name)
if file_input:
pass

View File

@ -64,7 +64,8 @@ class Command(BaseCommand):
)
i += len(documents)
print(
' - Archived %10d documents' % i, '\r',
' - Archived %10d documents' % i,
'\r',
)
sys.stdout.flush()
print('')
@ -73,7 +74,8 @@ class Command(BaseCommand):
b.delete()
i += len(documents)
print(
' - Deleted %10d documents' % i, '\r',
' - Deleted %10d documents' % i,
'\r',
)
sys.stdout.flush()
print('')
@ -94,14 +96,18 @@ class Command(BaseCommand):
for journal in b:
journal_file.write("%s %s" % (journal.time, force_str(journal).replace('\n', '\n ')))
i += b.count()
print(' - Archived %10d lines\r' % i,)
print(
' - Archived %10d lines\r' % i,
)
sys.stdout.flush()
print('')
i = 0
for b in batch(journals, window):
i += b.count()
b.delete()
print(' - Deleted %10d lines\r' % i,)
print(
' - Deleted %10d lines\r' % i,
)
sys.stdout.flush()
print('')

View File

@ -83,7 +83,12 @@ TEST_RUNNER = 'django.test.runner.DiscoverRunner'
MANAGERS = ADMINS
DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docbow',}}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'docbow',
}
}
# Hey Entr'ouvert is in France !!
@ -151,7 +156,9 @@ LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'syslog': {'format': PROJECT_NAME + '(pid=%(process)d) %(levelname)s %(name)s: %(message)s',},
'syslog': {
'format': PROJECT_NAME + '(pid=%(process)d) %(levelname)s %(name)s: %(message)s',
},
'syslog_debug': {
'format': PROJECT_NAME
+ '(pid=%(process)d) %(levelname)s %(asctime)s t_%(thread)s %(name)s: %(message)s',
@ -172,12 +179,26 @@ LOGGING = {
'filters': [],
'include_html': True,
},
'console': {'class': 'logging.StreamHandler', 'formatter': 'syslog_debug', 'level': 'DEBUG',},
'console': {
'class': 'logging.StreamHandler',
'formatter': 'syslog_debug',
'level': 'DEBUG',
},
},
'loggers': {
'django.db': {'handlers': [], 'level': 'INFO', 'propagate': True,},
'django.request': {'handlers': [], 'propagate': True,},
'': {'handlers': ['syslog'], 'level': 'INFO',},
'django.db': {
'handlers': [],
'level': 'INFO',
'propagate': True,
},
'django.request': {
'handlers': [],
'propagate': True,
},
'': {
'handlers': ['syslog'],
'level': 'INFO',
},
},
}

View File

@ -25,9 +25,9 @@ class eo_sdist(sdist):
def get_version():
'''Use the VERSION, if absent generates a version with git describe, if not
tag exists, take 0.0- and add the length of the commit log.
'''
"""Use the VERSION, if absent generates a version with git describe, if not
tag exists, take 0.0- and add the length of the commit log.
"""
if os.path.exists('VERSION'):
with open('VERSION', 'r') as v:
return v.read()

View File

@ -45,7 +45,7 @@ MEDIA_ROOT = tempfile.mkdtemp()
def create_users(num_user):
""" Creates 'num_user' User objects
"""Creates 'num_user' User objects
with a DocbowProfile for each User
Return the User list
"""
@ -72,7 +72,7 @@ def admin():
def create_filetypes(num_filetype):
""" Creates 'num_filetype' FileType objects
"""Creates 'num_filetype' FileType objects
Return the list of creqted FileType objects
"""
result = []

View File

@ -9,6 +9,8 @@ MELLON_ADAPTER = ('docbow_project.pfwb.mellon_adapter.PFWBMellonAdapter',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'TEST': {'NAME': 'docbow-test-%s' % os.environ.get("BRANCH_NAME", "").replace('/', '-')[:63],},
'TEST': {
'NAME': 'docbow-test-%s' % os.environ.get("BRANCH_NAME", "").replace('/', '-')[:63],
},
}
}

View File

@ -7,7 +7,9 @@ DOCBOW_PRIVATE_DOCUMENTS = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'TEST': {'NAME': 'docbow-test-%s' % os.environ.get("BRANCH_NAME", "").replace('/', '-')[:63],},
'TEST': {
'NAME': 'docbow-test-%s' % os.environ.get("BRANCH_NAME", "").replace('/', '-')[:63],
},
}
}

View File

@ -7,6 +7,8 @@ INSTALLED_APPS += ('mellon',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'TEST': {'NAME': 'docbow-test-%s' % os.environ.get("BRANCH_NAME", "").replace('/', '-')[:63],},
'TEST': {
'NAME': 'docbow-test-%s' % os.environ.get("BRANCH_NAME", "").replace('/', '-')[:63],
},
}
}

View File

@ -125,7 +125,12 @@ def test_delete_delegate_sso(a2settings, client, monkeypatch, user):
mellon.models.UserSAMLIdentifier.objects.create(name_id='1234', issuer=issuer, user=delegate)
client.login(username='user', password='password')
client.post('/profile/', {'delegate-delete-john.doe-1.x': True,})
client.post(
'/profile/',
{
'delegate-delete-john.doe-1.x': True,
},
)
assert not user.delegations_to.count()
call_args = mock_delete.call_args[1]
assert call_args['url'] == 'https://a2-url/api/users/1234'