Commit 0449b2c3 authored by Bryan  BRANCOTTE's avatar Bryan BRANCOTTE

Improving coverage

parent 2064ad94
{
" (C1)": {
" (r1)": "0",
" (r2)": "0"
},
" (C2)": {
" (r1)": "1",
" (r2)": "1"
}
}
\ No newline at end of file
......@@ -51,8 +51,7 @@ INSTALLED_APPS = [
'viralhostrangedb',
]
if DEBUG:
INSTALLED_APPS.append('django_extensions')
# INSTALLED_APPS.append('django_extensions')
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
......
......@@ -27,7 +27,7 @@ ViralHostResponse = namedtuple(
"col_id",
])
NameAndIdentifierRegexp = re.compile("([^(]+)([(]([^(]+)[)])?")
NameAndIdentifierRegexp = re.compile("([^(]*)([(]([^(]+)[)])?")
class ImportationObserver:
......@@ -219,8 +219,8 @@ def import_file(*, data_source, file, importation_observer: ImportationObserver
# former mapping, if present empty dict otherwise
former_mapping = dict(data_source.get_mapping(only_pk=True))
for vhr in parse_file(file, importation_observer):
if vhr.virus == "" or vhr.host == "" or vhr.response == "":
continue
# if vhr.virus == "" or vhr.host == "" or vhr.response == "":
# continue
explicit_virus = explicit_item(vhr.virus, vhr.virus_identifier)
try:
# search virus in dict
......
......@@ -8,6 +8,7 @@ from django.test import TestCase
from django.utils import timezone
from viralhostrangedb import business_process, models
from viralhostrangedb.business_process import extract_name_and_identifier, ImportationObserver
from viralhostrangedb.tests.test_views_others import ViewTestCase
logger = logging.getLogger(__name__)
......@@ -206,6 +207,18 @@ class DataFileReaderTestCase(TestCase):
self.assertEqual(models.Virus.objects.count(), 3)
self.assertEqual(models.Host.objects.count(), 4)
def test_import_in_db_failure(self):
filename = os.path.join(self.test_data, "fails.xlsx")
data_source, created = models.DataSource.objects.get_or_create(
raw_name=filename,
kind="FILE",
owner=self.owner,
creation_date=timezone.now(),
last_edition_date=timezone.now(),
)
self.assertRaises(ValueError, business_process.import_file, data_source=data_source, file=filename)
business_process.import_file(data_source=data_source, file=filename, importation_observer=ImportationObserver())
class DataFileReaderWithIdentifierTestCase(TestCase):
test_data = "./test_data"
......@@ -358,3 +371,50 @@ class ResetMappingTestCase(ViewTestCase):
self.assertFalse(models.ViralHostResponseValueInDataSource.objects \
.filter(data_source=self.four_reponse_simple) \
.filter(~Q(response=self.not_mapped_yet)).exists())
class TestOthers(TestCase):
def test_extract_name_and_identifier(self):
expected_name = "A"
expected_identifier = "i"
for p in [
"{} ({})",
"{}({})",
" {} ({})",
" {}({})",
" {}({}) ",
" {}({}) ",
"{} ( {})",
"{}( {})",
" {} ( {})",
" {}( {})",
" {}( {}) ",
" {}( {}) ",
"{} ({} )",
"{}({} )",
" {} ({} )",
" {}({} )",
" {}({} ) ",
" {}({} ) ",
]:
name, identifier = extract_name_and_identifier(p.format(expected_name, expected_identifier))
self.assertEqual(name, expected_name)
self.assertEqual(identifier, expected_identifier)
for p in [
"{}",
"{} ",
" {} ",
" {}",
]:
name, identifier = extract_name_and_identifier(p.format(expected_name))
self.assertEqual(name, expected_name)
self.assertEqual(identifier, "")
for p in [
"({})",
"({}) ",
" ({}) ",
" ({})",
]:
name, identifier = extract_name_and_identifier(p.format(expected_identifier))
self.assertEqual(name, "")
self.assertEqual(identifier, expected_identifier)
from django.contrib.auth.models import AnonymousUser
from django.test import RequestFactory
from viralhostrangedb import mixins, models
from viralhostrangedb.tests import test_models_methods
......@@ -16,6 +19,34 @@ class DataSourceDownloadTestCase(test_models_methods.ModelsTestCaseMixin):
self.assertIn(self.public_data_source_of_user_mapped.pk, my_set)
self.assertNotIn(self.private_data_source_but_granted_of_titi.pk, my_set)
def test_visibility_only_public_or_owned_or_staff_queryset_filter_req(self):
request = RequestFactory().get('/blabla')
request.user = AnonymousUser()
my_set = set([o.pk for o in mixins.only_public_or_owned_or_staff_queryset_filter(
self=None,
request=request,
queryset=models.DataSource.objects.all(),
user=None
)])
self.assertNotIn(self.private_data_source_of_user.pk, my_set)
self.assertIn(self.public_data_source_of_user.pk, my_set)
self.assertIn(self.public_data_source_of_user_mapped.pk, my_set)
self.assertNotIn(self.private_data_source_but_granted_of_titi.pk, my_set)
def test_visibility_only_public_or_owned_or_staff_queryset_filter_admin_user(self):
self.toto.is_staff = True
self.toto.save()
my_set = set([o.pk for o in mixins.only_public_or_owned_or_staff_queryset_filter(
self=None,
request=None,
queryset=models.DataSource.objects.all(),
user=self.toto
)])
self.assertIn(self.private_data_source_of_user.pk, my_set)
self.assertIn(self.public_data_source_of_user.pk, my_set)
self.assertIn(self.public_data_source_of_user_mapped.pk, my_set)
self.assertIn(self.private_data_source_but_granted_of_titi.pk, my_set)
def test_unicity_ok_only_public_or_owned_or_staff_queryset_filter(self):
my_set = set()
for ds in mixins.only_public_or_owned_or_staff_queryset_filter(
......@@ -84,6 +115,19 @@ class DataSourceDownloadTestCase(test_models_methods.ModelsTestCaseMixin):
self.assertNotIn(self.public_data_source_of_user_mapped.pk, my_set)
self.assertNotIn(self.private_data_source_but_granted_of_titi.pk, my_set)
def test_visibility_only_owned_queryset_filter_from_virus(self):
my_set = set([o.pk for o in mixins.only_owned_queryset_filter(
self=None,
request=None,
queryset=models.Virus.objects.all(),
user=self.toto,
path_to_data_source="data_source__",
)])
self.assertNotIn(self.private_data_source_of_user.pk, my_set)
self.assertNotIn(self.public_data_source_of_user.pk, my_set)
self.assertNotIn(self.public_data_source_of_user_mapped.pk, my_set)
self.assertNotIn(self.private_data_source_but_granted_of_titi.pk, my_set)
def test_unicity_ok_only_owned_queryset_filter(self):
my_set = set()
for ds in mixins.only_owned_queryset_filter(
......@@ -118,6 +162,19 @@ class DataSourceDownloadTestCase(test_models_methods.ModelsTestCaseMixin):
self.assertIn(self.public_data_source_of_user_mapped.pk, my_set)
self.assertNotIn(self.private_data_source_but_granted_of_titi.pk, my_set)
def test_visibility_only_public_or_owned_queryset_filter_req(self):
request = RequestFactory().get('/blabla')
request.user = AnonymousUser()
my_set = set([o.pk for o in mixins.only_public_or_owned_queryset_filter(
self=None,
request=request,
queryset=models.DataSource.objects.all(),
)])
self.assertNotIn(self.private_data_source_of_user.pk, my_set)
self.assertIn(self.public_data_source_of_user.pk, my_set)
self.assertIn(self.public_data_source_of_user_mapped.pk, my_set)
self.assertNotIn(self.private_data_source_but_granted_of_titi.pk, my_set)
def test_unicity_ok_only_public_or_owned_queryset_filter(self):
my_set = set()
for ds in mixins.only_public_or_owned_queryset_filter(
......
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.utils import timezone
from viralhostrangedb import models
from viralhostrangedb.templatetags.viralhostrange_tags import can_edit, can_see
class TemplateTagsTests(TestCase):
def setUp(self) -> None:
self.user = get_user_model().objects.create(
username="user",
email="b@a.a",
)
self.toto = get_user_model().objects.create(
username="toto",
email="toto@a.a",
)
self.d_user = models.DataSource.objects.create(
owner=self.user,
name="d_user",
raw_name="d_user",
creation_date=timezone.now(),
)
self.d_toto = models.DataSource.objects.create(
owner=self.toto,
name="d_toto",
raw_name="d_toto",
creation_date=timezone.now(),
)
@override_settings(DEBUG=True)
def test_can_edit_wrong_param_debug(self):
self.assertRaises(Exception, can_edit, self.user, self.user)
@override_settings(DEBUG=False)
def test_can_edit_wrong_param(self):
self.assertFalse(can_edit(self.user, self.user))
@override_settings(DEBUG=False)
def test_can_edit(self):
self.assertFalse(can_edit(self.user, self.d_toto))
self.assertFalse(can_edit(self.toto, self.d_user))
self.assertTrue(can_edit(self.toto, self.d_toto))
self.assertTrue(can_edit(self.user, self.d_user))
@override_settings(DEBUG=True)
def test_can_see_wrong_param_debug(self):
self.assertRaises(Exception, can_see, self.user, self.user)
self.assertRaises(NotImplementedError, can_see, self.user, get_user_model().objects.all())
@override_settings(DEBUG=False)
def test_can_see_wrong_param(self):
self.assertFalse(can_see(self.user, self.user))
@override_settings(DEBUG=False)
def test_can_see(self):
self.assertFalse(can_see(self.user, self.d_toto))
self.assertFalse(can_see(self.toto, self.d_user))
self.assertTrue(can_see(self.toto, self.d_toto))
self.assertTrue(can_see(self.user, self.d_user))
......@@ -7,7 +7,7 @@ from django.urls import reverse
from viralhostrangedb import models, mixins
from viralhostrangedb.tests.test_views_others import ViewTestCase
from viralhostrangedb.views_api import MyAPIView
from viralhostrangedb.views_api import MyAPIView, to_int_array
class ResponseAggregatedTestCase(ViewTestCase):
......@@ -727,6 +727,11 @@ class DummyTest(TestCase):
class InfectionRatioTestCase(ViewTestCase):
def test_wrong_slug(self):
url = reverse('viralhostrangedb-api:aggregated-infection-ratio-list', args=["toto"]) + "?virus=%i" % self.r1.pk
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
def test_works__and_focus_list_or_detail_idempotent(self):
url = reverse('viralhostrangedb-api:aggregated-infection-ratio-detail', args=[
"virus",
......@@ -970,6 +975,12 @@ class InfectionRatioTestCase(ViewTestCase):
class SearchTestCase(ViewTestCase):
def test_ko(self):
url = reverse('viralhostrangedb-api:search')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertIn("err", json.loads(response.content, encoding='utf8'))
def test_works_no_auth(self):
url = reverse('viralhostrangedb-api:search') + "?search=privateprivateprivate"
response = self.client.get(url)
......@@ -987,6 +998,14 @@ class SearchTestCase(ViewTestCase):
response = json.loads(response.content, encoding='utf8')
self.assertGreater(response["data_source"]["count"], 0)
def test_works_ui_help(self):
url = reverse('viralhostrangedb-api:search') + "?search=private%20user&ui_help=True"
self.client.force_login(self.user)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
response = json.loads(response.content, encoding='utf8')
self.assertGreater(response["data_source"]["count"], 0)
def test_privacy_cross_auth(self):
url = reverse('viralhostrangedb-api:search') + "?search=private%20user"
self.client.force_login(self.toto)
......@@ -1032,3 +1051,8 @@ class SearchTestCase(ViewTestCase):
self.client.logout()
response = json.loads(self.client.get(url).content, encoding='utf8')
self.assertEqual(response["host"]["count"], 0)
class OtherTests(TestCase):
def test_functions(self):
self.assertEqual(list(to_int_array(["e", "1", "2", "1", "1"])), [1, 2, 1, 1])
......@@ -653,6 +653,10 @@ class VirusDetailViewTestCase(ViewTestCase):
self.client.force_login(self.toto)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.rx.identifier = "ee"
self.rx.save()
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_cross_users(self):
url = reverse('viralhostrangedb:virus-detail', args=[self.rx.pk])
......@@ -683,6 +687,10 @@ class HostDetailViewTestCase(ViewTestCase):
self.client.force_login(self.toto)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.Cx.identifier = "ee"
self.Cx.save()
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_cross_users(self):
url = reverse('viralhostrangedb:host-detail', args=[self.Cx.pk])
......
......@@ -3,7 +3,7 @@ from typing import List
from urllib.parse import urlencode
from django.db.models import Avg, Q, Count, Func, When, IntegerField, Case, Value, Max, Min
from django.http import JsonResponse
from django.http import JsonResponse, HttpResponseBadRequest
from django.urls import reverse
from rest_framework import views as drf_views, viewsets
from rest_framework.filters import BaseFilterBackend
......@@ -266,8 +266,8 @@ class VirusInfectionRatioViewSet(MyAPIView):
other_slug = 'host'
elif slug == 'host':
other_slug = 'virus'
elif slug != None:
return NotImplementedError("unknown slug '%s'" % slug)
else:
return HttpResponseBadRequest("unknown slug '%s'" % slug)
# filter only for the current slug
if slug_pk != None:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment