Source

fudge / fudge / __init__.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
 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
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322

"""Fudge is a module for replacing real objects with fakes (mocks, stubs, etc) while testing.

See :ref:`using-fudge` for common scenarios.

"""

__version__ = '1.0.3'
import os
import re
import sys
import thread
import warnings
from fudge.exc import FakeDeclarationError
from fudge.patcher import *
from fudge.util import wraps, fmt_val, fmt_dict_vals

__all__ = ['Fake', 'patch', 'test', 'clear_calls', 'verify',
           'clear_expectations']

class Registry(object):
    """An internal, thread-safe registry of expected calls.

    You do not need to use this directly, use Fake.expects(...), etc
    """

    def __init__(self):
        self.expected_calls = {}
        self.expected_call_order = {}
        self.call_stacks = []

    def __contains__(self, obj):
        return obj in self.get_expected_calls()

    def clear_actual_calls(self):
        for exp in self.get_expected_calls():
            exp.was_called = False

    def clear_all(self):
        self.clear_actual_calls()
        self.clear_expectations()

    def clear_calls(self):
        """Clears out any calls that were made on previously
        registered fake objects and resets all call stacks.

        You do not need to use this directly.  Use fudge.clear_calls()
        """
        self.clear_actual_calls()
        for stack in self.call_stacks:
            stack.reset()
        for fake, call_order in self.get_expected_call_order().items():
            call_order.reset_calls()

    def clear_expectations(self):
        c = self.get_expected_calls()
        c[:] = []
        d = self.get_expected_call_order()
        d.clear()

    def expect_call(self, expected_call):
        c = self.get_expected_calls()
        c.append(expected_call)
        call_order = self.get_expected_call_order()
        if expected_call.fake in call_order:
            this_call_order = call_order[expected_call.fake]
            this_call_order.add_expected_call(expected_call)

    def get_expected_calls(self):
        self.expected_calls.setdefault(thread.get_ident(), [])
        return self.expected_calls[thread.get_ident()]

    def get_expected_call_order(self):
        self.expected_call_order.setdefault(thread.get_ident(), {})
        return self.expected_call_order[thread.get_ident()]

    def remember_expected_call_order(self, expected_call_order):
        ordered_fakes = self.get_expected_call_order()
        fake = expected_call_order.fake
        ## does nothing if called twice like:
        # Fake().remember_order().remember_order()
        ordered_fakes.setdefault(fake, expected_call_order)

    def register_call_stack(self, call_stack):
        self.call_stacks.append(call_stack)

    def verify(self):
        """Ensure all expected calls were called,
        raise AssertionError otherwise.

        You do not need to use this directly.  Use fudge.verify()
        """
        try:
            for exp in self.get_expected_calls():
                exp.assert_called()
                exp.assert_times_called()
            for fake, call_order in self.get_expected_call_order().items():
                call_order.assert_order_met(finalize=True)
        finally:
            self.clear_calls()

registry = Registry()


def clear_calls():
    """Begin a new set of calls on fake objects.

    Specifically, clear out any calls that
    were made on previously registered fake
    objects and reset all call stacks.
    You should call this any time you begin
    making calls on fake objects.

    This is also available in :func:`fudge.patch`, :func:`fudge.test` and :func:`fudge.with_fakes`
    """
    registry.clear_calls()


def verify():
    """Verify that all methods have been called as expected.

    Specifically, analyze all registered fake
    objects and raise an AssertionError if an
    expected call was never made to one or more
    objects.

    This is also available in :func:`fudge.patch`, :func:`fudge.test` and :func:`fudge.with_fakes`
    """
    registry.verify()


## Deprecated:

def start():
    """Start testing with fake objects.

    Deprecated.  Use :func:`fudge.clear_calls` instead.
    """
    warnings.warn(
        "fudge.start() has been deprecated.  Use fudge.clear_calls() instead",
        DeprecationWarning, 3)
    clear_calls()


def stop():
    """Stop testing with fake objects.

    Deprecated.  Use :func:`fudge.verify` instead.
    """
    warnings.warn(
        "fudge.stop() has been deprecated.  Use fudge.verify() instead",
        DeprecationWarning, 3)
    verify()

##


def clear_expectations():
    registry.clear_expectations()


def with_fakes(method):
    """Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards.
    """
    @wraps(method)
    def apply_clear_and_verify(*args, **kw):
        clear_calls()
        method(*args, **kw)
        verify() # if no exceptions
    return apply_clear_and_verify


