django-livesettings / livesettings / tests.py

  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
from django.conf import settings as djangosettings
from django.core.urlresolvers import reverse
from django.test import TestCase
import keyedcache
import livesettings
from livesettings import *
import logging
log = logging.getLogger('test');

class ConfigurationFunctionTest(TestCase):

    def testSetSingleConfigItem(self):
        value = IntegerValue(BASE_GROUP, 'SingleItem')
        config_register(value)
        self.assert_(config_exists(BASE_GROUP, 'SingleItem'))

    def testSetTwoConfigItems(self):
        s = [IntegerValue(BASE_GROUP, 'testTwoA'), StringValue(BASE_GROUP, 'testTwoB')]
        config_register_list(*s)

        self.assert_(config_exists(BASE_GROUP, 'testTwoA'))
        self.assert_(config_exists(BASE_GROUP, 'testTwoB'))

    def testSetGroup(self):
        g1 = ConfigurationGroup('test1','test1')
        value = IntegerValue(g1, 'SingleGroupedItem')
        config_register(value)
        self.assertFalse(config_exists(BASE_GROUP, 'SingleGroupedItem'))
        self.assert_(config_exists(g1, 'SingleGroupedItem'))


class ConfigurationTestSettings(TestCase):

    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()
        g = ConfigurationGroup('test2','test2')
        self.g = g
        config_register(StringValue(g, 's1'))
        config_register(IntegerValue(g, 's2', default=10))
        config_register(IntegerValue(g, 's3', default=10))

    def testSetSetting(self):
        c = config_get('test2', 's1')
        c.update('test')

        self.assertEqual(c.value, 'test')
        self.assertEqual(c.setting.value, 'test')

    def testSettingDefault(self):
        c = config_get('test2', 's2')
        self.assertEqual(c.value, 10)

    def testSetAndReset(self):
        """Test setting one value and then updating"""
        c = config_get('test2', 's1')
        c.update('test1')

        self.assertEqual(c.value, 'test1')

        # should be true, since it is an update
        self.assert_(c.update('test2'))
        self.assertEqual(c.value, 'test2')

    def testTwice(self):
        """Config items should respond False to duplicate requests to update."""

        c = config_get('test2', 's1')
        c.update('test1')

        self.assertFalse(c.update('test1'))


    def testDeletesDefault(self):
        c = config_get('test2', 's3')
        # false because it isn't saving a default value
        self.assertFalse(c.update(10))

        self.assert_(c.update(20))
        self.assertEqual(c.value, 20)
        try:
            s = c.setting
        except SettingNotSet:
            self.fail("Should have a setting now")

        # now delete and go back to no setting by setting the default
        self.assert_(c.update(10))
        self.assertEqual(c.value, 10)

        try:
            s = c.setting
            self.fail('Should throw SettingNotSet')
        except SettingNotSet:
            pass


class ConfigTestDotAccess(TestCase):
    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        g = ConfigurationGroup('test3','test3')
        self.g = g
        c1 = config_register(BooleanValue(g, 's1', default=True))
        c2 = config_register(IntegerValue(g, 's2', default=10))
        c2.update(100)

    def testDotAccess(self):
        self.assert_(ConfigurationSettings().test3.s1.value)
        self.assertEqual(ConfigurationSettings().test3.s2.value, 100)

    def testSettingProperty(self):
        c = config_get('test3','s2')
        s = c.setting
        self.assert_(s.value, 100)

    def testDictValues(self):
        d = self.g.dict_values()
        self.assertEqual(d, {'s1': True, 's2' : 100})

class ConfigTestModuleValue(TestCase):
    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        g = ConfigurationGroup('modules','module test')
        self.g = g
        self.c = config_register(ModuleValue(g, 'test'))

    def testModule(self):
        c = config_get('modules', 'test')
        c.update('django')

        self.assert_(hasattr(self.c.value, 'get_version'))

