Skip to content

Commit

Permalink
Merge pull request #111 from biocompute-objects/104-unit-testing-for-api
Browse files Browse the repository at this point in the history
104 unit testing for api
  • Loading branch information
HadleyKing authored Apr 28, 2022
2 parents 56f1a20 + 43725fb commit fa15d62
Show file tree
Hide file tree
Showing 6 changed files with 170 additions and 57 deletions.
20 changes: 13 additions & 7 deletions bco_api/api/model/groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
from api.scripts.utilities.DbUtils import DbUtils
from api.scripts.utilities.UserUtils import UserUtils


usr_utils = UserUtils()
db_utils = DbUtils()


class GroupInfo(models.Model):
"""Some additional information for Group.
This information is stored separately from
Expand All @@ -26,7 +26,7 @@ class GroupInfo(models.Model):
"""

delete_members_on_group_deletion = models.BooleanField(default=False)
description = models.TextField(blank = True)
description = models.TextField(blank=True)
expiration = models.DateTimeField(blank=True, null=True)
group = models.ForeignKey(Group, on_delete=models.CASCADE, to_field='name')
max_n_members = models.IntegerField(blank=True, null=True)
Expand Down Expand Up @@ -66,6 +66,7 @@ def post_api_groups_info(request):
# user.get_all_permissions()
# user.get_group_permissions()


def post_api_groups_create(request):
"""
Instantiate any necessary imports.
Expand Down Expand Up @@ -113,7 +114,6 @@ def post_api_groups_create(request):
creation_object['max_n_members'] = -1

Group.objects.create(name=creation_object['name'])

group_admin.groups.add(
Group.objects.get(name=creation_object['name'])
)
Expand Down Expand Up @@ -178,6 +178,7 @@ def post_api_groups_create(request):

return Response(status=status.HTTP_200_OK, data=returning)


def post_api_groups_delete(request):
"""Instantiate any necessary imports."""

Expand All @@ -196,7 +197,7 @@ def post_api_groups_delete(request):
# the request.
returning = []
any_failed = False

# Since bulk_request is an array, go over each
# item in the array.
for deletion_object in bulk_request:
Expand All @@ -220,15 +221,15 @@ def post_api_groups_delete(request):
if deleted_count < 3:
# Too few deleted, error with this delete
returning.append(db_utils.messages(parameters={
'group': grouped.name })['404_missing_bulk_parameters'])
'group': grouped.name})['404_missing_bulk_parameters'])
any_failed = True
continue

elif deleted_count > 3:
print(deleted_count, 'deleted_count')
# We don't expect there to be duplicates, so while this was successful it should throw a warning
returning.append(db_utils.messages(parameters={
'group': grouped.name })['418_too_many_deleted'])
'group': grouped.name})['418_too_many_deleted'])
any_failed = True
continue
# Everything looks OK
Expand All @@ -247,6 +248,7 @@ def post_api_groups_delete(request):

return Response(status=status.HTTP_200_OK, data=returning)


def post_api_groups_modify(request):
"""Instantiate any necessary imports."""

Expand Down Expand Up @@ -280,6 +282,10 @@ def post_api_groups_modify(request):

# Check that the requestor is the group admin.
if requestor_info.is_superuser == True or grouped in requestor_info.groups.all():
# TODO: We shouldn't use a try/except as an if statement; I think there is actually
# a get_or_create() function:
# group_information = GroupInfo.objects.get_or_create(group=grouped, owner_user=requestor_info)
# But would need to be tested
try:
group_information = GroupInfo.objects.get(group=grouped)
except:
Expand Down Expand Up @@ -370,7 +376,6 @@ def post_api_groups_modify(request):
for user in users:
user.groups.add(grouped)


# Get the users in the groups provided, if any.
if 'inherit_from' in action_set:
# Get all the groups first, then get the user list.
Expand All @@ -397,6 +402,7 @@ def post_api_groups_modify(request):
# but NOT necessarily each item in the request.
return Response(status=status.HTTP_200_OK, data=returning)


@receiver(post_save, sender=User)
def associate_user_group(sender, instance, created, **kwargs):
"""Create Group and GroupInfo
Expand Down
13 changes: 13 additions & 0 deletions bco_api/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,19 @@ class new_users(models.Model):
# Source: https://stackoverflow.com/a/32411560
created = models.DateTimeField(default=timezone.now)

def __email__(self):
return str(self.email)

def __token__(self):
return str(self.token)

def __hostname__(self):
return str(self.hostname)

def __temp_identifier__(self):
return str(self.temp_identifier)




# def get_first_name(self):
Expand Down
42 changes: 30 additions & 12 deletions bco_api/api/tests/test_model_bco.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,39 @@
# from django.urls import reverse
from api.models import BCO


class BcoTestCase(TestCase):
"""Test for BCO"""

def setUp(self):
self.object_id_root = 'BCO_000001'
self.object_id_version = '/1.5'
self.owner_user = 'anon'
self.owner_group = 'bco_drafter'
self.prefix = 'BCO'
self.schema = 'IEEE'
self.state = 'PUBLISHED'
self.object_id = 'http://localhost:8000/{}{}'.format(self.object_id_root, self.object_id_version)

def create_bco(self):
"""Create Test BCO
Generates a sample BCO to verify that all fields that can be
dynamically created pass a functional test.
"""