def test(method):
    """Decorator for a test that uses fakes directly (not patched).

    Most of the time you probably want to use :func:`fudge.patch` instead.

    .. doctest::
        :hide:

        >>> import fudge

    .. doctest::

        >>> @fudge.test
        ... def test():
        ...     db = fudge.Fake('db').expects('connect')
        ...     # do stuff...
        ...
        >>> test()
        Traceback (most recent call last):
        ...
        AssertionError: fake:db.connect() was not called

    .. doctest::
        :hide:

        >>> fudge.clear_expectations()

    """
    @wraps(method)
    def clear_and_verify(*args, **kw):
        clear_expectations()
        clear_calls()
        try:
            v = method(*args, **kw)
            verify() # if no exceptions
        finally:
            clear_expectations()
        return v
    return clear_and_verify
test.__test__ = False # Nose: do not collect

class Call(object):
    """A call that can be made on a Fake object.

    You do not need to use this directly, use Fake.provides(...), etc

    index=None
        When numerical, this indicates the position of the call
        (as in, a CallStack)

    callable=False
        Means this object acts like a function, not a method of an
        object.

    call_order=ExpectedCallOrder()
        A call order to append each call to.  Default is None
    """

    def __init__(self, fake, call_name=None, index=None,
                 callable=False, call_order=None):
        self.fake = fake
        self.call_name = call_name
        self.call_replacement = None
        self.expected_arg_count = None
        self.expected_kwarg_count = None
        self.expected_args = None
        self.expected_kwargs = None
        self.expected_matching_args = None
        self.expected_matching_kwargs = None
        self.unexpected_args = None
        self.unexpected_kwargs = None
        self.index = index
        self.exception_to_raise = None
        self.return_val = None
        self.was_called = False
        self.expected_times_called = None
        self.actual_times_called = 0
        self.callable = callable
        self.call_order = call_order

    def __call__(self, *args, **kwargs):
        self.was_called = True
        self.actual_times_called += 1
        if self.call_order:
            self.call_order.add_actual_call(self)
            self.call_order.assert_order_met(finalize=False)

        # make sure call count doesn't go over :
        if self.expected_times_called is not None and \
                self.actual_times_called > self.expected_times_called:
            raise AssertionError(
                '%s was called %s time(s). Expected %s.' % (
                    self, self.actual_times_called,
                    self.expected_times_called))

        return_val = None
        replacement_return = None

        if self.call_replacement:
            replacement_return = self.call_replacement(*args, **kwargs)
        if self.return_val is not None:
            # this wins:
            return_value = self.return_val
        else:
            # but it is intuitive to otherwise
            # return the replacement's return:
            return_value = replacement_return

        # determine whether we should inspect arguments or not:
        with_args = (self.expected_args or self.expected_kwargs)

        if with_args:
            # check keyword args first because of python arg coercion...
            if self.expected_kwargs is None:
                self.expected_kwargs = {} # empty **kw
            if self.expected_kwargs != kwargs:
                raise AssertionError(
                    "%s was called unexpectedly with args %s" % (
                            self,
                            self._repr_call(args, kwargs,
                                            shorten_long_vals=False)))

            if self.expected_args is None:
                self.expected_args = tuple([]) # empty *args
            if self.expected_args != args:
                raise AssertionError(
                    "%s was called unexpectedly with args %s" % (
                            self,
                            self._repr_call(args, kwargs,
                                            shorten_long_vals=False)))

        # now check for matching keyword args.
        # i.e. keyword args that are only checked if the call provided them
        if self.expected_matching_kwargs:
            for expected_arg, expected_value in \
                                self.expected_matching_kwargs.items():
                if expected_arg in kwargs:
                    if expected_value != kwargs[expected_arg]:
                        raise AssertionError(
                            "%s was called unexpectedly with args %s" % (
                                    self,
                                    self._repr_call(args,
                                        {expected_arg: kwargs[expected_arg]},
                                        shorten_long_vals=False))
                        )

        # now check for matching args.
        # i.e. args that are only checked if the call provided them
        if self.expected_matching_args:
            if self.expected_matching_args != args:
                raise AssertionError(
                    "%s was called unexpectedly with args %s" % (
                            self,
                            self._repr_call(args, kwargs,
                                            shorten_long_vals=False)))

        # determine whether we should inspect argument counts or not:
        with_arg_counts = (self.expected_arg_count is not None or
                           self.expected_kwarg_count is not None)

        if with_arg_counts:
            if self.expected_arg_count is None:
                self.expected_arg_count = 0
            if len(args) != self.expected_arg_count:
                raise AssertionError(
                    "%s was called with %s arg(s) but expected %s" % (
                        self, len(args), self.expected_arg_count))

            if self.expected_kwarg_count is None:
                self.expected_kwarg_count = 0
            if len(kwargs.keys()) != self.expected_kwarg_count:
                raise AssertionError(
                    "%s was called with %s keyword arg(s) but expected %s" % (
                        self, len(kwargs.keys()), self.expected_kwarg_count))

        if self.unexpected_kwargs:
            for un_key, un_val in self.unexpected_kwargs.items():
                if un_key in kwargs and kwargs[un_key] == un_val:
                    raise AssertionError(
                        "%s was called unexpectedly with kwarg %s=%s" %
                        (self, un_key, un_val)
                    )

        if self.unexpected_args:
            for un_arg in self.unexpected_args:
                if un_arg in args:
                    raise AssertionError(
                        "%s was called unexpectedly with arg %s" %
                        (self, un_arg)
                    )

        if self.exception_to_raise is not None:
            raise self.exception_to_raise

        return return_value

    ## hmmm, arg diffing (for Call().__call__()) needs more thought

    # def _arg_diff(self, actual_args, expected_args):
    #     """return differnce between keywords"""
    #     if len(actual_args) > len(expected_args):
    #         pass
    #
    #
    # def _keyword_diff(self, actual_kwargs, expected_kwargs):
    #     """returns difference between keywords.
    #     """
    #     expected_keys = set(expected_kwargs.keys())
    #     if (len(expected_keys)<=1 and len(actual_kwargs.keys())<=1):
    #         # no need for detailed messages
    #         if actual_kwargs == expected_kwargs:
    #             return (True, "")
    #         else:
    #             return (False, "")
    #
    #     for k,v in actual_kwargs.items():
    #         if k not in expected_keys:
    #             return (False, "keyword %r was not expected" % k)
    #         if v != expected_kwargs[k]:
    #             return (False, "%s=%r != %s=%r" % (k, v, k, expected_kwargs[k]))
    #         expected_keys.remove(k)
    #
    #     exp_key_len = len(expected_keys)
    #     if exp_key_len:
    #         these = exp_key_len==1 and "this keyword" or "these keywords"
    #         return (False, "%s never showed up: %r" % (these, tuple(expected_keys)))
    #
    #     return (True, "")

    def _repr_call(self, expected_args, expected_kwargs, shorten_long_vals=True):
        args = []
        if expected_args:
            args.extend([fmt_val(a, shorten=shorten_long_vals) for a in expected_args])
        if expected_kwargs:
            args.extend(fmt_dict_vals(expected_kwargs, shorten=shorten_long_vals))
        if args:
            call = "(%s)" % ", ".join(args)
        else:
            call = "()"
        return call

    def __repr__(self):
        cls_name = repr(self.fake)
        if self.call_name and not self.callable:
            call = "%s.%s" % (cls_name, self.call_name)
        else:
            call = "%s" % cls_name
        call = "%s%s" % (call, self._repr_call(self.expected_args, self.expected_kwargs))
        if self.index is not None:
            call = "%s[%s]" % (call, self.index)
        return call

    def get_call_object(self):
        """return self.

        this exists for compatibility with :class:`CallStack`
        """
        return self

    def assert_times_called(self):
        if self.expected_times_called is not None and \
                self.actual_times_called != self.expected_times_called:
            raise AssertionError(
                '%s was called %s time(s). Expected %s.' % (
                    self, self.actual_times_called, self.expected_times_called))



