<commit_before>from django.test import TestCase
from django.contrib.auth import get_user_model
from django.contrib.gis.geos import Polygon, Point
from django.urls import reverse
from io import BytesIO
import json
# from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
# from unittest import skip
import uuid

from occurrence.models import (
    AreaEncounter, ObservationGroup, HabitatComposition, PlantCount, CountMethod, CountAccuracy,
    AnimalObservation, SecondarySigns, FileAttachment, SampleType, TaxonAreaEncounter,
    EncounterType,
)
from taxonomy.models import Taxon

User = get_user_model()


class AreaEncounterSerializerTests(TestCase):

    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user('testuser', '<EMAIL>', '<PASSWORD>')
        self.user.is_staff = True
        self.user.is_superuser = True  # TODO: test user/group permissions properly
        self.user.save()
        self.client.login(username='testuser', password='<PASSWORD>')
        # token = Token.objects.get(user__username='testuser')
        # self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
        self.ae = AreaEncounter.objects.create(
            source_id=uuid.uuid4(),
            description='Test polygon AreaEncounter',
            geom=Polygon(((115.0, -32.0), (115.0, -33.0), (116.0, -33.0), (116.0, -32.0), (115.0, -32.0)))
        )
        self.ae_point = AreaEncounter.objects.create(
            source_id=uuid.uuid4(),
            description='Test point AreaEncounter',
            point=Point((115.0, -32.0))
        )
        self.og = ObservationGroup.objects.create(encounter=self.ae)
        self.hc = HabitatComposition.objects.create(encounter=self.ae)
        self.taxon = Taxon.objects.create(name_id=0, name='Test taxon')
        self.taxon_ae = TaxonAreaEncounter.objects.create(
            source_id=uuid.uuid4(),
            description='Test taxon area encounter',
            geom=self.ae.geom,
            taxon=self.taxon
        )
        self.enc_type = EncounterType.objects.create(code='enctype', label='Encounter type')

    def test_occ_areas_get(self):
        for i in ['occurrence_area_polys', 'occurrence_area_points', 'occurrence_taxonarea_polys', 'occurrence_taxonarea_points']:
            url = reverse('api:{}-list'.format(i))
            resp = self.client.get(url, {'format': 'json'})
            self.assertEqual(resp.status_code, 200)

    def test_occ_areas_post(self):
        url = reverse('api:occurrence_area_polys-list') + '?format=json'
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'geom': 'POLYGON ((115 -32, 115 -33, 116 -33, 116 -32, 115 -32))',
            },
        )
        self.assertEqual(resp.status_code, 201)
        data = json.loads(resp.content)
        url = reverse('api:occurrence_area_polys-detail', kwargs={'pk': data['id']})
        # Also check the detail view for the new object.
        resp = self.client.get(url, {'format': 'json'})
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.content)
        self.assertEqual(data['geometry']['type'], 'Polygon')

    def test_occ_points_post(self):
        url = reverse('api:occurrence_area_points-list')
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'point': 'POINT (115 -32)',
            },
        )
        self.assertEqual(resp.status_code, 201)

    def test_occ_taxonareas_post(self):
        url = reverse('api:occurrence_taxonarea_polys-list') + '?format=json'
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'taxon': self.taxon.name_id,
                'encountered_by': self.user.pk,
                'encounter_type': self.enc_type.pk,
                'geom': 'POLYGON ((115 -32, 115 -33, 116 -33, 116 -32, 115 -32))',
            },
        )
        self.assertEqual(resp.status_code, 201)
        data = json.loads(resp.content)
        url = reverse('api:occurrence_taxonarea_polys-detail', kwargs={'pk': data['id']})
        # Also check the detail view for the new object.
        resp = self.client.get(url, {'format': 'json'})
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.content)
        self.assertEqual(data['geometry']['type'], 'Polygon')

    def test_occ_taxonpoints_post(self):
        url = reverse('api:occurrence_taxonarea_points-list')
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'taxon': self.taxon.name_id,
                'encountered_by': self.user.pk,
                'encounter_type': self.enc_type.pk,
                'point': 'POINT (115 -32)',
            },
        )
        self.assertEqual(resp.status_code, 201)

