summaryrefslogtreecommitdiff
path: root/archaeological_context_records/tests.py
blob: 8349793690af30c869e3ee3168ed61cf4f2d374c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2018 Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.

import csv
import json
from StringIO import StringIO

from django.conf import settings
from django.contrib.auth.models import Permission
from django.core.exceptions import ValidationError, ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.test.client import Client

from ishtar_common.models import IshtarSiteProfile, ImporterModel, \
    UserProfile, ProfileType, Town, Area

from archaeological_operations.tests import OperationInitTest, \
    ImportTest, FILE_TOWNS_FIXTURES, FILE_FIXTURES, OPERATION_TOWNS_FIXTURES
from archaeological_operations import models as models_ope
from archaeological_context_records import models

from ishtar_common.tests import WizardTest, WizardTestFormData as FormData, \
    create_superuser, create_user, TestCase

from archaeological_context_records import views

CONTEXT_RECORD_FIXTURES = FILE_FIXTURES + [
    settings.ROOT_PATH +
    '../archaeological_context_records/fixtures/initial_data-fr.json',
    '../archaeological_context_records/fixtures/'
    'initial_data_relation_type_norel-fr.json',
    '../archaeological_context_records/fixtures/'
    'initial_data_relation_type-fr.json',
]

CONTEXT_RECORD_TOWNS_FIXTURES = FILE_TOWNS_FIXTURES + [
    settings.ROOT_PATH +
    '../archaeological_context_records/fixtures/initial_data-fr.json',
    '../archaeological_context_records/fixtures/'
    'initial_data_relation_type_norel-fr.json',
    '../archaeological_context_records/fixtures/'
    'initial_data_relation_type-fr.json',
]


class ImportContextRecordTest(ImportTest, TestCase):
    fixtures = CONTEXT_RECORD_TOWNS_FIXTURES

    def test_mcc_import_contextrecords(self):
        old_nb = models.ContextRecord.objects.count()
        mcc, form = self.init_context_record_import()

        self.assertTrue(form.is_valid())
        impt = form.save(self.ishtar_user)
        impt.initialize()

        self.init_cr_targetkey(impt)
        impt.importation()
        # new context records has now been imported
        current_nb = models.ContextRecord.objects.count()
        self.assertEqual(current_nb, old_nb + 4)
        self.assertEqual(
            models.ContextRecord.objects.filter(
                unit__txt_idx='not_in_context').count(), 3)
        self.assertEqual(
            models.ContextRecord.objects.filter(
                unit__txt_idx='negative').count(), 1)

    def test_model_limitation(self):
        old_nb = models.ContextRecord.objects.count()
        mcc, form = self.init_context_record_import()
        mcc.created_models.clear()

        self.assertTrue(form.is_valid())
        impt = form.save(self.ishtar_user)
        impt.initialize()

        self.init_cr_targetkey(impt)
        impt.importation()
        # no model defined in created_models: normal import
        current_nb = models.ContextRecord.objects.count()
        self.assertEqual(current_nb, old_nb + 4)

        # add an inadequate model to make created_models non empty
        for cr in models.ContextRecord.objects.all():
            cr.delete()
        mcc, form = self.init_context_record_import()
        mcc.created_models.clear()
        mcc.created_models.add(ImporterModel.objects.get(
            klass='ishtar_common.models.Organization'
        ))
        impt = form.save(self.ishtar_user)
        impt.initialize()
        self.init_cr_targetkey(impt)
        # Dating is not in models that can be created but force new is
        # set for a column that references Dating
        impt.importation()
        self.assertEqual(len(impt.errors), 5)
        self.assertTrue(
            "doesn't exist in the database." in impt.errors[0]['error'] or
            "n'existe pas dans la base" in impt.errors[0]['error']
        )

        # retry with only Dating (no context record)
        for cr in models.ContextRecord.objects.all():
            cr.delete()
        mcc, form = self.init_context_record_import()
        mcc.created_models.clear()
        dat_model, c = ImporterModel.objects.get_or_create(
            klass='archaeological_context_records.models.Dating',
            defaults={"name": 'Dating'})
        mcc.created_models.add(dat_model)
        impt = form.save(self.ishtar_user)
        impt.initialize()
        self.init_cr_targetkey(impt)
        impt.importation()

        current_nb = models.ContextRecord.objects.count()
        self.assertEqual(current_nb, 0)

        # add a context record model
        for cr in models.ContextRecord.objects.all():
            cr.delete()
        mcc, form = self.init_context_record_import()
        mcc.created_models.clear()
        mcc.created_models.add(ImporterModel.objects.get(
            klass='archaeological_context_records.models.ContextRecord'
        ))
        mcc.created_models.add(dat_model)
        impt = form.save(self.ishtar_user)
        impt.initialize()
        self.init_cr_targetkey(impt)
        impt.importation()
        current_nb = models.ContextRecord.objects.count()
        self.assertEqual(current_nb, 4)
        '''

        # add a context record model
        for cr in models.ContextRecord.objects.all():
            cr.delete()
        mcc, form = self.init_context_record_import()
        mcc.created_models.clear()
        mcc.created_models.add(ImporterModel.objects.get(
            klass='archaeological_context_records.models.ContextRecord'
        ))
        impt = form.save(self.ishtar_user)
        impt.initialize()
        self.init_cr_targetkey(impt)
        impt.importation()
        current_nb = models.ContextRecord.objects.count()
        self.assertEqual(current_nb, 4)
        '''


