wheezy.validation / src / wheezy / validation / rules.py

Andriy Kornatsky… bac5e9a 



Andriy Kornatsky… 0075e75 

Andriy Kornatsky… b7f2ec9 



Andriy Kornatsky… 4f54570 
Andriy Kornatsky… 0075e75 
Andriy Kornatsky… 4f54570 

Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… b7f2ec9 
Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… bac5e9a 

Andriy Kornatsky… 474e626 
Andriy Kornatsky… 08cb601 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… bac5e9a 
Andriy Kornatsky… bbb37d8 













Andriy Kornatsky… fbc2590 
Andriy Kornatsky… 4d9aa78 




Andriy Kornatsky… bbb37d8 

Andriy Kornatsky… 4d9aa78 

Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 




Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 



Andriy Kornatsky… b7f2ec9 


Andriy Kornatsky… 4d9aa78 



Andriy Kornatsky… b7f2ec9 
Andriy Kornatsky… fbc2590 
Andriy Kornatsky… bac5e9a 



Andriy Kornatsky… 5b4e5dd 


Andriy Kornatsky… f22815c 
Andriy Kornatsky… 5b4e5dd 
















































Andriy Kornatsky… bac5e9a 
Andriy Kornatsky… 474e626 


Andriy Kornatsky… f22815c 
Andriy Kornatsky… bac5e9a 
Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 




Andriy Kornatsky… f22815c 
Andriy Kornatsky… 4d9aa78 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… 4d9aa78 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… 4d9aa78 

Andriy Kornatsky… bac5e9a 



Andriy Kornatsky… f22815c 
Andriy Kornatsky… bbb37d8 


Andriy Kornatsky… bac5e9a 

Andriy Kornatsky… f22815c 
Andriy Kornatsky… bbb37d8 


Andriy Kornatsky… bac5e9a 


Andriy Kornatsky… f22815c 
Andriy Kornatsky… bbb37d8 

Andriy Kornatsky… bac5e9a 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… bac5e9a 
Andriy Kornatsky… fbc2590 
Andriy Kornatsky… 4d9aa78 




Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 



Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 4d9aa78 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 4d9aa78 

Andriy Kornatsky… bbb37d8 

Andriy Kornatsky… 4d9aa78 

Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 




Andriy Kornatsky… f22815c 

Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 


Andriy Kornatsky… f22815c 







Andriy Kornatsky… 4d9aa78 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 4d9aa78 

Andriy Kornatsky… bbb37d8 

Andriy Kornatsky… 4d9aa78 

Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 




Andriy Kornatsky… f22815c 

Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 


Andriy Kornatsky… f22815c 







Andriy Kornatsky… 4d9aa78 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 4d9aa78 
Andriy Kornatsky… bbb37d8 

Andriy Kornatsky… 4d9aa78 
Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 

Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 




Andriy Kornatsky… f22815c 

Andriy Kornatsky… bbb37d8 
Andriy Kornatsky… 4d9aa78 







Andriy Kornatsky… f22815c 







Andriy Kornatsky… bac5e9a 

Andriy Kornatsky… 4f54570 
Andriy Kornatsky… 08cb601 
Andriy Kornatsky… 474e626 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… 4f54570 
Andriy Kornatsky… 9538608 
Andriy Kornatsky… 4f54570 




Andriy Kornatsky… f22815c 
Andriy Kornatsky… 9538608 

Andriy Kornatsky… f22815c 
Andriy Kornatsky… 4f54570 


Andriy Kornatsky… f22815c 
Andriy Kornatsky… 4f54570 


Andriy Kornatsky… 9538608 

Andriy Kornatsky… f22815c 
Andriy Kornatsky… 9538608 


Andriy Kornatsky… f22815c 

Andriy Kornatsky… 4f54570 







Andriy Kornatsky… f22815c 

Andriy Kornatsky… 4f54570 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 4f54570 














Andriy Kornatsky… f22815c 







Andriy Kornatsky… 9538608 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 9538608 













Andriy Kornatsky… 4f54570 
Andriy Kornatsky… f22815c 






Andriy Kornatsky… 4f54570 
Andriy Kornatsky… 0075e75 



Andriy Kornatsky… f22815c 
Andriy Kornatsky… 0075e75 
Andriy Kornatsky… d7bbf37 
Andriy Kornatsky… 0075e75 