class ObservationGroupSerializerTests(AreaEncounterSerializerTests):

    def setUp(self):
        super(ObservationGroupSerializerTests, self).setUp()
        self.url = reverse('api:occurrence_observation_group-list')

    def test_occ_observation_get(self):
        """Test the occurrence_observation_group API endpoint, unfiltered
        """
        resp = self.client.get(self.url, {'format': 'json'})
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.content)
        # Response should return two objects.
        self.assertEqual(data['count'], 2)

    def test_occ_observation_get_filtered(self):
        """Test the occurrence_observation_group API endpoint, filtered
        """
        resp = self.client.get(self.url, {'format': 'json', 'obstype': 'HabitatComposition'})
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.content)
        # Response should return one HabitatComposition object (no ObservationGroup objects).
        self.assertEqual(data['count'], 1)
        self.assertFalse('ObservationGroup' in [i['obstype'] for i in data['results']])
<commit_msg>Add unit tests to POST CommunityAreaEncounter model types.<commit_after>from django.test import TestCase
from django.contrib.auth import get_user_model
from django.contrib.gis.geos import Polygon, Point
from django.urls import reverse
from io import BytesIO
import json
# from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
# from unittest import skip
import uuid

from occurrence.models import (
    AreaEncounter, ObservationGroup, HabitatComposition, CountMethod, CountAccuracy,
    EncounterType, SecondarySigns, SampleType, TaxonAreaEncounter, CommunityAreaEncounter,
)
from taxonomy.models import Community, Taxon

User = get_user_model()