class ContextRecordInit(OperationInitTest):
    def create_context_record(self, data=None, user=None, force=False):
        if not data:
            data = {}

        if not getattr(self, 'context_records', None):
            self.context_records = []

        default = {'label': "Context record"}
        if force or not data.get('operation') \
                or not models.Operation.objects.filter(
                    pk=data['operation'].pk).count():
            data['operation'] = self.get_default_operation(force=force,
                                                           user=user)
        if not data.get('parcel') or not data['parcel'].pk \
            or not models.Parcel.objects.filter(
                pk=data['parcel'].pk).count():
            data['parcel'] = self.get_default_parcel(force=force)
        if user:
            data['history_modifier'] = user
        elif not data.get('history_modifier'):
            data['history_modifier'] = self.get_default_user()

        default.update(data)
        data['operation'] = models.Operation.objects.get(
            pk=data['operation'].pk)
        data['parcel'] = models.Parcel.objects.get(
            pk=data['parcel'].pk)
        self.context_records.append(models.ContextRecord.objects.create(
            **default))
        return self.context_records

    def get_default_context_record(self, force=False, user=None):
        if force:
            return self.create_context_record(force=force, user=user)[-1]
        return self.create_context_record(force=force, user=user)[0]

    def tearDown(self):
        if hasattr(self, 'context_records'):
            for cr in self.context_records:
                try:
                    cr.delete()
                except:
                    pass
            self.context_records = []
        super(ContextRecordInit, self).tearDown()


class ExportTest(ContextRecordInit, TestCase):
    fixtures = CONTEXT_RECORD_TOWNS_FIXTURES

    def setUp(self):
        self.username, self.password, self.user = create_superuser()

    def test_ishtar_export_ue(self):
        ope = self.create_operation()[0]
        ope.code_patriarche = "45000"
        ope.save()
        cr = self.create_context_record(data={"label": u"CR 1"})[0]
        c = Client()
        url = reverse('get-by-importer',
                      kwargs={'slug': 'ishtar-context-record',
                              'type': 'csv'})
        response = c.get(url)
        # no result when no authentication
        self.assertTrue(not response.content)
        c.login(username=self.username, password=self.password)
        response = c.get(url)
        rows = list(csv.reader(StringIO(response.content)))
        # one header + one context record
        self.assertEqual(len(rows), 2)
        row_cr = rows[1]
        self.assertEqual(row_cr[0], '45000')
        self.assertEqual(row_cr[1], '12345')
        self.assertEqual(row_cr[2], 'A1')