class ConfigTestSortOrder(TestCase):
    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        g1 = ConfigurationGroup('group1', 'Group 1', ordering=-1001)
        g2 = ConfigurationGroup('group2', 'Group 2', ordering=-1002)
        g3 = ConfigurationGroup('group3', 'Group 3', ordering=-1003)

        self.g1 = g1
        self.g2 = g2
        self.g3 = g3

        self.g1c1 = config_register(IntegerValue(g1, 'c1'))
        self.g1c2 = config_register(IntegerValue(g1, 'c2'))
        self.g1c3 = config_register(IntegerValue(g1, 'c3'))

        self.g2c1 = config_register(IntegerValue(g2, 'c1'))
        self.g2c2 = config_register(IntegerValue(g2, 'c2'))
        self.g2c3 = config_register(IntegerValue(g2, 'c3'))

        self.g3c1 = config_register(IntegerValue(g3, 'c1'))
        self.g3c2 = config_register(IntegerValue(g3, 'c2'))
        self.g3c3 = config_register(IntegerValue(g3, 'c3'))

    def testGroupOrdering(self):
        mgr = ConfigurationSettings()
        self.assertEqual(mgr[2].key, self.g1.key)
        self.assertEqual(mgr[1].key, self.g2.key)
        self.assertEqual(mgr[0].key, self.g3.key)


class TestMultipleValues(TestCase):

    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        g1 = ConfigurationGroup('m1', 'Multiple Group 1', ordering=1000)
        self.g1 = g1

        self.g1c1 = config_register(MultipleStringValue(g1,
            'c1',
            choices=((1,'one'),(2,'two'),(3,'three'))))

    def testSave(self):

        c = config_get('m1','c1')
        c.update([1,2])
        self.assertEqual(c.value, [1,2])

    def testAddChoice(self):

        config_add_choice('m1','c1',(4, 'four'))
        c = config_get('m1','c1')
        self.assertEqual(c.choices, ((1,'one'),(2,'two'),(3,'three'),(4,'four')))

    def testChoiceValues(self):
        self.g1c1.update([1,2])

        self.assertEqual(self.g1c1.value, [1,2])
        self.assertEqual(self.g1c1.choice_values, [(1, 'one'),(2, 'two')])

        choices = config_choice_values('m1', 'c1')
        self.assertEqual(choices, [(1, 'one'),(2, 'two')])

class TestMultipleValuesWithDefault(TestCase):

    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        g1 = ConfigurationGroup('mv2', 'Multiple Group 2', ordering=1000)
        self.g1 = g1

        self.g1c1 = config_register(MultipleStringValue(g1,
            'c1',
            choices=((1,'one'),(2,'two'),(3,'three')),
            default=[1,2]))

    def testDefault(self):

        c = config_get('mv2','c1')
        self.assertEqual(c.value, [1,2])

        c.update([1,2,3])
        self.assertEqual(c.value, [1,2,3])

class ConfigTestChoices(TestCase):

    def testAddPreregisteredChoice(self):
        """Test that we can register choices before the config is actually set up."""
        config_add_choice('ctg1', 'c1', ('a', 'Item A'))
        config_add_choice('ctg1', 'c1', ('b', 'Item B'))
        config_add_choice('ctg1', 'c1', ('c', 'Item C'))

        g1 = ConfigurationGroup('ctg1', 'Choice 1', ordering=1000)
        config_register(StringValue(g1, 'c1'))

        c = config_get('ctg1','c1')

        self.assertEqual(c.choices, [('a','Item A'), ('b','Item B'), ('c','Item C')])