Andriy Kornatsky… 33b0a0a 
Andriy Kornatsky… 0075e75 






Andriy Kornatsky… d7bbf37 







Andriy Kornatsky… 0075e75 
Andriy Kornatsky… d7bbf37 
Andriy Kornatsky… 0075e75 

Andriy Kornatsky… 33b0a0a 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 0075e75 




Andriy Kornatsky… f22815c 

Andriy Kornatsky… 0075e75 




Andriy Kornatsky… d7bbf37 



Andriy Kornatsky… f22815c 



Andriy Kornatsky… d7bbf37 


Andriy Kornatsky… f22815c 

Andriy Kornatsky… d7bbf37 




Andriy Kornatsky… 33b0a0a 










Andriy Kornatsky… f22815c 
Andriy Kornatsky… 33b0a0a 

Andriy Kornatsky… d7bbf37 

Andriy Kornatsky… 57549b1 
Andriy Kornatsky… 33b0a0a 






















Andriy Kornatsky… f22815c 
Andriy Kornatsky… 33b0a0a 


Andriy Kornatsky… d7bbf37 

Andriy Kornatsky… 33b0a0a 
Andriy Kornatsky… 57549b1 
Andriy Kornatsky… 33b0a0a 










Andriy Kornatsky… 53ab867 










Andriy Kornatsky… 57549b1 

Andriy Kornatsky… 53ab867 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… 53ab867 






Andriy Kornatsky… f22815c 
Andriy Kornatsky… 53ab867 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… 53ab867 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… 53ab867 





Andriy Kornatsky… f22815c 
Andriy Kornatsky… 53ab867 
Andriy Kornatsky… 57549b1 
Andriy Kornatsky… 53ab867 

Andriy Kornatsky… f22815c 
Andriy Kornatsky… 53ab867 
Andriy Kornatsky… 57549b1 

Andriy Kornatsky… 53ab867 


Andriy Kornatsky… f22815c 
Andriy Kornatsky… 53ab867 
Andriy Kornatsky… 57549b1 
Andriy Kornatsky… 53ab867 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… 53ab867 













Andriy Kornatsky… f22815c 

Andriy Kornatsky… 53ab867 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 53ab867 

Andriy Kornatsky… b7f2ec9 
Andriy Kornatsky… 53ab867 








Andriy Kornatsky… f22815c 

Andriy Kornatsky… 53ab867 



Andriy Kornatsky… f22815c 







Andriy Kornatsky… 53ab867 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 53ab867 

Andriy Kornatsky… b7f2ec9 
Andriy Kornatsky… 53ab867 








Andriy Kornatsky… f22815c 

Andriy Kornatsky… 53ab867 



Andriy Kornatsky… f22815c 







Andriy Kornatsky… 53ab867 
Andriy Kornatsky… f22815c 

Andriy Kornatsky… 53ab867 

Andriy Kornatsky… b7f2ec9 
Andriy Kornatsky… 53ab867 









Andriy Kornatsky… f22815c 

Andriy Kornatsky… 53ab867 








Andriy Kornatsky… f22815c 






Andriy Kornatsky… 53ab867 

Andriy Kornatsky… afde5be 
Andriy Kornatsky… d371115 
Andriy Kornatsky… afde5be 









Andriy Kornatsky… f22815c 
Andriy Kornatsky… afde5be 



Andriy Kornatsky… f22815c 
Andriy Kornatsky… afde5be 












Andriy Kornatsky… 2f4a5fe 













Andriy Kornatsky… f22815c 
Andriy Kornatsky… 2f4a5fe 



Andriy Kornatsky… f22815c 
Andriy Kornatsky… 2f4a5fe 















Andriy Kornatsky… afde5be 




Andriy Kornatsky… f22815c 

Andriy Kornatsky… afde5be 




Andriy Kornatsky… f22815c 
Andriy Kornatsky… afde5be 



Andriy Kornatsky… f22815c 
Andriy Kornatsky… afde5be 







Andriy Kornatsky… f22815c 

Andriy Kornatsky… afde5be 









Andriy Kornatsky… 8a2a3a4 




Andriy Kornatsky… f22815c 
Andriy Kornatsky… 8a2a3a4 

Andriy Kornatsky… f22815c 

Andriy Kornatsky… 8a2a3a4 

Andriy Kornatsky… f22815c 