class ContextRecordTest(ContextRecordInit, TestCase):
    fixtures = CONTEXT_RECORD_TOWNS_FIXTURES

    def setUp(self):
        IshtarSiteProfile.objects.create()
        self.username, self.password, self.user = create_superuser()
        self.create_context_record(data={"label": u"CR 1"})
        self.create_context_record(data={"label": u"CR 2"})

        cr_1 = self.context_records[0]
        cr_2 = self.context_records[1]
        sym_rel_type = models.RelationType.objects.filter(
            symmetrical=True).all()[0]
        self.cr_rel_type = sym_rel_type
        models.RecordRelations.objects.create(
            left_record=cr_1, right_record=cr_2, relation_type=sym_rel_type)

    def test_external_id(self):
        cr = self.context_records[0]
        self.assertEqual(
            cr.external_id,
            u"{}-{}".format(cr.parcel.external_id, cr.label))

    def test_lost_parcel_dont_delete_context_record(self):
        cr = self.create_context_record(force=True)[0]
        parcel = models.Parcel.objects.get(pk=cr.parcel.pk)
        parcel.operation = None
        parcel.save()
        # associated context record is not removed
        self.assertEqual(
            models.ContextRecord.objects.filter(pk=cr.pk).count(), 1)
        # associated operation is restored
        self.assertEqual(
            models.Parcel.objects.get(pk=parcel.pk).operation,
            cr.operation
        )

    def test_search_vector_update(self):
        cr = self.create_context_record(force=True)[0]
        cr = models.ContextRecord.objects.get(pk=cr.pk)
        cr.label = "Label label"
        cr.location = "I am heeere"
        cr.save()
        for key in ('label', 'heeer'):
            self.assertIn(key, cr.search_vector)
        cr.operation.code_patriarche = "PATRIARCHE"
        cr.operation.save()
        cr = models.ContextRecord.objects.get(pk=cr.pk)
        self.assertIn(settings.ISHTAR_OPE_PREFIX.lower() + "patriarch",
                      cr.search_vector)

    def test_upstream_cache_update(self):
        cr = self.create_context_record()[0]
        cr_pk = cr.pk
        # OP2010 - 1 | A | 1 | CR 1
        ope_id, parcel_sec, parcel_nb, cr_label = cr.cached_label.split(' | ')
        self.assertEqual(ope_id, 'OP2010-1')
        self.assertEqual(parcel_sec, cr.parcel.section)
        self.assertEqual(parcel_nb, cr.parcel.parcel_number)
        self.assertEqual(cr_label, cr.label)

        new_lbl = "UE 2"
        cr.label = new_lbl
        cr.save()
        cr = models.ContextRecord.objects.get(pk=cr_pk)
        ope_id, parcel_sec, parcel_nb, cr_label = cr.cached_label.split(' | ')
        self.assertEqual(cr_label, new_lbl)

        new_sec, new_nb = "B", "42"
        parcel = cr.parcel
        parcel.section = new_sec
        parcel.parcel_number = new_nb
        parcel.save()
        cr = models.ContextRecord.objects.get(pk=cr_pk)
        ope_id, parcel_sec, parcel_nb, cr_label = cr.cached_label.split(' | ')
        self.assertEqual(parcel_sec, new_sec)
        self.assertEqual(parcel_nb, new_nb)

        cr.operation.year = 2017
        cr.operation.save()
        cr = models.ContextRecord.objects.get(pk=cr_pk)
        ope_id, parcel_sec, parcel_nb, cr_label = cr.cached_label.split(' | ')
        self.assertEqual(ope_id, 'OP2017-1')

    def test_downstream_cache_update(self):
        cr = self.create_context_record()[0]

        from archaeological_finds.models import Find, BaseFind, MaterialType

        data = {
            'label': "Find me a reason",
            'context_record': cr,
            'history_modifier': self.get_default_user()
        }
        bf = BaseFind.objects.create(**data)
        find = Find.objects.create(
            history_modifier=self.get_default_user(),
            label='Find me too'
        )
        find.base_finds.add(bf)

        mat = MaterialType.objects.create(
            label='Adamentium', txt_idx='admentium', code='ADA')
        find.material_types.add(mat)

        class TestObj(object):
            def __init__(self):
                self.find_reached = []

            def reached(self, sender, **kwargs):
                instance = kwargs.get('instance')
                if sender in (Find, BaseFind):
                    self.find_reached.append(instance)

        test_obj = TestObj()
        cr = models.ContextRecord.objects.get(pk=cr.pk)
        cr.test_obj = test_obj
        cr.label = "New label!"
        cr.save()

        # verify the relevance of the update
        bf = BaseFind.objects.get(pk=bf.pk)
        self.assertIn("New label!", bf.cache_complete_id)

        # bulk update of find cached label gen don't have to be
        # reached
        self.assertEqual(len(test_obj.find_reached), 0)

    def test_show(self):
        obj = self.context_records[0]
        c = Client()
        response = c.get(reverse('show-contextrecord', kwargs={'pk': obj.pk}))
        self.assertEqual(response.status_code, 200)
        # empty content when not allowed
        self.assertEqual(response.content, "")

        c.login(username=self.username, password=self.password)
        response = c.get(reverse('show-contextrecord', kwargs={'pk': obj.pk}))
        self.assertEqual(response.status_code, 200)
        self.assertIn('class="card sheet"', response.content)

    def test_redundant_dating_clean(self):
        obj = self.context_records[0]
        values = {'period': models.Period.objects.all()[0]}
        values_2 = {'period': models.Period.objects.all()[0],
                    'quality': models.DatingQuality.objects.all()[0]}

        obj.datings.add(models.Dating.objects.create(**values))
        obj.datings.add(models.Dating.objects.create(**values))
        obj.datings.add(models.Dating.objects.create(**values_2))
        obj.datings.add(models.Dating.objects.create(**values_2))
        self.assertEqual(obj.datings.count(), 4)
        obj.fix()
        self.assertEqual(obj.datings.count(), 2)


