Skip to content

Commit

Permalink
Task admin tests resolves #881
Browse files Browse the repository at this point in the history
  • Loading branch information
k1o0 committed Jan 8, 2025
1 parent e5274c6 commit 33b6c15
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 3 deletions.
1 change: 1 addition & 0 deletions alyx/alyx/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,7 @@ def has_change_permission(self, request, obj=None):
# [CR 2024-03-12]
# HACK: following a request by Charu R from cortexlab, we authorize all users in the
# special Husbandry group to edit litters.
# FIXME This should be moved to the individual model admin has_change_permission methods
husbandry = 'husbandry' in ', '.join(_.name.lower() for _ in request.user.groups.all())
if husbandry:
if obj.__class__.__name__ in ('Litter', 'Subject', 'BreedingPair'):
Expand Down
2 changes: 2 additions & 0 deletions alyx/jobs/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class TaskAdmin(BaseAdmin):
def has_change_permission(self, request, obj=None):
if request.user.is_superuser:
return True
if request.user.is_public_user:
return False
if obj:
if obj.session:
# Check if session user or member of the same lab
Expand Down
4 changes: 1 addition & 3 deletions alyx/jobs/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from django.contrib.auth import get_user_model
from django.urls import reverse
from django.core.management import call_command
from datetime import datetime, timedelta

from actions.models import Session
Expand All @@ -15,10 +14,9 @@


class APISubjectsTests(BaseTests):
fixtures = ['experiments.probemodel.json', 'experiments.brainregion.json']

def setUp(self):
call_command('loaddata', 'experiments/fixtures/experiments.probemodel.json', verbosity=0)
call_command('loaddata', 'experiments/fixtures/experiments.brainregion.json', verbosity=0)
self.superuser = get_user_model().objects.create_superuser('test', 'test', 'test')
self.client.login(username='test', password='test')
self.session = Session.objects.first()
Expand Down
80 changes: 80 additions & 0 deletions alyx/jobs/tests_admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
from unittest.mock import MagicMock

from django.test import TestCase
from django.test import Client
from django.contrib.admin.sites import AdminSite
from django.forms import fields
# from django.contrib.auth.models import Group, Permission

from misc.models import LabMember, Lab, LabMembership
from subjects.models import Subject
from actions.models import Session
from data.models import DataRepositoryType, DataRepository
from misc.management.commands.set_user_permissions import Command
from jobs.admin import TaskAdmin
from jobs.models import Task


class TestJobsAdminViews(TestCase):
fixtures = ['data.datarepositorytype.json', 'misc.lab.json']

def setUp(self):
self.client = Client()
self.user = LabMember.objects.create_user(
username='foo', password='bar123', email='foo@example.com')
self.user.is_staff = self.user.is_active = True # used by below Command instance
self.user.save()

self.superuser = LabMember.objects.create_superuser(
username='admin', password='admin', email='admin@example.com')
Command().handle() # set user group permissions
self.client.login(username='foo', password='bar123')
repo_type = DataRepositoryType.objects.get(name='Fileserver')
self.repo = DataRepository.objects.create(name='test_repo', repository_type=repo_type)
self.task = Task.objects.create(
name='test_task', status=10, level=0, data_repository=self.repo)
self.lab = Lab.objects.get(name='cortexlab')
self.lab.repositories.add(self.repo)

def test_admin_add_form_view(self):
"""Test the task add form view."""
response = self.client.get('/admin/jobs/task/add/', follow=True)
self.assertEqual(response.status_code, 200)
self.client.login(username='admin', password='admin')
response = self.client.get('/admin/jobs/task/add/', follow=True)
self.assertEqual(response.status_code, 200)
ta = TaskAdmin(model=Task, admin_site=AdminSite())
self.assertCountEqual(['session', 'log', 'parents'], ta.readonly_fields)
request = MagicMock()
request.user = self.user
form = ta.get_form(request)
# All model fields should be present in the form except the following
expected = {'session', 'id', 'datetime', 'log'}
excluded = {x.name for x in Task._meta.fields} - set(form.base_fields.keys())
self.assertEqual(expected, excluded)
self.assertIsInstance(form.base_fields['status'], fields.ChoiceField)
# response = ta.add_view(request) # in future we may want to test form submission

def test_has_change_permission(self):
"""Test the has_change_permission method of the TaskAdmin class."""
ta = TaskAdmin(model=Task, admin_site=AdminSite())
request = MagicMock()
request.user = self.user

self.assertEqual(18, len(ta.get_fields(request)))
# Check if the user has permission to change a task
self.assertFalse(ta.has_change_permission(request))
self.assertFalse(ta.has_change_permission(request, obj=self.task))
# Check if the user has permission to change task when member of the same lab
membership = LabMembership.objects.create(lab=self.lab, user=self.user)
self.user.lab_id().contains(self.lab)
self.assertTrue(ta.has_change_permission(request, obj=self.task))
# Check if the user has permission to change task when user of the task session
membership.delete()
subject = Subject.objects.create(nickname='586', lab=self.lab)
session = Session.objects.create(
subject=subject, number=1, type='Experiment', task_protocol='foo')
session.users.add(self.user)
# Check superuser permissions
request.user = self.superuser
self.assertTrue(ta.has_change_permission(request))

0 comments on commit 33b6c15

Please sign in to comment.