Andriy Kornatsky… 8a2a3a4 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… 8a2a3a4 

























Andriy Kornatsky… f22815c 
Andriy Kornatsky… 8a2a3a4 







Andriy Kornatsky… f22815c 
Andriy Kornatsky… 8a2a3a4 



Andriy Kornatsky… f22815c 
Andriy Kornatsky… 8a2a3a4 




Andriy Kornatsky… f22815c 
Andriy Kornatsky… 8a2a3a4 


Andriy Kornatsky… f22815c 
Andriy Kornatsky… 8a2a3a4 







Andriy Kornatsky… f22815c 

Andriy Kornatsky… 8a2a3a4 






Andriy Kornatsky… f22815c 

Andriy Kornatsky… 8a2a3a4 






Andriy Kornatsky… f22815c 

Andriy Kornatsky… 8a2a3a4 


















Andriy Kornatsky… 9538608 
Andriy Kornatsky… 8a2a3a4 

Andriy Kornatsky… f22815c 

Andriy Kornatsky… 8a2a3a4 








Andriy Kornatsky… f22815c 

Andriy Kornatsky… 8a2a3a4 









Andriy Kornatsky… f22815c 

Andriy Kornatsky… 8a2a3a4 








Andriy Kornatsky… f22815c 
Andriy Kornatsky… 8a2a3a4 















Andriy Kornatsky… 9538608 
Andriy Kornatsky… 8a2a3a4 






























Andriy Kornatsky… f22815c 
Andriy Kornatsky… 8a2a3a4 




Andriy Kornatsky… afde5be 
Andriy Kornatsky… f22815c 
Andriy Kornatsky… afde5be 




Andriy Kornatsky… 53ab867 
Andriy Kornatsky… afde5be 
Andriy Kornatsky… 2f4a5fe 
Andriy Kornatsky… afde5be 
Andriy Kornatsky… 8a2a3a4 

  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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
""" ``rules`` module.
"""

import re

from datetime import date
from datetime import datetime
from datetime import time

from wheezy.validation.comp import ref_getter
from wheezy.validation.comp import regex_pattern


_ = lambda s: s
required_but_missing = [date.min, datetime.min, time.min]


class RequiredRule(object):
    """ Any value evaluated to boolean ``True`` pass this rule.
    """
    __slots__ = ('message_template')

    def __init__(self, message_template=None):
        self.message_template = message_template or _(
                'Required field cannot be left blank.')

    def __call__(self, message_template):
        """ Let you customize message template.

            >>> r = required('customized')
            >>> assert r != required
            >>> r.message_template
            'customized'
        """
        return RequiredRule(message_template)

    def validate(self, value, name, model, result, gettext):
        """
            If ``value`` is evaluated to ``False`` than it cause
            this rule to fail.

            >>> result = []
            >>> r = RequiredRule(message_template='required')
            >>> r.validate(None, None, None, result, _)
            False
            >>> result
            ['required']

            Anything that python interprets as ``True`` is passing
            this rule.

            >>> result = []
            >>> r.validate('abc', None, None, result, _)
            True
            >>> result
            []

            >>> r.validate(date.min, None, None, result, _)
            False

            ``required`` is a shortcut

            >>> assert isinstance(required, RequiredRule)
        """
        if not value or value in required_but_missing:
            result.append(gettext(self.message_template))
            return False
        return True


class MissingRule(object):
    """ Any value evaluated to boolean ``False`` pass this rule.
    """
    __slots__ = ('message_template')

    def __init__(self, message_template=None):
        self.message_template = message_template or _(
                'Field cannot have a value.')

    def __call__(self, message_template):
        """ Let you customize message template.

            >>> r = missing('customized')
            >>> assert r != missing
            >>> r.message_template
            'customized'
        """
        return MissingRule(message_template)

    def validate(self, value, name, model, result, gettext):
        """
            If ``value`` is evaluated to ``True`` than it cause
            this rule to fail.

            >>> result = []
            >>> r = MissingRule(message_template='error')
            >>> r.validate(100, None, None, result, _)
            False
            >>> result
            ['error']

            Anything that python interprets as ``False`` is passing
            this rule.

            >>> result = []
            >>> r.validate('', None, None, result, _)
            True
            >>> result
            []

            >>> r.validate(date.min, None, None, result, _)
            True

            ``missing`` is a shortcut

            >>> assert isinstance(missing, MissingRule)
        """
        if value and value not in required_but_missing:
            result.append(gettext(self.message_template))
            return False
        return True