class ContextRecordSearchTest(ContextRecordInit, TestCase):
    fixtures = CONTEXT_RECORD_TOWNS_FIXTURES

    def setUp(self):
        IshtarSiteProfile.objects.create()
        self.username, self.password, self.user = create_superuser()
        self.create_context_record(data={"label": u"CR 1"})
        self.create_context_record(data={"label": u"CR 2"})

        cr_1 = self.context_records[0]
        cr_2 = self.context_records[1]
        sym_rel_type = models.RelationType.objects.filter(
            symmetrical=True).all()[0]
        self.cr_rel_type = sym_rel_type
        models.RecordRelations.objects.create(
            left_record=cr_1, right_record=cr_2, relation_type=sym_rel_type)

    def test_town_search(self):
        c = Client()
        c.login(username=self.username, password=self.password)

        data = {'numero_insee': '98989', 'name': 'base_town'}
        base_town = self.create_towns(datas=data)[-1]

        parcel = self.create_parcel(data={'town': base_town,
                                    'section': 'A', 'parcel_number': '1'})[-1]
        self.context_records[0].parcel = parcel
        self.context_records[0].save()

        data = {'numero_insee': '56789', 'name': 'parent_town'}
        parent_town = self.create_towns(datas=data)[-1]
        parent_town.children.add(base_town)

        data = {'numero_insee': '01234', 'name': 'child_town'}
        child_town = self.create_towns(datas=data)[-1]
        base_town.children.add(child_town)

        # simple search
        search = {'town': base_town.pk}
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['recordsTotal'], 1)

        # parent search
        search = {'town': parent_town.pk}
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['recordsTotal'], 1)

        # child search
        search = {'town': child_town.pk}
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['recordsTotal'], 1)

    def testSearchExport(self):
        c = Client()
        response = c.get(reverse('get-contextrecord'))
        # no result when no authentification
        self.assertTrue(not json.loads(response.content))
        c.login(username=self.username, password=self.password)
        response = c.get(reverse('get-contextrecord'))
        self.assertTrue(json.loads(response.content)['recordsTotal'] == 2)
        # test search label
        response = c.get(reverse('get-contextrecord'),
                         {'label': 'cr 1'})
        self.assertEqual(json.loads(response.content)['recordsTotal'], 1)
        # test search between relations
        response = c.get(reverse('get-contextrecord'),
                         {'label': 'cr 1',
                          'cr_relation_types_0': self.cr_rel_type.pk})
        self.assertEqual(json.loads(response.content)['recordsTotal'], 2)
        # test search vector
        response = c.get(reverse('get-contextrecord'),
                         {'search_vector': 'CR'})
        self.assertEqual(json.loads(response.content)['recordsTotal'], 2)
        # the 2 context records have the same operation
        response = c.get(reverse('get-contextrecord'),
                         {'search_vector': 'op2010'})
        self.assertEqual(json.loads(response.content)['recordsTotal'], 2)
        # test search between related operations
        first_ope = self.operations[0]
        first_ope.year = 2010
        first_ope.save()
        cr_1 = self.context_records[0]
        cr_1.operation = first_ope
        cr_1.save()
        other_ope = self.operations[1]
        other_ope.year = 2016
        other_ope.save()
        cr_2 = self.context_records[1]
        cr_2.operation = other_ope
        cr_2.save()
        rel_ope = models_ope.RelationType.objects.create(
            symmetrical=True, label='Linked', txt_idx='link')
        models_ope.RecordRelations.objects.create(
            left_record=other_ope,
            right_record=first_ope,
            relation_type=rel_ope)
        response = c.get(reverse('get-contextrecord'),
                         {'operation__year': 2010,
                          'ope_relation_types_0': rel_ope.pk})
        self.assertEqual(json.loads(response.content)['recordsTotal'], 2)
        # export
        response = c.get(reverse('get-contextrecord-full',
                                 kwargs={'type': 'csv'}), {'submited': '1'})
        # 2 lines + header
        lines = [line for line in response.content.split('\n') if line]
        self.assertEqual(len(lines), 3)

    def testUnitHierarchicSearch(self):
        cr = self.context_records[0]
        c = Client()

        su = models.Unit.objects.get(txt_idx='stratigraphic-unit')
        neg = models.Unit.objects.get(txt_idx='negative')
        dest = models.Unit.objects.get(txt_idx='sector')
        dest.parent = su
        dest.save()
        cr.unit = (neg)
        cr.save()
        search = {'unit': neg.pk}

        # no result when no authentication
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(not json.loads(response.content))

        # one result for exact search
        c.login(username=self.username, password=self.password)
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        res = json.loads(response.content)
        self.assertTrue(res['recordsTotal'] == 1)
        self.assertEqual(res["rows"][0]["unit"],
                         unicode(neg))

        # no result for the brother
        search = {'unit': dest.pk}
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['recordsTotal'], 0)

        # one result for the father
        search = {'unit': su.pk}
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['recordsTotal'], 1)

    def testPeriodHierarchicSearch(self):
        cr = self.context_records[0]
        c = Client()

        neo = models.Period.objects.get(txt_idx='neolithic')
        final_neo = models.Period.objects.get(txt_idx='final-neolithic')
        recent_neo = models.Period.objects.get(txt_idx='recent-neolithic')
        dating = models.Dating.objects.create(
            period=final_neo
        )
        cr.datings.add(dating)

        search = {'datings__period': final_neo.pk}

        # no result when no authentication
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(not json.loads(response.content))

        # one result for exact search
        c.login(username=self.username, password=self.password)
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        res = json.loads(response.content)
        self.assertTrue(res['recordsTotal'] == 1)

        # no result for the brother
        search = {'datings__period': recent_neo.pk}
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['recordsTotal'], 0)

        # one result for the father
        search = {'datings__period': neo.pk}
        response = c.get(reverse('get-contextrecord'), search)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['recordsTotal'], 1)