class ConfigTestRequires(TestCase):

    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        g1 = ConfigurationGroup('req1', 'Requirements 1', ordering=1000)

        self.g1 = g1

        bool1 = config_register(BooleanValue(g1, 'bool1', default=False, ordering=1))
        bool2 = config_register(BooleanValue(g1, 'bool2', ordering=2))

        self.g1c1 = config_register(IntegerValue(g1, 'c1', requires=bool1, ordering=3))

        self.g1c2 = config_register(IntegerValue(g1, 'c2', requires=bool2, ordering=4))
        self.g1c3 = config_register(IntegerValue(g1, 'c3', ordering=5))

        bool2.update(True)

    def testSimpleRequires(self):

        v = config_value('req1', 'bool2')
        self.assertTrue(v)

        keys = [cfg.key for cfg in self.g1]
        self.assertEqual(keys, ['bool1', 'bool2', 'c2','c3'])

        c = config_get('req1','bool1')
        c.update(True)

        keys = [cfg.key for cfg in self.g1]
        self.assertEqual(keys, ['bool1', 'bool2', 'c1', 'c2', 'c3'])

class ConfigTestRequiresChoices(TestCase):

    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        g1 = ConfigurationGroup('req2', 'Requirements 2', ordering=1000)

        self.g1 = g1

        choices1 = config_register(MultipleStringValue(BASE_GROUP, 'rc1', ordering=1))

        self.g1c1 = config_register(IntegerValue(g1, 'c1', requires=choices1, ordering=3))
        self.g1c2 = config_register(IntegerValue(g1, 'c2', requires=choices1, ordering=4))
        self.g1c3 = config_register(IntegerValue(g1, 'c3', ordering=5))

        choices1.update('c1')

        g2 = ConfigurationGroup('req3', 'Requirements 3', ordering=1000)

        self.g2 = g2

        choices2 = config_register(StringValue(BASE_GROUP, 'choices2', ordering=1))

        self.g2c1 = config_register(IntegerValue(g2, 'c1', requires=choices2, ordering=3))
        self.g2c2 = config_register(IntegerValue(g2, 'c2', requires=choices2, ordering=4))
        self.g2c3 = config_register(IntegerValue(g2, 'c3', requires=choices2, ordering=5))

        choices2.update('c1')

    def testSimpleRequiresChoices(self):

        v = config_value('BASE', 'rc1')
        self.assertEquals(v, ['c1'])

        g = config_get_group('req2')
        keys = [cfg.key for cfg in g]
        self.assertEqual(keys, ['c1','c3'])

        c = config_get('BASE', 'rc1')
        c.update(['c1','c2'])

        g = config_get_group('req2')
        keys = [cfg.key for cfg in g]
        self.assertEqual(keys, ['c1', 'c2', 'c3'])

    def testRequiresSingleValue(self):
        v = config_value('BASE', 'choices2')
        self.assertEquals(v, 'c1')

        keys = [cfg.key for cfg in self.g2]
        self.assertEqual(keys, ['c1'])

        c = config_get('BASE', 'choices2')
        c.update('c2')

        keys = [cfg.key for cfg in self.g2]
        self.assertEqual(keys, ['c2'])