class ExpectedCall(Call):
    """An expectation that a call will be made on a Fake object.

    You do not need to use this directly, use Fake.expects(...), etc
    """

    def __init__(self, *args, **kw):
        super(ExpectedCall, self).__init__(*args, **kw)
        registry.expect_call(self)

    def assert_called(self):
        if not self.was_called:
            raise AssertionError("%s was not called" % (self))

class ExpectedCallOrder(object):
    """An expectation that calls should be called in a specific order."""

    def __init__(self, fake):
        self.fake = fake
        self._call_order = []
        self._actual_calls = []

    def __repr__(self):
        return "%r(%r)" % (self.fake, self._call_order)

    __str__ = __repr__

    def _repr_call_list(self, call_list):
        if not len(call_list):
            return "no calls"
        else:
            stack = ["#%s %r" % (i+1,c) for i,c in enumerate(call_list)]
            stack.append("end")
            return ", ".join(stack)

    def add_expected_call(self, call):
        self._call_order.append(call)

    def add_actual_call(self, call):
        self._actual_calls.append(call)

    def assert_order_met(self, finalize=False):
        """assert that calls have been made in the right order."""
        error = None
        actual_call_len = len(self._actual_calls)
        expected_call_len = len(self._call_order)

        if actual_call_len == 0:
            error = "Not enough calls were made"
        else:
            for i,call in enumerate(self._call_order):
                if actual_call_len < i+1:
                    if not finalize:
                        # we're not done asserting calls so
                        # forget about not having enough calls
                        continue

                    calls_made = len(self._actual_calls)
                    if calls_made == 1:
                        error = "Only 1 call was made"
                    else:
                        error = "Only %s calls were made" % calls_made
                    break

                ac_call = self._actual_calls[i]
                if ac_call is not call:
                    error = "Call #%s was %r" % (i+1, ac_call)
                    break

            if not error:
                if actual_call_len > expected_call_len:
                    # only show the first extra call since this
                    # will be triggered before all calls are finished:
                    error = "#%s %s was unexpected" % (
                        expected_call_len+1,
                        self._actual_calls[expected_call_len]
                    )

        if error:
            msg = "%s; Expected: %s" % (
                    error, self._repr_call_list(self._call_order))
            raise AssertionError(msg)

    def reset_calls(self):
        self._actual_calls[:] = []