class ContextRecordPermissionTest(ContextRecordInit, TestCase):
    fixtures = CONTEXT_RECORD_TOWNS_FIXTURES

    def setUp(self):
        IshtarSiteProfile.objects.create()
        self.username, self.password, self.user = create_superuser()
        self.alt_username, self.alt_password, self.alt_user = create_user()
        self.alt_user.user_permissions.add(Permission.objects.get(
            codename='view_own_contextrecord'))
        self.alt_user.user_permissions.add(Permission.objects.get(
            codename='change_own_contextrecord'))
        self.alt_username2, self.alt_password2, self.alt_user2 = create_user(
            username='luke', password='iamyourfather'
        )
        profile = UserProfile.objects.create(
            profile_type=ProfileType.objects.get(txt_idx='collaborator'),
            person=self.alt_user2.ishtaruser.person,
            current=True
        )

        town = Town.objects.create(name='Tatouine', numero_insee='66000')
        area = Area.objects.create(label='Galaxie', txt_idx='galaxie')
        area.towns.add(town)

        profile.areas.add(area)

        self.orgas = self.create_orgas(self.user)
        self.operations = self.create_operation(self.user, self.orgas[0])
        self.operations += self.create_operation(self.alt_user, self.orgas[0])
        self.operations[1].towns.add(town)

        self.create_context_record(user=self.user, data={"label": u"CR 1",
                                         "operation": self.operations[0]})
        self.create_context_record(
            user=self.alt_user,
            data={"label": u"CR 2", "operation": self.operations[1]})
        self.cr_1 = self.context_records[0]
        self.cr_2 = self.context_records[1]

    def test_own_search(self):
        # no result when no authentification
        c = Client()
        response = c.get(reverse('get-contextrecord'))
        self.assertTrue(not json.loads(response.content))

        # possession
        c = Client()
        c.login(username=self.alt_username, password=self.alt_password)
        response = c.get(reverse('get-contextrecord'))
        # only one "own" context record available
        self.assertTrue(json.loads(response.content))
        self.assertEqual(json.loads(response.content)['recordsTotal'], 1)

        # area filter
        c = Client()
        c.login(username=self.alt_username2, password=self.alt_password2)
        response = c.get(reverse('get-contextrecord'))
        # only one "own" operation available
        self.assertTrue(json.loads(response.content))
        self.assertEqual(json.loads(response.content)['recordsTotal'], 1)

    def test_own_modify(self):
        # no result when no authentification
        c = Client()
        response = c.get(reverse('record_modify', args=[self.cr_2.pk]))
        self.assertRedirects(response, "/")

        modif_url = '/record_modification/operation-record_modification'

        # possession
        c = Client()
        c.login(username=self.alt_username, password=self.alt_password)
        response = c.get(reverse('record_modify', args=[self.cr_2.pk]),
                         follow=True)
        self.assertRedirects(response, modif_url)
        response = c.get(modif_url)

        self.assertEqual(response.status_code, 200)
        response = c.get(reverse('record_modify', args=[self.cr_1.pk]),
                         follow=True)
        self.assertRedirects(response, "/")

        # area filter
        c = Client()
        c.login(username=self.alt_username2, password=self.alt_password2)
        response = c.get(reverse('record_modify', args=[self.cr_2.pk]),
                         follow=True)
        self.assertRedirects(response, modif_url)
        response = c.get(modif_url)
        self.assertEqual(response.status_code, 200)
        response = c.get(reverse('record_modify', args=[self.cr_1.pk]),
                         follow=True)
        self.assertRedirects(response, "/")