class LengthRule(object):
    """ Result of python function ``len()`` must fall within a range
        defined by this rule.
    """
    __slots__ = ('validate', 'min', 'max', 'message_template')

    def __init__(self, min=None, max=None, message_template=None):
        """
            Initialization selects the most appropriate validation
            strategy.

            >>> r = LengthRule(min=2)
            >>> assert r.validate == r.check_min
            >>> r = LengthRule(max=2)
            >>> assert r.validate == r.check_max
            >>> r = LengthRule()
            >>> assert r.validate == r.succeed
            >>> r = LengthRule(min=1, max=2)
        """
        if min:
            self.min = min
            if not max:
                self.min = min
                self.validate = self.check_min
                self.message_template = message_template or _(
                        'Required to be a minimum of %(min)d characters'
                        ' in length.')
            else:
                self.max = max
                self.validate = self.check
                self.message_template = message_template or _(
                        'The length must fall within the range %(min)d'
                        ' - %(max)d characters.')
        else:
            if max:
                self.max = max
                self.validate = self.check_max
                self.message_template = message_template or _(
                        'Exceeds maximum length of %(max)d.')
            else:
                self.validate = self.succeed

    def succeed(self, value, name, model, result, gettext):
        """
            >>> r = LengthRule()

            Succeed if ``value`` is None

            >>> r.validate(None, None, None, None, _)
            True

            Since no range specified it chooses ``succeed`` strategy.

            >>> r.validate('abc', None, None, None, _)
            True
        """
        return True

    def check_min(self, value, name, model, result, gettext):
        """ ``check_min`` strategy fails

            >>> result = []
            >>> r = LengthRule(min=2, message_template='min %(min)d')
            >>> r.validate('a', None, None, result, _)
            False
            >>> result
            ['min 2']

            ``check_min`` strategy succeed

            >>> result = []
            >>> r = LengthRule(min=2)
            >>> r.validate(None, None, None, result, _)
            True
            >>> r.validate('ab', None, None, result, _)
            True
            >>> result
            []
        """
        if value is None:
            return True
        if len(value) < self.min:
            result.append(gettext(self.message_template)
                    % {'min': self.min})
            return False
        return True

    def check_max(self, value, name, model, result, gettext):
        """ ``check_max`` strategy fails

            >>> result = []
            >>> r = LengthRule(max=2, message_template='max %(max)d')
            >>> r.validate('abc', None, None, result, _)
            False
            >>> result
            ['max 2']

            ``check_max`` strategy succeed

            >>> result = []
            >>> r = LengthRule(max=2)
            >>> r.validate(None, None, None, result, _)
            True
            >>> r.validate('ab', None, None, result, _)
            True
            >>> result
            []
        """
        if value is None:
            return True
        if len(value) > self.max:
            result.append(gettext(self.message_template)
                    % {'max': self.max})
            return False
        return True

    def check(self, value, name, model, result, gettext):
        """ ``check`` strategy fails

            >>> r = LengthRule(min=2, max=3,
            ...         message_template='range %(min)d-%(max)d')
            >>> result = []
            >>> r.validate('a', None, None, result, _)
            False
            >>> result
            ['range 2-3']

            ``check`` strategy succeed

            >>> result = []
            >>> r = LengthRule(min=1, max=2)
            >>> r.validate(None, None, None, result, _)
            True
            >>> r.validate('ab', None, None, result, _)
            True
            >>> result
            []

            ``length`` is shortcut

            >>> assert length is LengthRule
        """
        if value is None:
            return True
        l = len(value)
        if l < self.min or l > self.max:
            result.append(gettext(self.message_template)
                    % {'min': self.min, 'max': self.max})
            return False
        return True