class AreaEncounterSerializerTests(TestCase):

    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user('testuser', '<EMAIL>', '<PASSWORD>')
        self.user.is_staff = True
        self.user.is_superuser = True  # TODO: test user/group permissions properly
        self.user.save()
        self.client.login(username='testuser', password='<PASSWORD>')
        # token = Token.objects.get(user__username='testuser')
        # self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
        self.ae = AreaEncounter.objects.create(
            source_id=uuid.uuid4(),
            description='Test polygon AreaEncounter',
            geom=Polygon(((115.0, -32.0), (115.0, -33.0), (116.0, -33.0), (116.0, -32.0), (115.0, -32.0)))
        )
        self.ae_point = AreaEncounter.objects.create(
            source_id=uuid.uuid4(),
            description='Test point AreaEncounter',
            point=Point((115.0, -32.0))
        )
        self.og = ObservationGroup.objects.create(encounter=self.ae)
        self.hc = HabitatComposition.objects.create(encounter=self.ae)
        self.taxon = Taxon.objects.create(name_id=0, name='Test taxon')
        self.taxon_ae = TaxonAreaEncounter.objects.create(
            source_id=uuid.uuid4(),
            description='Test taxon area encounter',
            geom=self.ae.geom,
            taxon=self.taxon
        )
        self.enc_type = EncounterType.objects.create(code='enctype', label='Encounter type')

    def test_occ_areas_get(self):
        for i in [
            'occurrence_area_polys', 'occurrence_area_points', 'occurrence_taxonarea_polys',
            'occurrence_taxonarea_points', 'occurrence_communityarea_polys', 'occurrence_communityarea_points',
        ]:
            url = reverse('api:{}-list'.format(i))
            resp = self.client.get(url, {'format': 'json'})
            self.assertEqual(resp.status_code, 200)

    def test_occ_areas_post(self):
        url = reverse('api:occurrence_area_polys-list') + '?format=json'
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'geom': 'POLYGON ((115 -32, 115 -33, 116 -33, 116 -32, 115 -32))',
            },
        )
        self.assertEqual(resp.status_code, 201)
        data = json.loads(resp.content)
        url = reverse('api:occurrence_area_polys-detail', kwargs={'pk': data['id']})
        # Also check the detail view for the new object.
        resp = self.client.get(url, {'format': 'json'})
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.content)
        self.assertEqual(data['geometry']['type'], 'Polygon')

    def test_occ_points_post(self):
        url = reverse('api:occurrence_area_points-list')
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'point': 'POINT (115 -32)',
            },
        )
        self.assertEqual(resp.status_code, 201)

    def test_occ_taxonareas_post(self):
        url = reverse('api:occurrence_taxonarea_polys-list') + '?format=json'
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'taxon': self.taxon.name_id,
                'encountered_by': self.user.pk,
                'encounter_type': self.enc_type.pk,
                'geom': 'POLYGON ((115 -32, 115 -33, 116 -33, 116 -32, 115 -32))',
            },
        )
        self.assertEqual(resp.status_code, 201)
        data = json.loads(resp.content)
        url = reverse('api:occurrence_taxonarea_polys-detail', kwargs={'pk': data['id']})
        # Also check the detail view for the new object.
        resp = self.client.get(url, {'format': 'json'})
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.content)
        self.assertEqual(data['geometry']['type'], 'Polygon')

    def test_occ_taxonpoints_post(self):
        url = reverse('api:occurrence_taxonarea_points-list')
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'taxon': self.taxon.name_id,
                'encountered_by': self.user.pk,
                'encounter_type': self.enc_type.pk,
                'point': 'POINT (115 -32)',
            },
        )
        self.assertEqual(resp.status_code, 201)

    def test_occ_communityareas_post(self):
        community = Community.objects.create(code='comm1', name='Test community')
        url = reverse('api:occurrence_communityarea_polys-list')
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'community': 'comm1',
                'encountered_by': self.user.pk,
                'encounter_type': self.enc_type.pk,
                'geom': 'POLYGON ((115 -32, 115 -33, 116 -33, 116 -32, 115 -32))',
            },
        )
        self.assertEqual(resp.status_code, 201)

    def test_occ_communitypoints_post(self):
        community = Community.objects.create(code='comm1', name='Test community')
        url = reverse('api:occurrence_communityarea_points-list')
        resp = self.client.post(
            url,
            {
                'source': 0,
                'source_id': str(uuid.uuid4()),
                'code': 'code',
                'label': 'Label',
                'name': 'Name',
                'community': 'comm1',
                'encountered_by': self.user.pk,
                'encounter_type': self.enc_type.pk,
                'point': 'POINT (115 -32)',
            },
        )
        self.assertEqual(resp.status_code, 201)


class ObservationGroupSerializerTests(AreaEncounterSerializerTests):

    def setUp(self):
        super(ObservationGroupSerializerTests, self).setUp()
        self.url = reverse('api:occurrence_observation_group-list')

    def test_occ_observation_get(self):
        """Test the occurrence_observation_group API endpoint, unfiltered
        """
        resp = self.client.get(self.url, {'format': 'json'})
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.content)
        # Response should return two objects.
        self.assertEqual(data['count'], 2)

    def test_occ_observation_get_filtered(self):
        """Test the occurrence_observation_group API endpoint, filtered
        """
        resp = self.client.get(self.url, {'format': 'json', 'obstype': 'HabitatComposition'})
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.content)
        # Response should return one HabitatComposition object (no ObservationGroup objects).
        self.assertEqual(data['count'], 1)
        self.assertFalse('ObservationGroup' in [i['obstype'] for i in data['results']])

{'fraction_non_alphanumeric': 0.13170533721166205, 'fraction_numerical': 0.022322938510451192, 'mean_word_length': 2.2104234527687296, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4200181', 'n_tokens_mistral': 4694, 'n_tokens_neox': 4347, 'n_words': 852}