class ConfigTestRequiresValue(TestCase):

    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        g1 = ConfigurationGroup('reqval', 'Requirements 3', ordering=1000)

        self.g1 = g1

        choices1 = config_register(MultipleStringValue(BASE_GROUP, 'valchoices', ordering=1))

        self.g1c1 = config_register(IntegerValue(g1, 'c1', requires=choices1, requiresvalue='foo', ordering=3))
        self.g1c2 = config_register(IntegerValue(g1, 'c2', requires=choices1, requiresvalue='bar', ordering=4))
        self.g1c3 = config_register(IntegerValue(g1, 'c3', ordering=5))

        choices1.update('foo')

        g2 = ConfigurationGroup('reqval2', 'Requirements 4', ordering=1000)

        self.g2 = g2

        choices2 = config_register(StringValue(BASE_GROUP, 'valchoices2', ordering=1,
            choices=(('a','test a'),('b', 'test b'),('c', 'test c'))))

        self.g2c1 = config_register(IntegerValue(g2, 'c1', requires=choices2, requiresvalue='a', ordering=3))
        self.g2c2 = config_register(IntegerValue(g2, 'c2', requires=choices2, requiresvalue='b', ordering=4))
        self.g2c3 = config_register(IntegerValue(g2, 'c3', requires=choices2, requiresvalue='c', ordering=5))

        choices2.update('a')

    def testRequiresValue(self):
        v = config_value('BASE', 'valchoices')
        self.assertEquals(v, ['foo'])

        g = config_get_group('reqval')

        keys = [cfg.key for cfg in g]
        self.assertEqual(keys, ['c1','c3'])

        c = config_get('BASE', 'valchoices')
        c.update(['foo','bar'])

        g = config_get_group('reqval')
        keys = [cfg.key for cfg in g]
        self.assertEqual(keys, ['c1', 'c2', 'c3'])

    def testRequiresSingleValue(self):
        v = config_value('BASE', 'valchoices2')
        self.assertEquals(v, 'a')

        keys = [cfg.key for cfg in self.g2]
        self.assertEqual(keys, ['c1'])

        c = config_get('BASE', 'valchoices2')
        c.update('b')

        keys = [cfg.key for cfg in self.g2]
        self.assertEqual(keys, ['c2'])

class ConfigTestGroupRequires(TestCase):
    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        choices1 = config_register(MultipleStringValue(BASE_GROUP, 'groupchoice', ordering=1))
        choices2 = config_register(MultipleStringValue(BASE_GROUP, 'groupchoice2', ordering=1))

        g1 = ConfigurationGroup('groupreq', 'Requirements 4', ordering=1000, requires=choices1)
        self.g1 = g1

        self.g1c1 = config_register(IntegerValue(g1, 'c1', ordering=3))
        self.g1c2 = config_register(IntegerValue(g1, 'c2', requires=choices2, requiresvalue='bar', ordering=4))
        self.g1c3 = config_register(IntegerValue(g1, 'c3', ordering=5))

    def testRequiresValue(self):
        c = config_get('BASE', 'groupchoice')
        self.assertEquals(c.value, [])

        keys = [cfg.key for cfg in self.g1]
        self.assertEqual(keys, [])

        c2 = config_get('BASE', 'groupchoice2')
        c2.update('bar')

        keys = [cfg.key for cfg in self.g1]
        self.assertEqual(keys, ['c2'])

        c.update(['groupreq'])

        keys = [cfg.key for cfg in self.g1]
        self.assertEqual(keys, ['c1', 'c2', 'c3'])

class ConfigCollectGroup(TestCase):
    def setUp(self):
        keyedcache.cache_delete()
        choices = config_register(MultipleStringValue(BASE_GROUP, 'collect', ordering=1))
        self.choices = choices

        g1 = ConfigurationGroup('coll1', 'Collection 1')
        g2 = ConfigurationGroup('coll2', 'Collection 2')
        g3 = ConfigurationGroup('coll3', 'Collection 3')

        g1c1 = config_register(StringValue(g1, 'test'))
        g1c2 = config_register(StringValue(g1, 'test1'))
        g2c1 = config_register(StringValue(g2, 'test'))
        g3c1 = config_register(StringValue(g3, 'test'))

        g1c1.update('set a')
        g1c2.update('set b')
        g2c1.update('set a')
        g3c1.update('set d')

        choices.update(['coll1','coll3'])

    def testCollectSimple(self):
        v = config_collect_values('BASE', 'collect', 'test')

        self.assertEqual(v, ['set a', 'set d'])

    def testCollectUnique(self):
        self.choices.update(['coll1','coll2','coll3'])

        v = config_collect_values('BASE', 'collect', 'test', unique=False)

        self.assertEqual(v, ['set a', 'set a', 'set d'])

        v = config_collect_values('BASE', 'collect', 'test', unique=True)

        self.assertEqual(v, ['set a', 'set d'])