class CallStack(object):
    """A stack of :class:`Call` objects

    Calling this object behaves just like Call except
    the Call instance you operate on gets changed each time __call__() is made

    expected=False
        When True, this indicates that the call stack was derived
        from an expected call.  This is used by Fake to register
        each call on the stack.

    call_name
        Name of the call

    """

    def __init__(self, fake, initial_calls=None, expected=False, call_name=None):
        self.fake = fake
        self._pointer = 0 # position of next call to be made (can be reset)
        self._calls = []
        if initial_calls is not None:
            for c in initial_calls:
                self.add_call(c)
        self.expected = expected
        self.call_name = call_name
        registry.register_call_stack(self)

    def __iter__(self):
        for c in self._calls:
            yield c

    def __repr__(self):
        return "<%s for %r>" % (self.__class__.__name__, self._calls)

    __str__ = __repr__

    def add_call(self, call):
        self._calls.append(call)
        call.index = len(self._calls)-1

    def get_call_object(self):
        """returns the last *added* call object.

        this is so Fake knows which one to alter
        """
        return self._calls[len(self._calls)-1]

    def reset(self):
        self._pointer = 0

    def __call__(self, *args, **kw):
        try:
            current_call = self._calls[self._pointer]
        except IndexError:
            raise AssertionError(
                "This attribute of %s can only be called %s time(s).  "
                "Call reset() if necessary or fudge.clear_calls()." % (
                                                self.fake, len(self._calls)))
        self._pointer += 1
        return current_call(*args, **kw)