class CompareRule(object):
    """ Compares attribute being validated with some other attribute value.
    """
    __slots__ = ('validate', 'comparand', 'message_template')

    def __init__(self, equal=None, not_equal=None, message_template=None):
        """
            Initialization selects the most appropriate validation
            strategy.

            >>> r = CompareRule(equal='confirm_password')
            >>> assert r.validate == r.check_equal

            >>> r = CompareRule(not_equal='other')
            >>> assert r.validate == r.check_not_equal
        """
        if equal:
            self.comparand = equal
            self.validate = self.check_equal
            self.message_template = message_template or _(
                    'The value failed equality comparison'
                    ' with "%(comparand)s".')
        elif not_equal:
            self.comparand = not_equal
            self.validate = self.check_not_equal
            self.message_template = message_template or _(
                    'The value failed not equal comparison'
                    ' with "%(comparand)s".')
        else:
            self.validate = self.check

    def check(self, value, name, model, result, gettext):
        """
            No any comparer selected

            >>> r = CompareRule()
            >>> r.validate('abc', None, None, None, _)
            True
        """
        return True

    def check_equal(self, value, name, model, result, gettext):
        """
            ``check_equal`` strategy succeed.

            >>> result = []
            >>> r = CompareRule(equal='confirm_password')
            >>> model = {
            ...         'confirm_password': 'x'
            ... }
            >>> r.validate('x', None, model, result, _)
            True

            ``check_equal`` strategy fails.

            >>> result = []
            >>> r.validate('z', None, model, result, _)
            False
        """
        getter = ref_getter(model)
        comparand_value = getter(model, self.comparand)
        if value != comparand_value:
            result.append(gettext(self.message_template)
                    % {'comparand': self.comparand})
            return False
        return True

    def check_not_equal(self, value, name, model, result, gettext):
        """ ``check_not_equal`` strategy succeed.

            >>> result = []
            >>> r = CompareRule(not_equal='previous_password')
            >>> model = {
            ...         'previous_password': 'x'
            ... }
            >>> r.validate('y', None, model, result, _)
            True

            ``check_not_equal`` strategy fails.

            >>> result = []
            >>> r.validate('x', None, model, result, _)
            False
        """
        getter = ref_getter(model)
        comparand_value = getter(model, self.comparand)
        if value == comparand_value:
            result.append(gettext(self.message_template)
                    % {'comparand': self.comparand})
            return False
        return True


class RegexRule(object):
    """ Search for regular expression pattern.
    """
    __slots__ = ('validate', 'regex', 'message_template')

    def __init__(self, regex=None, negated=False, message_template=None):
        """
            ``regex`` - a regular expression pattern to search for
            or a pre-compiled regular expression.

            >>> result = []
            >>> r = regex(re.compile(r'\w+'))
            >>> r.validate('x', None, None, result, _)
            True
        """
        if isinstance(regex, regex_pattern):
            self.regex = re.compile(regex)
        else:
            self.regex = regex
        if negated:
            self.validate = self.check_not_found
            self.message_template = message_template or _(
                    'Required to not match validation pattern.')
        else:
            self.validate = self.check_found
            self.message_template = message_template or _(
                    'Required to match validation pattern.')

    def check_found(self, value, name, model, result, gettext):
        """
            >>> result = []
            >>> r = RegexRule(r'\d+')
            >>> r.validate(None, None, None, result, _)
            True
            >>> r.validate('1234', None, None, result, _)
            True
            >>> r.validate('x', None, None, result, _)
            False
        """
        if value is None:
            return True
        if not self.regex.search(value):
            result.append(gettext(self.message_template))
            return False
        return True

    def check_not_found(self, value, name, model, result, gettext):
        """
            >>> result = []
            >>> r = RegexRule(r'\d+', negated=True)
            >>> r.validate(None, None, None, result, _)
            True
            >>> r.validate('x', None, None, result, _)
            True
            >>> r.validate('1234', None, None, result, _)
            False
        """
        if value is None:
            return True
        if self.regex.search(value):
            result.append(gettext(self.message_template))
            return False
        return True


class SlugRule(RegexRule):
    """ Ensures only letters, numbers, underscores or hyphens.

        >>> r = slug
        >>> result = []
        >>> r.validate('x14', None, None, result, _)
        True
        >>> r.validate('x%', None, None, result, _)
        False
    """
    __slots__ = ()

    def __init__(self, message_template=None):
        super(SlugRule, self).__init__(r'^[-\w]+$', False,
                message_template or _(
        'Invalid slug. The value must consist of letters, '
        'digits, underscopes and/or hyphens.'))

    def __call__(self, message_template):
        """ Let you customize message template.

            >>> r = slug('customized')
            >>> assert r != slug
            >>> r.message_template
            'customized'
        """
        return SlugRule(message_template)