class RecordRelationsTest(ContextRecordInit, TestCase):
    fixtures = OPERATION_TOWNS_FIXTURES
    model = models.ContextRecord

    def setUp(self):
        # two different context records
        self.create_context_record({"label": u"CR 1"})
        self.create_context_record({"label": u"CR 2"})

    def testRelations(self):
        sym_rel_type = models.RelationType.objects.create(
            symmetrical=True, txt_idx='sym')
        rel_type_1 = models.RelationType.objects.create(
            symmetrical=False, txt_idx='rel_1')
        # cannot be symmetrical and have an inverse_relation
        with self.assertRaises(ValidationError):
            rel_test = models.RelationType.objects.create(
                symmetrical=True, inverse_relation=rel_type_1, txt_idx='rel_3')
            rel_test.full_clean()
        # auto fill inverse relations
        rel_type_2 = models.RelationType.objects.create(
            symmetrical=False, inverse_relation=rel_type_1, txt_idx='rel_2')
        self.assertEqual(rel_type_1.inverse_relation, rel_type_2)

        cr_1 = self.context_records[0]
        cr_2 = self.context_records[1]

        # inserting a new symmetrical relation automatically creates the same
        # relation for the second context record
        rel = models.RecordRelations.objects.create(
            left_record=cr_1, right_record=cr_2, relation_type=sym_rel_type)
        self.assertEqual(models.RecordRelations.objects.filter(
            left_record=cr_2, right_record=cr_1,
            relation_type=sym_rel_type).count(), 1)

        # removing one symmetrical relation removes the other
        rel.delete()
        self.assertEqual(models.RecordRelations.objects.filter(
            left_record=cr_2, right_record=cr_1,
            relation_type=sym_rel_type).count(), 0)

        # for non-symmetrical relation, adding one relation automatically
        # adds the inverse
        rel = models.RecordRelations.objects.create(
            left_record=cr_1, right_record=cr_2, relation_type=rel_type_1)
        self.assertEqual(models.RecordRelations.objects.filter(
            left_record=cr_2, right_record=cr_1,
            relation_type=rel_type_2).count(), 1)