class LongSettingTest(TestCase):
    def setUp(self):
        keyedcache.cache_delete()
        wide = config_register(LongStringValue(BASE_GROUP, 'LONG', ordering=1, default="woot"))
        self.wide = wide
        self.wide.update('*' * 1000)

    def testLongStorage(self):
        w = config_value('BASE', 'LONG')
        self.assertEqual(len(w), 1000)
        self.assertEqual(w, '*'*1000)

    def testShortInLong(self):
        self.wide.update("test")
        w = config_value('BASE', 'LONG')
        self.assertEqual(len(w), 4)
        self.assertEqual(w, 'test')

    def testDelete(self):
        remember = self.wide.setting.id
        self.wide.update('woot')

        try:
            q = LongSetting.objects.get(pk = remember)
            self.fail("Should be deleted")
        except LongSetting.DoesNotExist:
            pass

class OverrideTest(TestCase):
    """Test settings overrides"""
    def setUp(self):
        # clear out cache from previous runs
        keyedcache.cache_delete()

        djangosettings.LIVESETTINGS_OPTIONS = {
            1 : {
                'DB' : False,
                'SETTINGS' : {
                        'overgroup' : {
                            's2' : '100',
                            'choices' : '["one","two","three"]'
                        }
                    }
                }
            }

        g = ConfigurationGroup('overgroup','Override Group')
        self.g = g
        config_register(StringValue(g, 's1'))
        config_register(IntegerValue(g, 's2', default=10))
        config_register(IntegerValue(g, 's3', default=10))
        config_register(MultipleStringValue(g, 'choices'))

    def tearDown(self):
        djangosettings.LIVESETTINGS_OPTIONS = {}

    def testOverriddenSetting(self):
        """Accessing an overridden setting should give the override value."""
        c = config_get('overgroup', 's2')
        self.assertEquals(c.value, 100)

    def testCantChangeSetting(self):
        """When overridden, setting a value should not work, should get the overridden value"""
        c = config_get('overgroup', 's2')
        c.update(1)

        c = config_get('overgroup', 's2')
        self.assertEquals(c.value, 100)

    def testNotOverriddenSetting(self):
        """Settings which are not overridden should return their defaults"""
        c = config_get('overgroup', 's3')

        self.assertEquals(c.value, 10)

    def testOverriddenListSetting(self):
        """Make sure lists work when overridden"""

        c = config_get('overgroup', 'choices')
        v = c.value
        self.assertEqual(len(v), 3)
        self.assertEqual(v[0], "one")
        self.assertEqual(v[1], "two")
        self.assertEqual(v[2], "three")