class EmailRule(RegexRule):
    """ Ensures a valid email.

        >>> r = email
        >>> result = []
        >>> r.validate('x.14@somewhere.org', None, None, result, _)
        True
        >>> r.validate('x%', None, None, result, _)
        False
    """
    __slots__ = ()

    def __init__(self, message_template=None):
        super(EmailRule, self).__init__(
                re.compile(r'[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,5}',
                    re.IGNORECASE), False,
                message_template or
                _('Required to be a valid email address.'))

    def __call__(self, message_template):
        """ Let you customize message template.

            >>> r = email('customized')
            >>> assert r != slug
            >>> r.message_template
            'customized'
        """
        return EmailRule(message_template)


class RangeRule(object):
    """ Ensures value is in range defined by this rule.

        Works with any numbers including decimal.

        >>> from decimal import Decimal
        >>> result = []
        >>> r = range(max=Decimal('15.79'))
        >>> r.validate(Decimal('10'), None, None, result, _)
        True
        >>> r.validate(Decimal('20'), None, None, result, _)
        False
    """
    __slots__ = ('validate', 'min', 'max', 'message_template')

    def __init__(self, min=None, max=None, message_template=None):
        """
            Initialization selects the most appropriate validation
            strategy.

            >>> r = RangeRule(min=2)
            >>> assert r.validate == r.check_min
            >>> r = RangeRule(max=2)
            >>> assert r.validate == r.check_max
            >>> r = RangeRule()
            >>> assert r.validate == r.succeed
            >>> r = RangeRule(min=1, max=2)
        """
        if min:
            self.min = min
            if not max:
                self.min = min
                self.validate = self.check_min
                self.message_template = message_template or _(
                        'Required to be greater or equal to %(min)s.')
            else:
                self.max = max
                self.validate = self.check
                self.message_template = message_template or _(
                        'The value must fall within the range %(min)s'
                        ' - %(max)s')
        else:
            if max:
                self.max = max
                self.validate = self.check_max
                self.message_template = message_template or _(
                        'Exceeds maximum allowed value of %(max)s.')
            else:
                self.validate = self.succeed

    def succeed(self, value, name, model, result, gettext):
        """
            >>> r = RangeRule()

            Succeed if ``value`` is None

            >>> r.validate(None, None, None, None, _)
            True

            Since no range specified it chooses ``succeed`` strategy.

            >>> r.validate(100, None, None, None, _)
            True
        """
        return True

    def check_min(self, value, name, model, result, gettext):
        """ ``check_min`` strategy fails

            >>> result = []
            >>> r = RangeRule(min=10, message_template='min %(min)s')
            >>> r.validate(1, None, None, result, _)
            False
            >>> result
            ['min 10']

            ``check_min`` strategy succeed

            >>> result = []
            >>> r = RangeRule(min=10)
            >>> r.validate(None, None, None, result, _)
            True
            >>> r.validate(10, None, None, result, _)
            True
            >>> result
            []
        """
        if value is None:
            return True
        if value < self.min:
            result.append(gettext(self.message_template)
                    % {'min': self.min})
            return False
        return True

    def check_max(self, value, name, model, result, gettext):
        """ ``check_max`` strategy fails

            >>> result = []
            >>> r = RangeRule(max=10, message_template='max %(max)s')
            >>> r.validate(11, None, None, result, _)
            False
            >>> result
            ['max 10']

            ``check_max`` strategy succeed

            >>> result = []
            >>> r = RangeRule(max=10)
            >>> r.validate(None, None, None, result, _)
            True
            >>> r.validate(10, None, None, result, _)
            True
            >>> result
            []
        """
        if value is None:
            return True
        if value > self.max:
            result.append(gettext(self.message_template)
                    % {'max': self.max})
            return False
        return True

    def check(self, value, name, model, result, gettext):
        """ ``check`` strategy fails

            >>> r = RangeRule(min=2, max=3,
            ...         message_template='range %(min)s-%(max)s')
            >>> result = []
            >>> r.validate(1, None, None, result, _)
            False
            >>> result
            ['range 2-3']

            ``check`` strategy succeed

            >>> result = []
            >>> r = RangeRule(min=1, max=2)
            >>> r.validate(None, None, None, result, _)
            True
            >>> r.validate(2, None, None, result, _)
            True
            >>> result
            []

            ``length`` is shortcut

            >>> assert length is LengthRule
        """
        if value is None:
            return True
        if value < self.min or value > self.max:
            result.append(gettext(self.message_template)
                    % {'min': self.min, 'max': self.max})
            return False
        return True