class Fake(object):
    """A fake object that replaces a real one while testing.

    Most calls with a few exceptions return ``self`` so that you can chain
    them together to create readable code.

    Instance methods will raise either AssertionError or :class:`fudge.FakeDeclarationError`

    Keyword arguments:

    **name=None**
        Name of the class, module, or function you mean to replace. If not
        specified, Fake() will try to guess the name by inspecting the calling
        frame (if possible).

    **allows_any_call=False**
        This is **deprecated**.  Use :meth:`Fake:is_a_stub()` instead.

    **callable=False**
        This is **deprecated**.  Use :meth:`Fake.is_callable` instead.

    **expect_call=True**
        This is **deprecated**.  Use :meth:`Fake.expects_call` instead.

    """

    def __init__(self, name=None, allows_any_call=False,
                 callable=False, expect_call=False):
        self._attributes = {}
        self._declared_calls = {}
        self._name = (name or self._guess_name())
        self._last_declared_call_name = None
        self._is_a_stub = False
        if allows_any_call:
            warnings.warn('Fake(allows_any_call=True) is deprecated;'
                          ' use Fake.is_a_stub()',
                          DeprecationWarning, 3)
            self.is_a_stub()
        self._call_stack = None
        if expect_call:
            self.expects_call()
        elif callable or allows_any_call:
            self.is_callable()
        else:
            self._callable = None
        self._expected_call_order = None

    def __getattribute__(self, name):
        """Favors stubbed out attributes, falls back to real attributes

        """
        # this getter circumvents infinite loops:
        def g(n):
            return object.__getattribute__(self, n)

        if name in g('_declared_calls'):
            # if it's a call that has been declared
            # as that of the real object then hand it over:
            return g('_declared_calls')[name]
        elif name in g('_attributes'):
            # return attribute declared on real object
            return g('_attributes')[name]
        else:
            # otherwise, first check if it's a call
            # of Fake itself (i.e. returns(),  with_args(), etc)
            try:
                self_call = g(name)
            except AttributeError:
                pass
            else:
                return self_call

            if g('_is_a_stub'):
                # Lazily create a attribute (which might later get called):
                stub = Fake(name=self._endpoint_name(name)).is_a_stub()
                self.has_attr(**{name: stub})
                return getattr(self, name)

            raise AttributeError(
                    "%s object does not allow call or attribute '%s' "
                    "(maybe you want %s.is_a_stub() ?)" % (
                                    self, name, self.__class__.__name__))

    def __call__(self, *args, **kwargs):
        if '__init__' in self._declared_calls:
            # special case, simulation of __init__():
            call = self._declared_calls['__init__']
            result = call(*args, **kwargs)
            if result is None:
                # assume more calls were expected / provided by the same fake
                return self
            else:
                # a new custom object has been declared
                return result
        elif self._callable:
            return self._callable(*args, **kwargs)
        elif self._is_a_stub:
            self.is_callable().returns_fake().is_a_stub()
            return self.__call__(*args, **kwargs)
        else:
            raise RuntimeError(
                "%s object cannot be called (maybe you want "
                "%s.is_callable() ?)" % (self, self.__class__.__name__))

    def __setattr__(self, name, val):
        if hasattr(self, '_attributes') and name in self._attributes:
            self._attributes[name] = val
        else:
            object.__setattr__(self, name, val)

    def __repr__(self):
        return "fake:%s" % (self._name or "unnamed")

    def _declare_call(self, call_name, call):
        self._declared_calls[call_name] = call

    _assignment = re.compile(r"\s*(?P<name>[a-zA-Z0-9_]+)\s*=\s*(fudge\.)?Fake\(.*")
    def _guess_asn_from_file(self, frame):
        if frame.f_code.co_filename:
            if os.path.exists(frame.f_code.co_filename):
                cofile = open(frame.f_code.co_filename,'r')
                try:
                    for ln, line in enumerate(cofile):
                        # I'm not sure why -1 is needed
                        if ln==frame.f_lineno-1:
                            possible_asn = line
                            m = self._assignment.match(possible_asn)
                            if m:
                                return m.group('name')
                finally:
                    cofile.close()

    def _guess_name(self):
        if not hasattr(sys, '_getframe'):
            # Stackless?
            return None
        if sys.platform.startswith('java'):
            # frame objects are completely different,
            # not worth the hassle.
            return None

        # get frame where class was instantiated,
        #   my_obj = Fake()
        #   ^
        #   we want to set self._name = 'my_obj'
        frame = sys._getframe(2)
        if len(frame.f_code.co_varnames):
            # at the top-most frame:
            co_names = frame.f_code.co_varnames
        else:
            # any other frame:
            co_names = frame.f_code.co_names

        # find names that are not locals.
        # this probably indicates my_obj = ...

        candidates = [n for n in co_names if n not in frame.f_locals]
        if len(candidates)==0:
            # the value was possibly queued for deref
            #   foo = 44
            #   foo = Fake()
            return self._guess_asn_from_file(frame)
        elif len(candidates)==1:
            return candidates[0]
        else:
            # we are possibly halfway through a module
            # where not all names have been compiled
            return self._guess_asn_from_file(frame)

    def _get_current_call(self):
        if not self._last_declared_call_name:
            if not self._callable:
                raise FakeDeclarationError(
                    "Call to a method that expects a predefined call but no such call exists.  "
                    "Maybe you forgot expects('method') or provides('method') ?")
            return self._callable.get_call_object()
        exp = self._declared_calls[self._last_declared_call_name].get_call_object()
        return exp

    def _endpoint_name(self, endpoint):
        p = [self._name or 'unnamed']
        if endpoint != self._name:
            p.append(str(endpoint))
        return '.'.join(p)

    def expects_call(self):
        """The fake must be called.

        .. doctest::
            :hide:

            >>> import fudge
            >>> fudge.clear_expectations()
            >>> fudge.clear_calls()

        This is useful for when you stub out a function
        as opposed to a class.  For example::

            >>> import fudge
            >>> remove = fudge.Fake('os.remove').expects_call()
            >>> fudge.verify()
            Traceback (most recent call last):
            ...
            AssertionError: fake:os.remove() was not called

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        """
        self._callable = ExpectedCall(self, call_name=self._name,
                                      callable=True)
        return self

    def is_callable(self):
        """The fake can be called.

        This is useful for when you stub out a function
        as opposed to a class.  For example::

            >>> import fudge
            >>> remove = Fake('os.remove').is_callable()
            >>> remove('some/path')

        """
        self._callable = Call(self, call_name=self._name, callable=True)
        return self

    def is_a_stub(self):
        """Turns this fake into a stub.

        When a stub, any method is allowed to be called on the Fake() instance
        and any attribute can be accessed.  When an unknown attribute or
        call is made, a new Fake() is returned.  You can of course override
        any of this with :meth:`Fake.expects` and the other methods.
        """
        self._is_a_stub = True
        return self

    def calls(self, call):
        """Redefine a call.

        The fake method will execute your function.  I.E.::

            >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there')
            >>> f.hello()
            'Why, hello there'

        """
        exp = self._get_current_call()
        exp.call_replacement = call
        return self

    def expects(self, call_name):
        """Expect a call.

        .. doctest::
            :hide:

            >>> import fudge
            >>> fudge.clear_expectations()
            >>> fudge.clear_calls()

        If the method *call_name* is never called, then raise an error.  I.E.::

            >>> session = Fake('session').expects('open').expects('close')
            >>> session.open()
            >>> fudge.verify()
            Traceback (most recent call last):
            ...
            AssertionError: fake:session.close() was not called

        .. note::
            If you want to also verify the order these calls are made in,
            use :func:`fudge.Fake.remember_order`.  When using :func:`fudge.Fake.next_call`
            after ``expects(...)``, each new call will be part of the expected order

        Declaring ``expects()`` multiple times is the same as
        declaring :func:`fudge.Fake.next_call`
        """
        if call_name in self._declared_calls:
            return self.next_call(for_method=call_name)

        self._last_declared_call_name = call_name
        c = ExpectedCall(self, call_name, call_order=self._expected_call_order)
        self._declare_call(call_name, c)
        return self

    def has_attr(self, **attributes):
        """Sets available attributes.

        I.E.::

            >>> User = Fake('User').provides('__init__').has_attr(name='Harry')
            >>> user = User()
            >>> user.name
            'Harry'

        """
        self._attributes.update(attributes)
        return self

    def next_call(self, for_method=None):
        """Start expecting or providing multiple calls.

        .. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called`

        Up until calling this method, calls are infinite.

        For example, before next_call() ... ::

            >>> from fudge import Fake
            >>> f = Fake().provides('status').returns('Awake!')
            >>> f.status()
            'Awake!'
            >>> f.status()
            'Awake!'

        After next_call() ... ::

            >>> from fudge import Fake
            >>> f = Fake().provides('status').returns('Awake!')
            >>> f = f.next_call().returns('Asleep')
            >>> f = f.next_call().returns('Dreaming')
            >>> f.status()
            'Awake!'
            >>> f.status()
            'Asleep'
            >>> f.status()
            'Dreaming'
            >>> f.status()
            Traceback (most recent call last):
            ...
            AssertionError: This attribute of fake:unnamed can only be called 3 time(s).  Call reset() if necessary or fudge.clear_calls().

        If you need to affect the next call of something other than the last declared call,
        use ``next_call(for_method="other_call")``.  Here is an example using getters and setters
        on a session object ::

            >>> from fudge import Fake
            >>> sess = Fake('session').provides('get_count').returns(1)
            >>> sess = sess.provides('set_count').with_args(5)

        Now go back and adjust return values for get_count() ::

            >>> sess = sess.next_call(for_method='get_count').returns(5)

        This allows these calls to be made ::

            >>> sess.get_count()
            1
            >>> sess.set_count(5)
            >>> sess.get_count()
            5

        When using :func:`fudge.Fake.remember_order` in combination with :func:`fudge.Fake.expects` and :func:`fudge.Fake.next_call` each new call will be part of the expected order.

        """
        last_call_name = self._last_declared_call_name
        if for_method:
            if for_method not in self._declared_calls:
                raise FakeDeclarationError(
                            "next_call(for_method=%r) is not possible; "
                            "declare expects(%r) or provides(%r) first" % (
                                                        for_method, for_method, for_method))
            else:
                # set this for the local function:
                last_call_name = for_method
                # reset this for subsequent methods:
                self._last_declared_call_name = last_call_name

        if last_call_name:
            exp = self._declared_calls[last_call_name]
        elif self._callable:
            exp = self._callable
        else:
            raise FakeDeclarationError('next_call() must follow provides(), '
                                       'expects() or is_callable()')

        if getattr(exp, 'expected_times_called', None) is not None:
            raise FakeDeclarationError("Cannot use next_call() in combination with times_called()")

        if not isinstance(exp, CallStack):
            # lazily create a stack with the last defined
            # expected call as the first on the stack:
            stack = CallStack(self, initial_calls=[exp],
                                    expected=isinstance(exp, ExpectedCall),
                                    call_name=exp.call_name)

            # replace the old call obj using the same name:
            if last_call_name:
                self._declare_call(last_call_name, stack)
            elif self._callable:
                self._callable = stack
        else:
            stack = exp

        # hmm, we need a copy here so that the last call
        # falls off the stack.
        if stack.expected:
            next_call = ExpectedCall(self, call_name=exp.call_name, call_order=self._expected_call_order)
        else:
            next_call = Call(self, call_name=exp.call_name)
        stack.add_call(next_call)
        return self

    def provides(self, call_name):
        """Provide a call.

        The call acts as a stub -- no error is raised if it is not called.::

            >>> session = Fake('session').provides('open').provides('close')
            >>> import fudge
            >>> fudge.clear_expectations() # from any previously declared fakes
            >>> fudge.clear_calls()
            >>> session.open()
            >>> fudge.verify() # close() not called but no error

        Declaring ``provides()`` multiple times is the same as
        declaring :func:`fudge.Fake.next_call`

        """
        if call_name in self._declared_calls:
            return self.next_call(for_method=call_name)

        self._last_declared_call_name = call_name
        c = Call(self, call_name)
        self._declare_call(call_name, c)
        return self

    def raises(self, exc):
        """Set last call to raise an exception class or instance.

        For example::

            >>> import fudge
            >>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert"))
            >>> db.insert()
            Traceback (most recent call last):
            ...
            ValueError: not enough parameters for insert

        """
        exp = self._get_current_call()
        exp.exception_to_raise = exc
        return self

    def remember_order(self):
        """Verify that subsequent :func:`fudge.Fake.expects` are called in the right order.

        For example::

            >>> import fudge
            >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update')
            >>> db.update()
            Traceback (most recent call last):
            ...
            AssertionError: Call #1 was fake:db.update(); Expected: #1 fake:db.insert(), #2 fake:db.update(), end
            >>> fudge.clear_expectations()

        When declaring multiple calls using :func:`fudge.Fake.next_call`, each subsequent call will be added
        to the expected order of calls ::

            >>> import fudge
            >>> sess = fudge.Fake("session").remember_order().expects("get_id").returns(1)
            >>> sess = sess.expects("set_id").with_args(5)
            >>> sess = sess.next_call(for_method="get_id").returns(5)

        Multiple calls to ``get_id()`` are now expected ::

            >>> sess.get_id()
            1
            >>> sess.set_id(5)
            >>> sess.get_id()
            5
            >>> fudge.verify()
            >>> fudge.clear_expectations()

        """
        if self._callable:
            raise FakeDeclarationError(
                    "remember_order() cannot be used for Fake(callable=True) or Fake(expect_call=True)")
        self._expected_call_order = ExpectedCallOrder(self)
        registry.remember_expected_call_order(self._expected_call_order)
        return self

    def returns(self, val):
        """Set the last call to return a value.

        Set a static value to return when a method is called.  I.E.::

            >>> f = Fake().provides('get_number').returns(64)
            >>> f.get_number()
            64

        """
        exp = self._get_current_call()
        exp.return_val = val
        return self

    def returns_fake(self, *args, **kwargs):
        """Set the last call to return a new :class:`fudge.Fake`.

        Any given arguments are passed to the :class:`fudge.Fake` constructor

        Take note that this is different from the cascading nature of
        other methods.  This will return an instance of the *new* Fake,
        not self, so you should be careful to store its return value in a new
        variable.

        I.E.::

            >>> session = Fake('session')
            >>> query = session.provides('query').returns_fake(name="Query")
            >>> assert query is not session
            >>> query = query.provides('one').returns(['object'])

            >>> session.query().one()
            ['object']

        """
        exp = self._get_current_call()
        endpoint = kwargs.get('name', exp.call_name)
        name = self._endpoint_name(endpoint)
        kwargs['name'] = '%s()' % name
        fake = self.__class__(*args, **kwargs)
        exp.return_val = fake
        return fake

    def times_called(self, n):
        """Set the number of times an object can be called.

        When working with provided calls, you'll only see an
        error if the expected call count is exceeded ::

            >>> auth = Fake('auth').provides('login').times_called(1)
            >>> auth.login()
            >>> auth.login()
            Traceback (most recent call last):
            ...
            AssertionError: fake:auth.login() was called 2 time(s). Expected 1.

        When working with expected calls, you'll see an error if
        the call count is never met ::

            >>> import fudge
            >>> auth = fudge.Fake('auth').expects('login').times_called(2)
            >>> auth.login()
            >>> fudge.verify()
            Traceback (most recent call last):
            ...
            AssertionError: fake:auth.login() was called 1 time(s). Expected 2.

        .. note:: This cannot be used in combination with :func:`fudge.Fake.next_call`

        """
        if self._last_declared_call_name:
            actual_last_call = self._declared_calls[self._last_declared_call_name]
            if isinstance(actual_last_call, CallStack):
                raise FakeDeclarationError("Cannot use times_called() in combination with next_call()")
        # else: # self._callable is in effect

        exp = self._get_current_call()
        exp.expected_times_called = n
        return self

    def with_args(self, *args, **kwargs):
        """Set the last call to expect specific argument values.

        The app under test must send all declared arguments and keyword arguments
        otherwise your test will raise an AssertionError.  For example:

        .. doctest::

            >>> import fudge
            >>> counter = fudge.Fake('counter').expects('increment').with_args(25, table='hits')
            >>> counter.increment(24, table='clicks')
            Traceback (most recent call last):
            ...
            AssertionError: fake:counter.increment(25, table='hits') was called unexpectedly with args (24, table='clicks')

        If you need to work with dynamic argument values
        consider using :func:`fudge.Fake.with_matching_args` to make looser declarations.
        You can also use :mod:`fudge.inspector` functions.  Here is an example of providing
        a more flexible ``with_args()`` declaration using inspectors:

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        .. doctest::

            >>> import fudge
            >>> from fudge.inspector import arg
            >>> counter = fudge.Fake('counter')
            >>> counter = counter.expects('increment').with_args(
            ...                                         arg.any(),
            ...                                         table=arg.endswith("hits"))
            ...

        The above declaration would allow you to call counter like this:

        .. doctest::

            >>> counter.increment(999, table="image_hits")
            >>> fudge.verify()

        .. doctest::
            :hide:

            >>> fudge.clear_calls()

        Or like this:

        .. doctest::

            >>> counter.increment(22, table="user_profile_hits")
            >>> fudge.verify()

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        """
        exp = self._get_current_call()
        if args:
            exp.expected_args = args
        if kwargs:
            exp.expected_kwargs = kwargs
        return self

    def with_matching_args(self, *args, **kwargs):
        """Set the last call to expect specific argument values if those arguments exist.

        Unlike :func:`fudge.Fake.with_args` use this if you want to only declare
        expectations about matching arguments.  Any unknown keyword arguments
        used by the app under test will be allowed.

        For example, you can declare positional arguments but ignore keyword arguments:

        .. doctest::

            >>> import fudge
            >>> db = fudge.Fake('db').expects('transaction').with_matching_args('insert')

        With this declaration, any keyword argument is allowed:

        .. doctest::

            >>> db.transaction('insert', isolation_level='lock')
            >>> db.transaction('insert', isolation_level='shared')
            >>> db.transaction('insert', retry_on_error=True)

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        .. note::

            you may get more mileage out of :mod:`fudge.inspector` functions as
            described in :func:`fudge.Fake.with_args`

        """
        exp = self._get_current_call()
        if args:
            exp.expected_matching_args = args
        if kwargs:
            exp.expected_matching_kwargs = kwargs
        return self

    def without_args(self, *args, **kwargs):
        """Set the last call to expect that certain arguments will not exist.

        This is the opposite of :func:`fudge.Fake.with_matching_args.  It will
        fail if any of the arguments are passed.

        .. doctest::

            >>> import fudge
            >>> query = fudge.Fake('query').expects_call().without_args(
            ...     'http://example.com', name="Steve"
            ... )
            >>> query('http://python.org', name="Joe")
            >>> query('http://example.com')
            Traceback (most recent call last):
            ...
            AssertionError: fake:query() was called unexpectedly with arg http://example.com
            >>> query('http://python.org', name='Steve')
            Traceback (most recent call last):
            ...
            AssertionError: fake:query() was called unexpectedly with kwarg name=Steve

        """
        exp = self._get_current_call()
        if args:
            exp.unexpected_args = args
        if kwargs:
            exp.unexpected_kwargs = kwargs
        return self

    def with_arg_count(self, count):
        """Set the last call to expect an exact argument count.

        I.E.::

            >>> auth = Fake('auth').provides('login').with_arg_count(2)
            >>> auth.login('joe_user') # forgot password
            Traceback (most recent call last):
            ...
            AssertionError: fake:auth.login() was called with 1 arg(s) but expected 2

        """
        exp = self._get_current_call()
        exp.expected_arg_count = count
        return self

    def with_kwarg_count(self, count):
        """Set the last call to expect an exact count of keyword arguments.

        I.E.::

            >>> auth = Fake('auth').provides('login').with_kwarg_count(2)
            >>> auth.login(username='joe') # forgot password=
            Traceback (most recent call last):
            ...
            AssertionError: fake:auth.login() was called with 1 keyword arg(s) but expected 2

        """
        exp = self._get_current_call()
        exp.expected_kwarg_count = count
        return self