json_file = open('api/tests/test_bcos.json')
data = json.load(json_file)
return BCO.objects.create(
contents=json.dumps(data[0]),
object_class=None,
object_id='http://localhost:8000/BCO_000001/1.5',
owner_user=User.objects.get(username='anon'),
owner_group=Group.objects.get(name='bco_drafter'),
prefix='BCO',
schema='IEEE',
state='PUBLISHED',
object_id=self.object_id,
owner_user=User.objects.get(username=self.owner_user),
owner_group=Group.objects.get(name=self.owner_group),
prefix=self.prefix,
schema=self.schema,
state=self.state,
last_update=timezone.now()
)

Expand All @@ -42,16 +56,20 @@ def test_bco_creation(self):
biocompute = self.create_bco()
self.assertTrue(isinstance(biocompute, BCO))
self.assertEqual(biocompute.__str__(), biocompute.object_id)
self.assertEqual(biocompute.__str__(), self.object_id)
self.assertEqual(biocompute.state, self.state)
self.assertEqual(biocompute.schema, self.schema)
self.assertEqual(str(biocompute.prefix), self.prefix)
self.assertEqual(biocompute.owner_group, Group.objects.get(name=self.owner_group))
self.assertEqual(biocompute.owner_user, User.objects.get(username=self.owner_user))

def test_bco_view(self):
"""Test BCO Published view submission
"""

biocompute = self.create_bco()
self.assertTrue(isinstance(biocompute, BCO))
object_id_root = 'BCO_000001'
object_id_version = '/1.5'
resp = self.client.get(f'/{object_id_root}{object_id_version}')
bco_respone = json.loads(resp.data[0])
self.assertTrue(isinstance(bco_respone, dict))
resp = self.client.get(f'/{self.object_id_root}{self.object_id_version}')
bco_response = json.loads(resp.data[0])
self.assertTrue(isinstance(bco_response, dict))
self.assertEqual(resp.status_code, 200)
50 changes: 36 additions & 14 deletions bco_api/api/tests/test_model_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,65 @@
import json
from django.test import TestCase
from django.contrib.auth.models import Group, User
from django.utils import timezone
from datetime import timedelta
# from django.urls import reverse
from api.model.groups import GroupInfo


class GroupsTestCase(TestCase):
"""Test for BCO"""

def setUp(self):
self.group_name = "test"
self.username = "wheel"
self.delete_members_on_group_deletion = False
self.description = "A test group."
self.max_n_members = 100
self.expiration = timezone.now() + timedelta(seconds=600) # make valid for 10 minutes

def create_group(self):
"""Create Test Group
"""

json_file = open('api/tests/test_bcos.json')
data = json.load(json_file)

return [
Group.objects.create(name='test'),
# Return a tuple so we can distinguish easier in the test_group_creation (readability)
return (
Group.objects.create(name=self.group_name),
GroupInfo.objects.create(
delete_members_on_group_deletion=False,
group=Group.objects.get(name='test'),
owner_user=User.objects.get(username='wheel'),
delete_members_on_group_deletion=self.delete_members_on_group_deletion,
group=Group.objects.get(name=self.group_name),
owner_user=User.objects.get(username=self.username),
description=self.description,
max_n_members=self.max_n_members,
expiration=self.expiration
)
]
)

def test_group_creation(self):
"""Test Group creation
Creates Group,
Creates Group, asserts that group and group info are properly set.
"""

new_group = self.create_group()
self.assertTrue(isinstance(new_group[0], Group))
self.assertTrue(isinstance(new_group[1], GroupInfo))
new_group, new_group_info = self.create_group()
# Group assertions
self.assertTrue(isinstance(new_group, Group))
self.assertEqual(new_group.name, self.group_name)

# GroupInfo assertions
self.assertTrue(isinstance(new_group_info, GroupInfo))
self.assertEqual(new_group_info.delete_members_on_group_deletion, self.delete_members_on_group_deletion)
self.assertEqual(new_group_info.description, self.description)
self.assertEqual(new_group_info.group, Group.objects.get(name=self.group_name))
self.assertEqual(new_group_info.owner_user, User.objects.get(username=self.username))
self.assertEqual(new_group_info.max_n_members, self.max_n_members)
self.assertEqual(new_group_info.expiration, self.expiration)

# def test_bco_view(self):
# """Test BCO Published view submission
# """

# biocompute = self.create_bco()
# self.assertTrue(isinstance(biocompute, BCO))
# object_id_root = 'BCO_000001'
Expand Down
47 changes: 47 additions & 0 deletions bco_api/api/tests/test_model_new_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env python3

"""Models Testing
"""

import json
from django.test import TestCase
from django.utils import timezone
from django.contrib.auth.models import Group, Permission, User
# from django.urls import reverse
from api.models import new_users


class NewUserTestCase(TestCase):
"""Test for BCO"""

def setUp(self):
self.email = "[email protected]"
self.temp_identifier = "OOO"
self.token = "SampleToken"
self.hostname = "UserDB"

def create_user(self):
"""Create Test User
"""

return new_users.objects.create(
email="[email protected]",
temp_identifier="OOO",
token="SampleToken",
hostname="UserDB"
)

def test_user_creation(self):
"""Test user creation
Creates new user, asserts that it is an instance of new_user, and asserts the email,
token, and hostname match.
"""

user = self.create_user()
self.assertTrue(isinstance(user, new_users))
self.assertEqual(user.__email__(), self.email)
self.assertEqual(user.__token__(), self.token)
self.assertEqual(user.__hostname__(), self.hostname)
self.assertEqual(user.__temp_identifier__(), self.temp_identifier)
Loading

0 comments on commit fa15d62

Please sign in to comment.