class AndRule(object):
    """ Applies all ``rules`` regardless of validation result.

        >>> result = []
        >>> r = and_(required, range(1, 5))
        >>> r.validate(1, None, None, result, _)
        True
        >>> r.validate(0, None, None, result, _)
        False
        >>> len(result)
        2
    """
    __slots__ = ('rules')

    def __init__(self, *rules):
        """ Initializes rule by converting ``rules`` to tuple.
        """
        assert len(rules) > 1
        self.rules = tuple(rules)

    def validate(self, value, name, model, result, gettext):
        """ Iterate over each rule and check whenever any item in value fail.

            ``value`` - iteratable.
        """
        succeed = True
        for rule in self.rules:
            succeed &= rule.validate(value, name, model, result, gettext)
        return succeed


class OrRule(object):
    """ Succeed if at least one rule in ``rules`` succeed.

        >>> result = []
        >>> r = or_(range(1, 5), range(11, 15))
        >>> r.validate(1, None, None, result, _)
        True
        >>> r.validate(12, None, None, result, _)
        True
        >>> r.validate(0, None, None, result, _)
        False
        >>> len(result)
        2
    """
    __slots__ = ('rules')

    def __init__(self, *rules):
        """ Initializes rule by converting ``rules`` to tuple.
        """
        assert len(rules) > 1
        self.rules = tuple(rules)

    def validate(self, value, name, model, result, gettext):
        """ Iterate over each rule and check whenever value fail.
            Stop on first succeed.
        """
        succeed = True
        r = []
        for rule in self.rules:
            succeed = rule.validate(value, name, model, r, gettext)
            if succeed:
                return True
        result.extend(r)
        return succeed


class IteratorRule(object):
    """ Applies ``rules`` to each item.

        >>> result = []
        >>> r = iterator([required, range(1, 5)])
        >>> r.validate(None, None, None, result, _)
        True
        >>> r.validate([1, 2, 3], None, None, result, _)
        True
        >>> r.validate([1, 7], None, None, result, _)
        False
    """
    __slots__ = ('rules', 'stop')

    def __init__(self, rules, stop=True):
        """ Initializes rule by converting ``rules`` to tuple.
        """
        assert rules
        self.rules = tuple(rules)
        self.stop = stop

    def validate(self, value, name, model, result, gettext):
        """ Iterate over each rule and check whenever any item in value fail.

            ``value`` - iteratable.
        """
        if value is None:
            return True
        succeed = True
        for rule in self.rules:
            for item in value:
                rule_succeed = rule.validate(item, name, model,
                        result, gettext)
                succeed &= rule_succeed
                if not rule_succeed and self.stop:
                    break
        return succeed


class OneOfRule(object):
    """ Value must match at least one element from ``items``.

        >>> result = []
        >>> r = one_of([1, 2, 3, None])
        >>> r.validate(3, None, None, result, _)
        True
        >>> r.validate(None, None, None, result, _)
        True
        >>> r.validate(7, None, None, result, _)
        False
        >>> r = one_of([1, 2, 3])
        >>> r.validate(None, None, None, result, _)
        False
    """
    __slots__ = ('items', 'message_template')

    def __init__(self, items, message_template=None):
        """
        """
        self.items = tuple(items)
        self.message_template = message_template or _(
                'The value does not belong to the list of known items.')

    def validate(self, value, name, model, result, gettext):
        """ Check whenever value belongs to ``self.items``.
        """
        if value not in self.items:
            result.append(gettext(self.message_template))
            return False
        return True