class PermissionTest(TestCase):
    """Test access permissions"""
    urls = 'livesettings.test_urls'

    def setUp(self):
        from django.contrib.auth.models import Permission, User
        from django.contrib.contenttypes.models import ContentType
        # Users with different permissions
        # staff member
        user1 = User.objects.create_user('warehouseman', 'john@example.com', 'secret')
        user1.is_staff = True
        user1.save()
        # developper with limited permissions
        user2 = User.objects.create_user('cautious_developer', 'fred@example.com', 'secret')
        user2.is_staff = True
        user2.user_permissions.add(Permission.objects.get(codename='change_setting', \
                content_type=ContentType.objects.get(app_label='livesettings', model='setting')))
        user2.save()
        # superuser
        user3 = User.objects.create_user('superuser', 'paul@example.com', 'secret')
        user3.is_superuser = True
        user3.save()

        keyedcache.cache_delete()
        # Example config
        config_register(IntegerValue(BASE_GROUP, 'SingleItem', default=0))

    def test_unauthorized_form(self):
        "Testing users without enought additional permission"
        # usually login_url_mask % nexturl is '/accounts/login/?next=/settings/'
        login_url_mask = '%s?next=%%s' % reverse('django.contrib.auth.views.login')
        # unauthorized
        response = self.client.get(reverse('satchmo_site_settings')) # usually '/settings/'
        self.assertRedirects(response, login_url_mask % '/settings/', msg_prefix='unathorized user should first login')
        # few authorized
        self.client.login(username='warehouseman', password='secret')
        response = self.client.get(reverse('satchmo_site_settings'))
        self.assertRedirects(response, login_url_mask % '/settings/', msg_prefix='user with small permission should not read normal settings')
        # authorized enough but not for secret values
        self.client.login(username='cautious_developer', password='secret')
        response = self.client.get(reverse('settings_export'))  # usually '/settings/export/'
        self.assertRedirects(response, login_url_mask % '/settings/export/', msg_prefix='user without superuser permission should not export sensitive settings')

    def test_authorized_enough(self):
        "Testing a sufficiently authorized user"
        self.client.login(username='cautious_developer', password='secret')
        response = self.client.get(reverse('satchmo_site_settings'))
        self.assertContains(response, 'SingleItem')
        self.client.login(username='superuser', password='secret')
        response = self.client.get(reverse('settings_export'))
        self.assertContains(response, 'LIVESETTINGS_OPTIONS = ')

    def test_export(self):
        "Details of exported settings"
        self.client.login(username='superuser', password='secret')
        val2 = IntegerValue(BASE_GROUP, 'ModifiedItem', default=0)
        config_register(val2)
        val2.update(6789)
        response = self.client.get('/settings/export/')
        self.assertContains(response, "LIVESETTINGS_OPTIONS =", 1)
        self.assertContains(response, "'DB': False", 1)
        self.assertContains(response, "u'BASE':",1)
        self.assertContains(response, "u'ModifiedItem': u'6789'", 1)

    def test_secret_password(self):
        "Verify that password is saved but not re-echoed if render_value=False"
        # example of value, where reading is more sensitive than writing
        val1 = PasswordValue(BASE_GROUP, 'password_to_reading_external_payment_gateway', render_value=False)
        config_register(val1)
        val1.update('secret')
        val2 = PasswordValue(BASE_GROUP, 'unsecure_password')
        config_register(val2)
        val2.update('unsecure_pwd')
        self.client.login(username='superuser', password='secret')
        response = self.client.get('/settings/')
        self.assertContains(response, 'password_to_reading_external_payment_gateway')
        self.assertNotContains(response, 'secret')
        self.assertContains(response, 'unsecure_password')
        self.assertContains(response, 'unsecure_pwd')