class ContextRecordWizardCreationTest(WizardTest, ContextRecordInit, TestCase):
    fixtures = OPERATION_TOWNS_FIXTURES
    url_name = 'record_creation'
    wizard_name = 'record_wizard'
    steps = views.record_creation_steps
    form_datas = [
        FormData(
            "Create a simple context record",
            form_datas={
                'selec': {},
                'general': {
                    'label': "First"
                },
                'relations': [],
            },
            ignored=('datings',
                     'interpretation',
                     )
        ),
        FormData(
            "Create a context record with a relation and datings",
            form_datas={
                'selec': {},
                'general': {
                    'label': "Second"
                },
                'relations': [],
                'datings': []
            },
            ignored=('interpretation',)
        ),
    ]

    def pre_wizard(self):
        profile, created = IshtarSiteProfile.objects.get_or_create(
            slug='default', active=True)
        profile.context_record = True
        profile.save()

        ope = self.get_default_operation()
        parcel = self.get_default_parcel()
        for form_data in self.form_datas:
            form_data.set('selec', 'operation_id', ope.pk)
            form_data.set('general', 'parcel', parcel.pk)

        self.related_cr = self.create_context_record(data={'operation': ope})[0]

        self.form_datas[1].append(
            'relations',
            {'right_record': self.related_cr.pk,
             'relation_type': models.RelationType.objects.create(
                 label="Test", symmetrical=False).pk}
        )

        period = models.Period.objects.all()[0].pk
        self.form_datas[1].append(
            'datings', {'period': period}
        )
        self.form_datas[1].append(
            'datings', {'period': period}
        )

        self.cr_nb = models.ContextRecord.objects.count()
        super(ContextRecordWizardCreationTest, self).pre_wizard()

    def post_wizard(self):
        self.assertEqual(models.ContextRecord.objects.count(),
                         self.cr_nb + 2)
        self.assertEqual(self.related_cr.left_relations.count(),
                         1)
        # identical datings, only one should be finaly save
        cr = models.ContextRecord.objects.order_by('-pk')[0]
        self.assertEqual(cr.datings.count(), 1)