class RelativeDeltaRule(object):
    """ Check if value is in relative date/time range.

        >>> r = RelativeDeltaRule()
        >>> r.now() # doctest: +ELLIPSIS
        Traceback (most recent call last):
            ...
        NotImplementedError: ...
    """
    __slots__ = ('validate', 'min', 'max', 'message_template')

    def __init__(self, min=None, max=None, message_template=None):
        """
        """
        if min:
            self.min = min
            if not max:
                self.min = min
                self.validate = self.check_min
                self.message_template = message_template or _(
                        'Required to be above a minimum allowed.')
            else:
                self.max = max
                self.validate = self.check
                self.message_template = message_template or _(
                        'Must fall within a valid range.')
        else:
            if max:
                self.max = max
                self.validate = self.check_max
                self.message_template = message_template or _(
                        'Exceeds maximum allowed.')
            else:
                self.validate = self.succeed

    def now(self):
        raise NotImplementedError('Subclasses must override method now()')

    def succeed(self, value, name, model, result, gettext):
        return True

    def check_min(self, value, name, model, result, gettext):
        if value is None:
            return True
        if value < self.now() + self.min:
            result.append(gettext(self.message_template)
                    % {'min': self.min})
            return False
        return True

    def check_max(self, value, name, model, result, gettext):
        if value is None:
            return True
        if value > self.now() + self.max:
            result.append(gettext(self.message_template)
                    % {'max': self.max})
            return False
        return True

    def check(self, value, name, model, result, gettext):
        if value is None:
            return True
        now = self.now()
        if value < now + self.min or value > now + self.max:
            result.append(gettext(self.message_template)
                    % {'min': self.min, 'max': self.max})
            return False
        return True


class RelativeDateDeltaRule(RelativeDeltaRule):
    """
        No range succeed.

        >>> result = []
        >>> r = relative_date()
        >>> r.validate(date.today(), None, None, result, _)
        True

        Min range strategy

        >>> from datetime import timedelta
        >>> result = []
        >>> r = relative_date(min=timedelta(days=-7))
        >>> r.validate(None, None, None, result, _)
        True
        >>> r.validate(date.today(), None, None, result, _)
        True
        >>> d = date.today() - timedelta(days=8)
        >>> r.validate(d, None, None, result, _)
        False

        Max range strategy

        >>> r = relative_date(max=timedelta(days=7))
        >>> r.validate(None, None, None, result, _)
        True
        >>> r.validate(date.today(), None, None, result, _)
        True
        >>> d = date.today() + timedelta(days=8)
        >>> r.validate(d, None, None, result, _)
        False

        Min - Max range strategy

        >>> result = []
        >>> r = relative_date(min=timedelta(days=-7), max=timedelta(days=7))
        >>> r.validate(None, None, None, result, _)
        True
        >>> r.validate(date.today(), None, None, result, _)
        True
        >>> d = date.today() - timedelta(days=8)
        >>> r.validate(d, None, None, result, _)
        False
        >>> d = date.today() + timedelta(days=8)
        >>> r.validate(d, None, None, result, _)
        False
    """
    __slots__ = ()

    def now(self):
        return date.today()


class RelativeDateTimeDeltaRule(RelativeDeltaRule):
    """
        No range succeed.

        >>> result = []
        >>> r = relative_datetime()
        >>> r.validate(datetime.today(), None, None, result, _)
        True

        Min range strategy

        >>> from datetime import timedelta
        >>> result = []
        >>> r = relative_datetime(min=timedelta(days=-7))
        >>> r.validate(datetime.today(), None, None, result, _)
        True
        >>> d = datetime.today() - timedelta(days=8)
        >>> r.validate(d, None, None, result, _)
        False

        Max range strategy

        >>> r = relative_datetime(max=timedelta(days=7))
        >>> r.validate(datetime.today(), None, None, result, _)
        True
        >>> d = datetime.today() + timedelta(days=8)
        >>> r.validate(d, None, None, result, _)
        False

        Min - Max range strategy

        >>> result = []
        >>> r = relative_datetime(min=timedelta(days=-7),
        ...                     max=timedelta(days=7))
        >>> r.validate(datetime.today(), None, None, result, _)
        True
        >>> d = datetime.today() - timedelta(days=8)
        >>> r.validate(d, None, None, result, _)
        False
        >>> d = datetime.today() + timedelta(days=8)
        >>> r.validate(d, None, None, result, _)
        False
    """
    __slots__ = ()

    def now(self):
        return datetime.now()


required = RequiredRule()
missing = optional = empty = MissingRule()
length = LengthRule
compare = CompareRule
regex = RegexRule
slug = SlugRule()
email = EmailRule()
range = RangeRule
and_ = AndRule
or_ = OrRule
iterator = IteratorRule
one_of = OneOfRule
relative_date = RelativeDateDeltaRule
relative_datetime = RelativeDateTimeDeltaRule
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.