class WebClientPostTest(TestCase):
    """
    Tests of the web interface with POST.
    These tests require temporary removing all earlier defined values.
    Then are all values restored because it can be important for testing an application which uses livesettings.
    """
    urls = 'livesettings.test_urls'

    def setUp(self):
        from django.contrib.auth.models import User
        from django.utils.datastructures import SortedDict
        # The following hack works like completely replaced ConfigurationSettings internal state only, if
        # no the same group name is used inside and outside the test.
        self.saved_conf_inst = ConfigurationSettings._ConfigurationSettings__instance.settings
        ConfigurationSettings.__dict__['_ConfigurationSettings__instance'].settings = SortedDict()
        
        keyedcache.cache_delete()
        # set new users and values
        user = User.objects.create_user('admin', 'admin@example.com', 'secret')
        user.is_superuser = True
        user.save()
        self.client.login(username='admin', password='secret')
        GROUP2 = ConfigurationGroup('Group2', 'g')
        value = IntegerValue(GROUP2, 'SingleItem')
        config_register(value)

    def tearDown(self):
        # restore the original configuration
        ConfigurationSettings.__dict__['_ConfigurationSettings__instance'].settings = self.saved_conf_inst

    def test_post(self):
        "Tests of POST, verify is saved"
        response = self.client.post('/settings/', {'Group2__SingleItem': '7890'})
        # test can not use assertRedirects because it would consume the next get
        self.assertEqual((response.status_code, response.get('Location', '')), (302, 'http://testserver/settings/'))
        response = self.client.get('/settings/')
        self.assertContains(response, 'Updated')
        self.assertContains(response, '7890')

    def test_empty_fields(self):
        "test an empty value in the form should not raise an exception"
        # Some test features had been temporary commented out before some ..Values classes are fixed
        # because I do not want to display many old inconsistencies now. (hynekcer)
        def extract_val(content):
            regr = re.search(r'SingleItem.*value="([^"]*)"', content, flags=re.MULTILINE)
            return regr and regr.group(1) or ''   # html value
        def get_setting_like_in_db(x):
            try:
                return x.setting.value
            except SettingNotSet:
                return 'Error'
        def test_empty_value_type(value_type, protocol, reject_empty=False):
            "empty value can be accepted or rejected by validation rules"
            value = value_type(GROUP2, 'SingleItem')  # first it does it to easy get the class name
            type_name = value.__class__.__name__
            value = value_type(GROUP2, 'SingleItem', description = 'type %s' % type_name)
            config_register(value)
            response = self.client.get('/settings/')
            html_value = extract_val(response.content)
            #print '%s "%s"' % (type_name, html_value)
            response = self.client.post('/settings/', {'Group2__SingleItem': ''}) # See in the traceback a line one level Up
            if reject_empty:
                # option reject_empty had been tested before all Value types were fixed to be similar accepting empty value
                # this is a typical text from validation warning
                self.assertContains(response, 'Please correct the error below.')
            else:
                self.assertRedirects(response, '/settings/')
                response = self.client.get('/settings/')
                html_value = extract_val(response.content)
                #print '%s "%s" "%s" "%s"' % (type_name, html_value, value.value, get_setting_like_in_db(value))
                #self.assertNotContains(response, '<object object at 0x[0-9a-f]+>')  # rendered NOTSET = object()
                #if re.search('SingleItem.*value="', response.content):
                #    self.assertTrue(re.search('SingleItem.*value="([0.]*|\[\])"', response.content))
            protocol.add(value_type)
        #
        import re
        GROUP2 = ConfigurationGroup('Group2', 'g')
        protocol = set()
        # tested values
        test_empty_value_type(BooleanValue, protocol)
        test_empty_value_type(DecimalValue, protocol)
        test_empty_value_type(DurationValue, protocol)
        test_empty_value_type(FloatValue, protocol)
        test_empty_value_type(IntegerValue, protocol)
        test_empty_value_type(PositiveIntegerValue, protocol)
        test_empty_value_type(StringValue, protocol)
        test_empty_value_type(LongStringValue, protocol)
        test_empty_value_type(MultipleStringValue, protocol)
        test_empty_value_type(LongMultipleStringValue, protocol)
        test_empty_value_type(ModuleValue, protocol)
        test_empty_value_type(PasswordValue, protocol)
        # verify completness of the test
        classes_to_test = set(getattr(livesettings.values, k) for k in livesettings.values.__all__ if \
                not k in ('BASE_GROUP', 'ConfigurationGroup', 'Value', 'SortedDotDict', 'PercentValue'))
        self.assertEqual(protocol, classes_to_test, msg='The tested classes have been not all exactly the same as expected')

    def test_csrf(self):
        "test CSRF"
        from django.test import Client
        csrf_client = Client(enforce_csrf_checks=True)
        csrf_client.login(username='admin', password='secret')
        # get CSFR token
        response = csrf_client.get('/settings/')
        csrfmiddlewaretoken = response.context['csrf_token'] + ''
        self.assertContains(response, csrfmiddlewaretoken, msg_prefix='has not csrf')
        # expect OK
        response = csrf_client.post('/settings/', {'Group2__SingleItem': '1234', 'csrfmiddlewaretoken': csrfmiddlewaretoken})
        self.assertRedirects(response, expected_url='/settings/')
        # expect 403
        response = csrf_client.post('/settings/', {'Group2__SingleItem': '1234'})
        self.assertContains(response, 'CSRF', status_code=403, msg_prefix='should require csrf')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.