doublex-1.8.2/0000755000175000017500000000000012435722065012246 5ustar piotrpiotrdoublex-1.8.2/.gitignore0000644000175000017500000000047312435722065014242 0ustar piotrpiotr*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 __pycache__ # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject doublex-1.8.2/.hgignore0000644000175000017500000000003312435722065014045 0ustar piotrpiotrsyntax: glob .svn/* *.pyc doublex-1.8.2/.hgtags0000644000175000017500000000145012435722065013524 0ustar piotrpiotr4afef1efc69f21d6447585bcdf300911f16184b6 v0.3 9d106a5b924ad58d5c5b8fef4c6f7bdd1b0ae433 v1.5 3eb55b287dbf93f56fd139ad863ad5fe6e798273 v1.5.1 3eb55b287dbf93f56fd139ad863ad5fe6e798273 v1.5.1 088989a406631e0a686621669534d6a0d08e4add v1.5.1 cb8ba0df2e024d602fed236bb5ed5a7ceee91b20 v1.6 80ae08749c28b16fe38b82eae1423923512ae0c3 v1.6.1 ce8cdff71b8e3528380c305bf7d9ca75a64f6460 v1.6.2 bc4f19e466eb484e0046e17ad7821048d35c5a9e v1.6.3 9ad7b1696f919753306228eb2d8df8c92cc5f6ba v1.6.4 1094f91a921bb89a0e3fc2abedda9d91a8fbbd40 v1.6.5 3fe85008b9ee8ff34a456c71f20afcedf42e8ab4 v1.6.6 916c8e557345335449a3a85c70b1413a331e2136 v1.7 c16348f54bf84ca75b10ee1290a272f321d82cf5 v1.7.1 df2b3bda0eef64b5ddc6d6b3cc5a6380fb98e132 v1.7.2 6a18735bf3b0277eb19c4676c7655966237afa03 v1.7.3 d041251a38aeeb6bd6bcdf715b79e2345e0fb113 v1.8.1 doublex-1.8.2/.travis.yml0000644000175000017500000000041412435722065014356 0ustar piotrpiotrlanguage: python python: 2.7 env: - TOX_ENV=py26 - TOX_ENV=py27 - TOX_ENV=py32 - TOX_ENV=py33 install: - pip install -r requirements.txt - pip install tox script: - tox -e $TOX_ENV notifications: email: on_success: change on_failure: change doublex-1.8.2/BUGS0000644000175000017500000000007212435722065012730 0ustar piotrpiotr Spy stubbed method avoid collaborator method invocation doublex-1.8.2/CHANGES.rst0000644000175000017500000000436412435722065014057 0ustar piotrpiotr20141126 ======== - Release 1.8.2 - Bug fixed: https://bitbucket.org/DavidVilla/python-doublex/issue/22 - returns_input() may return several parameters - delegates() accepts dictionaries. - method_returning() and assert_raises() are now spies: https://bitbucket.org/DavidVilla/python-doublex/issue/21 - 20140107 ======== - Release 1.8.1 - PyHamcrest must be a requirement. Thanks to Javier Santacruz and Guillermo Pascual https://bitbucket.org/DavidVilla/python-doublex/pull-request/7 https://bitbucket.org/DavidVilla/python-doublex/issue/18 20140101 ======== - Release 1.8a - [NEW] inline stubbing and mocking functions: when, expect_call (merge with feature-inline-stubbing) - [NEW] Testing Python 2.6, 2.7, 3.2 and 3.3 using tox - [NEW] Add AttributeFactory type: wrapper_descriptor for builtin method (such as list.__setitem__) 20131227 ======== - [NEW] Double methods copy original __name__ attribute - [NEW] Mock support for properties 20131107 ======== - Release 1.7.2 - [NEW] support for varargs (*args, **kargs) methods - [NEW] tracer for doubles, methods and properties 20130712 ======== - Release 1.6.8 - [NEW] with_some_args matcher - [NEW] set_default_behavior() module function to define behavior for non stubbed methods. 20130513 ======== - ANY_ARG is not allowed as keyword value - ANY_ARG must be the last positional argument value 20130427 ======== - Release 1.6.6 - [FIXED] stub/empty_stub were missing in pyDoubles wrapper 20130215 ======== - Release 1.6.3 - [FIXED] async race condition bug 20130211 ======== - [NEW] Access to spy invocations with _method_.calls 20130110 ======== - Release 1.6 - [NEW] Ad-hoc stub attributes - [NEW] AttributeFactory callable types: function, method (Closes: #bitbucket:issue/7) - [NEW] BuiltingSignature for non Python functions 20121118 ======== - [NEW] ProxySpy propagates stubbed invocations too 20121025 ======== - Merge feature-async branch: Spy async checking 20121008 ======== - Release 1.5 to replace pyDoubles 20120928 ======== - ANY_ARG must be different to any other thing. 20120911 ======== - API CHANGE: called_with() is now called().with_args() (magmax suggestion) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. End: doublex-1.8.2/LICENSE0000644000175000017500000010446112435722065013261 0ustar piotrpiotrGNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . doublex-1.8.2/MANIFEST.in0000644000175000017500000000005412435722065014003 0ustar piotrpiotrinclude README.rst include requirements.txt doublex-1.8.2/README.rst0000644000175000017500000000556512435722065013750 0ustar piotrpiotr.. image:: https://pypip.in/v/doublex/badge.png :target: https://crate.io/packages/doublex/ :alt: Latest PyPI version .. image:: https://pypip.in/d/doublex/badge.png :target: https://crate.io/packages/doublex/ :alt: Number of PyPI downloads .. image:: https://travis-ci.org/davidvilla/python-doublex.svg?branch=master :target: https://travis-ci.org/davidvilla/python-doublex :alt: Travis CI status Powerful test doubles framework for Python [ `install `_ | `docs `_ | `changelog `_ | `sources `_ | `issues `_ | `PyPI `_ | `buildbot `_ ] a trivial example ----------------- .. sourcecode:: python import unittest from doublex import Spy, assert_that, called class SpyUseExample(unittest.TestCase): def test_spy_example(self): # given spy = Spy(SomeCollaboratorClass) cut = YourClassUnderTest(spy) # when cut.a_method_that_call_the_collaborator() # then assert_that(spy.some_method, called()) See more about `doublex doubles `_. Features -------- * doubles have not public API framework methods. It could cause silent misspelling. * doubles do not require collaborator instances, just classes, and it never instantiate them. * ``assert_that()`` is used for ALL assertions. * mock invocation order is relevant by default. * supports old and new style classes. * **supports Python versions: 2.6, 2.7, 3.2, 3.3, 3.4** Debian ^^^^^^ * `official package `_ (may be outdated) * amateur repository: ``deb http://babel.esi.uclm.es/arco/ sid main`` (always updated) * `official ubuntu package `_ * debian dir: ``svn://svn.debian.org/svn/python-modules/packages/doublex/trunk`` related ------- * `slides `_ * `pyDoubles `_ * `crate `_ * `github clone `_ * `other doubles `_ * `ludibrio `_ .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End:doublex-1.8.2/ToDo0000644000175000017500000000012512435722065013034 0ustar piotrpiotr- function doubles (supporting __call__ method) - orphan spy methods - double chains doublex-1.8.2/docs/0000755000175000017500000000000012435722065013176 5ustar piotrpiotrdoublex-1.8.2/docs/Makefile0000644000175000017500000001567612435722065014655 0ustar piotrpiotr# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext all: html help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" GENERATED=doubles.rst reference.rst methods.rst delegates.rst observers.rst mimics.rst async-spies.rst calls.rst properties.rst clean: rm -rf $(BUILDDIR)/* $(RM) $(GENERATED) *~ html: index.rst release-notes.rst $(GENERATED) $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." %.rst: %.rst.test sed 's/^.. doctest::.*$$//g' $< > $@ sed -i 's/^.. testcode::.*$$//g' $@ sed -i 's/^.. testoutput::$$//g' $@ dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/doublex.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/doublex.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/doublex" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/doublex" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." doublex-1.8.2/docs/README.rst.inc0000777000175000017500000000000012435722065017334 2../README.rstustar piotrpiotrdoublex-1.8.2/docs/README.rst.inc.old0000644000175000017500000000470612435722065016221 0ustar piotrpiotr.. image:: https://pypip.in/v/doublex/badge.png :target: https://crate.io/packages/doublex/ :alt: Latest PyPI version .. image:: https://pypip.in/d/doublex/badge.png :target: https://crate.io/packages/doublex/ :alt: Number of PyPI downloads Powerful test doubles framework for Python. design principles ----------------- * doubles should not have public API framework methods. It avoids silent misspelling. * doubles do not require collaborator instances, just classes, and it never instantiate them. * ``assert_that()`` is used for ALL assertions. * invocation order for mocks is relevant by default. * supports old and new style classes. a trivial example ----------------- .. sourcecode:: python import unittest from doublex import Spy, assert_that, called class SpyUseExample(unittest.TestCase): def test_spy_example(self): # given spy = Spy(SomeCollaboratorClass) cut = YourClassUnderTest(spy) # when cut.a_method_that_call_the_collaborator() # then assert_that(spy.some_method, called()) See more about `doublex doubles `_. relevant links -------------- * `install `_ * `documentation `_ * `release notes `_ * `slides `_ * `sources `_ * `PyPI project `_ * `pyDoubles `_ * `crate `_ * `buildbot job `_ * `other doubles `_ Debian ^^^^^^ * `official package `_ (may be outdated) * amateur repository: ``deb http://babel.esi.uclm.es/arco/ sid main`` (always updated) * `official ubuntu package `_ * debian dir: ``svn://svn.debian.org/svn/python-modules/packages/doublex/trunk`` .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/api.rst0000644000175000017500000001121212435722065014476 0ustar piotrpiotr=== API === Double classes ============== .. py:class:: Stub([collaborator]) .. py:class:: Spy([collaborator]) .. py:class:: ProxySpy([collaborator]) .. py:class:: Mock([collaborator]) .. py:class:: Mimic(double, collaborator) Stubbing ======== .. py:method:: Method.raises(exception) Stub method will raise the given `exception` when invoked. Method parameters are relevant, and they may be literal values or hamcrest matchers:: with Stub() as stub: stub.method().raises(ValueError) See :ref:`raises`. .. py:method:: Method.returns(value) Stub method will return the given value when invoked:: with Stub() as stub: stub.method().returns(100) See :ref:`stub`. .. py:method:: Method.returns_input() Stub method will return input parameters when invoked:: with Stub() as stub: stub.method().returns_input() See :ref:`returns_input`. .. py:method:: Method.delegates(delegate) Stub method will return values generated by the `delegate`, that may be a function, generator or iterable object:: with Stub() as stub: stub.method().delegates([1, 2, 4, 8]) See :ref:`delegates`. .. py:method:: Method.attach(callable) Stub methods are observable. You may attach arbitrary callable that will be invoked any time the stub method does:: counter = itertools.count() stub.method.attach(counter.next) See :ref:`observers`. Matchers ======== .. py:class:: never(matcher) Just a cosmetic alias to the hamcrest matcher :py:func:`is_not`. See :ref:`never`. for Spy methods --------------- .. py:class:: called Asserts a spy method was called:: assert_that(spy.method, called()) See :ref:`called`. .. py:method:: called.async(timeout) The ``called`` assertion waits the corresponding invocation a maximum of `timeout` seconds. :param int timeout: how many second wait before assume assertion fails. :: assert_that(spy.method, called().async(1)) See :ref:`async`. .. py:method:: called.times(value) The spy method must be invoked `value` times to consider the assertion right. The `value` parameter may an integer or hamcrest matcher as well. :param value: how many times the method should be called. :type value: int or hamcrest Matcher :: assert_that(spy.method, called().times(less_that(3))) See :ref:`times`. .. py:method:: called.with_args(*args, **kargs) The spy method must be invoked with the given positional or/and named parameters. All of them may be literal values and hamcrest matchers. :: assert_that(spy.method, called().with_args("mary", greater_that(4))) See :ref:`with_args`. .. py:method:: called.with_some_args(**kargs) The spy method must be invoked with AT LEAST the given parameter values. It supports literal values and hamcrest matchers. :: assert_that(spy.method, called().with_some_args(name="mary")) See :ref:`with_some_args`. for properties -------------- .. py:class:: property_got() .. py:class:: property_set() .. py:method:: property_set.to(value) See :ref:`properties`. for mocks --------- .. py:class:: verify() Checks the given mock meets the given expectations. :: assert_that(mock, verify()) See :ref:`verify`. .. py:class:: any_order_verify() Checks the given mock meets the given expectations even when the invocation sequence has a different order to the expectations. :: assert_that(mock, any_order_verify()) See :ref:`verify`. Module level functions ====================== .. py:function:: assert_that(item, matcher) A convenient replace for the hamcrest `assert_that` method. See :ref:`sec assert_that`. .. py:function:: wait_that(item, matcher, reason='', delta=1, timeout=5) It test the `matcher` over `item` until it matches or fails after `timemout` seconds, polling the matcher each `delta` seconds. .. py:function:: method_returning(value) Creates an independent Stub method that returns the given value. It may be added to any object:: some.method = method_returning(20) See :ref:`ad-hoc methods`. .. py:function:: method_raising() Creates an independent Stub method that raises the given exception. It may be added to any object:: some.method = method_raising(ValueError) See :ref:`ad-hoc methods`. .. py:function:: set_default_behavior() Set the default behavior for undefined Stub methods. The built-in behavior is to return **None**. See :ref:`set_default_behavior`. .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-column: 90 .. End: doublex-1.8.2/docs/async-spies.rst0000644000175000017500000000621612435722065016173 0ustar piotrpiotr.. _async: Asynchronous spies ================== .. versionadded:: 1.5.1 Sometimes interaction among your SUT class and their collaborators does not meet a synchronous behavior. That may happen when the SUT performs collaborator invocations in a different thread, or when the invocation pass across a message queue, publish/subscribe service, etc. Something like that: .. sourcecode:: python class Collaborator(object): def write(self, data): print "your code here" class SUT(object): def __init__(self, collaborator): self.collaborator = collaborator def some_method(self): thread.start_new_thread(self.collaborator.write, ("something",)) If you try to test your collaborator is called using a Spy, you will get a wrong behavior: .. sourcecode:: python # THE WRONG WAY class AsyncTests(unittest.TestCase): def test_wrong_try_to_test_an_async_invocation(self): # given spy = Spy(Collaborator) sut = SUT(spy) # when sut.some_method() # then assert_that(spy.write, called()) due to the ``called()`` assertion may happen before the ``write()`` invocation, although not always... You may be tempted to put a sleep before the assertion, but this is a bad solution. A right way to solve that issue is to use something like a barrier. The `threading.Event`__ may be used as a barrier. See this new test version: __ http://docs.python.org/2/library/threading.html#event-objects .. sourcecode:: python # THE DIRTY WAY class AsyncTests(unittest.TestCase): def test_an_async_invocation_with_barrier(self): # given barrier = threading.Event() with Spy(Collaborator) as spy: spy.write.attach(lambda *args: barrier.set) sut = SUT(spy) # when sut.some_method() barrier.wait(1) # then assert_that(spy.write, called()) The ``spy.write.attach()`` is part of the doublex stub-observer `mechanism`__, a way to run arbitrary code when stubbed methods are called. __ http://python-doublex.readthedocs.org/en/latest/reference.html#stub-observers That works because the ``called()`` assertion is performed only when the spy releases the barrier. If the ``write()`` invocation never happens, the ``barrier.wait()`` continues after 1 second but the test fails, as must do. When all is right, the barrier waits just the required time. Well, this mechanism is a doublex builtin (the ``async`` matcher) since release 1.5.1 providing the same behavior in a clearer way. The next is functionally equivalent to the listing just above: .. sourcecode:: python # THE DOUBLEX WAY class AsyncTests(unittest.TestCase): def test_test_an_async_invocation_with_doublex_async(self): # given spy = Spy(Collaborator) sut = SUT(spy) # when sut.some_method() # then assert_that(spy.write, called().async(timeout=1)) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-column: 90 .. End: doublex-1.8.2/docs/async-spies.rst.test0000644000175000017500000000630212435722065017145 0ustar piotrpiotr.. _async: Asynchronous spies ================== .. versionadded:: 1.5.1 Sometimes interaction among your SUT class and their collaborators does not meet a synchronous behavior. That may happen when the SUT performs collaborator invocations in a different thread, or when the invocation pass across a message queue, publish/subscribe service, etc. Something like that: .. testcode:: .. sourcecode:: python class Collaborator(object): def write(self, data): print "your code here" class SUT(object): def __init__(self, collaborator): self.collaborator = collaborator def some_method(self): thread.start_new_thread(self.collaborator.write, ("something",)) If you try to test your collaborator is called using a Spy, you will get a wrong behavior: .. testcode:: .. sourcecode:: python # THE WRONG WAY class AsyncTests(unittest.TestCase): def test_wrong_try_to_test_an_async_invocation(self): # given spy = Spy(Collaborator) sut = SUT(spy) # when sut.some_method() # then assert_that(spy.write, called()) due to the ``called()`` assertion may happen before the ``write()`` invocation, although not always... You may be tempted to put a sleep before the assertion, but this is a bad solution. A right way to solve that issue is to use something like a barrier. The `threading.Event`__ may be used as a barrier. See this new test version: __ http://docs.python.org/2/library/threading.html#event-objects .. testcode:: .. sourcecode:: python # THE DIRTY WAY class AsyncTests(unittest.TestCase): def test_an_async_invocation_with_barrier(self): # given barrier = threading.Event() with Spy(Collaborator) as spy: spy.write.attach(lambda *args: barrier.set) sut = SUT(spy) # when sut.some_method() barrier.wait(1) # then assert_that(spy.write, called()) The ``spy.write.attach()`` is part of the doublex stub-observer `mechanism`__, a way to run arbitrary code when stubbed methods are called. __ http://python-doublex.readthedocs.org/en/latest/reference.html#stub-observers That works because the ``called()`` assertion is performed only when the spy releases the barrier. If the ``write()`` invocation never happens, the ``barrier.wait()`` continues after 1 second but the test fails, as must do. When all is right, the barrier waits just the required time. Well, this mechanism is a doublex builtin (the ``async`` matcher) since release 1.5.1 providing the same behavior in a clearer way. The next is functionally equivalent to the listing just above: .. testcode:: .. sourcecode:: python # THE DOUBLEX WAY class AsyncTests(unittest.TestCase): def test_test_an_async_invocation_with_doublex_async(self): # given spy = Spy(Collaborator) sut = SUT(spy) # when sut.some_method() # then assert_that(spy.write, called().async(timeout=1)) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-column: 90 .. End: doublex-1.8.2/docs/calls.rst0000644000175000017500000000201212435722065015021 0ustar piotrpiotrcalls: low-level access to invocation records --------------------------------------------- .. versionadded:: 1.6.3 Invocation over spy methods are available in the ``calls`` attribute. You may use that to get invocation argument values and perform complex assertions (i.e: check invocations arguments were specific instances). However, you should prefer ``called()`` matcher assertions over this. An example: .. sourcecode:: python from doublex import Spy, assert_that, ANY_ARG, is_ class TheCollaborator(object): def method(self, *args, **kargs): pass with Spy(TheCollaborator) as spy: spy.method(ANY_ARG).returns(100) spy.method(1, 2, 3) spy.method(key=2, val=5) assert_that(spy.method.calls[0].args, is_((1, 2, 3))) assert_that(spy.method.calls[1].kargs, is_(dict(key=2, val=5))) assert_that(spy.method.calls[1].retval, is_(100)) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/calls.rst.test0000644000175000017500000000203512435722065016004 0ustar piotrpiotrcalls: low-level access to invocation records --------------------------------------------- .. versionadded:: 1.6.3 Invocation over spy methods are available in the ``calls`` attribute. You may use that to get invocation argument values and perform complex assertions (i.e: check invocations arguments were specific instances). However, you should prefer ``called()`` matcher assertions over this. An example: .. testcode:: calls .. sourcecode:: python from doublex import Spy, assert_that, ANY_ARG, is_ class TheCollaborator(object): def method(self, *args, **kargs): pass with Spy(TheCollaborator) as spy: spy.method(ANY_ARG).returns(100) spy.method(1, 2, 3) spy.method(key=2, val=5) assert_that(spy.method.calls[0].args, is_((1, 2, 3))) assert_that(spy.method.calls[1].kargs, is_(dict(key=2, val=5))) assert_that(spy.method.calls[1].retval, is_(100)) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/conf.py0000644000175000017500000002371712435722065014507 0ustar piotrpiotr# -*- coding: utf-8 -*- # # doublex documentation build configuration file, created by # sphinx-quickstart on Sat Dec 21 00:18:51 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.doctest'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'doublex' copyright = u'2013,2014, David Villa Alises' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.8' # The full version, including alpha/beta/rc tags. release = '1.8.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'doublexdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'doublex.tex', u'doublex', u'David Villa Alises', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'doublex', u'doublex', [u'David Villa Alises'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'doublex', u'doublex', u'David Villa Alises', 'doublex', 'Python test doubles', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'doublex' epub_author = u'David Villa Alises' epub_publisher = u'David Villa Alises' epub_copyright = u'2013, David Villa Alises' # The basename for the epub file. It defaults to the project name. #epub_basename = u'doublex' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True doublex-1.8.2/docs/contents.rst.inc0000644000175000017500000000051012435722065016331 0ustar piotrpiotrUser's Guide ------------ .. toctree:: :maxdepth: 2 install doubles reference methods properties delegates observers mimics async-spies inline-setup calls api pyDoubles release-notes Indices and tables ------------------ * :ref:`genindex` .. :ref:`modindex` .. :ref:`search` doublex-1.8.2/docs/delegates.rst0000644000175000017500000000150312435722065015664 0ustar piotrpiotr.. index:: single: Stub delegates .. _delegates: Stub delegates ============== The value returned by the stub may be delegated from a function, method or other callable... .. sourcecode:: python def get_user(): return "Freddy" with Stub() as stub: stub.user().delegates(get_user) stub.foo().delegates(lambda: "hello") assert_that(stub.user(), is_("Freddy")) assert_that(stub.foo(), is_("hello")) It may be delegated from iterables or generators too!: .. sourcecode:: python with Stub() as stub: stub.foo().delegates([1, 2, 3]) assert_that(stub.foo(), is_(1)) assert_that(stub.foo(), is_(2)) assert_that(stub.foo(), is_(3)) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/delegates.rst.test0000644000175000017500000000153512435722065016647 0ustar piotrpiotr.. index:: single: Stub delegates .. _delegates: Stub delegates ============== The value returned by the stub may be delegated from a function, method or other callable... .. testcode:: .. sourcecode:: python def get_user(): return "Freddy" with Stub() as stub: stub.user().delegates(get_user) stub.foo().delegates(lambda: "hello") assert_that(stub.user(), is_("Freddy")) assert_that(stub.foo(), is_("hello")) It may be delegated from iterables or generators too!: .. testcode:: .. sourcecode:: python with Stub() as stub: stub.foo().delegates([1, 2, 3]) assert_that(stub.foo(), is_(1)) assert_that(stub.foo(), is_(2)) assert_that(stub.foo(), is_(3)) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/doubles.rst0000644000175000017500000001474712435722065015402 0ustar piotrpiotr======= Doubles ======= Some very basic examples are shown below. Remember that test doubles are created to be invoked by your `SUT `_, and a RealWorld™ test never directly invokes doubles. Here we do it that way, but just for simplicity. .. index:: single: Stub .. _stub: Stub ==== Hint: *Stubs tell you what you wanna hear.* A ``Stub`` is a double object that may be programmed to return specified values depending on method invocations and their arguments. You must use a context (the ``with`` keyword) for that. Invocations over the ``Stub`` must meet the collaborator interface: .. testsetup:: * import unittest class SomeException(Exception): pass class Collaborator(object): def hello(self): return "hello" def add(self, a, b): return a + b .. sourcecode:: python from doublex import Stub, ANY_ARG, assert_that, is_ class Collaborator: def hello(self): return "hello" def add(self, a, b): return a + b with Stub(Collaborator) as stub: stub.hello().raises(SomeException) stub.add(ANY_ARG).returns(4) assert_that(stub.add(2,3), is_(4)) If you call an nonexistent method you will get an ``AttributeError`` exception. .. sourcecode:: python >>> with Stub(Collaborator) as stub: ... stub.foo().returns(True) Traceback (most recent call last): ... AttributeError: 'Collaborator' object has no attribute 'foo' Wrong argument number: .. sourcecode:: python >>> with Stub(Collaborator) as stub: ... stub.hello(1).returns(2) # interface mismatch exception Traceback (most recent call last): ... TypeError: Collaborator.hello() takes exactly 1 argument (2 given) "free" Stub ----------- This allows you to invoke any method you want because it is not restricted to an interface. .. sourcecode:: python from doublex import Stub, assert_that, is_ # given with Stub() as stub: stub.foo('hi').returns(10) # when result = stub.foo('hi') # then assert_that(result, is_(10)) .. index:: single: Spy Spy === Hint: *Spies remember everything that happens to them.* Spy extends the Stub functionality allowing you to assert on the invocation it receives since its creation. Invocations over the Spy must meet the collaborator interface. .. sourcecode:: python from hamcrest import contains_string from doublex import Spy, assert_that, called class Sender: def say(self): return "hi" def send_mail(self, address, force=True): pass # [some amazing code] sender = Spy(Sender) sender.send_mail("john.doe@example.net") # right, Sender.send_mail interface support this assert_that(sender.send_mail, called()) assert_that(sender.send_mail, called().with_args("john.doe@example.net")) assert_that(sender.send_mail, called().with_args(contains_string("@example.net"))) sender.bar() # interface mismatch exception .. sourcecode:: python Traceback (most recent call last): ... AttributeError: 'Sender' object has no attribute 'bar' .. sourcecode:: python >>> sender = Spy(Sender) >>> sender.send_mail() Traceback (most recent call last): ... TypeError: Sender.send_mail() takes at least 2 arguments (1 given) .. sourcecode:: python >>> sender = Spy(Sender) >>> sender.send_mail(wrong=1) Traceback (most recent call last): ... TypeError: Sender.send_mail() got an unexpected keyword argument 'wrong' .. sourcecode:: python >>> sender = Spy(Sender) >>> sender.send_mail('foo', wrong=1) Traceback (most recent call last): ... TypeError: Sender.send_mail() got an unexpected keyword argument 'wrong' "free" Spy ---------- As the "free" Stub, this is a spy not restricted by a collaborator interface. .. sourcecode:: python from doublex import Stub, assert_that # given with Spy() as sender: sender.helo().returns("OK") # when sender.send_mail('hi') sender.send_mail('foo@bar.net') # then assert_that(sender.helo(), is_("OK")) assert_that(sender.send_mail, called()) assert_that(sender.send_mail, called().times(2)) assert_that(sender.send_mail, called().with_args('foo@bar.net')) .. index:: single: ProxySpy ProxySpy -------- Hint: *Proxy spies forward invocations to its actual instance.* The ``ProxySpy`` extends the ``Spy`` invoking the actual instance when the corresponding spy method is called .. warning:: Note the ``ProxySpy`` breaks isolation. It is not really a double. Therefore is always the worst double and the last resource. .. sourcecode:: python from doublex import ProxySpy, assert_that sender = ProxySpy(Sender()) # NOTE: It takes an instance (not class) assert_that(sender.say(), is_("hi")) assert_that(sender.say, called()) sender.say('boo!') # interface mismatch exception .. sourcecode:: python Traceback (most recent call last): ... TypeError: Sender.say() takes exactly 1 argument (2 given) .. index:: single: Mock .. _verify: Mock ==== Hint: *Mock forces the predefined script.* Mock objects may be programmed with a sequence of method calls. Later, the double must receive exactly the same sequence of invocations (including argument values). If the sequence does not match, an AssertionError is raised. "free" mocks are provided too: .. sourcecode:: python from doublex import Mock, assert_that, verify with Mock() as smtp: smtp.helo() smtp.mail(ANY_ARG) smtp.rcpt("bill@apple.com") smtp.data(ANY_ARG).returns(True).times(2) smtp.helo() smtp.mail("poormen@home.net") smtp.rcpt("bill@apple.com") smtp.data("somebody there?") smtp.data("I am afraid..") assert_that(smtp, verify()) ``verify()`` asserts invocation order. If your test does not require strict invocation order just use ``any_order_verify()`` matcher instead: .. sourcecode:: python from doublex import Mock, assert_that, any_order_verify with Mock() as mock: mock.foo() mock.bar() mock.bar() mock.foo() assert_that(mock, any_order_verify()) Programmed invocation sequence also may specify stubbed return values: .. sourcecode:: python from doublex import Mock, assert_that with Mock() as mock: mock.foo().returns(10) assert_that(mock.foo(), is_(10)) assert_that(mock, verify()) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/doubles.rst.test0000644000175000017500000001525112435722065016347 0ustar piotrpiotr======= Doubles ======= Some very basic examples are shown below. Remember that test doubles are created to be invoked by your `SUT `_, and a RealWorld™ test never directly invokes doubles. Here we do it that way, but just for simplicity. .. index:: single: Stub .. _stub: Stub ==== Hint: *Stubs tell you what you wanna hear.* A ``Stub`` is a double object that may be programmed to return specified values depending on method invocations and their arguments. You must use a context (the ``with`` keyword) for that. Invocations over the ``Stub`` must meet the collaborator interface: .. testsetup:: * import unittest class SomeException(Exception): pass class Collaborator(object): def hello(self): return "hello" def add(self, a, b): return a + b .. testcode:: .. sourcecode:: python from doublex import Stub, ANY_ARG, assert_that, is_ class Collaborator: def hello(self): return "hello" def add(self, a, b): return a + b with Stub(Collaborator) as stub: stub.hello().raises(SomeException) stub.add(ANY_ARG).returns(4) assert_that(stub.add(2,3), is_(4)) If you call an nonexistent method you will get an ``AttributeError`` exception. .. doctest:: .. sourcecode:: python >>> with Stub(Collaborator) as stub: ... stub.foo().returns(True) Traceback (most recent call last): ... AttributeError: 'Collaborator' object has no attribute 'foo' Wrong argument number: .. doctest:: .. sourcecode:: python >>> with Stub(Collaborator) as stub: ... stub.hello(1).returns(2) # interface mismatch exception Traceback (most recent call last): ... TypeError: Collaborator.hello() takes exactly 1 argument (2 given) "free" Stub ----------- This allows you to invoke any method you want because it is not restricted to an interface. .. testcode:: .. sourcecode:: python from doublex import Stub, assert_that, is_ # given with Stub() as stub: stub.foo('hi').returns(10) # when result = stub.foo('hi') # then assert_that(result, is_(10)) .. index:: single: Spy Spy === Hint: *Spies remember everything that happens to them.* Spy extends the Stub functionality allowing you to assert on the invocation it receives since its creation. Invocations over the Spy must meet the collaborator interface. .. testcode:: .. sourcecode:: python from hamcrest import contains_string from doublex import Spy, assert_that, called class Sender: def say(self): return "hi" def send_mail(self, address, force=True): pass # [some amazing code] sender = Spy(Sender) sender.send_mail("john.doe@example.net") # right, Sender.send_mail interface support this assert_that(sender.send_mail, called()) assert_that(sender.send_mail, called().with_args("john.doe@example.net")) assert_that(sender.send_mail, called().with_args(contains_string("@example.net"))) sender.bar() # interface mismatch exception .. testoutput:: .. sourcecode:: python Traceback (most recent call last): ... AttributeError: 'Sender' object has no attribute 'bar' .. doctest:: .. sourcecode:: python >>> sender = Spy(Sender) >>> sender.send_mail() Traceback (most recent call last): ... TypeError: Sender.send_mail() takes at least 2 arguments (1 given) .. doctest:: .. sourcecode:: python >>> sender = Spy(Sender) >>> sender.send_mail(wrong=1) Traceback (most recent call last): ... TypeError: Sender.send_mail() got an unexpected keyword argument 'wrong' .. doctest:: .. sourcecode:: python >>> sender = Spy(Sender) >>> sender.send_mail('foo', wrong=1) Traceback (most recent call last): ... TypeError: Sender.send_mail() got an unexpected keyword argument 'wrong' "free" Spy ---------- As the "free" Stub, this is a spy not restricted by a collaborator interface. .. testcode:: .. sourcecode:: python from doublex import Stub, assert_that # given with Spy() as sender: sender.helo().returns("OK") # when sender.send_mail('hi') sender.send_mail('foo@bar.net') # then assert_that(sender.helo(), is_("OK")) assert_that(sender.send_mail, called()) assert_that(sender.send_mail, called().times(2)) assert_that(sender.send_mail, called().with_args('foo@bar.net')) .. index:: single: ProxySpy ProxySpy -------- Hint: *Proxy spies forward invocations to its actual instance.* The ``ProxySpy`` extends the ``Spy`` invoking the actual instance when the corresponding spy method is called .. warning:: Note the ``ProxySpy`` breaks isolation. It is not really a double. Therefore is always the worst double and the last resource. .. testcode:: .. sourcecode:: python from doublex import ProxySpy, assert_that sender = ProxySpy(Sender()) # NOTE: It takes an instance (not class) assert_that(sender.say(), is_("hi")) assert_that(sender.say, called()) sender.say('boo!') # interface mismatch exception .. testoutput:: .. sourcecode:: python Traceback (most recent call last): ... TypeError: Sender.say() takes exactly 1 argument (2 given) .. index:: single: Mock .. _verify: Mock ==== Hint: *Mock forces the predefined script.* Mock objects may be programmed with a sequence of method calls. Later, the double must receive exactly the same sequence of invocations (including argument values). If the sequence does not match, an AssertionError is raised. "free" mocks are provided too: .. testcode:: .. sourcecode:: python from doublex import Mock, assert_that, verify with Mock() as smtp: smtp.helo() smtp.mail(ANY_ARG) smtp.rcpt("bill@apple.com") smtp.data(ANY_ARG).returns(True).times(2) smtp.helo() smtp.mail("poormen@home.net") smtp.rcpt("bill@apple.com") smtp.data("somebody there?") smtp.data("I am afraid..") assert_that(smtp, verify()) ``verify()`` asserts invocation order. If your test does not require strict invocation order just use ``any_order_verify()`` matcher instead: .. testcode:: .. sourcecode:: python from doublex import Mock, assert_that, any_order_verify with Mock() as mock: mock.foo() mock.bar() mock.bar() mock.foo() assert_that(mock, any_order_verify()) Programmed invocation sequence also may specify stubbed return values: .. testcode:: .. sourcecode:: python from doublex import Mock, assert_that with Mock() as mock: mock.foo().returns(10) assert_that(mock.foo(), is_(10)) assert_that(mock, verify()) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/index.rst0000644000175000017500000000013712435722065015040 0ustar piotrpiotr:orphan: ======= doublex ======= .. include :: README.rst.inc .. include :: contents.rst.inc doublex-1.8.2/docs/inline-setup.rst0000644000175000017500000000210312435722065016340 0ustar piotrpiotrInline stubbing and mocking =========================== .. versionadded:: 1.8 - Proposed by `Carlos Ble `_ Several pyDoubles users ask for an alternative to set stubbing and mocking in a way similar to pyDoubles API, that is, instead of use the double context manager: .. sourcecode:: python with Stub() as stub: stub.foo(1).returns(100) with Mock() as mock: mock.bar(2).returns(50) You may invoke the :py:func:`when` and :py:func:`except_call` functions to get the same setup. .. sourcecode:: python stub = Stub() when(stub).foo(1).returns(100) mock = Mock() expect_call(mock).bar(2).returns(50) Note that :py:func:`when` and :py:func:`except_call` internally provide almost the same functionality. Two functions are provided only for test readability purposes. :py:func:`when` is intented for stubs, spies and proxyspies, and :py:func:`except_call` is intented for mocks. .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-column: 90 .. End: doublex-1.8.2/docs/install.rst0000644000175000017500000000143312435722065015377 0ustar piotrpiotr======= Install ======= The simplest install method is to use ``pip``:: $ sudo pip install doublex Or you can download the last release tarball, available in the `PyPI project `_:: $ gunzip doublex-X.X.tar.gz $ tar xvf doublex-X.X.tar $ cd doublex-X.X/ To install:: $ sudo python setup.py install Or use pip:: $ sudo pip install doubles-X.X.tar.gz .. note:: doublex depends on PyHamcrest, but if you use ``pip`` it is automatically installed too. Also it is available as Debian and Ubuntu official packages, although may be outdated:: $ sudo apt-get install python-doublex .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/methods.rst0000644000175000017500000000133512435722065015375 0ustar piotrpiotr.. _ad-hoc methods: Ad-hoc stub methods =================== Create a standalone stub method directly over any instance (even no doubles), with :py:func:`method_returning` and :py:func:`method_raising`: .. sourcecode:: python from doublex import method_returning, method_raising, assert_that collaborator = Collaborator() collaborator.foo = method_returning("bye") assert_that(collaborator.foo(), is_("bye")) collaborator.foo = method_raising(SomeException) collaborator.foo() # raises SomeException Traceback (most recent call last): ... SomeException .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/methods.rst.test0000644000175000017500000000137112435722065016353 0ustar piotrpiotr.. _ad-hoc methods: Ad-hoc stub methods =================== Create a standalone stub method directly over any instance (even no doubles), with :py:func:`method_returning` and :py:func:`method_raising`: .. testcode:: .. sourcecode:: python from doublex import method_returning, method_raising, assert_that collaborator = Collaborator() collaborator.foo = method_returning("bye") assert_that(collaborator.foo(), is_("bye")) collaborator.foo = method_raising(SomeException) collaborator.foo() # raises SomeException .. testoutput:: Traceback (most recent call last): ... SomeException .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/mimics.rst0000644000175000017500000000221012435722065015204 0ustar piotrpiotr.. index:: single: Mimic doubles Mimic doubles ============= Usually double instances behave as collaborator surrogates, but they do not expose the same class hierarchy, and usually this is pretty enough when the code uses "duck typing": .. testsetup:: mimic .. sourcecode:: python class A(object): pass class B(A): pass .. sourcecode:: python >>> from doublex import Spy >>> spy = Spy(B()) >>> isinstance(spy, Spy) True >>> isinstance(spy, B) False But some third party library DOES strict type checking using ``isinstance()``. That invalidates our doubles. For these cases you can use Mimic's. Mimic class decorates any double class to achieve full replacement instances (Liskov principle): .. sourcecode:: python >>> from doublex import Stub, Mimic >>> spy = Mimic(Spy, B) >>> isinstance(spy, B) True >>> isinstance(spy, A) True >>> isinstance(spy, Spy) True >>> isinstance(spy, Stub) True >>> isinstance(spy, object) True .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/mimics.rst.test0000644000175000017500000000225412435722065016172 0ustar piotrpiotr.. index:: single: Mimic doubles Mimic doubles ============= Usually double instances behave as collaborator surrogates, but they do not expose the same class hierarchy, and usually this is pretty enough when the code uses "duck typing": .. testsetup:: mimic .. sourcecode:: python class A(object): pass class B(A): pass .. doctest:: mimic .. sourcecode:: python >>> from doublex import Spy >>> spy = Spy(B()) >>> isinstance(spy, Spy) True >>> isinstance(spy, B) False But some third party library DOES strict type checking using ``isinstance()``. That invalidates our doubles. For these cases you can use Mimic's. Mimic class decorates any double class to achieve full replacement instances (Liskov principle): .. doctest:: mimic .. sourcecode:: python >>> from doublex import Stub, Mimic >>> spy = Mimic(Spy, B) >>> isinstance(spy, B) True >>> isinstance(spy, A) True >>> isinstance(spy, Spy) True >>> isinstance(spy, Stub) True >>> isinstance(spy, object) True .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/observers.rst0000644000175000017500000000120512435722065015740 0ustar piotrpiotr.. index:: single: Stub observers .. _observers: Stub observers ============== Stub observers allow you to execute extra code (similar to python-mock "side effects", but easier): .. sourcecode:: python class Observer(object): def __init__(self): self.state = None def notify(self, *args, **kargs): self.state = args[0] observer = Observer() stub = Stub() stub.foo.attach(observer.notify) stub.foo(2) assert_that(observer.state, is_(2)) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/observers.rst.test0000644000175000017500000000122212435722065016715 0ustar piotrpiotr.. index:: single: Stub observers .. _observers: Stub observers ============== Stub observers allow you to execute extra code (similar to python-mock "side effects", but easier): .. testcode:: .. sourcecode:: python class Observer(object): def __init__(self): self.state = None def notify(self, *args, **kargs): self.state = args[0] observer = Observer() stub = Stub() stub.foo.attach(observer.notify) stub.foo(2) assert_that(observer.state, is_(2)) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/properties.rst0000644000175000017500000000432512435722065016130 0ustar piotrpiotr.. index:: single: Properties .. _properties: Properties ========== **doublex** supports stub and spy properties in a pretty easy way in relation to other frameworks like python-mock. That requires two constraints: * It does not support "free" doubles. ie: you must give a collaborator in the constructor. * collaborator must be a new-style class. See the next example. Stubbing properties ------------------- .. sourcecode:: python from doublex import Spy, assert_that, is_ with Spy(Collaborator) as spy: spy.prop = 2 # stubbing 'prop' value assert_that(spy.prop, is_(2)) # double property getter invoked Spying properties ----------------- Continuing previous example: .. sourcecode:: python from doublex import Spy, assert_that, never from doublex import property_got, property_set class Collaborator(object): @property def prop(self): return 1 @prop.setter def prop(self, value): pass spy = Spy(Collaborator) value = spy.prop assert_that(spy, property_got('prop')) # property 'prop' was read. spy.prop = 4 spy.prop = 5 spy.prop = 5 assert_that(spy, property_set('prop')) # was set to any value assert_that(spy, property_set('prop').to(4)) assert_that(spy, property_set('prop').to(5).times(2)) assert_that(spy, never(property_set('prop').to(6))) Mocking properties ------------------ Getting property: .. sourcecode:: python from doublex import Mock, assert_that, verify with Mock(Collaborator) as mock: mock.prop mock.prop assert_that(mock, verify()) Setting property: .. sourcecode:: python from doublex import Mock, assert_that, verify with Mock(Collaborator) as mock: mock.prop = 5 mock.prop = 5 assert_that(mock, verify()) Using matchers: .. sourcecode:: python from hamcrest import all_of, greater_than, less_than from doublex import Mock, assert_that, verify with Mock(Collaborator) as mock: mock.prop = all_of(greater_than(8), less_than(12)) mock.prop = 10 assert_that(mock, verify()) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/properties.rst.test0000644000175000017500000000453012435722065017104 0ustar piotrpiotr.. index:: single: Properties .. _properties: Properties ========== **doublex** supports stub and spy properties in a pretty easy way in relation to other frameworks like python-mock. That requires two constraints: * It does not support "free" doubles. ie: you must give a collaborator in the constructor. * collaborator must be a new-style class. See the next example. Stubbing properties ------------------- .. testcode:: stub-property .. sourcecode:: python from doublex import Spy, assert_that, is_ with Spy(Collaborator) as spy: spy.prop = 2 # stubbing 'prop' value assert_that(spy.prop, is_(2)) # double property getter invoked Spying properties ----------------- Continuing previous example: .. testcode:: spy-property .. sourcecode:: python from doublex import Spy, assert_that, never from doublex import property_got, property_set class Collaborator(object): @property def prop(self): return 1 @prop.setter def prop(self, value): pass spy = Spy(Collaborator) value = spy.prop assert_that(spy, property_got('prop')) # property 'prop' was read. spy.prop = 4 spy.prop = 5 spy.prop = 5 assert_that(spy, property_set('prop')) # was set to any value assert_that(spy, property_set('prop').to(4)) assert_that(spy, property_set('prop').to(5).times(2)) assert_that(spy, never(property_set('prop').to(6))) Mocking properties ------------------ Getting property: .. testcode:: spy-property .. sourcecode:: python from doublex import Mock, assert_that, verify with Mock(Collaborator) as mock: mock.prop mock.prop assert_that(mock, verify()) Setting property: .. testcode:: spy-property .. sourcecode:: python from doublex import Mock, assert_that, verify with Mock(Collaborator) as mock: mock.prop = 5 mock.prop = 5 assert_that(mock, verify()) Using matchers: .. testcode:: spy-property .. sourcecode:: python from hamcrest import all_of, greater_than, less_than from doublex import Mock, assert_that, verify with Mock(Collaborator) as mock: mock.prop = all_of(greater_than(8), less_than(12)) mock.prop = 10 assert_that(mock, verify()) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/pyDoubles.rst0000644000175000017500000000612212435722065015677 0ustar piotrpiotr========= pyDoubles ========= ``doublex`` started as a attempt to improve and simplify the codebase and API of the `pyDoubles `_ framework (by Carlos Ble). Respect to pyDoubles, ``doublex`` has these features: * Just hamcrest matchers (for all features). * Only ProxySpy requires an instance. Other doubles accept a class too, but they never instantiate it. * Properties may be stubbed and spied. * Stub observers: Notify arbitrary hooks when methods are invoked. Useful to add "side effects". * Stub delegates: Use callables, iterables or generators to create stub return values. * Mimic doubles: doubles that inherit the same collaborator subclasses. This provides full `LSP `_ for code that make strict type checking. ``doublex`` solves all the issues and supports all the feature requests notified in the pyDoubles issue tracker: * `assert keyword argument values `_ * `assert that a method is called exactly one `_ * `mocks impose invocation order `_ * `doubles have framework public API `_ * `stubs support keyword positional arguments `_ And some other features requested in the user group: * `doubles for properties `_ * `creating doubles without instantiating real class `_ * `using hamcrest with kwargs `_ ``doublex`` provides the pyDoubles API as a wrapper for easy transition to doublex for pyDoubles users. However, there are small differences. The bigger diference is that pyDoubles matchers are not supported anymore, although you may get the same feature using standard hamcrest matchers. Anyway, formally provided pyDoubles matchers are available as hamcrest aliases. ``doublex`` supports all the pyDoubles features and some more that can not be easily backported. If you are a pyDoubles user you can run your tests using doublex.pyDoubles module. However, we recommed the `native doublex API `_ for your new developments. In most cases the only required change in your code is the ``import`` sentence, that change from: .. sourcecode:: python import pyDoubles.framework.* to: .. sourcecode:: python from doublex.pyDoubles import * See the old pyDoubles documentation at ``__ (that was formerly available in the pydoubles.org site). .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/reference.rst0000644000175000017500000003347612435722065015703 0ustar piotrpiotr========= Reference ========= .. index:: single: assert_that() .. _sec assert_that: assert_that() ============= `assert()`__ evaluates a boolean expression, but ``assert_that()`` takes an arbitrary object and a `matcher`__, that is applied over the former. This way makes possible to build up complex assertions by means of matcher composition. __ http://docs.python.org/2/reference/simple_stmts.html#the-assert-statement __ http://pythonhosted.org/PyHamcrest/tutorial.html CAUTION: Be ware about ``hamcrest.assert_that()`` ------------------------------------------------- Note the `hamcrest.assert_that()`__ function has two different behavior depending of its arguments: __ https://github.com/hamcrest/PyHamcrest/blob/master/hamcrest/core/assert_that.py#L39 * ``assert_that(actual, matcher, [reason])`` In this form the ``matcher`` is applied to the ``actual`` object. If the matcher fails, it raises AssertionError showing the optional reason. * ``assert_that(value, [reason])`` If the boolean interpretation of ``value`` is False, it raises AssertionError showing the optional reason. It implies that something like: .. sourcecode:: python from hamcrest import assert_that assert_that(foo, bar) If ``bar`` is not a matcher, the assertion is satisfied for any non-false ``foo``, independently of the value of ``bar``. A more obvious example: .. sourcecode:: python from hamcrest import assert_that assert_that(2 + 2, 5) # OMG! that assertion IS satisfied! For this reason, when you need compare values (equivalent to the unit ``assertEquals``) you must always use a matcher, like ``is_`` or ``equal_to``: .. sourcecode:: python assert_that(2 + 2, is_(5)) # that assertion is NOT satisfied! assert_that(2 + 2, equal_to(5)) # that assertion is NOT satisfied! .. index:: single: assert_that() Prefer ``doublex.assert_that`` ------------------------------ .. versionadded:: 1.7 - (thanks to `Eduardo Ferro`__) __ https://bitbucket.org/DavidVilla/python-doublex/pull-request/5/assert_that-raises To avoid the issues described in the previous section, doublex provides an alternative ``assert_that()`` implementation that enforces a matcher as second argument. .. sourcecode:: python >>> from doublex import assert_that >>> assert_that(1, 1) Traceback (most recent call last): ... MatcherRequiredError: 1 should be a hamcrest Matcher .. index:: single: Stub Stubbing ======== The stub provides all methods in the collaborator interface. When the collaborator is not given (a free stub), the stub seems to have any method you invoke on it. The default behavior for non stubbed methods is to return ``None``, although it can be changed (see :ref:`set_default_behavior`). .. sourcecode:: python >>> from doublex import Stub >>> stub = Stub() >>> stub.method() This behavior may be customized in each test using the Python context manager facility: .. sourcecode:: python from doublex import Stub with Stub() as stub: stub.method().returns() `Hamcrest `_ matchers may be used to define amazing stub conditions: .. sourcecode:: python from hamcrest import all_of, has_length, greater_than, less_than from doublex import Stub, assert_that, is_ with Stub() as stub: stub.foo(has_length(less_than(4))).returns('<4') stub.foo(has_length(4)).returns('four') stub.foo(has_length( all_of(greater_than(4), less_than(8)))).returns('48') assert_that(stub.foo((1, 2)), is_('<4')) assert_that(stub.foo('abcd'), is_('four')) assert_that(stub.foo('abcde'), is_('48')) .. _returns_input: Stubs returning input --------------------- .. sourcecode:: python from doublex import Stub, assert_that def test_returns_input(self): with Stub() as stub: stub.foo(1).returns_input() assert_that(stub.foo(1), is_(1)) .. _raises: Stubs raising exceptions ------------------------ .. sourcecode:: python from doublex import Stub def test_raises(self): with Stub() as stub: stub.foo(2).raises(SomeException) with self.assertRaises(SomeException): stub.foo(2) .. _set_default_behavior: Changing default stub behavior ------------------------------ .. versionadded:: 1.7 - (thanks to `Eduardo Ferro`__) __ https://bitbucket.org/DavidVilla/python-doublex/pull-request/4/stub-configuration-for-raise-an-error-when Any non-stubbed method returns ``None``. But this behavior can be changed by means of ``set_default_behavior()`` function. It can be applied to any double class: ``Stub``, ``Spy``, ``ProxySpy`` or ``Mock``. .. sourcecode:: python from doublex import Stub, assert_that from doublex import set_default_behavior, method_returning set_default_behavior(Stub, method_returning(20)) stub = Stub() assert_that(stub.unknown(), is_(20)) Or to a specific instance: .. sourcecode:: python from doublex import Stub, assert_that, is_ from doublex import set_default_behavior, method_returning stub = Stub() set_default_behavior(stub, method_returning(20)) assert_that(stub.unknown(), is_(20)) Also, it is possible to raise some exception: .. sourcecode:: python >>> from doublex import Stub, set_default_behavior, method_raising >>> stub = Stub() >>> set_default_behavior(stub, method_raising(SomeException)) >>> stub.unknown() Traceback (most recent call last): ... SomeException Asserting method calls ====================== To assert method invocations you need a ``Spy`` and the ``called()`` matcher. .. index:: single: called() .. _called: called() -------- ``called()`` matches method invocation (argument values are not relevant): .. sourcecode:: python from doublex import Spy, assert_that, called spy = Spy() spy.m1() spy.m2(None) spy.m3("hi", 3.0) spy.m4([1, 2]) assert_that(spy.m1, called()) assert_that(spy.m2, called()) assert_that(spy.m3, called()) assert_that(spy.m4, called()) .. index:: single: with_args() .. _with_args: with_args(): asserting calling argument values ---------------------------------------------- Match explicit argument values: .. sourcecode:: python from hamcrest import contains_string, less_than, greater_than from doublex import Spy, assert_that, called spy = Spy() spy.m1() spy.m2(None) spy.m3(2) spy.m4("hi", 3.0) spy.m5([1, 2]) spy.m6(name="john doe") assert_that(spy.m1, called()) assert_that(spy.m2, called()) assert_that(spy.m1, called().with_args()) assert_that(spy.m2, called().with_args(None)) assert_that(spy.m3, called().with_args(2)) assert_that(spy.m4, called().with_args("hi", 3.0)) assert_that(spy.m5, called().with_args([1, 2])) assert_that(spy.m6, called().with_args(name="john doe")) Remember that `hamcrest matchers `_ matchers are fully supported: .. sourcecode:: python assert_that(spy.m3, called().with_args(less_than(3))) assert_that(spy.m3, called().with_args(greater_than(1))) assert_that(spy.m6, called().with_args(name=contains_string("doe"))) Other example with a string argument and combining several matchers: .. sourcecode:: python from hamcrest import has_length, greater_than, less_than from doublex import Spy, assert_that, called, never spy = Spy() spy.foo("abcd") assert_that(spy.foo, called().with_args(has_length(4))) assert_that(spy.foo, called().with_args(has_length(greater_than(3)))) assert_that(spy.foo, called().with_args(has_length(less_than(5)))) assert_that(spy.foo, never(called().with_args(has_length(greater_than(5))))) .. index:: single: hamcrest; anything() anything(): asserting wildcard values ------------------------------------- The ``anything()`` hamcrest matcher may be used to match any single value. That is useful when only some arguments are relevant: .. sourcecode:: python from hamcrest import anything spy.foo(1, 2, 20) spy.bar(1, key=2) assert_that(spy.foo, called().with_args(1, anything(), 20)) assert_that(spy.bar, called().with_args(1, key=anything())) .. index:: single: ANY_ARG ANY_ARG: greedy argument value wildcard --------------------------------------- ``ANY_ARG`` is a special value that matches any subsequent argument values, including no args. That is, ``ANY_ANG`` means "any value for any argument from here". If ``anything()`` is similar to the regular expression ``?``, ``ANY_ARG`` would be equivalent to ``*``. For this reason, it has **no sense** to give other values or matchers after an ``ANY_ARG``. It is also applicable to keyword arguments due they have no order. In summary, ``ANY_ARG``: * it must be the last positional argument value. * it can not be given as keyword value. * it can not be given together keyword arguments. Since version 1.7 a ``WrongAPI`` exception is raised if that situations (see `issue 9 `_). An example: .. sourcecode:: python from doublex import ANY_ARG spy.arg0() spy.arg1(1) spy.arg3(1, 2, 3) spy.arg_karg(1, key1='a') assert_that(spy.arg0, called()) assert_that(spy.arg0, called().with_args(ANY_ARG)) # equivalent to previous assert_that(spy.arg1, called()) assert_that(spy.arg1, called().with_args(ANY_ARG)) # equivalent to previous assert_that(spy.arg3, called().with_args(1, ANY_ARG)) assert_that(spy.arg_karg, called().with_args(1, ANY_ARG)) Also for stubs: .. sourcecode:: python from doublex import Stub, assert_that, ANY_ARG, is_ with Stub() as stub: stub.foo(ANY_ARG).returns(True) stub.bar(1, ANY_ARG).returns(True) assert_that(stub.foo(), is_(True)) assert_that(stub.foo(1), is_(True)) assert_that(stub.foo(key1='a'), is_(True)) assert_that(stub.foo(1, 2, 3, key1='a', key2='b'), is_(True)) assert_that(stub.foo(1, 2, 3), is_(True)) assert_that(stub.foo(1, key1='a'), is_(True)) .. index:: single: with_some_args() .. _with_some_args: with_some_args(): asserting just relevant arguments --------------------------------------------------- .. versionadded:: 1.7 When a method has several arguments and you need to assert an invocation giving a specific value just for some of them, you may use the :py:func:`anything` matcher for the rest of them. That works but the resulting code is a bit dirty: .. sourcecode:: python from hamcrest import anything from doublex import Spy, assert_that, ANY_ARG class Foo: def five_args_method(self, a, b, c, d, e=None): return 4 spy = Spy(Foo) spy.five_args_method(1, 2, 'bob', 4) # only the 'c' argument is important in the test assert_that(spy.five_args_method, called().with_args(anything(), anything(), 'bob', anything())) # assert only 'b' argument assert_that(spy.five_args_method, called().with_args(anything(), 2, ANY_ARG)) The :py:func:`with_some_args()` allows to specify just some arguments, assuming all other can take any value. The same example using :py:func:`with_some_arg()`: .. sourcecode:: python from doublex import Spy, assert_that, called class Foo: def five_args_method(self, a, b, c, d, e=None): return 4 spy = Spy(Foo) spy.five_args_method(1, 2, 'bob', 4) # only the 'c' argument is important in the test assert_that(spy.five_args_method, called().with_some_args(c='bob')) # assert only 'b' argument assert_that(spy.five_args_method, called().with_some_args(b=2)) This method may be used with both keyword and non-keyword arguments. .. warning:: Formal argument name is mandatory, so this is only applicable to restricted spies (those that are instantiated giving a collaborator). .. index:: single: never() .. _never: never() ------- Convenient replacement for ``hamcrest.is_not()``: .. sourcecode:: python from hamcrest import is_not from doublex import Spy, assert_that, called, never spy = Spy() assert_that(spy.m5, is_not(called())) # is_not() works assert_that(spy.m5, never(called())) # but prefer never() due to better error report messages .. index:: single: times() .. _times: times(): asserting number of calls ---------------------------------- .. sourcecode:: python from hamcrest import anything, all_of, greater_than, less_than from doublex import Spy, assert_that, called, ANY_ARG, never spy = Spy() spy.foo() spy.foo(1) spy.foo(1) spy.foo(2) assert_that(spy.unknown, never(called())) # = 0 times assert_that(spy.foo, called()) # > 0 assert_that(spy.foo, called().times(greater_than(0))) # > 0 (same) assert_that(spy.foo, called().times(4)) # = 4 assert_that(spy.foo, called().times(greater_than(2))) # > 2 assert_that(spy.foo, called().times(less_than(6))) # < 6 assert_that(spy.foo, never(called().with_args(5))) # = 0 times assert_that(spy.foo, called().with_args().times(1)) # = 1 assert_that(spy.foo, called().with_args(anything())) # > 0 assert_that(spy.foo, called().with_args(ANY_ARG).times(4)) # = 4 assert_that(spy.foo, called().with_args(1).times(2)) # = 2 assert_that(spy.foo, called().with_args(1).times(greater_than(1))) # > 1 assert_that(spy.foo, called().with_args(1).times(less_than(5))) # < 5 assert_that(spy.foo, called().with_args(1).times( all_of(greater_than(1), less_than(8)))) # 1 < times < 8 .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/reference.rst.test0000644000175000017500000003415412435722065016653 0ustar piotrpiotr========= Reference ========= .. index:: single: assert_that() .. _sec assert_that: assert_that() ============= `assert()`__ evaluates a boolean expression, but ``assert_that()`` takes an arbitrary object and a `matcher`__, that is applied over the former. This way makes possible to build up complex assertions by means of matcher composition. __ http://docs.python.org/2/reference/simple_stmts.html#the-assert-statement __ http://pythonhosted.org/PyHamcrest/tutorial.html CAUTION: Be ware about ``hamcrest.assert_that()`` ------------------------------------------------- Note the `hamcrest.assert_that()`__ function has two different behavior depending of its arguments: __ https://github.com/hamcrest/PyHamcrest/blob/master/hamcrest/core/assert_that.py#L39 * ``assert_that(actual, matcher, [reason])`` In this form the ``matcher`` is applied to the ``actual`` object. If the matcher fails, it raises AssertionError showing the optional reason. * ``assert_that(value, [reason])`` If the boolean interpretation of ``value`` is False, it raises AssertionError showing the optional reason. It implies that something like: .. sourcecode:: python from hamcrest import assert_that assert_that(foo, bar) If ``bar`` is not a matcher, the assertion is satisfied for any non-false ``foo``, independently of the value of ``bar``. A more obvious example: .. sourcecode:: python from hamcrest import assert_that assert_that(2 + 2, 5) # OMG! that assertion IS satisfied! For this reason, when you need compare values (equivalent to the unit ``assertEquals``) you must always use a matcher, like ``is_`` or ``equal_to``: .. sourcecode:: python assert_that(2 + 2, is_(5)) # that assertion is NOT satisfied! assert_that(2 + 2, equal_to(5)) # that assertion is NOT satisfied! .. index:: single: assert_that() Prefer ``doublex.assert_that`` ------------------------------ .. versionadded:: 1.7 - (thanks to `Eduardo Ferro`__) __ https://bitbucket.org/DavidVilla/python-doublex/pull-request/5/assert_that-raises To avoid the issues described in the previous section, doublex provides an alternative ``assert_that()`` implementation that enforces a matcher as second argument. .. doctest:: assert_that .. sourcecode:: python >>> from doublex import assert_that >>> assert_that(1, 1) Traceback (most recent call last): ... MatcherRequiredError: 1 should be a hamcrest Matcher .. index:: single: Stub Stubbing ======== The stub provides all methods in the collaborator interface. When the collaborator is not given (a free stub), the stub seems to have any method you invoke on it. The default behavior for non stubbed methods is to return ``None``, although it can be changed (see :ref:`set_default_behavior`). .. doctest:: .. sourcecode:: python >>> from doublex import Stub >>> stub = Stub() >>> stub.method() This behavior may be customized in each test using the Python context manager facility: .. sourcecode:: python from doublex import Stub with Stub() as stub: stub.method().returns() `Hamcrest `_ matchers may be used to define amazing stub conditions: .. testcode:: .. sourcecode:: python from hamcrest import all_of, has_length, greater_than, less_than from doublex import Stub, assert_that, is_ with Stub() as stub: stub.foo(has_length(less_than(4))).returns('<4') stub.foo(has_length(4)).returns('four') stub.foo(has_length( all_of(greater_than(4), less_than(8)))).returns('48') assert_that(stub.foo((1, 2)), is_('<4')) assert_that(stub.foo('abcd'), is_('four')) assert_that(stub.foo('abcde'), is_('48')) .. _returns_input: Stubs returning input --------------------- .. testcode:: .. sourcecode:: python from doublex import Stub, assert_that def test_returns_input(self): with Stub() as stub: stub.foo(1).returns_input() assert_that(stub.foo(1), is_(1)) .. _raises: Stubs raising exceptions ------------------------ .. testcode:: .. sourcecode:: python from doublex import Stub def test_raises(self): with Stub() as stub: stub.foo(2).raises(SomeException) with self.assertRaises(SomeException): stub.foo(2) .. _set_default_behavior: Changing default stub behavior ------------------------------ .. versionadded:: 1.7 - (thanks to `Eduardo Ferro`__) __ https://bitbucket.org/DavidVilla/python-doublex/pull-request/4/stub-configuration-for-raise-an-error-when Any non-stubbed method returns ``None``. But this behavior can be changed by means of ``set_default_behavior()`` function. It can be applied to any double class: ``Stub``, ``Spy``, ``ProxySpy`` or ``Mock``. .. sourcecode:: python from doublex import Stub, assert_that from doublex import set_default_behavior, method_returning set_default_behavior(Stub, method_returning(20)) stub = Stub() assert_that(stub.unknown(), is_(20)) Or to a specific instance: .. testcode:: default-hehavior-instance .. sourcecode:: python from doublex import Stub, assert_that, is_ from doublex import set_default_behavior, method_returning stub = Stub() set_default_behavior(stub, method_returning(20)) assert_that(stub.unknown(), is_(20)) Also, it is possible to raise some exception: .. doctest:: default-behavior-exception .. sourcecode:: python >>> from doublex import Stub, set_default_behavior, method_raising >>> stub = Stub() >>> set_default_behavior(stub, method_raising(SomeException)) >>> stub.unknown() Traceback (most recent call last): ... SomeException Asserting method calls ====================== To assert method invocations you need a ``Spy`` and the ``called()`` matcher. .. index:: single: called() .. _called: called() -------- ``called()`` matches method invocation (argument values are not relevant): .. testcode:: .. sourcecode:: python from doublex import Spy, assert_that, called spy = Spy() spy.m1() spy.m2(None) spy.m3("hi", 3.0) spy.m4([1, 2]) assert_that(spy.m1, called()) assert_that(spy.m2, called()) assert_that(spy.m3, called()) assert_that(spy.m4, called()) .. index:: single: with_args() .. _with_args: with_args(): asserting calling argument values ---------------------------------------------- Match explicit argument values: .. testcode:: .. sourcecode:: python from hamcrest import contains_string, less_than, greater_than from doublex import Spy, assert_that, called spy = Spy() spy.m1() spy.m2(None) spy.m3(2) spy.m4("hi", 3.0) spy.m5([1, 2]) spy.m6(name="john doe") assert_that(spy.m1, called()) assert_that(spy.m2, called()) assert_that(spy.m1, called().with_args()) assert_that(spy.m2, called().with_args(None)) assert_that(spy.m3, called().with_args(2)) assert_that(spy.m4, called().with_args("hi", 3.0)) assert_that(spy.m5, called().with_args([1, 2])) assert_that(spy.m6, called().with_args(name="john doe")) Remember that `hamcrest matchers `_ matchers are fully supported: .. testcode:: .. sourcecode:: python assert_that(spy.m3, called().with_args(less_than(3))) assert_that(spy.m3, called().with_args(greater_than(1))) assert_that(spy.m6, called().with_args(name=contains_string("doe"))) Other example with a string argument and combining several matchers: .. testcode:: .. sourcecode:: python from hamcrest import has_length, greater_than, less_than from doublex import Spy, assert_that, called, never spy = Spy() spy.foo("abcd") assert_that(spy.foo, called().with_args(has_length(4))) assert_that(spy.foo, called().with_args(has_length(greater_than(3)))) assert_that(spy.foo, called().with_args(has_length(less_than(5)))) assert_that(spy.foo, never(called().with_args(has_length(greater_than(5))))) .. index:: single: hamcrest; anything() anything(): asserting wildcard values ------------------------------------- The ``anything()`` hamcrest matcher may be used to match any single value. That is useful when only some arguments are relevant: .. testcode:: .. sourcecode:: python from hamcrest import anything spy.foo(1, 2, 20) spy.bar(1, key=2) assert_that(spy.foo, called().with_args(1, anything(), 20)) assert_that(spy.bar, called().with_args(1, key=anything())) .. index:: single: ANY_ARG ANY_ARG: greedy argument value wildcard --------------------------------------- ``ANY_ARG`` is a special value that matches any subsequent argument values, including no args. That is, ``ANY_ANG`` means "any value for any argument from here". If ``anything()`` is similar to the regular expression ``?``, ``ANY_ARG`` would be equivalent to ``*``. For this reason, it has **no sense** to give other values or matchers after an ``ANY_ARG``. It is also applicable to keyword arguments due they have no order. In summary, ``ANY_ARG``: * it must be the last positional argument value. * it can not be given as keyword value. * it can not be given together keyword arguments. Since version 1.7 a ``WrongAPI`` exception is raised if that situations (see `issue 9 `_). An example: .. testcode:: .. sourcecode:: python from doublex import ANY_ARG spy.arg0() spy.arg1(1) spy.arg3(1, 2, 3) spy.arg_karg(1, key1='a') assert_that(spy.arg0, called()) assert_that(spy.arg0, called().with_args(ANY_ARG)) # equivalent to previous assert_that(spy.arg1, called()) assert_that(spy.arg1, called().with_args(ANY_ARG)) # equivalent to previous assert_that(spy.arg3, called().with_args(1, ANY_ARG)) assert_that(spy.arg_karg, called().with_args(1, ANY_ARG)) Also for stubs: .. testcode:: .. sourcecode:: python from doublex import Stub, assert_that, ANY_ARG, is_ with Stub() as stub: stub.foo(ANY_ARG).returns(True) stub.bar(1, ANY_ARG).returns(True) assert_that(stub.foo(), is_(True)) assert_that(stub.foo(1), is_(True)) assert_that(stub.foo(key1='a'), is_(True)) assert_that(stub.foo(1, 2, 3, key1='a', key2='b'), is_(True)) assert_that(stub.foo(1, 2, 3), is_(True)) assert_that(stub.foo(1, key1='a'), is_(True)) .. index:: single: with_some_args() .. _with_some_args: with_some_args(): asserting just relevant arguments --------------------------------------------------- .. versionadded:: 1.7 When a method has several arguments and you need to assert an invocation giving a specific value just for some of them, you may use the :py:func:`anything` matcher for the rest of them. That works but the resulting code is a bit dirty: .. testcode:: .. sourcecode:: python from hamcrest import anything from doublex import Spy, assert_that, ANY_ARG class Foo: def five_args_method(self, a, b, c, d, e=None): return 4 spy = Spy(Foo) spy.five_args_method(1, 2, 'bob', 4) # only the 'c' argument is important in the test assert_that(spy.five_args_method, called().with_args(anything(), anything(), 'bob', anything())) # assert only 'b' argument assert_that(spy.five_args_method, called().with_args(anything(), 2, ANY_ARG)) The :py:func:`with_some_args()` allows to specify just some arguments, assuming all other can take any value. The same example using :py:func:`with_some_arg()`: .. testcode:: .. sourcecode:: python from doublex import Spy, assert_that, called class Foo: def five_args_method(self, a, b, c, d, e=None): return 4 spy = Spy(Foo) spy.five_args_method(1, 2, 'bob', 4) # only the 'c' argument is important in the test assert_that(spy.five_args_method, called().with_some_args(c='bob')) # assert only 'b' argument assert_that(spy.five_args_method, called().with_some_args(b=2)) This method may be used with both keyword and non-keyword arguments. .. warning:: Formal argument name is mandatory, so this is only applicable to restricted spies (those that are instantiated giving a collaborator). .. index:: single: never() .. _never: never() ------- Convenient replacement for ``hamcrest.is_not()``: .. testcode:: .. sourcecode:: python from hamcrest import is_not from doublex import Spy, assert_that, called, never spy = Spy() assert_that(spy.m5, is_not(called())) # is_not() works assert_that(spy.m5, never(called())) # but prefer never() due to better error report messages .. index:: single: times() .. _times: times(): asserting number of calls ---------------------------------- .. testcode:: times .. sourcecode:: python from hamcrest import anything, all_of, greater_than, less_than from doublex import Spy, assert_that, called, ANY_ARG, never spy = Spy() spy.foo() spy.foo(1) spy.foo(1) spy.foo(2) assert_that(spy.unknown, never(called())) # = 0 times assert_that(spy.foo, called()) # > 0 assert_that(spy.foo, called().times(greater_than(0))) # > 0 (same) assert_that(spy.foo, called().times(4)) # = 4 assert_that(spy.foo, called().times(greater_than(2))) # > 2 assert_that(spy.foo, called().times(less_than(6))) # < 6 assert_that(spy.foo, never(called().with_args(5))) # = 0 times assert_that(spy.foo, called().with_args().times(1)) # = 1 assert_that(spy.foo, called().with_args(anything())) # > 0 assert_that(spy.foo, called().with_args(ANY_ARG).times(4)) # = 4 assert_that(spy.foo, called().with_args(1).times(2)) # = 2 assert_that(spy.foo, called().with_args(1).times(greater_than(1))) # > 1 assert_that(spy.foo, called().with_args(1).times(less_than(5))) # < 5 assert_that(spy.foo, called().with_args(1).times( all_of(greater_than(1), less_than(8)))) # 1 < times < 8 .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/docs/release-notes.rst0000644000175000017500000001141212435722065016475 0ustar piotrpiotrRelease notes / Changelog ========================= doublex 1.8 ----------- * NEW inline stubbing and mocking with :py:func:`when` and :py:func:`expect_call`. See `doc`__ and `tests`__. * Added support for mocking properties. See `doc`__ and `tests`__. * Testing with tox for Python 2.6, 2.7, 3.2 and 3.3. * Documentation now at ``_ __ http://python-doublex.readthedocs.org/en/latest/inline-setup.html __ https://bitbucket.org/DavidVilla/python-doublex/src/7b22f6d23455712b3e8894e40ae6272fc852762e/doublex/test/unit_tests.py?at=default#cl-1482 __ http://python-doublex.readthedocs.org/en/latest/properties.html#mocking-properties __ https://bitbucket.org/DavidVilla/python-doublex/src/7b22f6d23455712b3e8894e40ae6272fc852762e/doublex/test/unit_tests.py?at=default#cl-1204 doublex 1.7.2 ------------- * Added support for varargs methods (\*args, \*\*kargs). Fixes `issue 14`__. * NEW tracer mechanism to log double invocations. See `test`__. * NEW module level ``wait_that()`` function. __ https://bitbucket.org/DavidVilla/python-doublex/issue/14/problem-spying-a-method-with-a-decorator __ https://bitbucket.org/DavidVilla/python-doublex/src/df2b3bda0eef64b5ddc6d6b3cc5a6380fb98e132/doublex/test/unit_tests.py?at=default#cl-1414 doublex 1.7 ----------- * NEW ``with_some_args()`` matcher to specify just relevant argument values in spy assertions. See `doc`__ and `tests`__. * NEW module level ``set_default_behavior()`` function to define behavior for non stubbed methods. Thanks to `Eduardo Ferro`__. See `doc`__ and `tests`__. __ http://python-doublex.readthedocs.org/en/latest/reference.html#with-some-args-asserting-just-relevant-arguments __ https://bitbucket.org/DavidVilla/python-doublex/src/147de5e7a52efae3c871c3065c082794b7272819/doublex/test/unit_tests.py?at=default#cl-1218 __ https://bitbucket.org/eferro __ http://python-doublex.readthedocs.org/en/latest/reference.html#changing-default-stub-behavior __ https://bitbucket.org/DavidVilla/python-doublex/src/147de5e7a52efae3c871c3065c082794b7272819/doublex/test/unit_tests.py?at=default#cl-1243 doublex 1.6.6 ------------- * bug fix update: Fixes `issue 11`__. __ https://bitbucket.org/DavidVilla/python-doublex/issue/11/there-are-no-stub-empy_stub-in-the doublex 1.6.5 ------------- * bug fix update: Fixes `issue 10`__. __ https://bitbucket.org/DavidVilla/python-doublex/issue/10/any_order_verify-fails-when-method-are doublex 1.6.4 ------------- * Asynchronous spy assertion race condition bug fixed. * Reading double attributes returns collaborator.class attribute values by default. doublex 1.6.2 ------------- * Invocation stubbed return value is now stored. * New low level spy API: double "calls" property provides access to invocations and their argument values. Each 'call' has an "args" sequence and "kargs dictionary". This provides support to perform individual assertions and direct access to invocation argument values. (see `test`__ and `doc`__). __ https://bitbucket.org/DavidVilla/python-doublex/src/ce8cdff71b8e3528380c305bf7d9ca75a64f6460/doublex/test/unit_tests.py?at=v1.6.2#cl-271 __ http://python-doublex.readthedocs.org/en/latest/reference.html#calls-low-level-access-to-invocation-records doublex 1.6 ----------- * First release supporting Python 3 (up to Python 3.2) [fixes `issue 7`__]. * Ad-hoc stub attributes (see `test`__). * Partial support for non native Python functions. * ProxySpy propagated stubbed invocations too (see `test`__). __ https://bitbucket.org/DavidVilla/python-doublex/issue/7 __ https://bitbucket.org/DavidVilla/python-doublex/src/cb8ba0df2e024d602fed236bb5ed5a7ceee91b20/doublex/test/unit_tests.py?at=v1.6#cl-146 __ https://bitbucket.org/DavidVilla/python-doublex/src/cb8ba0df2e024d602fed236bb5ed5a7ceee91b20/doublex/test/unit_tests.py?at=v1.6#cl-340 doublex 1.5.1 ------------- This release includes support for asynchronous spy assertions. See `this blog post `_ for the time being, soon in the official documentation. doublex/pyDoubles 1.5 --------------------- Since this release, doublex supports the pyDoubles API by means a wrapper. See `pyDoubles `_ for details. In most cases the only required change in your code is the ``import`` sentence, that change from:: import pyDoubles.framework.* to:: from doublex.pyDoubles import * If you have problems migrating to the 1.5 release or migrating from pyDoubles to doublex, please ask for help in the `discussion forum `_ or in the `issue tracker `_. .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. fill-columnd: 90 .. End: doublex-1.8.2/doctests/0000755000175000017500000000000012435722065014076 5ustar piotrpiotrdoublex-1.8.2/doctests/Makefile0000644000175000017500000001143112435722065015536 0ustar piotrpiotr # Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest all: doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* $(RM) -r _build *~ *.inc html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/doubles.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/doubles.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/doubles" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/doubles" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." %.rst.inc: ../docs/%.rst.test sed 's/^.. sourcecode:: python//g' $< > $@ GENERATED=doubles.rst.inc reference.rst.inc methods.rst.inc properties.rst.inc delegates.rst.inc observers.rst.inc mimics.rst.inc async-spies.rst.inc calls.rst.inc doctest: $(GENERATED) $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." doublex-1.8.2/doctests/conf.py0000644000175000017500000001530212435722065015376 0ustar piotrpiotr# -*- coding: utf-8 -*- # # doubles documentation build configuration file, created by # sphinx-quickstart on Sun Feb 27 13:08:19 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # ensures that somemodule can be imported sys.path.append(os.path.dirname(__file__)) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.doctest'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'doublex' copyright = u'2013, David Villa Alises' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.7' # The full version, including alpha/beta/rc tags. release = '1.7.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme_path = '.' # html_theme = 'python_mock_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { } # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = False # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'doublexdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'doublex.tex', u'doublex Documentation', u'David Villa Alises', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'doubles', u'doubles Documentation', [u'Gary Bernhardt'], 1) ] doublex-1.8.2/doctests/index.rst0000644000175000017500000000002612435722065015735 0ustar piotrpiotr.. toctree:: test doublex-1.8.2/doctests/test.rst0000644000175000017500000000044212435722065015607 0ustar piotrpiotr:orphan: .. include :: doubles.rst.inc .. include :: reference.rst.inc .. include :: methods.rst.inc .. include :: properties.rst.inc .. include :: delegates.rst.inc .. include :: observers.rst.inc .. include :: mimics.rst.inc .. include :: async-spies.rst.inc .. include :: calls.rst.inc doublex-1.8.2/doublex.svg0000644000175000017500000001043212435722065014431 0ustar piotrpiotr image/svg+xml X X doublex-1.8.2/doublex/0000755000175000017500000000000012435722065013710 5ustar piotrpiotrdoublex-1.8.2/doublex/__init__.py0000644000175000017500000000127112435722065016022 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- from .doubles import * from .matchers import * from .tracer import Tracer from .internal import WrongApiUsage def set_default_behavior(double, func): double._default_behavior = func def when(double): if not isinstance(double, Stub): raise WrongApiUsage("when() takes a double, '%s' given" % double) if isinstance(double, Mock): raise WrongApiUsage("when() takes a stub or spy. Use expect_call() for mocks") return double._activate_next() def expect_call(mock): if not isinstance(mock, Mock): raise WrongApiUsage("expect_call() takes a mock, '%s' given" % mock) return mock._activate_next() doublex-1.8.2/doublex/doubles.py0000644000175000017500000001451012435722065015720 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012, 2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import inspect import hamcrest from .internal import (ANY_ARG, OperationList, Method, MockBase, SpyBase, AttributeFactory, WrongApiUsage) from .proxy import create_proxy, get_class from .matchers import MockIsExpectedInvocation __all__ = ['Stub', 'Spy', 'ProxySpy', 'Mock', 'Mimic', 'method_returning', 'method_raising', 'ANY_ARG'] class Stub(object): _default_behavior = lambda x: None _new_attr_hooks = [] def __new__(cls, collaborator=None): '''Creates a fresh class clone per instance. This is required due to ad-hoc stub properties are class attributes''' klass = cls._clone_class() return object.__new__(klass) @classmethod def _clone_class(cls): return type(cls.__name__, (cls,), dict(cls.__dict__)) def __init__(self, collaborator=None): self._proxy = create_proxy(collaborator) self._stubs = OperationList() self._setting_up = False self._new_attr_hooks = self._new_attr_hooks[:] self._deactivate = False self.__class__.__setattr__ = self.__setattr__hook def _activate_next(self): self.__enter__() self._deactivate = True return self def __enter__(self): self._setting_up = True return self def __exit__(self, *args): self._setting_up = False def _manage_invocation(self, invocation): self._proxy.assure_signature_matches(invocation) if self._setting_up: self._stubs.append(invocation) return invocation self._prepare_invocation(invocation) stubbed_retval = self._default_behavior() if invocation in self._stubs: stubbed = self._stubs.lookup(invocation) stubbed_retval = stubbed._apply_stub(invocation) actual_retval = self._perform_invocation(invocation) retval = stubbed_retval if stubbed_retval is not None else actual_retval invocation.context.retval = retval return retval def _prepare_invocation(self, invocation): pass def _perform_invocation(self, invocation): return None def __getattr__(self, key): AttributeFactory.create(self, key) return object.__getattribute__(self, key) def __setattr__hook(self, key, value): if key in self.__dict__: object.__setattr__(self, key, value) return try: AttributeFactory.create(self, key) except AttributeError: # collaborator has not attribute 'key', creaing it ad-hoc pass # descriptor protocol compliant object.__setattr__(self, key, value) def _classname(self): name = self._proxy.collaborator_classname() return name or self.__class__.__name__ class Spy(Stub, SpyBase): def __init__(self, collaborator=None): self._recorded = OperationList() super(Spy, self).__init__(collaborator) def _prepare_invocation(self, invocation): self._recorded.append(invocation) def _received_invocation(self, invocation, times, cmp_pred=None): return hamcrest.is_(times).matches( self._recorded.count(invocation, cmp_pred)) def _get_invocations_to(self, name): return [i for i in self._recorded if self._proxy.same_method(name, i.name)] class ProxySpy(Spy): def __init__(self, collaborator): self._assure_is_instance(collaborator) super(ProxySpy, self).__init__(collaborator) def _assure_is_instance(self, thing): if thing is None or inspect.isclass(thing): raise TypeError("ProxySpy takes an instance (got %s instead)" % thing) def _perform_invocation(self, invocation): return invocation._apply_on_collaborator() class Mock(Spy, MockBase): def _prepare_invocation(self, invocation): hamcrest.assert_that(self, MockIsExpectedInvocation(invocation)) super(Mock, self)._prepare_invocation(invocation) def Mimic(double, collab): def __getattribute__hook(self, key): if key in ['__class__', '__dict__', '_get_method', '_methods'] or \ key in [x[0] for x in inspect.getmembers(double)] or \ key in self.__dict__: return object.__getattribute__(self, key) return self._get_method(key) def _get_method(self, key): if key not in list(self._methods.keys()): typename = self._proxy.get_attr_typename(key) if typename not in ['instancemethod', 'function', 'method']: raise WrongApiUsage( "Mimic does not support attribute '%s' (type '%s')" % (key, typename)) method = Method(self, key) self._methods[key] = method return self._methods[key] assert issubclass(double, Stub), \ "Mimic() takes a double class as first argument (got %s instead)" & double collab_class = get_class(collab) generated_class = type( "Mimic_%s_for_%s" % (double.__name__, collab_class.__name__), (double, collab_class) + collab_class.__bases__, dict(_methods = {}, __getattribute__ = __getattribute__hook, _get_method = _get_method)) return generated_class(collab) def method_returning(value): with Spy() as stub: method = Method(stub, 'orphan') method(ANY_ARG).returns(value) return method def method_raising(exception): with Spy() as stub: method = Method(stub, 'orphan') method(ANY_ARG).raises(exception) return method doublex-1.8.2/doublex/internal.py0000644000175000017500000003532412435722065016105 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013,2014 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import threading import collections import hamcrest from hamcrest.core.base_matcher import BaseMatcher try: from functools import total_ordering except ImportError: from .py27_backports import total_ordering from .safeunicode import get_string class WrongApiUsage(Exception): pass class Constant(str): def __repr__(self): return str(self) def __eq__(self, other): return self is other ANY_ARG = Constant('ANY_ARG') UNSPECIFIED = Constant('UNSPECIFIED') def add_indent(text, indent=0): return "%s%s" % (' ' * indent, text) class OperationList(list): def lookup(self, invocation): if not invocation in self: raise LookupError return [i for i in self if invocation == i][-1] def show(self, indent=0): if not self: return add_indent("No one", indent) lines = [add_indent(i, indent) for i in self] return str.join('\n', lines) def count(self, invocation, predicate=None): if predicate is None: return list.count(self, invocation) return [predicate(invocation, i) for i in self].count(True) class Observable(object): def __init__(self): self.observers = [] def attach(self, observer): self.observers.append(observer) def notify(self, *args, **kargs): for ob in self.observers: ob(*args, **kargs) class Method(Observable): def __init__(self, double, name): super(Method, self).__init__() self.double = double self.name = name self.__name__ = name self._event = threading.Event() def __call__(self, *args, **kargs): invocation = self._create_invocation(args, kargs) retval = self.double._manage_invocation(invocation) if not self.double._setting_up: self._event.set() self.notify(*args, **kargs) if self.double._deactivate: self.double._setting_up = self.double._deactivate = False return retval def _create_invocation(self, args, kargs): return Invocation._from_args(self.double, self.name, args, kargs) @property def calls(self): if not isinstance(self.double, SpyBase): raise WrongApiUsage("Only Spy derivates store invocations") return [x.context for x in self.double._get_invocations_to(self.name)] def _was_called(self, context, times): invocation = Invocation(self.double, self.name, context) return self.double._received_invocation(invocation, times) def describe_to(self, description): pass def _show(self, indent=0): return add_indent(self, indent) def __repr__(self): return "%s.%s" % (self.double._classname(), self.name) def _show_history(self): method = "method '%s.%s'" % (self.double._classname(), self.name) invocations = self.double._get_invocations_to(self.name) if not invocations: return method + " never invoked" retval = method + " was invoked this way:\n" for i in invocations: retval += add_indent("%s\n" % i, 10) return retval def func_returning(value=None): return lambda *args, **kargs: value def func_returning_input(invocation): def func(*args, **kargs): if not args: raise TypeError("%s has no input args" % invocation) if len(args) == 1: return args[0] return args return func def func_raising(e): def raise_(e): raise e return lambda *args, **kargs: raise_(e) @total_ordering class Invocation(object): def __init__(self, double, name, context=None): self.double = double self.name = name self.context = context or InvocationContext() self.context.signature = double._proxy.get_signature(name) self.__delegate = func_returning(None) @classmethod def _from_args(cls, double, name, args=(), kargs={}): return Invocation(double, name, InvocationContext(*args, **kargs)) def delegates(self, delegate): if isinstance(delegate, collections.Callable): self.__delegate = delegate return if isinstance(delegate, collections.Mapping): self.__delegate = delegate.get return try: self.__delegate = iter(delegate).next except TypeError: reason = "delegates() must be called with callable or iterable instance (got '%s' instead)" % delegate raise WrongApiUsage(reason) def returns(self, value): self.context.retval = value self.delegates(func_returning(value)) return self def returns_input(self): if not self.context.args: raise TypeError("%s has no input args" % self) self.delegates(func_returning_input(self)) return self def raises(self, e): self.delegates(func_raising(e)) def times(self, n): if n < 1: raise WrongApiUsage("times must be >= 1. Use is_not(called()) for 0 times") for i in range(1, n): self.double._manage_invocation(self) def _apply_stub(self, actual_invocation): return actual_invocation.context.apply_on(self.__delegate) def _apply_on_collaborator(self): return self.double._proxy.perform_invocation(self) def __eq__(self, other): return self.double._proxy.same_method(self.name, other.name) and \ self.context.matches(other.context) def __lt__(self, other): return any([self.name < other.name, self.context < other.context]) def __repr__(self): return "%s.%s%s" % (self.double._classname(), self.name, self.context) def _show(self, indent=0): return add_indent(self, indent) ANY_ARG_MUST_BE_LAST = "ANY_ARG must be the last positional argument. " ANY_ARG_WITHOUT_KARGS = "Keyword arguments are not allowed if ANY_ARG is given. " ANY_ARG_CAN_BE_KARG = "ANY_ARG is not allowed as keyword value. " ANY_ARG_DOC = "See http://goo.gl/R6mOt" @total_ordering class InvocationContext(object): def __init__(self, *args, **kargs): self.update_args(args, kargs) self.retval = None self.signature = None self.check_some_args = False def update_args(self, args, kargs): self._check_ANY_ARG_sanity(args, kargs) self.args = args self.kargs = kargs def _check_ANY_ARG_sanity(self, args, kargs): def find_ANY_ARG(args): for i, v in enumerate(args): if id(ANY_ARG) == id(v): return i raise ValueError try: # if args.index(ANY_ARG) != len(args) - 1: if find_ANY_ARG(args) != len(args) - 1: raise WrongApiUsage(ANY_ARG_MUST_BE_LAST + ANY_ARG_DOC) if kargs: raise WrongApiUsage(ANY_ARG_WITHOUT_KARGS + ANY_ARG_DOC) except ValueError: pass if ANY_ARG in kargs.values(): raise WrongApiUsage(ANY_ARG_CAN_BE_KARG + ANY_ARG_DOC) def apply_on(self, method): return method(*self.args, **self.kargs) @classmethod def _assert_kargs_match(cls, kargs1, kargs2): assert sorted(kargs1.keys()) == sorted(kargs2.keys()) for key in kargs1: cls._assert_values_match(kargs1[key], kargs2[key]) @classmethod def _assert_values_match(cls, a, b): if all(isinstance(x, tuple) for x in (a, b)): return cls._assert_tuple_args_match(a, b) if all(isinstance(x, dict) for x in (a, b)): return cls._assert_kargs_match(a, b) if isinstance(a, BaseMatcher): a, b = b, a hamcrest.assert_that(a, hamcrest.is_(b)) @classmethod def _assert_tuple_args_match(cls, a, b): if len(a) != len(b): a, b = cls._adapt_tuples(a, b) for i, j in zip(a, b): cls._assert_values_match(i, j) @classmethod def _adapt_tuples(cls, a, b): if len(a) > len(b): return cls._adapt_tuples(b, a) if a[:-1] != ANY_ARG: raise AssertionError("Incompatible argument list: %s, %s" % (a, b)) a = a[:-1] + (hamcrest.anything(),) * (len(b) - len(a)) return a, b def copy(self): retval = InvocationContext(*self.args, **self.kargs) retval.signature = self.signature return retval def replace_ANY_ARG(self, actual): index = None for i, val in enumerate(self.args): if val is ANY_ARG: index = i if index is None: return self retval = self.copy() args = list(self.args[0:index]) args.extend([hamcrest.anything()] * (len(actual.args) - index)) retval.args = tuple(args) retval.kargs = actual.kargs.copy() return retval def matches(self, other): if ANY_ARG in self.args: matcher, actual = self, other else: matcher, actual = other, self matcher = matcher.replace_ANY_ARG(actual) if matcher.check_some_args: matcher.kargs = self.add_unspecifed_args(matcher) matcher_call_args = matcher.signature.get_call_args(matcher) actual_call_args = actual.signature.get_call_args(actual) try: self._assert_kargs_match(matcher_call_args, actual_call_args) return True except AssertionError: return False def add_unspecifed_args(self, context): arg_spec = context.signature.get_arg_spec() if arg_spec is None: raise WrongApiUsage( 'free spies does not support the with_some_args() matcher') if arg_spec.keywords is not None: raise WrongApiUsage( 'with_some_args() can not be applied to method %s' % self.signature) keys = arg_spec.args retval = dict((k, hamcrest.anything()) for k in keys) retval.update(context.kargs) return retval def __lt__(self, other): if ANY_ARG in other.args or self.args < other.args: return True return sorted(self.kargs.items()) < sorted(other.kargs.items()) def __str__(self): return str(InvocationFormatter(self)) def __repr__(self): return str(self) class InvocationFormatter(object): def __init__(self, context): self.context = context def __str__(self): arg_values = self._format_args(self.context.args) arg_values.extend(self._format_kargs(self.context.kargs)) retval = "(%s)" % str.join(', ', arg_values) if self.context.retval is not None: retval += "-> %s" % repr(self.context.retval) return retval @classmethod def _format_args(cls, args): return [cls._format_value(arg) for arg in args] @classmethod def _format_kargs(cls, kargs): return ['%s=%s' % (key, cls._format_value(val)) for key, val in sorted(kargs.items())] @classmethod def _format_value(cls, arg): if isinstance(arg, unicode): arg = get_string(arg) if isinstance(arg, (int, str, dict)): return repr(arg) return str(arg) class PropertyInvocation(Invocation): def __eq__(self, other): return self.name == other.name class PropertyGet(PropertyInvocation): def __init__(self, double, name): super(PropertyGet, self).__init__(double, name) def _apply_on_collaborator(self): return getattr(self.double._proxy.collaborator, self.name) def __repr__(self): return "get %s.%s" % (self.double._classname(), self.name) class PropertySet(PropertyInvocation): def __init__(self, double, name, value): self.value = value param = InvocationContext(value) super(PropertySet, self).__init__(double, name, param) def _apply_on_collaborator(self): return setattr(self.double._proxy.collaborator, self.name, self.value) def __eq__(self, other): return PropertyInvocation.__eq__(self, other) \ and self.context.matches(other.context) def __repr__(self): return "set %s.%s to %s" % (self.double._classname(), self.name, self.value) class Property(property, Observable): def __init__(self, double, key): self.double = double self.key = key property.__init__(self, self.get_value, self.set_value) Observable.__init__(self) def manage(self, invocation): return self.double._manage_invocation(invocation) def get_value(self, obj): if not self.double._setting_up: self.notify() return self.manage(PropertyGet(self.double, self.key)) def set_value(self, obj, value): prop = self.double._proxy.get_class_attr(self.key) if prop.fset is None: raise AttributeError("can't set attribute %s" % self.key) invocation = self.manage(PropertySet(self.double, self.key, value)) if self.double._setting_up: invocation.returns(value) else: self.notify(value) class AttributeFactory(object): """Create double methods, properties or attributes from collaborator""" typemap = dict( instancemethod = Method, method_descriptor = Method, wrapper_descriptor = Method, property = Property, # -- python3 -- method = Method, function = Method, ) @classmethod def create(cls, double, key): get_actual_attr = lambda double, key: double._proxy.get_attr(key) typename = double._proxy.get_attr_typename(key) factory = cls.typemap.get(typename, get_actual_attr) attr = factory(double, key) if isinstance(attr, property): setattr(double.__class__, key, attr) else: object.__setattr__(double, key, attr) for hook in double._new_attr_hooks: hook(attr) class SpyBase(object): pass class MockBase(object): pass doublex-1.8.2/doublex/matchers.py0000644000175000017500000002040012435722065016064 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import time import hamcrest from hamcrest.core.matcher import Matcher from hamcrest.core.base_matcher import BaseMatcher from hamcrest import is_, instance_of from .internal import ( Method, InvocationContext, ANY_ARG, MockBase, SpyBase, PropertyGet, PropertySet, WrongApiUsage, Invocation) __all__ = ['called', 'never', 'verify', 'any_order_verify', 'property_got', 'property_set', 'assert_that', 'wait_that', 'is_', 'instance_of'] # just hamcrest aliases at_least = hamcrest.greater_than_or_equal_to at_most = hamcrest.less_than_or_equal_to any_time = hamcrest.greater_than(0) class MatcherRequiredError(Exception): pass def assert_that(actual, matcher=None, reason=''): if matcher and not isinstance(matcher, Matcher): raise MatcherRequiredError("%s should be a hamcrest Matcher" % str(matcher)) return hamcrest.assert_that(actual, matcher, reason) def wait_that(actual, matcher, reason='', delta=1, timeout=5): ''' Poll the given matcher each 'delta' seconds until 'matcher' matches 'actual' or 'timeout' is reached. ''' exc = None init = time.time() timeout_reached = False while 1: try: if time.time() - init > timeout: timeout_reached = True break assert_that(actual, matcher, reason) break except AssertionError as e: time.sleep(delta) exc = e if timeout_reached: msg = exc.args[0] + ' after {0} seconds'.format(timeout) exc.args = msg, raise exc class OperationMatcher(BaseMatcher): pass class MethodCalled(OperationMatcher): def __init__(self, context=None, times=any_time): self.context = context or InvocationContext(ANY_ARG) self._times = times self._async_timeout = None def _matches(self, method): self._assure_is_spied_method(method) self.method = method if not self._async_timeout: return method._was_called(self.context, self._times) if self._async_timeout: if self._times != any_time: raise WrongApiUsage("'times' and 'async' are exclusive") self.method._event.wait(self._async_timeout) return method._was_called(self.context, self._times) def _assure_is_spied_method(self, method): if not isinstance(method, Method) or not isinstance(method.double, SpyBase): raise WrongApiUsage("takes a spy method (got %s instead)" % method) def describe_to(self, description): description.append_text('these calls:\n') description.append_text(self.method._show(indent=10)) description.append_text(str(self.context)) if self._times != any_time: description.append_text(' -- times: %s' % self._times) def describe_mismatch(self, actual, description): description.append_text("calls that actually ocurred were:\n") description.append_text(self.method.double._recorded.show(indent=10)) def with_args(self, *args, **kargs): self.context.update_args(args, kargs) return self def with_some_args(self, **kargs): self.context.update_args(tuple(), kargs) self.context.check_some_args = True return self def async(self, timeout): self._async_timeout = timeout return self def times(self, n): self._times = n return self def called(): return MethodCalled() class never(BaseMatcher): def __init__(self, matcher): if not isinstance(matcher, OperationMatcher): raise WrongApiUsage( "takes called/called_with instance (got %s instead)" % matcher) self.matcher = matcher def _matches(self, item): return not self.matcher.matches(item) def describe_to(self, description): description.append_text('none of ').append_description_of(self.matcher) def describe_mismatch(self, actual, description): self.matcher.describe_mismatch(actual, description) class MockIsExpectedInvocation(BaseMatcher): 'assert the invocation is a mock expectation' def __init__(self, invocation): self.invocation = invocation def _matches(self, mock): self.mock = mock return self.invocation in mock._stubs def describe_to(self, description): description.append_text("these calls:\n") description.append_text(self.mock._stubs.show(indent=10)) def describe_mismatch(self, actual, description): description.append_text("this call was not expected:\n") description.append_text(self.invocation._show(indent=10)) class verify(BaseMatcher): def _matches(self, mock): if not isinstance(mock, MockBase): raise WrongApiUsage("takes Mock instance (got %s instead)" % mock) self.mock = mock return self._expectations_match() def _expectations_match(self): return self.mock._stubs == self.mock._recorded def describe_to(self, description): description.append_text("these calls:\n") description.append_text(self.mock._stubs.show(indent=10)) def describe_mismatch(self, actual, description): description.append_text('calls that actually ocurred were:\n') description.append_text(self.mock._recorded.show(indent=10)) class any_order_verify(verify): def _expectations_match(self): return sorted(self.mock._stubs) == sorted(self.mock._recorded) class property_got(OperationMatcher): def __init__(self, propname, times=any_time): super(property_got, self).__init__() self.propname = propname self._times = times def _matches(self, double): self.double = double self.operation = PropertyGet(self.double, self.propname) return double._received_invocation( self.operation, 1, cmp_pred=Invocation.__eq__) def times(self, n): self._times = n return self def describe_to(self, description): description.append_text('these calls:\n') description.append_text(self.operation._show(indent=10)) if self._times != any_time: description.append_text(' -- times: %s' % self._times) def describe_mismatch(self, actual, description): description.append_text('calls that actually ocurred were:\n') description.append_text(self.double._recorded.show(indent=10)) class property_set(OperationMatcher): def __init__(self, property_name, value=hamcrest.anything(), times=any_time): super(property_set, self).__init__() self.property_name = property_name self.value = value self._times = times def _matches(self, double): self.double = double self.operation = PropertySet(self.double, self.property_name, self.value) return self.double._received_invocation( self.operation, self._times, cmp_pred=Invocation.__eq__) def to(self, value): self.value = value return self def times(self, n): self._times = n return self def describe_to(self, description): description.append_text('these calls:\n') description.append_text(self.operation._show(indent=10)) if self._times != any_time: description.append_text(' -- times: %s' % self._times) def describe_mismatch(self, actual, description): description.append_text('calls that actually ocurred were:\n') description.append_text(self.double._recorded.show(indent=10)) doublex-1.8.2/doublex/proxy.py0000644000175000017500000001422612435722065015450 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import inspect try: from inspect import getcallargs except ImportError: from .py27_backports import getcallargs from .internal import ANY_ARG def create_proxy(collaborator): if collaborator is None: return DummyProxy() return CollaboratorProxy(collaborator) class Proxy(object): def assure_signature_matches(self, invocation): pass def collaborator_classname(self): return None def get_signature(self, method_name): if self.is_property(method_name): return PropertySignature(self, method_name) if not self.is_method_or_func(method_name): return BuiltinSignature(self, method_name) return MethodSignature(self, method_name) def is_property(self, attr_name): attr = getattr(self.collaborator_class, attr_name) return isinstance(attr, property) def is_method_or_func(self, method_name): func = getattr(self.collaborator, method_name) if inspect.ismethod(func): func = func.im_func return inspect.isfunction(func) class DummyProxy(Proxy): def get_attr_typename(self, key): return 'instancemethod' def same_method(self, name1, name2): return name1 == name2 def get_signature(self, method_name): return DummySignature() def get_class(something): if inspect.isclass(something): return something else: return something.__class__ class CollaboratorProxy(Proxy): '''Represent the collaborator object''' def __init__(self, collaborator): self.collaborator = collaborator self.collaborator_class = get_class(collaborator) def isclass(self): return inspect.isclass(self.collaborator) def get_class_attr(self, key): return getattr(self.collaborator_class, key) def get_attr(self, key): return getattr(self.collaborator, key) def collaborator_classname(self): return self.collaborator_class.__name__ def assure_signature_matches(self, invocation): signature = self.get_signature(invocation.name) signature.assure_matches(invocation.context) def get_attr_typename(self, key): def raise_no_attribute(): reason = "'%s' object has no attribute '%s'" % \ (self.collaborator_classname(), key) raise AttributeError(reason) try: attr = getattr(self.collaborator_class, key) return type(attr).__name__ except AttributeError: if self.collaborator is self.collaborator_class: raise_no_attribute() try: attr = getattr(self.collaborator, key) return type(attr).__name__ except AttributeError: raise_no_attribute() def same_method(self, name1, name2): return getattr(self.collaborator, name1) == \ getattr(self.collaborator, name2) def perform_invocation(self, invocation): method = getattr(self.collaborator, invocation.name) return invocation.context.apply_on(method) class Signature(object): def __init__(self, proxy, name): self.proxy = proxy self.name = name self.method = getattr(proxy.collaborator, name) def get_arg_spec(self): pass def get_call_args(self, context): retval = context.kargs.copy() for n, i in enumerate(context.args): retval['_positional_%s' % n] = i return retval def __eq__(self, other): return (self.proxy, self.name, self.method) == \ (other.proxy, other.name, other.method) class DummySignature(Signature): def __init__(self): pass class BuiltinSignature(Signature): "builtin collaborator method signature" def assure_matches(self, context): doc = self.method.__doc__ if not ')' in doc: return rpar = doc.find(')') params = doc[:rpar] nkargs = params.count('=') nargs = params.count(',') + 1 - nkargs if len(context.args) != nargs: raise TypeError('%s.%s() takes exactly %s argument (%s given)' % ( self.proxy.collaborator_classname(), self.name, nargs, len(context.args))) class MethodSignature(Signature): "colaborator method signature" def __init__(self, proxy, name): super(MethodSignature, self).__init__(proxy, name) self.argspec = inspect.getargspec(self.method) def get_arg_spec(self): retval = inspect.getargspec(self.method) del retval.args[0] return retval def get_call_args(self, context): args = context.args if self.proxy.isclass(): args = (None,) + args # self retval = getcallargs(self.method, *args, **context.kargs) del retval['self'] return retval def assure_matches(self, context): if ANY_ARG in context.args: return try: self.get_call_args(context) except TypeError as e: raise TypeError("%s.%s" % (self.proxy.collaborator_classname(), e)) def __repr__(self): return "%s.%s%s" % (self.proxy.collaborator_classname(), self.name, inspect.formatargspec(*self.argspec)) class PropertySignature(Signature): def __init__(self, proxy, name): pass def assure_matches(self, context): pass doublex-1.8.2/doublex/py27_backports.py0000644000175000017500000001237112435722065017137 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- from inspect import getargspec, ismethod def total_ordering(cls): """Class decorator that fills in missing ordering methods""" convert = { '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), ('__le__', lambda self, other: self < other or self == other), ('__ge__', lambda self, other: not self < other)], '__le__': [('__ge__', lambda self, other: not self <= other or self == other), ('__lt__', lambda self, other: self <= other and not self == other), ('__gt__', lambda self, other: not self <= other)], '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)), ('__ge__', lambda self, other: self > other or self == other), ('__le__', lambda self, other: not self > other)], '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other), ('__gt__', lambda self, other: self >= other and not self == other), ('__lt__', lambda self, other: not self >= other)] } roots = set(dir(cls)) & set(convert) if not roots: raise ValueError('must define at least one ordering operation: < > <= >=') root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ for opname, opfunc in convert[root]: if opname not in roots: opfunc.__name__ = opname opfunc.__doc__ = getattr(int, opname).__doc__ setattr(cls, opname, opfunc) return cls def getcallargs(func, *positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" args, varargs, varkw, defaults = getargspec(func) f_name = func.__name__ arg2value = {} # The following closures are basically because of tuple parameter unpacking. assigned_tuple_params = [] def assign(arg, value): if isinstance(arg, str): arg2value[arg] = value else: assigned_tuple_params.append(arg) value = iter(value) for i, subarg in enumerate(arg): try: subvalue = next(value) except StopIteration: raise ValueError('need more than %d %s to unpack' % (i, 'values' if i > 1 else 'value')) assign(subarg,subvalue) try: next(value) except StopIteration: pass else: raise ValueError('too many values to unpack') def is_assigned(arg): if isinstance(arg,str): return arg in arg2value return arg in assigned_tuple_params if ismethod(func) and func.im_self is not None: # implicit 'self' (or 'cls' for classmethods) argument positional = (func.im_self,) + positional num_pos = len(positional) num_total = num_pos + len(named) num_args = len(args) num_defaults = len(defaults) if defaults else 0 for arg, value in zip(args, positional): assign(arg, value) if varargs: if num_pos > num_args: assign(varargs, positional[-(num_pos-num_args):]) else: assign(varargs, ()) elif 0 < num_args < num_pos: raise TypeError('%s() takes %s %d %s (%d given)' % ( f_name, 'at most' if defaults else 'exactly', num_args, 'arguments' if num_args > 1 else 'argument', num_total)) elif num_args == 0 and num_total: if varkw: if num_pos: # XXX: We should use num_pos, but Python also uses num_total: raise TypeError('%s() takes exactly 0 arguments ' '(%d given)' % (f_name, num_total)) else: raise TypeError('%s() takes no arguments (%d given)' % (f_name, num_total)) for arg in args: if isinstance(arg, str) and arg in named: if is_assigned(arg): raise TypeError("%s() got multiple values for keyword " "argument '%s'" % (f_name, arg)) else: assign(arg, named.pop(arg)) if defaults: # fill in any missing values with the defaults for arg, value in zip(args[-num_defaults:], defaults): if not is_assigned(arg): assign(arg, value) if varkw: assign(varkw, named) elif named: unexpected = next(iter(named)) if isinstance(unexpected, unicode): unexpected = unexpected.encode(sys.getdefaultencoding(), 'replace') raise TypeError("%s() got an unexpected keyword argument '%s'" % (f_name, unexpected)) unassigned = num_args - len([arg for arg in args if is_assigned(arg)]) if unassigned: num_required = num_args - num_defaults raise TypeError('%s() takes %s %d %s (%d given)' % ( f_name, 'at least' if defaults else 'exactly', num_required, 'arguments' if num_required > 1 else 'argument', num_total)) return arg2value doublex-1.8.2/doublex/pyDoubles/0000755000175000017500000000000012435722065015656 5ustar piotrpiotrdoublex-1.8.2/doublex/pyDoubles/__init__.py0000644000175000017500000001126012435722065017767 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ This is a wrapper to provide the pyDoubles API implemented over the doublex package. """ import hamcrest from hamcrest.library.object.hasproperty import has_property import doublex from doublex import ANY_ARG, method_returning, method_raising, WrongApiUsage UnexpectedBehavior = AssertionError ArgsDontMatch = AssertionError ApiMismatch = TypeError def empty_stub(): return doublex.Stub() def stub(collaborator=None): return doublex.Stub(collaborator) def empty_spy(): return doublex.Spy() def spy(collaborator=None): return doublex.Spy(collaborator) def proxy_spy(collaborator): return doublex.ProxySpy(collaborator) def empty_mock(): return mock() def assert_that_was_called(method): return assert_that_method(method).was_called() class mock(doublex.Mock): def assert_that_is_satisfied(self): hamcrest.assert_that(self, doublex.verify()) def assert_expectations(self): self.assert_that_is_satisfied() class expect_call(object): def __init__(self, method): if not isinstance(method, doublex.internal.Method): raise doublex.WrongApiUsage self.method = method self.invocation = None self.with_args(ANY_ARG) def with_args(self, *args, **kargs): self.args = args self.kargs = kargs self._remove_previous() with self.method.double: self.invocation = self.method(*args, **kargs) return self def returning(self, value): self._remove_previous() with self.method.double: self.invocation = self.method(*self.args, **self.kargs).returns(value) return self def times(self, n): if n < 2: raise doublex.WrongApiUsage with self.method.double: self.invocation.times(n) def _remove_previous(self): if self.invocation is None: return self.method.double._stubs.remove(self.invocation) class when(object): def __init__(self, method): self.method = method self.args = (ANY_ARG, ) self.kargs = {} def with_args(self, *args, **kargs): self.args = args self.kargs = kargs return self def then_return(self, retval): with self.method.double: self.method(*self.args, **self.kargs).returns(retval) def then_return_input(self): with self.method.double: self.method(*self.args, **self.kargs).returns_input() def then_raise(self, e): with self.method.double: self.method(*self.args, **self.kargs).raises(e) class assert_that_method(object): def __init__(self, method): if not isinstance(method, doublex.internal.Method): raise doublex.WrongApiUsage() self.method = method self.args = (ANY_ARG,) self.kargs = {} def was_called(self): return self.with_args(*self.args, **self.kargs) def was_never_called(self): hamcrest.assert_that(self.method, doublex.matchers.never(doublex.called())) def with_args(self, *args, **kargs): self.args = args self.kargs = kargs hamcrest.assert_that(self.method, doublex.called().with_args(*args, **kargs)) return self def times(self, n): hamcrest.assert_that( self.method, doublex.called().with_args(*self.args, **self.kargs).times( hamcrest.greater_than_or_equal_to(n))) #-- pyDoubles matchers -- str_containing = hamcrest.contains_string str_not_containing = lambda x: hamcrest.is_not(hamcrest.contains_string(x)) str_length = hamcrest.has_length def obj_with_fields(fields): if not isinstance(fields, dict): raise doublex.WrongApiUsage matchers = [] for key, value in list(fields.items()): matchers.append(has_property(key, value)) return hamcrest.all_of(*matchers) doublex-1.8.2/doublex/safeunicode.py0000644000175000017500000000131712435722065016551 0ustar piotrpiotr# -*- coding: utf-8 -*- import sys def __if_number_get_string(number): converted_str = number if isinstance(number, (int, float)): converted_str = str(number) return converted_str def get_unicode(strOrUnicode, encoding='utf-8'): strOrUnicode = __if_number_get_string(strOrUnicode) if isinstance(strOrUnicode, unicode): return strOrUnicode return unicode(strOrUnicode, encoding, errors='ignore') def get_string(strOrUnicode, encoding='utf-8'): strOrUnicode = __if_number_get_string(strOrUnicode) if sys.version_info >= (3,): return strOrUnicode if isinstance(strOrUnicode, unicode): return strOrUnicode.encode(encoding) return strOrUnicode doublex-1.8.2/doublex/test/0000755000175000017500000000000012435722065014667 5ustar piotrpiotrdoublex-1.8.2/doublex/test/README0000644000175000017500000000007712435722065015553 0ustar piotrpiotrTo run all tests just run "nosetests" in the parent directory. doublex-1.8.2/doublex/test/__init__.py0000644000175000017500000000000012435722065016766 0ustar piotrpiotrdoublex-1.8.2/doublex/test/async_race_condition_test.py0000644000175000017500000000147712435722065022466 0ustar piotrpiotr# -*- mode: python; coding: utf-8 -*- # All bugs by Oscar Aceña import time import thread import unittest from doublex import ProxySpy, assert_that, called class Collaborator(object): def write(self, data): time.sleep(0.3) class SUT(object): def __init__(self, collaborator): self.collaborator = collaborator def delayed_write(self): time.sleep(0.1) self.collaborator.write("something") def some_method(self): thread.start_new_thread(self.delayed_write, ()) class AsyncTests(unittest.TestCase): def test_wrong_try_to_test_an_async_invocation(self): # given spy = ProxySpy(Collaborator()) sut = SUT(spy) # when sut.some_method() # then assert_that(spy.write, called().async(1)) doublex-1.8.2/doublex/test/chain_tests.py0000644000175000017500000000057212435722065017551 0ustar piotrpiotr# -*- mode:python; coding:utf-8; tab-width:4 -*- from unittest import TestCase import doublex class ChainTests(TestCase): def test_chain_default_behavior(self): stub = doublex.Stub() doublex.set_default_behavior(stub, doublex.Spy) chained_spy = stub.foo() chained_spy.bar() doublex.assert_that(chained_spy.bar, doublex.called()) doublex-1.8.2/doublex/test/issue-14.py0000644000175000017500000000155612435722065016622 0ustar piotrpiotr# Thanks to Guillermo Pascual (@pasku1) # When you spy a method that has a decorator and you want to check the # arguments with a hamcrest matcher, it seems like matchers are # ignored. from functools import wraps import unittest from doublex import * from hamcrest import * class Collaborator(object): def simple_decorator(func): @wraps(func) def wrapper(self, *args, **kwargs): return func(self, *args, **kwargs) return wrapper @simple_decorator def method_with_two_arguments(self, one, two): pass class ExampleTest(unittest.TestCase): def test_spying_a_method_with_a_decorator(self): collaborator = Spy(Collaborator) collaborator.method_with_two_arguments(1, 'foo bar') assert_that(collaborator.method_with_two_arguments, called().with_args(1, ends_with('bar'))) doublex-1.8.2/doublex/test/pyDoubles/0000755000175000017500000000000012435722065016635 5ustar piotrpiotrdoublex-1.8.2/doublex/test/pyDoubles/__init__.py0000644000175000017500000000000012435722065020734 0ustar piotrpiotrdoublex-1.8.2/doublex/test/pyDoubles/hamcrest_integration_tests.py0000644000175000017500000000565012435722065024650 0ustar piotrpiotr# -*- coding: utf-8 -*- """ Authors: Carlos Ble (www.carlosble.com) Ruben Bernardez (www.rubenbp.com) www.iExpertos.com License: Apache 2 (http://www.apache.org/licenses/LICENSE-2.0.html) Project home: https://bitbucket.org/carlosble/pydoubles """ import unittest from hamcrest.core.core import * from hamcrest.library.collection.isdict_containing import has_entry from hamcrest.library.object.haslength import has_length from hamcrest.library.text.isequal_ignoring_case import equal_to_ignoring_case from hamcrest.library.text.stringstartswith import starts_with from doublex.pyDoubles import * from .unit_tests import Collaborator class HamcrestIntegrationTest(unittest.TestCase): def setUp(self): self.spy = spy(Collaborator()) def test_use_in_stub_method(self): when(self.spy.one_arg_method).with_args( starts_with('tt')).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method('ttxe')) def test_use_in_spy_call(self): self.spy.one_arg_method('ttxe') assert_that_was_called( self.spy.one_arg_method).with_args(starts_with('tt')) def test_is_matcher(self): class Customer: pass customer = Customer() when(self.spy.one_arg_method).with_args( is_(customer)).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method(customer)) def test_instance_of_matcher(self): when(self.spy.one_arg_method).with_args( instance_of(int)).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method(5)) def test_all_of_matcher(self): text = 'hello' when(self.spy.one_arg_method).with_args( all_of(starts_with('h'), equal_to(text))).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method(text)) def test_has_length_matcher(self): list = [10, 20, 30] when(self.spy.one_arg_method).with_args( has_length(3)).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method(list)) def test_has_entry_matcher(self): list = {'one': 1, 'two': 2} when(self.spy.one_arg_method).with_args( has_entry(equal_to('two'), 2)).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method(list)) def test_equal_to_ignoring_case_matcher(self): self.spy.one_arg_method('hello') assert_that_was_called(self.spy.one_arg_method).with_args( equal_to_ignoring_case('HEllO')) def test_matcher_error_is_human_readable(self): self.spy.one_arg_method('xe') try: assert_that_method(self.spy.one_arg_method).was_called().with_args( starts_with('tt')) except ArgsDontMatch as e: self.assertTrue("tt" in str(e.args)) self.assertTrue("string starting" in str(e.args)) if __name__ == "__main__": print("Use nosetest to run this tests: nosetest %s" % __file__) doublex-1.8.2/doublex/test/pyDoubles/unit_tests.py0000644000175000017500000006774412435722065021432 0ustar piotrpiotr# -*- coding: utf-8 -*- """ Authors: Carlos Ble (www.carlosble.com) Ruben Bernardez (www.rubenbp.com) www.iExpertos.com License: Apache 2 (http://www.apache.org/licenses/LICENSE-2.0.html) Project home: https://bitbucket.org/carlosble/pydoubles """ import sys import re from nose.tools import nottest from doublex.pyDoubles import * if sys.version_info >= (2, 7): import unittest else: import unittest2 as unittest class SomeException(Exception): pass class Collaborator: """ The original object we double in tests """ test_field = "OK" def hello(self): return "hello" def something(self): return "ok" def one_arg_method(self, arg1): return arg1 def two_args_method(self, arg1, arg2): return arg1 + arg2 def kwarg_method(self, key_param=False): return key_param def mixed_method(self, arg1, key_param=False): return key_param + arg1 def void_method(self): pass def method_one(self, arg1): return 1 alias_method = one_arg_method class ProxySpyTests(unittest.TestCase): def setUp(self): self.spy = proxy_spy(Collaborator()) def test_assert_was_called(self): self.spy.hello() assert_that_was_called(self.spy.hello) def test_other_way_of_assert_called(self): self.spy.hello() assert_that_method(self.spy.hello).was_called() def test_assert_was_called_on_any_method(self): self.spy.something() assert_that_was_called(self.spy.something) def test_assert_needs_always_a_method_from_a_double(self): with self.assertRaises(WrongApiUsage): assert_that_was_called(self.spy) def test_assert_needs_always_a_method_from_a_double_not_the_original(self): with self.assertRaises(WrongApiUsage): assert_that_was_called(Collaborator().hello) def test_one_method_called_other_wasnt(self): self.spy.something() with self.assertRaises(UnexpectedBehavior): assert_that_was_called(self.spy.hello) def test_two_methods_called_assert_on_the_first(self): self.spy.hello() self.spy.something() assert_that_was_called(self.spy.hello) # pyDobules internal API specific # def test_get_method_name(self): # name = _Introspector_().method_name(self.spy.hello) # # self.assertEqual("hello", name) def test_call_original_method(self): self.assertEqual("ok", self.spy.something()) # pyDobules internal API specific # def test_get_instance_from_method(self): # spy_found = _Introspector_().double_instance_from_method(self.spy.hello) # # self.assertEqual(self.spy, spy_found) def test_assert_was_called_when_wasnt(self): with self.assertRaises(UnexpectedBehavior): assert_that_was_called(self.spy.hello) def test_was_called_with_same_parameters(self): self.spy.one_arg_method(1) assert_that_was_called(self.spy.one_arg_method).with_args(1) def test_was_called_with_same_parameters_in_variables(self): arg1 = 1 self.spy.one_arg_method(arg1) assert_that_was_called(self.spy.one_arg_method).with_args(1) def test_was_called_with_same_parameters_when_not(self): self.spy.one_arg_method(1) args_checker = assert_that_was_called(self.spy.one_arg_method) with self.assertRaises(ArgsDontMatch): args_checker.with_args(2) def test_was_called_with_same_params_but_no_params_accepted(self): self.spy.hello() args_checker = assert_that_was_called(self.spy.hello) with self.assertRaises(TypeError): args_checker.with_args("something") def test_was_called_with_several_parameters(self): self.spy.two_args_method(1, 2) args_checker = assert_that_was_called(self.spy.two_args_method) args_checker.with_args(1, 2) def test_was_called_with_parameters_not_matching(self): self.spy.one_arg_method(1) args_checker = assert_that_was_called(self.spy.one_arg_method) with self.assertRaises(ArgsDontMatch): args_checker.with_args("2") def test_was_called_with_keyed_args_not_matching(self): self.spy.kwarg_method(key_param="foo") args_checker = assert_that_was_called(self.spy.kwarg_method) with self.assertRaises(ArgsDontMatch): args_checker.with_args(key_param="bar") def test_was_called_with_keyed_args_matching(self): self.spy.kwarg_method(key_param="foo") assert_that_was_called(self.spy.kwarg_method).with_args( key_param="foo") def test_recorded_call_params_are_displayed(self): self.spy.kwarg_method(key_param="foo") try: assert_that_was_called(self.spy.kwarg_method ).with_args("bar") except ArgsDontMatch as e: self.assertTrue(str(e).find("foo") != -1, str(e)) def test_stub_out_method(self): when(self.spy.one_arg_method).then_return(3) self.assertEqual(3, self.spy.one_arg_method(5)) def test_stub_method_was_called(self): when(self.spy.one_arg_method).then_return(3) self.spy.one_arg_method(5) assert_that_was_called(self.spy.one_arg_method).with_args(5) def test_stub_out_method_returning_a_list(self): when(self.spy.one_arg_method).then_return([1, 2, 3]) self.assertEqual([1, 2, 3], self.spy.one_arg_method(5)) def test_stub_method_returning_list_was_called(self): when(self.spy.one_arg_method).then_return([1, 2, 3]) self.spy.one_arg_method(5) assert_that_was_called(self.spy.one_arg_method).with_args(5) def test_stub_out_method_with_args(self): when(self.spy.one_arg_method).with_args(2).then_return(3) self.assertEqual(3, self.spy.one_arg_method(2)) def test_stub_method_with_args_was_called(self): when(self.spy.one_arg_method).with_args(2).then_return(3) self.spy.one_arg_method(2) assert_that_was_called(self.spy.one_arg_method).with_args(2) def test_stub_out_method_with_args_calls_actual(self): when(self.spy.one_arg_method).with_args(2).then_return(3) self.assertEqual(4, self.spy.one_arg_method(4)) assert_that_was_called(self.spy.one_arg_method).with_args(4) def test_stub_out_method_with_several_inputs(self): when(self.spy.one_arg_method).with_args(2).then_return(3) when(self.spy.one_arg_method).with_args(3).then_return(4) self.assertEqual(3, self.spy.one_arg_method(2)) self.assertEqual(4, self.spy.one_arg_method(3)) def test_recorded_calls_work_on_several_stubs(self): when(self.spy.one_arg_method).with_args(2).then_return(3) when(self.spy.one_arg_method).with_args(3).then_return(4) self.spy.one_arg_method(2) self.spy.one_arg_method(3) assert_that_was_called(self.spy.one_arg_method).with_args(2) assert_that_was_called(self.spy.one_arg_method).with_args(3) def test_matching_stub_definition_is_used(self): when(self.spy.one_arg_method).then_return(1000) when(self.spy.one_arg_method).with_args(2).then_return(3) self.assertEqual(3, self.spy.one_arg_method(2)) self.assertEqual(1000, self.spy.one_arg_method(8)) def test_stub_with_kwargs(self): when(self.spy.kwarg_method).with_args(key_param=2 ).then_return(3) self.assertEqual(3, self.spy.kwarg_method(key_param=2)) self.assertEqual(6, self.spy.kwarg_method(key_param=6)) def test_stub_raising_exception(self): when(self.spy.hello).then_raise(SomeException()) try: self.spy.hello() self.fail("not raised") except SomeException: pass def test_stub_returning_what_receives(self): when(self.spy.method_one).then_return_input() self.assertEqual(20, self.spy.method_one(20)) def test_stub_returning_what_receives_when_no_params(self): when(self.spy.hello).then_return_input() with self.assertRaises(ApiMismatch): self.spy.hello() def test_be_able_to_return_objects(self): when(self.spy.one_arg_method).then_return(Collaborator()) collaborator = self.spy.one_arg_method(1) self.assertEqual(1, collaborator.one_arg_method(1)) def test_any_arg_matcher(self): when(self.spy.two_args_method).with_args(1, ANY_ARG).then_return(1000) self.assertEqual(1000, self.spy.two_args_method(1, 2)) self.assertEqual(1000, self.spy.two_args_method(1, 5)) def test_any_arg_matcher_was_called(self): when(self.spy.two_args_method).with_args(1, 2).then_return(1000) self.spy.two_args_method(1, 2) assert_that_was_called(self.spy.two_args_method ).with_args(1, ANY_ARG) def test_stub_works_with_alias_method(self): when(self.spy.one_arg_method).with_args(1).then_return(1000) self.spy.alias_method(1) assert_that_was_called(self.spy.one_arg_method ).with_args(1) def test_was_never_called(self): assert_that_method(self.spy.one_arg_method).was_never_called() def test_was_never_called_is_false(self): self.spy.one_arg_method(1) try: assert_that_method(self.spy.one_arg_method).was_never_called() self.fail("it was called indeed!") except UnexpectedBehavior: pass def test_expect_several_times(self): self.spy.one_arg_method(1) try: assert_that_method(self.spy.one_arg_method).was_called().times(2) self.fail("Should have been called 2 times") except UnexpectedBehavior: pass def test_fail_incorrect_times_msg_is_human_readable(self): self.spy.one_arg_method(1) try: assert_that_method(self.spy.one_arg_method).was_called().times(5) self.fail("Should have been called 2 times") except UnexpectedBehavior as e: for arg in e.args: if re.search("5", arg) and re.search("one_arg_method", arg): return self.fail("No enough readable exception message") def test_expect_several_times_matches_exactly(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) assert_that_method(self.spy.one_arg_method).was_called().times(2) def test_expect_several_times_with_args_definition(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) assert_that_method(self.spy.one_arg_method).was_called().with_args(1).times(2) def test_expect_several_times_with_incorrect_args(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) try: assert_that_method(self.spy.one_arg_method).was_called().with_args(2).times(2) self.fail("Must have 1 as an argument") except ArgsDontMatch: pass def test_args_match_but_not_number_of_times(self): self.spy.one_arg_method(1) self.spy.one_arg_method(2) try: assert_that_method(self.spy.one_arg_method ).was_called().with_args(1).times(2) self.fail("Wrong assertion") except UnexpectedBehavior: pass # pyDobules internal API specific #class MethodPoolTests(unittest.TestCase): # # def setUp(self): # self.pool = _MethodPool_() # self.method_name = "some_method" # self.pool.add_invocation( # CallDescription(self.method_name, (1, 2))) # # def test_call_args_match(self): # self.assertTrue( # self.pool.matching_invocations_by_args( # CallDescription(self.method_name, (1, 2), {}))) # # def test_call_args_match_with_any(self): # self.assertTrue( # self.pool.matching_invocations_by_args( # CallDescription(self.method_name, (1, ANY_ARG), {}))) class SpyTests(unittest.TestCase): def setUp(self): self.spy = spy(Collaborator()) def test_override_original_method(self): self.assertTrue(self.spy.hello() is None) def test_override_original_method_and_is_called(self): self.spy.hello() assert_that_was_called(self.spy.hello) def test_spy_can_work_from_empty_object(self): self.spy = empty_spy() self.assertTrue(self.spy.hello() is None) def test_spy_without_args_is_empty_spy(self): self.spy = spy() self.assertTrue(self.spy.hello() is None) def test_spy_can_work_from_empty_and_is_called(self): self.spy.hello() assert_that_was_called(self.spy.hello) def test_spy_based_on_object_must_check_api_match(self): try: self.spy.hello("unexpected argument") self.fail('Expection should raise: Actual objet does not accept parameters') except ApiMismatch: pass def test_check_api_match_with_kwargs(self): self.assertTrue(self.spy.mixed_method(1, key_param=2) is None) def test_check_api_match_with_kwargs_not_used(self): self.assertTrue(self.spy.mixed_method(1) is None) def test_check_api_match_with_kwargs_not_matching(self): try: self.spy.mixed_method(1, 2, 3) self.fail('Api mismatch not detected') except ApiMismatch: pass def test_match_call_with_unicode_and_non_ascii_chars(self): non_ascii = u'España' self.spy.one_arg_method(non_ascii) assert_that_was_called(self.spy.one_arg_method).with_args( non_ascii) def test_stub_methods_can_be_handled_separately(self): when(self.spy.one_arg_method).with_args(1).then_return(1000) when(self.spy.two_args_method).with_args(5, 5).then_return(2000) handle1 = self.spy.one_arg_method handle2 = self.spy.two_args_method self.assertEqual(1000, handle1(1)) self.assertEqual(2000, handle2(5, 5)) assert_that_was_called(handle1).with_args(1) assert_that_was_called(handle2).with_args(5, 5) def test_assert_was_called_with_method_not_in_the_api(self): #:pyDoubles # self.failUnlessRaises(ApiMismatch, # assert_that_was_called, self.spy.unexisting_method) try: self.spy.unexisting_method() self.fail("Exception should be raised") except AttributeError: pass def test_do_not_call_callable_object_if_wasnt_generated_by_the_framework(self): class CallableObj(): just_testing = True def __call__(self, *args, **kwargs): raise Exception('should not happen') obj = CallableObj() when(self.spy.one_arg_method).then_return(obj) self.assertEqual(obj, self.spy.one_arg_method(1), "Wrong returned object") # bitbucket Issue #5 def test_fail_missing_fluent_method(self): try: self.spy.one_arg_method(1) assert_that_was_called(self.spy.one_arg_method).with_params(2) # should be with_args self.fail("TypeError should be raised") except AttributeError as e: expected = "'assert_that_method' object has no attribute 'with_params'" hamcrest.assert_that(str(e), hamcrest.contains_string(expected)) class MockTests(unittest.TestCase): def setUp(self): self.mock = mock(Collaborator()) def test_fail_on_unexpected_call(self): try: self.mock.hello() self.fail('UnexpectedBehavior should be raised') except UnexpectedBehavior: pass def test_fail_on_unexpected_call_msg_is_human_readable(self): try: self.mock.hello() except UnexpectedBehavior as e: for arg in e.args: if re.search("No one", arg): return self.fail("No enough readable exception message") def test_define_expectation_and_call_method(self): expect_call(self.mock.hello) self.assertTrue(self.mock.hello() is None) def test_define_several_expectatiosn(self): expect_call(self.mock.hello) expect_call(self.mock.one_arg_method) self.assertTrue(self.mock.hello() is None) self.assertTrue(self.mock.one_arg_method(1) is None) def test_define_expectation_args(self): expect_call(self.mock.one_arg_method).with_args(1) self.assertTrue(self.mock.one_arg_method(1) is None) def test_define_expectation_args_and_fail(self): expect_call(self.mock.one_arg_method).with_args(1) try: self.mock.one_arg_method(2) self.fail('Unexpected call') except UnexpectedBehavior: pass def test_several_expectations_with_args(self): expect_call(self.mock.one_arg_method).with_args(1) expect_call(self.mock.two_args_method).with_args(2, 3) self.assertTrue(self.mock.one_arg_method(1) is None) self.assertTrue(self.mock.two_args_method(2, 3) is None) def test_expect_call_returning_value(self): expect_call(self.mock.one_arg_method).with_args(1).returning(1000) self.assertEqual(1000, self.mock.one_arg_method(1)) def test_assert_expectations_are_satisfied(self): expect_call(self.mock.hello) try: self.mock.assert_that_is_satisfied() self.fail('Not satisfied!') except UnexpectedBehavior: pass def test_assert_expectations_alternative(self): expect_call(self.mock.hello) try: self.mock.assert_expectations() self.fail('Not satisfied') except UnexpectedBehavior: pass def test_assert_satisfied_when_it_really_is(self): expect_call(self.mock.hello) self.mock.hello() self.mock.assert_that_is_satisfied() def test_number_of_calls_matter(self): expect_call(self.mock.hello) self.mock.hello() self.mock.hello() with self.assertRaises(UnexpectedBehavior): self.mock.assert_that_is_satisfied() def test_using_when_or_expect_call_without_double(self): with self.assertRaises(WrongApiUsage): expect_call(Collaborator()) def test_expectations_on_synonyms(self): expect_call(self.mock.one_arg_method) self.mock.alias_method(1) self.mock.assert_that_is_satisfied() def test_several_expectations_with_different_args(self): expect_call(self.mock.one_arg_method).with_args(1) expect_call(self.mock.one_arg_method).with_args(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) with self.assertRaises(UnexpectedBehavior): self.mock.assert_that_is_satisfied() def test_expect_several_times(self): expect_call(self.mock.one_arg_method).with_args(1).times(2) self.mock.one_arg_method(1) with self.assertRaises(UnexpectedBehavior): self.mock.assert_that_is_satisfied() def test_expect_several_times_matches_exactly(self): expect_call(self.mock.one_arg_method).with_args(1).times(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) self.mock.assert_that_is_satisfied() def test_expect_several_times_without_args_definition(self): expect_call(self.mock.one_arg_method).times(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) self.mock.assert_that_is_satisfied() def test_defend_agains_less_than_2_times(self): try: expect_call(self.mock.one_arg_method).times(1) self.fail('times cant be less than 2') except WrongApiUsage: pass def test_times_and_return_value(self): expect_call(self.mock.one_arg_method).returning(1000).times(2) self.assertEqual(1000, self.mock.one_arg_method(1)) self.assertEqual(1000, self.mock.one_arg_method(1)) self.mock.assert_that_is_satisfied() def test_times_and_return_value_and_input_args(self): expect_call(self.mock.one_arg_method).with_args(10).returning(1000).times(2) self.assertEqual(1000, self.mock.one_arg_method(10)) self.assertEqual(1000, self.mock.one_arg_method(10)) self.mock.assert_that_is_satisfied() class MockFromEmptyObjectTests(unittest.TestCase): def setUp(self): self.mock = empty_mock() def test_mock_can_work_from_empty_object(self): expect_call(self.mock.hello) self.mock.hello() self.mock.assert_that_is_satisfied() def test_mock_without_args_is_empty_mock(self): self.mock = mock() expect_call(self.mock.hello) self.mock.hello() self.mock.assert_that_is_satisfied() def test_several_expectations_in_empty_mock(self): expect_call(self.mock.hello) expect_call(self.mock.one_arg_method).with_args(1) self.mock.hello() self.mock.one_arg_method(1) self.mock.assert_that_is_satisfied() def test_several_expectations_with_args_in_empty_mock(self): expect_call(self.mock.one_arg_method).with_args(1) expect_call(self.mock.one_arg_method).with_args(2) self.assertTrue(self.mock.one_arg_method(1) is None) self.assertTrue(self.mock.one_arg_method(2) is None) self.mock.assert_that_is_satisfied() class StubMethodsTests(unittest.TestCase): def setUp(self): self.collaborator = Collaborator() def test_method_returning_value(self): self.collaborator.hello = method_returning("bye") self.assertEqual("bye", self.collaborator.hello()) def test_method_args_returning_value(self): self.collaborator.one_arg_method = method_returning("bye") self.assertEqual("bye", self.collaborator.one_arg_method(1)) def test_method_raising_exception(self): self.collaborator.hello = method_raising(SomeException()) try: self.collaborator.hello() self.fail("exception not raised") except SomeException: pass class MatchersTests(unittest.TestCase): def setUp(self): self.spy = spy(Collaborator()) def test_str_cotaining_with_exact_match(self): when(self.spy.one_arg_method).with_args( str_containing("abc")).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method("abc")) def test_str_containing_with_substr(self): when(self.spy.one_arg_method).with_args( str_containing("abc")).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method("XabcX")) def test_str_containing_with_substr_unicode(self): when(self.spy.one_arg_method).with_args( str_containing("abc")).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method(u"XabcñX")) def test_str_containing_but_matcher_not_used(self): when(self.spy.one_arg_method).with_args( "abc").then_return(1000) self.assertNotEqual(1000, self.spy.one_arg_method("XabcX")) def test_was_called_and_substr_matcher(self): self.spy.one_arg_method("XabcX") assert_that_was_called(self.spy.one_arg_method).with_args( str_containing("abc")) def test_str_not_containing(self): when(self.spy.one_arg_method).with_args( str_not_containing("abc")).then_return(1000) self.assertNotEqual(1000, self.spy.one_arg_method("abc")) def test_str_not_containing_stubs_anything_else(self): when(self.spy.one_arg_method).with_args( str_not_containing("abc")).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method("xxx")) def test_str_not_containing_was_called(self): self.spy.one_arg_method("abc") assert_that_was_called(self.spy.one_arg_method).with_args( str_not_containing("xxx")) def test_several_matchers(self): when(self.spy.two_args_method).with_args( str_containing("abc"), str_containing("xxx")).then_return(1000) self.assertNotEqual(1000, self.spy.two_args_method("abc", "yyy")) def test_str_length_matcher(self): when(self.spy.one_arg_method).with_args( str_length(5)).then_return(1000) self.assertEqual(1000, self.spy.one_arg_method("abcde")) def test_matchers_when_passed_arg_is_none(self): when(self.spy.one_arg_method).with_args( str_length(5)).then_return(1000) self.assertTrue(self.spy.one_arg_method(None) is None) def test_compare_objects_is_not_possible_without_eq_operator(self): class SomeObject(): field1 = field2 = None obj = SomeObject() obj2 = SomeObject() self.spy.one_arg_method(obj) try: assert_that_method(self.spy.one_arg_method).was_called().with_args(obj2) self.fail('they should not match') except ArgsDontMatch: pass def test_if_doesnt_match_message_is_human_redable(self): self.spy.one_arg_method("XabcX") try: assert_that_was_called(self.spy.one_arg_method).with_args( str_containing("xxx")) except ArgsDontMatch as e: self.assertTrue("xxx" in str(e.args), str(e.args)) self.assertTrue("string containing" in str(e.args)) def test_obj_with_field_matcher(self): obj = Collaborator() obj.id = 20 self.spy.one_arg_method(obj) assert_that_method(self.spy.one_arg_method ).was_called().with_args(obj_with_fields({'id': 20})) def test_obj_with_several_fields_matcher(self): obj = Collaborator() obj.id = 21 self.spy.one_arg_method(obj) try: assert_that_method( self.spy.one_arg_method).was_called().with_args( obj_with_fields({ 'id': 20, 'test_field': 'OK'})) self.fail('Wrong assertion, id field is different') except ArgsDontMatch: pass def test_obj_with_field_defends_agains_wrong_usage(self): self.spy.one_arg_method(Collaborator()) try: assert_that_method( self.spy.one_arg_method).was_called().with_args( obj_with_fields('id = 20')) self.fail('Wrong assertion, argument should be a dictionary') except WrongApiUsage: pass class StubTests(unittest.TestCase): def test_free_stub(self): my_stub = empty_stub() self.assertTrue(my_stub.hello() is None) def test_restricted_stub(self): my_stub = stub(Collaborator()) when(my_stub.something).then_return(10) self.assertEqual(10, my_stub.something()) def test_restricted_stub_method_not_stubbed(self): my_stub = stub(Collaborator()) self.assertEqual(None, my_stub.hello()) # Create hamcrest matchers instead #class CustomMatchersTest(unittest.TestCase): # # def setUp(self): # self.spy = spy(Collaborator()) # # def test_use_custom_matcher(self): # class CustomMatcher(PyDoublesMatcher): # matcher_name = "test matcher" # # def __init__(self, arg): # self.defined_arg = arg # # def matches(self, item): # return True # # when(self.spy.one_arg_method).with_args( # CustomMatcher('zzz')).then_return(1000) # self.assertEqual(1000, self.spy.one_arg_method('xx')) # # def test_custom_matcher_do_not_follow_convention(self): # class CustomMatcher(PyDoublesMatcher): # def matches(self, item): # return False # # self.spy.one_arg_method(1) # try: # assert_that_was_called(self.spy.one_arg_method).with_args( # CustomMatcher()) # self.fail('args dont match!') # except ArgsDontMatch: # pass if __name__ == "__main__": print("Use nosetest to run this tests: nosetest %s" % __file__) doublex-1.8.2/doublex/test/pyDoubles_legacy_tests.py0000644000175000017500000006234712435722065021771 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- import sys if sys.version_info >= (2, 7): from unittest import TestCase else: from unittest2 import TestCase from hamcrest import is_not, all_of, contains_string, has_length from hamcrest.library.object.hasproperty import * from doublex import * from unit_tests import Collaborator class SomeException(Exception): pass class pyDoubles__ProxySpyTests(TestCase): def setUp(self): self.spy = ProxySpy(Collaborator()) #SAME as pyDoublesSpyTests.test_override_original_method_and_is_called def test_assert_was_called(self): self.spy.hello() assert_that(self.spy.hello, called()) def test_assert_was_called_on_any_method(self): self.spy.something() assert_that(self.spy.something, called()) def test_assert_needs_always_a_method_from_a_double(self): with self.assertRaises(WrongApiUsage): assert_that(self.spy, called()) def test_assert_needs_always_a_method_from_a_double_not_the_original(self): with self.assertRaises(WrongApiUsage): assert_that(Collaborator().hello, called()) def test_one_method_called_other_wasnt(self): self.spy.something() with self.assertRaises(AssertionError): assert_that(self.spy.hello, called()) def test_two_methods_called_assert_on_the_first(self): self.spy.hello() self.spy.something() assert_that(self.spy.hello, called()) # # This is testing internal API! Not applicable # def test_get_method_name(self): # name = _Introspector_().method_name(self.spy.hello) # # self.assertEqual("hello", name) def test_call_original_method(self): self.assertEqual("ok", self.spy.something()) # # This is testing internal API! Not applicable # def test_get_instance_from_method(self): # spy_found = _Introspector_().double_instance_from_method(self.spy.hello) # # self.assertEqual(self.spy, spy_found) def test_assert_was_called_when_wasnt(self): with self.assertRaises(AssertionError): assert_that(self.spy.hello, called()) def test_was_called_with_same_parameters(self): self.spy.one_arg_method(1) assert_that(self.spy.one_arg_method, called().with_args(1)) # this is exactly the same that previous! :-S def test_was_called_with_same_parameters_in_variables(self): arg1 = 1 self.spy.one_arg_method(arg1) assert_that(self.spy.one_arg_method, called().with_args(1)) def test_was_called_with_same_parameters_when_not(self): self.spy.one_arg_method(1) args_checker = called().with_args(2) assert_that(not args_checker.matches(self.spy.one_arg_method)) def test_was_called_with_same_params_but_no_params_accepted(self): self.spy.hello() args_checker = called().with_args("something") with self.assertRaises(TypeError): assert_that(not args_checker.matches(self.spy.hello)) def test_was_called_with_several_parameters(self): self.spy.two_args_method(1, 2) args_checker = called().with_args(1, 2) assert_that(args_checker.matches(self.spy.two_args_method)) #SAME as test_was_called_with_same_parameters_when_not def test_was_called_with_parameters_not_matching(self): self.spy.one_arg_method(1) args_checker = called().with_args("2") assert_that(not args_checker.matches(self.spy.one_arg_method)) def test_was_called_with_keyed_args_not_matching(self): self.spy.kwarg_method(key_param="foo") args_checker = called().with_args(key_param="bar") assert_that(not args_checker.matches(self.spy.kwarg_method)) def test_was_called_with_keyed_args_matching(self): self.spy.kwarg_method(key_param="foo") assert_that(self.spy.kwarg_method, called().with_args(key_param="foo")) def test_recorded_call_params_are_displayed(self): self.spy.kwarg_method(key_param="foo") try: assert_that(self.spy.kwarg_method, called().with_args("bar")) except AssertionError as e: assert_that(str(e), contains_string("foo")) def test_stub_out_method(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns(3) self.assertEqual(3, self.spy.one_arg_method(5)) def test_stub_method_was_called(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns(3) self.spy.one_arg_method(5) assert_that(self.spy.one_arg_method, called().with_args(5)) def test_stub_out_method_returning_a_list(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns([1, 2, 3]) assert_that(self.spy.one_arg_method(5), is_([1, 2, 3])) def test_stub_method_returning_list_was_called(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns([1, 2, 3]) self.spy.one_arg_method(5) assert_that(self.spy.one_arg_method, called().with_args(5)) def test_stub_out_method_with_args(self): with self.spy: self.spy.one_arg_method(2).returns(3) assert_that(self.spy.one_arg_method(2), is_(3)) def test_stub_method_with_args_was_called(self): with self.spy: self.spy.one_arg_method(2).returns(3) self.spy.one_arg_method(2) assert_that(self.spy.one_arg_method, called().with_args(2)) def test_stub_out_method_with_args_calls_actual(self): with self.spy: self.spy.one_arg_method(2).returns(3) assert_that(self.spy.one_arg_method(4), is_(4)) assert_that(self.spy.one_arg_method, called().with_args(4)) def test_stub_out_method_with_several_inputs(self): with self.spy: self.spy.one_arg_method(2).returns(3) self.spy.one_arg_method(3).returns(4) assert_that(self.spy.one_arg_method(2), is_(3)) assert_that(self.spy.one_arg_method(3), is_(4)) def test_recorded_calls_work_on_several_stubs(self): with self.spy: self.spy.one_arg_method(2).returns(3) self.spy.one_arg_method(3).returns(4) self.spy.one_arg_method(2) self.spy.one_arg_method(3) assert_that(self.spy.one_arg_method, called().with_args(2)) assert_that(self.spy.one_arg_method, called().with_args(3)) def test_matching_stub_definition_is_used(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns(1000) self.spy.one_arg_method(2).returns(3) assert_that(self.spy.one_arg_method(2), is_(3)) assert_that(self.spy.one_arg_method(8), is_(1000)) def test_stub_with_kwargs(self): with self.spy: self.spy.kwarg_method(key_param=2).returns(3) assert_that(self.spy.kwarg_method(key_param=2), is_(3)) assert_that(self.spy.kwarg_method(key_param=6), is_(6)) def test_stub_raising_exception(self): with self.spy: self.spy.hello().raises(SomeException) try: self.spy.hello() self.fail("not raised") except SomeException: pass def test_stub_returning_what_receives(self): with self.spy: self.spy.method_one(ANY_ARG).returns_input() assert_that(self.spy.method_one(20), is_(20)) # Different that pyDoubles. exception raised at setup def test_stub_returning_what_receives_when_no_params(self): try: with self.spy: self.spy.hello().returns_input() self.fail("TypeError should be raised") except TypeError as e: assert_that(str(e), contains_string("Collaborator.hello() has no input args")) def test_be_able_to_return_objects(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns(Collaborator()) collaborator = self.spy.one_arg_method(1) assert_that(collaborator.one_arg_method(1), is_(1)) def test_any_arg_matcher(self): with self.spy: self.spy.two_args_method(1, ANY_ARG).returns(1000) assert_that(self.spy.two_args_method(1, 2), is_(1000)) assert_that(self.spy.two_args_method(1, 5), is_(1000)) assert_that(self.spy.two_args_method(3, 5), is_not(1000)) # Not supported by pyDoubles def test_any_arg_matcher_with_kwargs(self): with self.spy: self.spy.kwarg_method(key_param=anything()).returns(1000) self.assertEqual(1000, self.spy.kwarg_method(key_param=2)) def test_any_arg_matcher_was_called(self): with self.spy: self.spy.two_args_method(1, 2).returns(1000) self.spy.two_args_method(1, 2) assert_that(self.spy.two_args_method, called().with_args(1, ANY_ARG)) def test_stub_works_with_alias_method(self): with self.spy: self.spy.one_arg_method(1).returns(1000) self.spy.alias_method(1) assert_that(self.spy.one_arg_method, called().with_args(1)) def test_was_never_called(self): assert_that(self.spy.one_arg_method, is_not(called())) def test_was_never_called_is_false(self): self.spy.one_arg_method(1) try: assert_that(self.spy.one_arg_method, is_not(called())) self.fail("it was called indeed!") except AssertionError: pass def test_expect_several_times(self): self.spy.one_arg_method(1) try: assert_that(self.spy.one_arg_method, called().times(2)) self.fail("Should have been called 2 times") except AssertionError: pass def test_fail_incorrect_times_msg_is_human_readable(self): self.spy.one_arg_method(1) try: assert_that(self.spy.one_arg_method, called().times(5)) self.fail("Should have been called 5 times") except AssertionError as e: assert_that(str(e), contains_string("5")) assert_that(str(e), contains_string("one_arg_method")) def test_expect_several_times_matches_exactly(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) assert_that(self.spy.one_arg_method, called().times(2)) def test_expect_several_times_with_args_definition(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) assert_that(self.spy.one_arg_method, called().with_args(1).times(2)) def test_expect_several_times_with_incorrect_args(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) try: assert_that(self.spy.one_arg_method, called().with_args(2).times(2)) self.fail("Must have 1 as an argument") except AssertionError: pass def test_args_match_but_not_number_of_times(self): self.spy.one_arg_method(1) self.spy.one_arg_method(2) try: assert_that(self.spy.one_arg_method, called().with_args(1).times(2)) self.fail("Wrong assertion") except AssertionError: pass class pyDoubles__SpyTests(TestCase): def setUp(self): self.spy = Spy(Collaborator()) def test_override_original_method(self): self.assertTrue(self.spy.hello() is None) def test_override_original_method_and_is_called(self): self.spy.hello() assert_that(self.spy.hello, called()) def test_spy_without_args_is_empty_spy(self): self.spy = Spy() self.assertTrue(self.spy.hello() is None) def test_spy_can_work_from_empty_and_is_called(self): self.spy.hello() assert_that(self.spy.hello, called()) def test_spy_based_on_object_must_check_api_match(self): try: self.spy.hello("unexpected argument") self.fail('Expection should raise: Actual object does not accept parameters') except TypeError: pass def test_check_api_match_with_kwargs(self): self.assertTrue(self.spy.mixed_method(1, key_param=2) is None) def test_check_api_match_with_kwargs_not_used(self): self.assertTrue(self.spy.mixed_method(1) is None) def test_check_api_match_with_kwargs_not_matching(self): try: self.spy.mixed_method(1, 2, 3) self.fail('TypeError not detected!') except TypeError: pass def test_match_call_with_unicode_and_non_ascii_chars(self): non_ascii = u'España' self.spy.one_arg_method(non_ascii) assert_that(self.spy.one_arg_method, called().with_args(non_ascii)) def test_stub_methods_can_be_handled_separately(self): with self.spy: self.spy.one_arg_method(1).returns(1000) self.spy.two_args_method(5, 5).returns(2000) handle1 = self.spy.one_arg_method handle2 = self.spy.two_args_method self.assertEqual(1000, handle1(1)) self.assertEqual(2000, handle2(5, 5)) assert_that(handle1, called().with_args(1)) assert_that(handle2, called().with_args(5, 5)) #SAME as VerifiedSpyTests.test_check_unexisting_method def test_assert_was_called_with_method_not_in_the_api(self): try: assert_that(self.spy.unexisting_method, called()) self.fail("AttributeError should be raised") except AttributeError: pass def test_do_not_call_callable_object_if_wasnt_generated_by_the_framework(self): class CallableObj(): just_testing = True def __call__(self, *args, **kwargs): raise Exception('should not happen') obj = CallableObj() with self.spy: self.spy.one_arg_method(ANY_ARG).returns(obj) self.assertEqual(obj, self.spy.one_arg_method(1), "Wrong returned object") class pyDoubles__MockTests(TestCase): def setUp(self): self.mock = Mock(Collaborator) def test_fail_on_unexpected_call(self): try: self.mock.hello() self.fail('AssertionError should be raised') except AssertionError: pass def test_fail_on_unexpected_call_msg_is_human_readable(self): try: self.mock.hello() except AssertionError as e: assert_that(str(e), contains_string("No one")) def test_define_expectation_and_call_method(self): with self.mock: self.mock.hello() self.assertTrue(self.mock.hello() is None) def test_define_several_expectatiosn(self): with self.mock: self.mock.hello() self.mock.one_arg_method(ANY_ARG) self.assertTrue(self.mock.hello() is None) self.assertTrue(self.mock.one_arg_method(1) is None) def test_define_expectation_args(self): with self.mock: self.mock.one_arg_method(1) self.assertTrue(self.mock.one_arg_method(1) is None) def test_define_expectation_args_and_fail(self): with self.mock: self.mock.one_arg_method(1) try: self.mock.one_arg_method(2) self.fail('Unexpected call') except AssertionError: pass def test_several_expectations_with_args(self): with self.mock: self.mock.one_arg_method(1) self.mock.two_args_method(2, 3) self.assertTrue(self.mock.one_arg_method(1) is None) self.assertTrue(self.mock.two_args_method(2, 3) is None) def test_expect_call_returning_value(self): with self.mock: self.mock.one_arg_method(1).returns(1000) self.assertEqual(1000, self.mock.one_arg_method(1)) def test_assert_expectations_are_satisfied(self): with self.mock: self.mock.hello() assert_that(self.mock, is_not(verify())) def test_assert_satisfied_when_it_really_is(self): with self.mock: self.mock.hello() self.mock.hello() assert_that(self.mock, verify()) def test_number_of_calls_matter(self): with self.mock: self.mock.hello() self.mock.hello() self.mock.hello() assert_that(self.mock, is_not(verify())) # Not applicable to doublex # def test_using_when_or_expect_call_without_double(self): # self.failUnlessRaises(WrongApiUsage, # expect_call, Collaborator()) def test_expectations_on_synonyms(self): with self.mock: self.mock.one_arg_method(ANY_ARG) self.mock.alias_method(1) assert_that(self.mock, verify()) def test_several_expectations_with_different_args(self): with self.mock: self.mock.one_arg_method(1) self.mock.one_arg_method(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) assert_that(self.mock, is_not(verify())) def test_expect_several_times(self): with self.mock: self.mock.one_arg_method(1).times(2) self.mock.one_arg_method(1) assert_that(self.mock, is_not(verify())) def test_expect_several_times_matches_exactly(self): with self.mock: self.mock.one_arg_method(1).times(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) assert_that(self.mock, verify()) def test_expect_several_times_without_args_definition(self): with self.mock: self.mock.one_arg_method(ANY_ARG).times(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) assert_that(self.mock, verify()) def test_defend_agains_less_than_2_times(self): try: with self.mock: self.mock.one_arg_method(ANY_ARG).times(0) self.fail('times cant be less than 1') except WrongApiUsage: pass def test_times_and_return_value(self): with self.mock: self.mock.one_arg_method(ANY_ARG).returns(1000).times(2) self.assertEqual(1000, self.mock.one_arg_method(1)) self.assertEqual(1000, self.mock.one_arg_method(1)) assert_that(self.mock, verify()) def test_times_and_return_value_and_input_args(self): with self.mock: self.mock.one_arg_method(10).returns(1000).times(2) self.assertEqual(1000, self.mock.one_arg_method(10)) self.assertEqual(1000, self.mock.one_arg_method(10)) assert_that(self.mock, verify()) class pyDoubles__MockFromEmptyObjectTests(TestCase): def setUp(self): self.mock = Mock() def test_mock_can_work_from_empty_object(self): with self.mock as mock: mock.hello() self.mock.hello() assert_that(self.mock, verify()) # Not applicable to doublex def test_mock_without_args_is_empty_mock(self): pass def test_several_expectations_in_empty_mock(self): with self.mock: self.mock.hello() self.mock.one_arg_method(1) self.mock.hello() self.mock.one_arg_method(1) assert_that(self.mock, verify()) def test_several_expectations_with_args_in_empty_mock(self): with self.mock: self.mock.one_arg_method(1) self.mock.one_arg_method(2) self.assertTrue(self.mock.one_arg_method(1) is None) self.assertTrue(self.mock.one_arg_method(2) is None) assert_that(self.mock, verify()) class pyDoubles__StubMethodsTests(TestCase): def setUp(self): self.collaborator = Collaborator() def test_method_returning_value(self): self.collaborator.hello = method_returning("bye") self.assertEqual("bye", self.collaborator.hello()) def test_method_args_returning_value(self): self.collaborator.one_arg_method = method_returning("bye") self.assertEqual("bye", self.collaborator.one_arg_method(1)) def test_method_raising_exception(self): self.collaborator.hello = method_raising(SomeException) try: self.collaborator.hello() self.fail("exception not raised") except SomeException: pass class pyDoubles__MatchersTests(TestCase): def setUp(self): self.spy = Spy(Collaborator) def test_str_cotaining_with_exact_match(self): with self.spy: self.spy.one_arg_method(contains_string("abc")).returns(1000) self.assertEqual(1000, self.spy.one_arg_method("abc")) def test_str_containing_with_substr(self): with self.spy: self.spy.one_arg_method(contains_string("abc")).returns(1000) self.assertEqual(1000, self.spy.one_arg_method("XabcX")) def test_str_containing_with_substr_unicode(self): with self.spy: self.spy.one_arg_method(contains_string("abc")).returns(1000) self.assertEqual(1000, self.spy.one_arg_method(u"XabcñX")) def test_str_containing_but_matcher_not_used(self): with self.spy: self.spy.one_arg_method("abc").returns(1000) self.assertNotEqual(1000, self.spy.one_arg_method("XabcX")) def test_was_called_and_substr_matcher(self): self.spy.one_arg_method("XabcX") assert_that(self.spy.one_arg_method, called().with_args(contains_string("abc"))) def test_str_not_containing(self): with self.spy: self.spy.one_arg_method(is_not(contains_string("abc"))).returns(1000) self.assertNotEqual(1000, self.spy.one_arg_method("abc")) def test_str_not_containing_stubs_anything_else(self): with self.spy: self.spy.one_arg_method(is_not(contains_string("abc"))).returns(1000) self.assertEqual(1000, self.spy.one_arg_method("xxx")) def test_str_not_containing_was_called(self): self.spy.one_arg_method("abc") assert_that(self.spy.one_arg_method, called().with_args(is_not(contains_string("xxx")))) def test_several_matchers(self): with self.spy: self.spy.two_args_method( contains_string("abc"), contains_string("xxx")).returns(1000) self.assertNotEqual(1000, self.spy.two_args_method("abc", "yyy")) def test_str_length_matcher(self): with self.spy: self.spy.one_arg_method(has_length(5)).returns(1000) self.assertEqual(1000, self.spy.one_arg_method("abcde")) def test_matchers_when_passed_arg_is_none(self): with self.spy: self.spy.one_arg_method(has_length(5)).returns(1000) self.assertTrue(self.spy.one_arg_method(None) is None) def test_compare_objects_is_not_possible_without_eq_operator(self): class SomeObject(): field1 = field2 = None obj = SomeObject() obj2 = SomeObject() self.spy.one_arg_method(obj) try: assert_that(self.spy.one_arg_method, called().with_args(obj2)) self.fail("they should not match") except AssertionError: pass def test_if_doesnt_match_message_is_human_redable(self): self.spy.one_arg_method("XabcX") try: assert_that(self.spy.one_arg_method, called().with_args(contains_string("xxx"))) except AssertionError as e: assert_that(str(e), contains_string("xxx")) assert_that( str(e), contains_string("string containing")) def test_obj_with_field_matcher(self): obj = Collaborator() obj.id = 20 self.spy.one_arg_method(obj) assert_that(self.spy.one_arg_method, called().with_args(has_property('id', 20))) def test_obj_with_several_fields_matcher(self): obj = Collaborator() obj.id = 21 self.spy.one_arg_method(obj) try: assert_that( self.spy.one_arg_method, called().with_args(all_of( has_property('id', 20), has_property('test_field', 'OK')))) self.fail('Wrong assertion, id field is different') except AssertionError: pass # Not applicable to doublex, cause doublex uses hamcrest matchers # def test_obj_with_field_defends_agains_wrong_usage(self): # self.spy.one_arg_method(Collaborator()) # try: # assert_that_method( # self.spy.one_arg_method).was_called().with_args( # obj_with_fields('id = 20')) # self.fail('Wrong assertion, argument should be a dictionary') # except WrongApiUsage: # pass # NOT APPLICABLE. doubles uses hamcrest matchers #class pyDoubles__CustomMatchersTest(unittest.TestCase): # # def setUp(self): # self.spy = spy(Collaborator()) # # def test_use_custom_matcher(self): # class CustomMatcher(PyDoublesMatcher): # matcher_name = "test matcher" # # def __init__(self, arg): # self.defined_arg = arg # # def matches(self, item): # return True # # when(self.spy.one_arg_method).with_args( # CustomMatcher('zzz')).then_return(1000) # self.assertEqual(1000, self.spy.one_arg_method('xx')) # # def test_custom_matcher_do_not_follow_convention(self): # class CustomMatcher(PyDoublesMatcher): # def matches(self, item): # return False # # self.spy.one_arg_method(1) # try: # assert_that_was_called(self.spy.one_arg_method).with_args( # CustomMatcher()) # self.fail('args dont match!') # except ArgsDontMatch: # pass doublex-1.8.2/doublex/test/report_tests.py0000644000175000017500000002530012435722065017776 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012, 2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA from unittest import TestCase from hamcrest import assert_that, is_, is_not, contains_string, greater_than from nose.tools import nottest import doublex from doublex.internal import Invocation, InvocationContext from unit_tests import ObjCollaborator def create_invocation(name, args=None, kargs=None, retval=None): stub = doublex.Stub() args = args or tuple() kargs = kargs or {} context = InvocationContext(*args, **kargs) context.retval = retval invocation = Invocation(stub, name, context) return invocation class InvocationReportTests(TestCase): def test_int_arg_method_returning_int(self): invocation = create_invocation('foo', (1,), None, retval=1) assert_that(str(invocation), is_('Stub.foo(1)-> 1')) def test_ANY_arg_method_returning_none(self): invocation = create_invocation('foo', (doublex.ANY_ARG,)) assert_that(str(invocation), is_('Stub.foo(ANY_ARG)')) # @nottest # def test_unicode_arg_method(self): # self.add_invocation('foo', (u'ñandú',)) # # print self.render() # # assert_that(self.render(), # is_("foo(u'ñandú')")) class MessageMixin(object): def assert_with_message(self, value, matcher, message): try: assert_that(value, matcher) self.fail("Exception should be raised") except AssertionError as e: assert_that(str(e).strip(), is_(message.strip())) class SpyReportTest(TestCase, MessageMixin): def test_called(self): spy = doublex.Spy() expected = ''' Expected: these calls: Spy.expected(ANY_ARG) but: calls that actually ocurred were: No one''' self.assert_with_message(spy.expected, doublex.called(), expected) def test_nerver_called(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) spy.unexpected(5) self.assert_with_message( spy.unexpected, doublex.never(doublex.called()), ''' Expected: none of these calls: Spy.unexpected(ANY_ARG) but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2) Spy.unexpected(5)''') def test_hamcrest_not_called(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) spy.unexpected(5) self.assert_with_message( spy.unexpected, is_not(doublex.called()), ''' Expected: not these calls: Spy.unexpected(ANY_ARG) but: was ''') def test_called_times_int(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) self.assert_with_message( spy.foo, doublex.called().times(1), ''' Expected: these calls: Spy.foo(ANY_ARG) -- times: 1 but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2)''') def test_called_times_matcher(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) self.assert_with_message( spy.foo, doublex.called().times(greater_than(3)), ''' Expected: these calls: Spy.foo(ANY_ARG) -- times: a value greater than <3> but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2)''') def test_called_with(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) self.assert_with_message( spy.expected, doublex.called().with_args(3), ''' Expected: these calls: Spy.expected(3) but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2)''') def test_never_called_with(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) spy.unexpected(2) self.assert_with_message( spy.unexpected, doublex.never(doublex.called().with_args(2)), ''' Expected: none of these calls: Spy.unexpected(2) but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2) Spy.unexpected(2)''') def test_hamcrest_not_called_with(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) spy.unexpected(2) self.assert_with_message( spy.unexpected, is_not(doublex.called().with_args(2)), ''' Expected: not these calls: Spy.unexpected(2) but: was ''') def test_called_with_matcher(self): spy = doublex.Spy() self.assert_with_message( spy.unexpected, doublex.called().with_args(greater_than(1)), ''' Expected: these calls: Spy.unexpected(a value greater than <1>) but: calls that actually ocurred were: No one''') def test_never_called_with_matcher(self): spy = doublex.Spy() spy.unexpected(2) self.assert_with_message( spy.unexpected, doublex.never(doublex.called().with_args(greater_than(1))), ''' Expected: none of these calls: Spy.unexpected(a value greater than <1>) but: calls that actually ocurred were: Spy.unexpected(2)''') def test__hamcrest_not__called_with_matcher(self): spy = doublex.Spy() spy.unexpected(2) self.assert_with_message( spy.unexpected, is_not(doublex.called().with_args(greater_than(1))), ''' Expected: not these calls: Spy.unexpected(a value greater than <1>) but: was ''') class MockReportTest(TestCase, MessageMixin): def setUp(self): self.mock = doublex.Mock() def assert_expectation_error(self, expected_message): self.assert_with_message(self.mock, doublex.verify(), expected_message) def test_expect_none_but_someting_unexpected_called(self): expected_message = ''' Expected: these calls: No one but: this call was not expected: Mock.unexpected() ''' try: self.mock.unexpected() self.fail("This should raise exception") except AssertionError as e: assert_that(str(e), is_(expected_message)) def test_expect_1_void_method_but_nothing_called(self): with self.mock: self.mock.expected() expected_message = ''' Expected: these calls: Mock.expected() but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_expect_2_void_methods_but_nothing_called(self): with self.mock: self.mock.foo() self.mock.bar() expected_message = ''' Expected: these calls: Mock.foo() Mock.bar() but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_expect_method_with_2_int_args_returning_int_but_nothing_called(self): with self.mock: self.mock.foo(1, 2).returns(1) expected_message = ''' Expected: these calls: Mock.foo(1, 2)-> 1 but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_except_method_with_2_str_args_returning_str_but_nothing_called(self): with self.mock: self.mock.foo('a', 'b').returns('c') expected_message = ''' Expected: these calls: Mock.foo('a', 'b')-> 'c' but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_except_method_with_2_kwargs_returning_dict_but_nothing_called(self): with self.mock: self.mock.foo(num=1, color='red').returns({'key': 1}) expected_message = ''' Expected: these calls: Mock.foo(color='red', num=1)-> {'key': 1} but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_expect_4_calls_but_only_2_called(self): with self.mock: self.mock.foo() self.mock.foo() self.mock.bar() self.mock.bar() self.mock.foo() self.mock.bar() expected_message = ''' Expected: these calls: Mock.foo() Mock.foo() Mock.bar() Mock.bar() but: calls that actually ocurred were: Mock.foo() Mock.bar() ''' self.assert_expectation_error(expected_message) class PropertyReportTests(TestCase, MessageMixin): def test_expected_get(self): spy = doublex.Spy(ObjCollaborator) expected_message = ''' Expected: these calls: get ObjCollaborator.prop but: calls that actually ocurred were: No one ''' self.assert_with_message( spy, doublex.property_got('prop'), expected_message) def test_unexpected_get(self): expected_message = ''' Expected: none of these calls: get ObjCollaborator.prop but: calls that actually ocurred were: get ObjCollaborator.prop ''' spy = doublex.Spy(ObjCollaborator) spy.prop self.assert_with_message( spy, doublex.never(doublex.property_got('prop')), expected_message) def test_expected_set(self): spy = doublex.Spy(ObjCollaborator) expected_message = ''' Expected: these calls: set ObjCollaborator.prop to ANYTHING but: calls that actually ocurred were: No one ''' self.assert_with_message( spy, doublex.property_set('prop'), expected_message) def test_unexpected_set(self): expected_message = ''' Expected: none of these calls: set ObjCollaborator.prop to ANYTHING but: calls that actually ocurred were: set ObjCollaborator.prop to unexpected ''' spy = doublex.Spy(ObjCollaborator) spy.prop = 'unexpected' self.assert_with_message( spy, doublex.never(doublex.property_set('prop')), expected_message) doublex-1.8.2/doublex/test/unit_tests.py0000644000175000017500000014725312435722065017456 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import sys import itertools import threading import thread if sys.version_info >= (2, 7): from unittest import TestCase else: from unittest2 import TestCase if sys.version_info >= (3, 0): unicode = str from io import StringIO else: from io import BytesIO as StringIO from hamcrest import is_not, all_of, contains_string, has_length, has_entry, starts_with from hamcrest.library.text.stringcontainsinorder import * from hamcrest.library.object.hasproperty import * from hamcrest.library.number.ordering_comparison import * from doublex import * from doublex.matchers import MatcherRequiredError from doublex.internal import InvocationContext class InvocationContextTests(TestCase): def test_order(self): c1 = InvocationContext(1) c2 = InvocationContext(2) contexts = [c2, c1] contexts.sort() assert_that(contexts[0], is_(c1)) def test_order_ANY_ARG(self): c1 = InvocationContext(1) c2 = InvocationContext(ANY_ARG) contexts = [c2, c1] contexts.sort() assert_that(contexts[0], is_(c1)) class FreeStubTests(TestCase): def setUp(self): self.stub = Stub() def test_record_invocation(self): with self.stub: self.stub.foo().returns(2) assert_that(self.stub.foo(), is_(2)) def test_using_alias_in_context(self): with self.stub as stub: stub.foo().returns(2) assert_that(self.stub.foo(), is_(2)) def test_creating_double_with_context(self): with Stub() as stub: stub.foo().returns(2) assert_that(stub.foo(), is_(2)) def test_record_invocation_with_args(self): with self.stub: self.stub.foo(1, param='hi').returns(2) assert_that(self.stub.foo(1, param='hi'), is_(2)) def test_record_invocation_with_wrong_args_returns_None(self): with self.stub: self.stub.foo(1, param='hi').returns(2) assert_that(self.stub.foo(1, param='wrong'), is_(None)) def test_not_stubbed_method_returns_None(self): with self.stub: self.stub.foo().returns(True) assert_that(self.stub.unknown(), is_(None)) def test_returns_input(self): with Stub() as stub: stub.foo(1).returns_input() assert_that(stub.foo(1), is_(1)) # new on 1.8.2 def test_returns_input_two_args(self): with Stub() as stub: stub.foo(ANY_ARG).returns_input() assert_that(stub.foo(1, 2), is_((1, 2))) def test_raises(self): with self.stub: self.stub.foo(2).raises(SomeException) try: self.stub.foo(2) self.fail("It should raise SomeException") except SomeException: pass class StubTests(TestCase): def setUp(self): self.stub = Stub(Collaborator) def test_stubbing_a_existing_method(self): with self.stub: self.stub.hello().returns("bye") assert_that(self.stub.hello(), is_("bye")) def test_from_instance(self): stub = Stub(Collaborator()) with stub: stub.hello().returns("bye") assert_that(stub.hello(), is_("bye")) def test_stubbing_a_unexisting_method_raises_error(self): try: with self.stub: self.stub.wrong().returns("bye") except AttributeError as e: expected = "'Collaborator' object has no attribute 'wrong'" assert_that(str(e), contains_string(expected)) def test_stubbing_with_wrong_args_raises_error(self): try: with self.stub: self.stub.hello(1).returns("bye") except TypeError as e: expected = "hello() takes exactly 1 argument (2 given)" if sys.version_info >= (3,): expected = "hello() takes exactly 1 positional argument (2 given)" if sys.version_info >= (3, 3): expected = "hello() takes 1 positional argument but 2 were given" assert_that(str(e), contains_string(expected)) # bitbucket issue #6 def test_keyword_or_positional(self): with self.stub: self.stub.kwarg_method(1).returns(1000) self.stub.kwarg_method(2).returns(2000) self.stub.kwarg_method(key_param=6).returns(6000) assert_that(self.stub.kwarg_method(1), is_(1000)) assert_that(self.stub.kwarg_method(2), is_(2000)) assert_that(self.stub.kwarg_method(key_param=6), is_(6000)) assert_that(self.stub.kwarg_method(key_param=6), is_(6000)) # new on 1.7 def test_keyworked_or_positional_are_equivalent(self): with self.stub: self.stub.kwarg_method(1).returns(1000) self.stub.kwarg_method(key_param=6).returns(6000) assert_that(self.stub.kwarg_method(1), is_(1000)) assert_that(self.stub.kwarg_method(key_param=1), is_(1000)) assert_that(self.stub.kwarg_method(6), is_(6000)) assert_that(self.stub.kwarg_method(key_param=6), is_(6000)) def test_last_stubbed_method_prevails(self): with self.stub: self.stub.hello().returns("hi!") with self.stub: self.stub.hello().returns("bye!") assert_that(self.stub.hello(), is_("bye!")) def test_last_stubbed_method_prevails_same_with(self): with self.stub: self.stub.hello().returns("hi!") self.stub.hello().returns("bye!") assert_that(self.stub.hello(), is_("bye!")) def test_returning_tuple(self): with self.stub: self.stub.hello().returns((3, 4)) assert_that(self.stub.hello(), is_((3, 4))) class AccessingActualAttributes(TestCase): def test_read_class_attribute_providing_class(self): stub = Stub(Collaborator) assert_that(stub.class_attr, is_("OK")) def test_read_class_attribute_providing_instance(self): stub = Stub(Collaborator()) assert_that(stub.class_attr, is_("OK")) # New in 1.6.5 def test_proxyspy_read_instance_attribute(self): stub = Stub(Collaborator()) assert_that(stub.instance_attr, is_(300)) class AdhocAttributesTests(TestCase): "all doubles accepts ad-hoc attributes" def test_add_attribute_for_free_stub(self): sut = Stub() sut.adhoc = 1 def test_add_attribute_for_verified_stub(self): sut = Stub(Collaborator) sut.adhoc = 1 def test_add_attribute_for_free_spy(self): sut = Spy() sut.adhoc = 1 def test_add_attribute_for_verified_spy(self): sut = Spy(Collaborator) sut.adhoc = 1 def test_add_attribute_for_proxyspy(self): sut = ProxySpy(Collaborator()) sut.adhoc = 1 def test_add_attribute_for_free_mock(self): sut = Mock() sut.adhoc = 1 def test_add_attribute_for_verified_mock(self): sut = Mock(Collaborator) sut.adhoc = 1 class FreeSpyTests(TestCase): def setUp(self): self.spy = Spy() def test_simple_invocation(self): self.spy.foo() def test_called(self): self.spy.foo() assert_that(self.spy.foo, called()) def test_not_called(self): self.spy.foo() assert_that(self.spy.bar, is_not(called())) def test_called_2_times(self): self.spy.foo() self.spy.foo() assert_that(self.spy.foo, called().times(2)) assert_that(self.spy.foo, is_not(called().times(1))) assert_that(self.spy.foo, is_not(called().times(3))) def test_called_without_args(self): self.spy.foo() assert_that(self.spy.foo, called().with_args()) def test_called_with_None(self): self.spy.foo(None) assert_that(self.spy.foo, called().with_args(None)) assert_that(self.spy.foo, is_not(called().with_args())) def test_not_called_without_args(self): self.spy.foo(1) assert_that(self.spy.foo, is_not(called().with_args())) def test_called_with_specified_args(self): self.spy.foo(1) assert_that(self.spy.foo, called().with_args(1)) def test_not_called_with_specified_args(self): self.spy.foo() self.spy.foo(2) assert_that(self.spy.foo, is_not(called().with_args(1))) def test_mixed_args(self): self.spy.send_mail('hi') self.spy.send_mail('foo@bar.net') assert_that(self.spy.send_mail, called()) assert_that(self.spy.send_mail, called().times(2)) assert_that(self.spy.send_mail, called().with_args('foo@bar.net')) def test_called_with_several_types_and_kargs(self): self.spy.foo(3.0, [1, 2], 'hi', color='red', width=10) assert_that(self.spy.foo, called().with_args( 3.0, [1, 2], 'hi', color='red', width=10)) assert_that(self.spy.foo, called().with_args( 3.0, [1, 2], 'hi', width=10, color='red')) assert_that(self.spy.foo, is_not(called().with_args( [1, 2], 'hi', width=10, color='red'))) assert_that(self.spy.foo, is_not(called().with_args( [1, 2], 3.0, 'hi', width=10, color='red'))) def test_called_with_args_and_times(self): self.spy.foo(1) self.spy.foo(1) self.spy.foo(2) assert_that(self.spy.foo, called().with_args(1).times(2)) assert_that(self.spy.foo, called().with_args(2)) assert_that(self.spy.foo, called().times(3)) # def test_called_anything_and_value(self): # spy = Spy(Collaborator) # spy.two_args_method(10, 20) # assert_that(spy.two_args_method, called().with_args(anything(), 20)) # # def test_called_name_arg_value(self): # spy = Spy(Collaborator) # spy.two_args_method(10, 20) # assert_that(spy.two_args_method, called().with_args(arg2=20)) # # def test_called_karg(self): # spy = Spy(Collaborator) # spy.mixed_method(2, True) # assert_that(spy.mixed_method, called().with_args(key_param=True)) class Spy_calls_tests(TestCase): def test_list_recorded_calls(self): class Collaborator: def method(self, *args, **kargs): pass with Spy(Collaborator) as spy: spy.method(ANY_ARG).returns(100) spy.method(1, 2, 3) spy.method(key=2, val=5) assert_that(spy.method.calls[0].args, is_((1, 2, 3))) assert_that(spy.method.calls[1].kargs, is_(dict(key=2, val=5))) assert_that(spy.method.calls[1].retval, is_(100)) def test_called_with_an_object(self): class Module: def getName(self): return "Module" class Visitor: def visitModule(self, m): pass class Parser: def __init__(self, visitor): self.visitor = visitor def accept(self, visitor): self.visitor.visitModule(Module()) visitor = Spy(Visitor) parser = Parser(visitor) parser.accept(visitor) assert_that(visitor.visitModule.calls[0].args[0].getName(), is_("Module")) class SpyTests(TestCase): def setUp(self): self.spy = Spy(Collaborator) def test_from_instance(self): spy = Spy(Collaborator()) spy.hello() assert_that(spy.hello, called()) def test_call_unexisting_method(self): try: self.spy.wrong() self.fail('AttributeError should be raised') except AttributeError as e: expected = "'Collaborator' object has no attribute 'wrong'" assert_that(str(e), contains_string(expected)) def test_check_unexisting_method(self): try: assert_that(self.spy.wrong, called()) self.fail('AttributeError should be raised') except AttributeError as e: expected = "'Collaborator' object has no attribute 'wrong'" assert_that(str(e), contains_string(expected)) def test_create_from_oldstyle_class(self): Spy(Collaborator) def test_create_from_newstyle_class(self): Spy(ObjCollaborator) def test_wrong_call_args(self): self.spy.hello() with self.assertRaises(TypeError): assert_that(self.spy.hello, called().with_args('some')) class BuiltinSpyTests(TestCase): def test_builtin_method(self): spy = Spy(list) spy.append(10) assert_that(spy.append, called().with_args(10)) def test_builtin_method_wrong_num_args(self): spy = Spy(list) try: spy.append(10, 20) self.fail('AttributeError should be raised') except TypeError as e: expected = "list.append() takes exactly 1 argument (2 given)" assert_that(str(e), contains_string(expected)) def test_wrong_builtin_method(self): spy = Spy(list) try: spy.wrong(10) self.fail('AttributeError should be raised') except AttributeError as e: expected = "'list' object has no attribute 'wrong'" assert_that(str(e), contains_string(expected)) def test_dict_builtin_method(self): spy = Spy(dict) spy.__setitem__(3, 5) assert_that(spy.__setitem__, called().with_args(3, 5)) class ProxySpyTests(TestCase): def test_must_give_argument(self): with self.assertRaises(TypeError): ProxySpy() def test_given_argument_can_not_be_oldstyle_class(self): with self.assertRaises(TypeError): ProxySpy(Collaborator) def test_given_argument_can_not_be_newstyle_class(self): with self.assertRaises(TypeError): ProxySpy(ObjCollaborator) def test_propagate_stubbed_calls_to_collaborator(self): class Foo: def __init__(self): self.value = 0 def store_add(self, value): self.value = value return -value foo = Foo() with ProxySpy(foo) as spy: spy.store_add(3).returns(1000) assert_that(spy.store_add(2), is_(-2)) assert_that(foo.value, is_(2)) assert_that(spy.store_add(3), is_(1000)) assert_that(foo.value, is_(3)) class MockTests(TestCase): def test_with_args(self): mock = Mock() with mock: mock.hello(1) mock.bye(2) mock.bye(3) mock.hello(1) mock.bye(2) mock.bye(3) assert_that(mock, verify()) def test_with_several_args(self): mock = Mock() with mock: mock.hello(1, 1) mock.bye(2, 2) mock.bye(3, 3) mock.hello(1, 1) mock.bye(2, 2) mock.bye(3, 3) assert_that(mock, verify()) def test_with_kargs(self): mock = Mock() with mock: mock.hello(1, name=1) mock.bye(2, value=2) mock.bye(3, value=3) mock.hello(1, name=1) mock.bye(2, value=2) mock.bye(3, value=3) assert_that(mock, verify()) def test_from_instance(self): mock = Mock(Collaborator()) with mock: mock.hello() mock.hello() assert_that(mock, verify()) class MockOrderTests(TestCase): def setUp(self): self.mock = Mock() def test_order_matters__ok(self): with self.mock: self.mock.foo() self.mock.bar() self.mock.foo() self.mock.bar() assert_that(self.mock, verify()) def test_order_matters__fail(self): with self.mock: self.mock.foo() self.mock.bar() self.mock.bar() self.mock.foo() with self.assertRaises(AssertionError): assert_that(self.mock, verify()) def test_method_name_order_does_not_matter_with_any_order(self): with self.mock: self.mock.foo() self.mock.bar() self.mock.bar() self.mock.foo() assert_that(self.mock, any_order_verify()) def test_args_order_does_not_matter_with_any_order(self): with self.mock: self.mock.foo(2) self.mock.foo(1) self.mock.foo(1) self.mock.foo(2) assert_that(self.mock, any_order_verify()) def test_kwargs_order_does_not_matter_with_any_order(self): with self.mock: self.mock.foo(1, key='a') self.mock.foo(1, key='b') self.mock.foo(1, key='b') self.mock.foo(1, key='a') assert_that(self.mock, any_order_verify()) def test_several_args_with_any_order(self): with self.mock: self.mock.foo(2, 2) self.mock.bar(1) self.mock.foo(1, 1) self.mock.bar(2) self.mock.foo(1, 1) self.mock.bar(1) self.mock.foo(2, 2) self.mock.bar(2) assert_that(self.mock, any_order_verify()) def test_several_args_with_matcher_any_order(self): with self.mock: self.mock.foo(2, anything()) self.mock.bar(1) self.mock.foo(1, anything()) self.mock.bar(2) self.mock.foo(1, 1) self.mock.bar(1) self.mock.foo(2, 2) self.mock.bar(2) assert_that(self.mock, any_order_verify()) class DisplayResultsTests(TestCase): def setUp(self): with Spy() as self.empty_spy: self.empty_spy.foo(ANY_ARG).returns(True) with Spy(Collaborator) as self.spy: self.spy.method_one(ANY_ARG).returns(2) def test_empty_spy_stub_method(self): assert_that(self.empty_spy.foo._show_history(), reason="method 'Spy.foo' never invoked") def test_spy_stub_method(self): assert_that(self.spy.method_one._show_history(), reason="method 'Collaborator.method_one' never invoked") def test_empty_spy_stub_method_invoked(self): self.empty_spy.foo() expected = [ "method 'Spy.foo' was invoked", "foo()"] assert_that(self.empty_spy.foo._show_history(), string_contains_in_order(*expected)) def test_spy_stub_method_invoked(self): self.spy.method_one(1) expected = [ "method 'Collaborator.method_one' was invoked", 'method_one(1)'] assert_that(self.spy.method_one._show_history(), string_contains_in_order(*expected)) def test_empty_spy_non_stubbed_method_invoked(self): self.empty_spy.bar(1, 3.0, "text", key1="text", key2=[1, 2]) expected = [ "method 'Spy.bar' was invoked", "bar(1, 3.0, 'text', key1='text', key2=[1, 2])"] assert_that(self.empty_spy.bar._show_history(), string_contains_in_order(*expected)) def test_spy_several_invoked_same_method(self): self.spy.mixed_method(5, True) self.spy.mixed_method(8, False) expected = "method 'Collaborator.mixed_method' was invoked" assert_that(self.spy.mixed_method._show_history(), contains_string(expected)) class FrameworApiTest(TestCase): def test_called_requires_spy(self): stub = Stub() try: assert_that(stub.method, called()) self.fail('exception should be raised') except WrongApiUsage as e: assert_that(str(e), contains_string('takes a spy method (got')) class ApiMismatchTest(TestCase): def setUp(self): self.spy = Spy(Collaborator) def test_default_params(self): self.spy.mixed_method(1) def test_give_karg(self): self.spy.mixed_method(1, key_param=True) def test_give_karg_without_key(self): self.spy.mixed_method(1, True) def test_fail_missing_method(self): try: self.spy.missing() self.fail("TypeError should be raised") except AttributeError as e: expected = "'Collaborator' object has no attribute 'missing'" assert_that(str(e), contains_string(expected)) def test_fail_wrong_args(self): try: self.spy.hello("wrong") self.fail("TypeError should be raised") except TypeError as e: expected = "Collaborator.hello() takes exactly 1 argument (2 given)" if sys.version_info >= (3,): expected = "Collaborator.hello() takes exactly 1 positional argument (2 given)" if sys.version_info >= (3, 3): expected = "hello() takes 1 positional argument but 2 were given" assert_that(str(e), contains_string(expected)) def test_fail_wrong_kargs(self): try: self.spy.kwarg_method(wrong_key=1) self.fail("TypeError should be raised") except TypeError as e: expected = "Collaborator.kwarg_method() got an unexpected keyword argument 'wrong_key'" assert_that(str(e), contains_string(expected)) class ANY_ARG_StubTests(TestCase): def setUp(self): self.stub = Stub() def test_any_args(self): with self.stub: self.stub.foo(ANY_ARG).returns(True) assert_that(self.stub.foo(), is_(True)) assert_that(self.stub.foo(1), is_(True)) assert_that(self.stub.foo(key1='a'), is_(True)) assert_that(self.stub.foo(1, 2, 3, key1='a', key2='b'), is_(True)) def test_fixed_args_and_any_args(self): with self.stub: self.stub.foo(1, ANY_ARG).returns(True) assert_that(self.stub.foo(1, 2, 3), is_(True)) assert_that(self.stub.foo(1, key1='a'), is_(True)) def test_ANY_ARG_must_be_last_positional_argument(self): with self.assertRaises(WrongApiUsage): with self.stub: self.stub.method(1, ANY_ARG, 3).returns(True) class ANY_ARG_SpyTests(TestCase): def setUp(self): self.spy = Spy() def test_no_args(self): self.spy.foo() assert_that(self.spy.foo, called().with_args(ANY_ARG)) assert_that(self.spy.foo, never(called().with_args(anything()))) def test_one_arg(self): self.spy.foo(1) assert_that(self.spy.foo, called()) assert_that(self.spy.foo, called().with_args(ANY_ARG)) assert_that(self.spy.foo, called().with_args(anything())) def test_one_karg(self): self.spy.foo(key='val') assert_that(self.spy.foo, called().with_args(ANY_ARG)) def test_three_args(self): self.spy.foo(1, 2, 3) assert_that(self.spy.foo, called().with_args(1, ANY_ARG)) assert_that(self.spy.foo, never(called().with_args(2, ANY_ARG))) def test_args_and_kargs(self): self.spy.foo(1, 2, 3, key1='a', key2='b') assert_that(self.spy.foo, called().with_args(1, ANY_ARG)) assert_that(self.spy.foo, never(called().with_args(2, ANY_ARG))) def test__called__and__called_with_args__ANY_ARGS_is_the_same(self): self.spy.foo() self.spy.foo(3) self.spy.foo('hi') self.spy.foo(None) assert_that(self.spy.foo, called().times(4)) assert_that(self.spy.foo, called().with_args(ANY_ARG).times(4)) # issue 9 def test_ANY_ARG_forbbiden_as_keyword_value(self): person = Spy() person.set_info(name="John", surname="Doe") assert_that(person.set_info, called().with_args(name=anything(), surname="Doe")) with self.assertRaises(WrongApiUsage): assert_that(person.set_info, called().with_args(name=ANY_ARG, surname="Doe")) def test_ANY_ARG_must_be_last_positional_argument(self): self.spy.method(1, 2, 3) with self.assertRaises(WrongApiUsage): assert_that(self.spy.method, called().with_args(1, ANY_ARG, 3)) def test_ANY_ARG_must_be_last_positional_argument_with_xarg(self): self.spy.method(1, 2, 3, name='Bob') with self.assertRaises(WrongApiUsage): assert_that(self.spy.method, called().with_args(1, ANY_ARG, name='Bob')) def test_ANY_ARG_must_be_last_positional_argument__restricted_spy(self): spy = Spy(Collaborator) with self.assertRaises(WrongApiUsage): assert_that(spy.two_args_method, called().with_args(ANY_ARG, 2)) with self.assertRaises(WrongApiUsage): assert_that(spy.three_args_method, called().with_args(1, ANY_ARG, 3)) class MatcherTests(TestCase): def setUp(self): self.spy = Spy() def test_check_has_length(self): self.spy.foo("abcd") assert_that(self.spy.foo, called().with_args(has_length(4))) assert_that(self.spy.foo, called().with_args(has_length(greater_than(3)))) assert_that(self.spy.foo, called().with_args(has_length(less_than(5)))) assert_that(self.spy.foo, is_not(called().with_args(has_length(greater_than(5))))) def test_stub_has_length(self): with self.spy: self.spy.foo(has_length(less_than(4))).returns('<4') self.spy.foo(has_length(4)).returns('four') self.spy.foo( has_length( all_of(greater_than(4), less_than(8)))).returns('48') assert_that(self.spy.foo((1, 2)), is_('<4')) assert_that(self.spy.foo('abcd'), is_('four')) assert_that(self.spy.foo('abcde'), is_('48')) def test_stub_contains_string(self): with Stub() as stub: stub.method(contains_string("some")).returns(1000) assert_that(stub.method("awesome"), is_(1000)) # doc FIXME: assure this is tested with doctests and remove def test_times_arg_may_be_matcher(self): self.spy.foo() self.spy.foo(1) self.spy.foo(1) self.spy.foo(2) assert_that(self.spy.never, is_not(called())) # = 0 times assert_that(self.spy.foo, called()) # > 0 assert_that(self.spy.foo, called().times(greater_than(0))) # > 0 (same) assert_that(self.spy.foo, called().times(4)) # = 4 assert_that(self.spy.foo, called().times(greater_than(2))) # > 2 assert_that(self.spy.foo, called().times(less_than(6))) # < 6 assert_that(self.spy.foo, is_not(called().with_args(5))) # = 0 times assert_that(self.spy.foo, called().with_args().times(1)) # = 1 assert_that(self.spy.foo, called().with_args(anything())) # > 0 assert_that(self.spy.foo, called().with_args(ANY_ARG).times(4)) # = 4 assert_that(self.spy.foo, called().with_args(1).times(2)) # = 2 assert_that(self.spy.foo, called().with_args(1).times(greater_than(1))) # > 1 assert_that(self.spy.foo, called().with_args(1).times(less_than(5))) # < 5 # doc FIXME: assure this is tested with doctests and remove def test_called_args(self): self.spy.m1() self.spy.m2(None) self.spy.m3(2) self.spy.m4("hi", 3.0) self.spy.m5([1, 2]) self.spy.m6(name="john doe") assert_that(self.spy.m1, called()) assert_that(self.spy.m2, called()) assert_that(self.spy.m1, called().with_args()) assert_that(self.spy.m2, called().with_args(None)) assert_that(self.spy.m3, called().with_args(2)) assert_that(self.spy.m4, called().with_args("hi", 3.0)) assert_that(self.spy.m5, called().with_args([1, 2])) assert_that(self.spy.m6, called().with_args(name="john doe")) assert_that(self.spy.m3, called().with_args(less_than(3))) assert_that(self.spy.m3, called().with_args(greater_than(1))) assert_that(self.spy.m6, called().with_args(name=contains_string("doe"))) # new on 1.7 def test_assert_that_requires_a_matcher(self): self.assertRaises(MatcherRequiredError, assert_that, self.spy.m1, True) # from pydoubles docs def test_has_entry_matcher(self): with Spy() as spy: spy.one_arg_method(has_entry(is_('two'), 2)).returns(1000) assert_that(spy.one_arg_method({'one': 1, 'two': 2}), is_(1000)) def test_all_of_matcher(self): with Spy() as spy: spy.one_arg_method(all_of(starts_with('h'), instance_of(str))).returns(1000) assert_that(spy.one_arg_method('hello'), is_(1000)) class StubObserverTests(TestCase): def setUp(self): self.stub = Stub() def test_observer_called(self): observer = Observer() self.stub.foo.attach(observer.update) self.stub.foo(2) assert_that(observer.state, is_(2)) def test_observer_called_tested_using_a_doublex_spy(self): observer = Spy() self.stub.foo.attach(observer.update) self.stub.foo(2) assert_that(observer.update, called().with_args(2)) class StubDelegateTests(TestCase): def setUp(self): self.stub = Stub() def assert_012(self, method): for x in range(3): assert_that(method(), is_(x)) def test_delegate_to_other_method(self): with self.stub: self.stub.foo().delegates(Collaborator().hello) assert_that(self.stub.foo(), is_("hello")) def test_delegate_to_list(self): with self.stub: self.stub.foo().delegates(list(range(3))) self.assert_012(self.stub.foo) def test_delegate_to_generator(self): with self.stub: self.stub.foo().delegates(x for x in range(3)) self.assert_012(self.stub.foo) def test_delegate_to_count(self): with self.stub: self.stub.foo().delegates(itertools.count()) self.assert_012(self.stub.foo) def test_delegate_to_lambda(self): with self.stub: self.stub.foo().delegates(lambda: 2) assert_that(self.stub.foo(), is_(2)) def test_delegate_to_another_stub(self): stub2 = Stub() with stub2: stub2.bar().returns("hi!") with self.stub: self.stub.foo().delegates(stub2.bar) assert_that(self.stub.foo(), is_("hi!")) def test_not_delegable_object(self): try: with self.stub: self.stub.foo().delegates(None) self.fail("Exception should be raised") except WrongApiUsage as e: expected = "delegates() must be called with callable or iterable instance (got 'None' instead)" assert_that(str(e), contains_string(expected)) # FIXME: explain in docs def test_delegates_with_params(self): with self.stub: self.stub.foo(anything()).delegates(lambda x: x + 2) assert_that(self.stub.foo(3), is_(5)) # new on 1.8.2 # FIXME: include in docs def test_delegate_to_dict(self): with self.stub: self.stub.foo(anything()).delegates({0: 2, 1: 7, 2: 12}) assert_that(self.stub.foo(1), is_(7)) class MockDelegateTest(TestCase): def setUp(self): self.mock = Mock() def assert_012(self, method): for x in range(3): assert_that(method(), is_(x)) def test_delegate_to_list_is_only_an_expectation(self): with self.mock: self.mock.foo().delegates(list(range(3))) self.mock.foo() assert_that(self.mock, verify()) class MimicTests(TestCase): class A(object): def method_a(self, n): return n + 1 class B(A): def method_b(self): return "hi" def test_normal_spy_does_not_inherit_collaborator_superclasses(self): spy = Spy(self.B) assert_that(not isinstance(spy, self.B)) def test_mimic_spy_DOES_inherit_collaborator_superclasses(self): spy = Mimic(Spy, self.B) for cls in [self.B, self.A, Spy, Stub, object]: assert_that(spy, instance_of(cls)) def test_mimic_stub_works(self): stub = Mimic(Stub, self.B) with stub: stub.method_a(2).returns(3) assert_that(stub.method_a(2), is_(3)) def test_mimic_stub_from_instance(self): stub = Mimic(Stub, self.B()) with stub: stub.method_a(2).returns(3) assert_that(stub.method_a(2), is_(3)) def test_mimic_spy_works(self): spy = Mimic(Spy, self.B) with spy: spy.method_a(5).returns(True) assert_that(spy.method_a(5), is_(True)) assert_that(spy.method_a, called()) assert_that(spy.method_a, called().with_args(5)) def test_mimic_proxy_spy_works(self): spy = Mimic(ProxySpy, self.B()) assert_that(spy.method_a(5), is_(6)) assert_that(spy.method_a, called()) assert_that(spy.method_a, called().with_args(5)) def test_mimic_mock_works(self): mock = Mimic(Mock, self.B) with mock: mock.method_a(2) mock.method_a(2) assert_that(mock, verify()) class PropertyTests(TestCase): def test_stub_notset_property_is_None(self): stub = Stub(ObjCollaborator) assert_that(stub.prop, is_(None)) def test_stub_property(self): stub = Stub(ObjCollaborator) with stub: stub.prop = 2 assert_that(stub.prop, is_(2)) def test_spy_get_property_using_class(self): spy = Spy(ObjCollaborator) skip = spy.prop assert_that(spy, property_got('prop')) def test_spy_get_property_using_instance(self): spy = Spy(ObjCollaborator()) skip = spy.prop assert_that(spy, property_got('prop')) def test_spy_not_get_property(self): spy = Spy(ObjCollaborator) assert_that(spy, never(property_got('prop'))) def test_spy_get_property_fail(self): spy = Spy(ObjCollaborator) with self.assertRaises(AssertionError): assert_that(spy, property_got('prop')) def test_spy_set_property_using_class(self): spy = Spy(ObjCollaborator) spy.prop = 2 assert_that(spy, property_set('prop')) def test_spy_set_property_using_instance(self): spy = Spy(ObjCollaborator()) spy.prop = 2 assert_that(spy, property_set('prop')) def test_spy_not_set_property(self): spy = Spy(ObjCollaborator) assert_that(spy, never(property_set('prop'))) def test_spy_set_property_fail(self): spy = Spy(ObjCollaborator) with self.assertRaises(AssertionError): assert_that(spy, property_set('prop')) def test_spy_set_property_to(self): spy = Spy(ObjCollaborator) spy.prop = 2 assert_that(spy, property_set('prop').to(2)) assert_that(spy, never(property_set('prop').to(5))) def test_spy_set_property_times(self): spy = Spy(ObjCollaborator) spy.prop = 2 spy.prop = 3 assert_that(spy, property_set('prop').to(2)) assert_that(spy, property_set('prop').to(3)) assert_that(spy, property_set('prop').times(2)) def test_spy_set_property_to_times(self): spy = Spy(ObjCollaborator) spy.prop = 3 spy.prop = 3 assert_that(spy, property_set('prop').to(3).times(2)) def test_properties_are_NOT_shared_among_doubles(self): stub1 = Stub(ObjCollaborator) stub2 = Stub(ObjCollaborator) stub1.prop = 1000 assert_that(stub2.prop, is_not(1000)) assert_that(stub1.__class__ is not stub2.__class__) def test_spy_get_readonly_property_with_deco(self): spy = Spy(ObjCollaborator) skip = spy.prop_deco_readonly assert_that(spy, property_got('prop_deco_readonly')) def test_spy_SET_readonly_property_with_deco(self): spy = Spy(ObjCollaborator) try: spy.prop_deco_readonly = 'wrong' self.fail('should raise exception') except AttributeError: pass def test_hamcrest_matchers(self): spy = Spy(ObjCollaborator) spy.prop = 2 spy.prop = 3 assert_that(spy, property_set('prop').to(greater_than(1)). times(less_than(3))) def test_proxyspy_get_actual_property(self): collaborator = ObjCollaborator() sut = ProxySpy(collaborator) assert_that(sut.prop, is_(1)) def test_proxyspy_get_stubbed_property(self): collaborator = ObjCollaborator() with ProxySpy(collaborator) as sut: sut.prop = 2 assert_that(sut.prop, is_(2)) def test_proxyspy_set_property(self): collaborator = ObjCollaborator() sut = ProxySpy(collaborator) sut.prop = 20 assert_that(sut.prop, is_(20)) assert_that(collaborator.prop, is_(20)) # new on 1.8 class PropertyMockTests(TestCase): def test_mock_get(self): with Mock(ObjCollaborator) as mock: mock.prop mock.prop assert_that(mock, verify()) def test_mock_get_but_never_got(self): with Mock(ObjCollaborator) as mock: mock.prop with self.assertRaises(AssertionError): assert_that(mock, verify()) def test_mock_get_too_many_times(self): with Mock(ObjCollaborator) as mock: mock.prop mock.prop mock.prop with self.assertRaises(AssertionError): assert_that(mock, verify()) def test_mock_set(self): with Mock(ObjCollaborator) as mock: mock.prop = 5 mock.prop = 5 assert_that(mock, verify()) def test_mock_set_but_never_set(self): with Mock(ObjCollaborator) as mock: mock.prop = 5 with self.assertRaises(AssertionError): assert_that(mock, verify()) def test_mock_set_too_many_times(self): with Mock(ObjCollaborator) as mock: mock.prop = 5 mock.prop = 5 mock.prop = 5 with self.assertRaises(AssertionError): assert_that(mock, verify()) def test_mock_set_wrong_value(self): with Mock(ObjCollaborator) as mock: mock.prop = 5 with self.assertRaises(AssertionError): mock.prop = 8 def test_mock_set_anything(self): with Mock(ObjCollaborator) as mock: mock.prop = anything() mock.prop = 5 assert_that(mock, verify()) def test_mock_set_matcher(self): with Mock(ObjCollaborator) as mock: mock.prop = all_of(greater_than(8), less_than(12)) mock.prop = 10 assert_that(mock, verify()) class AsyncTests(TestCase): class SUT(object): def __init__(self, collaborator): self.collaborator = collaborator def send_data(self, data=0): thread.start_new_thread(self.collaborator.write, (data,)) def test_spy_call_without_async_feature(self): # given barrier = threading.Event() with Spy() as spy: spy.write.attach(lambda *args: barrier.set) sut = AsyncTests.SUT(spy) # when sut.send_data() barrier.wait(1) # test probably FAILS without this # then assert_that(spy.write, called()) def test_spy_call_with_async_feature(self): # given spy = Spy() sut = AsyncTests.SUT(spy) # when sut.send_data() # then assert_that(spy.write, called().async(timeout=1)) def test_spy_async_support_1_call_only(self): # given spy = Spy() sut = AsyncTests.SUT(spy) # when sut.send_data(3) sut.send_data(3) # then with self.assertRaises(WrongApiUsage): assert_that(spy.write, called().async(timeout=1).with_args(3).times(2)) def test_spy_async_stubbed(self): # given with Spy() as spy: spy.write(ANY_ARG).returns(100) sut = AsyncTests.SUT(spy) # when sut.send_data(3) # then assert_that(spy.write, called().async(timeout=1)) # new on 1.7 class with_some_args_matcher_tests(TestCase): def test_one_arg(self): spy = Spy(Collaborator) spy.mixed_method(5) assert_that(spy.mixed_method, called().with_args(5)) assert_that(spy.mixed_method, called().with_args(arg1=5)) def test_two_arg(self): spy = Spy(Collaborator) spy.two_args_method(5, 10) assert_that(spy.two_args_method, called().with_args(5, 10)) assert_that(spy.two_args_method, called().with_args(arg1=5, arg2=10)) assert_that(spy.two_args_method, called().with_some_args(arg1=5)) assert_that(spy.two_args_method, called().with_some_args(arg2=10)) assert_that(spy.two_args_method, called().with_some_args()) def test_free_spy(self): spy = Spy() spy.foo(1, 3) with self.assertRaises(WrongApiUsage): assert_that(spy.foo, called().with_some_args()) # new on 1.7 class Stub_default_behavior_tests(TestCase): def test_set_return_globally(self): StubClone = Stub._clone_class() set_default_behavior(StubClone, method_returning(20)) stub = StubClone() assert_that(stub.unknown(), is_(20)) def test_set_exception_globally(self): StubClone = Stub._clone_class() set_default_behavior(StubClone, method_raising(SomeException)) stub = StubClone() with self.assertRaises(SomeException): stub.unknown() def test_set_return_by_instance(self): stub = Stub() set_default_behavior(stub, method_returning(20)) assert_that(stub.unknown(), is_(20)) def test_set_exception_by_instance(self): stub = Stub() set_default_behavior(stub, method_raising(SomeException)) with self.assertRaises(SomeException): stub.unknown() def test_restricted_stub(self): stub = Stub(Collaborator) set_default_behavior(stub, method_returning(30)) with stub: stub.hello().returns(1000) assert_that(stub.something(), is_(30)) assert_that(stub.hello(), is_(1000)) # new on 1.7 class Spy_default_behavior_tests(TestCase): def test_set_return_globally(self): SpyClone = Spy._clone_class() set_default_behavior(SpyClone, method_returning(20)) spy = SpyClone() assert_that(spy.unknown(7), is_(20)) assert_that(spy.unknown, called().with_args(7)) assert_that(spy.unknown, never(called().with_args(9))) def test_set_return_by_instance(self): spy = Spy() set_default_behavior(spy, method_returning(20)) assert_that(spy.unknown(7), is_(20)) assert_that(spy.unknown, called().with_args(7)) # new on 1.7 class ProxySpy_default_behavior_tests(TestCase): def test_this_change_proxyspy_default_behavior(self): spy = ProxySpy(Collaborator()) assert_that(spy.hello(), is_("hello")) set_default_behavior(spy, method_returning(40)) assert_that(spy.hello(), is_(40)) class orphan_spy_method_tests(TestCase): # new on 1.8.2 # issue 21 def test_spy(self): m = method_returning(3) m() assert_that(m, called()) # FIXME: new on tip class new_style_orphan_methods_tests(TestCase): def setUp(self): self.obj = Collaborator() def test_stub_method(self): with Stub() as stub: stub.method(1).returns(100) stub.method(2).returns(200) self.obj.foo = stub.method assert_that(self.obj.foo(0), is_(None)) assert_that(self.obj.foo(1), is_(100)) assert_that(self.obj.foo(2), is_(200)) def test_spy_method(self): with Spy() as spy: spy.method(1).returns(100) spy.method(2).returns(200) spy.method(3).raises(SomeException) self.obj.foo = spy.method assert_that(self.obj.foo(0), is_(None)) assert_that(self.obj.foo(1), is_(100)) assert_that(self.obj.foo(2), is_(200)) with self.assertRaises(SomeException): self.obj.foo(3) assert_that(self.obj.foo, called().times(4)) assert_that(spy.method, called().times(4)) # def test_spy_method__brief_method(self): # with method() as self.obj.foo: # self.obj.foo().returns(100) # self.obj.foo(2).returns(200) # # assert_that(self.obj.foo(), is_(100)) # assert_that(self.obj.foo(2), is_(200)) # assert_that(self.obj.foo(3), is_(None)) # # assert_that(self.obj.foo, called().times(3)) # assert_that(spy.method, called().times(3)) class custom_types_tests(TestCase): # issue 22 def test_custom_equality_comparable_objects(self): class A(object): def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value with Stub() as stub: stub.foo(A(1)).returns(A(1)) self.assertEquals(A(1), stub.foo(A(1))) class when_tests(TestCase): def test_stub_when(self): stub = Stub() when(stub).add(2, 2).returns(5) when(stub).add(2, 4).returns(8) when(stub).sub(3, ANY_ARG).returns(100) when(stub).foo(ANY_ARG).returns_input() when(stub).foo(anything(), 7).returns(300) assert_that(stub.add(2, 2), is_(5)) assert_that(stub.add(2, 4), is_(8)) assert_that(stub.sub(3, 600), is_(100)) assert_that(stub.foo((8, 2)), is_((8, 2))) assert_that(stub.foo(3, 7), is_(300)) assert_that(stub.add(), is_(None)) def test_stub_when_with_args(self): stub = Stub() when(stub).some_calculation(5).returns(10) when(stub).some_calculation(10).returns(20) assert_that(stub.some_calculation(5), is_(10)) def test_spy_when(self): spy = Spy() when(spy).add(2, 2).returns(5) when(spy).add(2, 4).returns(8) assert_that(spy.add(2, 2), is_(5)) assert_that(spy.add(2, 4), is_(8)) assert_that(spy.add(), is_(None)) # from pydoubles docs def test_has_entry_matcher(self): spy = Spy() when(spy).one_arg_method(has_entry(is_('two'), 2)).returns(1000) assert_that(spy.one_arg_method({'one': 1, 'two': 2}), is_(1000)) def test_all_of_matcher(self): spy = Spy() when(spy).one_arg_method(all_of(starts_with('h'), instance_of(str))).returns(1000) assert_that(spy.one_arg_method('hello'), is_(1000)) class expect_call_tests(TestCase): def test_expect_call(self): mock = Mock() expect_call(mock).add(2, 4) expect_call(mock).add(2, 2).returns(5) mock.add(2, 4) assert_that(mock.add(2, 2), is_(5)) assert_that(mock, verify()) def test_except_call_with_stub_or_spy_forbidden(self): with self.assertRaises(WrongApiUsage): expect_call(Stub()).foo() with self.assertRaises(WrongApiUsage): expect_call(Spy()).foo() # new on 1.7.2 class VarArgsTest(TestCase): def test_stub_args(self): stub = Stub(Collaborator) with stub: stub.varargs(1).returns(10) stub.varargs(1, 2).returns(200) stub.varargs(1, 3, ANY_ARG).returns(300) stub.varargs(2, anything()).returns(400) assert_that(stub.varargs(42), is_(None)) assert_that(stub.varargs(1), is_(10)) assert_that(stub.varargs(1, 2), is_(200)) assert_that(stub.varargs(1, 2, 7), is_(None)) assert_that(stub.varargs(1, 3), is_(300)) assert_that(stub.varargs(1, 3, 7), is_(300)) assert_that(stub.varargs(1, 5), is_(None)) assert_that(stub.varargs(2), is_(None)) assert_that(stub.varargs(2, 3), is_(400)) assert_that(stub.varargs(2, 3, 4), is_(None)) def test_spy_args(self): spy = Spy(Collaborator) spy.varargs(1, 2, 3) assert_that(spy.varargs, called()) assert_that(spy.varargs, called().with_args(1, 2, 3)) assert_that(spy.varargs, called().with_args(1, ANY_ARG)) def test_spy_kargs(self): spy = Spy(Collaborator) spy.varargs(one=1, two=2) assert_that(spy.varargs, called()) assert_that(spy.varargs, called().with_args(one=1, two=2)) assert_that(spy.varargs, called().with_args(one=1, two=anything())) def test_with_some_args_is_not_applicable(self): spy = Spy(Collaborator) spy.varargs(one=1, two=2) try: assert_that(spy.varargs, called().with_some_args(one=1)) self.fail('exception should be raised') except WrongApiUsage as e: assert_that(str(e), contains_string('with_some_args() can not be applied to method Collaborator.varargs(self, *args, **kargs)')) # new on 1.7.2 class TracerTests(TestCase): def setUp(self): self.out = StringIO() self.tracer = Tracer(self.out.write) def test_trace_single_method(self): with Stub() as stub: stub.foo(ANY_ARG).returns(1) self.tracer.trace(stub.foo) stub.foo(1, two=2) assert_that(self.out.getvalue(), is_("Stub.foo(1, two=2)")) def test_trace_single_non_stubbed_method(self): stub = Stub() self.tracer.trace(stub.non) stub.non(1, "two") assert_that(self.out.getvalue(), is_("Stub.non(1, 'two')")) def test_trace_all_double_INSTANCE_methods(self): stub = Stub() self.tracer.trace(stub) stub.bar(2, "three") assert_that(self.out.getvalue(), is_("Stub.bar(2, 'three')")) def test_trace_all_double_CLASS_methods(self): self.tracer.trace(Stub) stub = Stub() stub.fuzz(3, "four") assert_that(self.out.getvalue(), is_("Stub.fuzz(3, 'four')")) def test_trace_get_property(self): stub = Stub(ObjCollaborator) self.tracer.trace(stub) stub.prop assert_that(self.out.getvalue(), is_("ObjCollaborator.prop gotten")) def test_trace_set_property(self): stub = Stub(ObjCollaborator) self.tracer.trace(stub) stub.prop = 2 assert_that(self.out.getvalue(), is_("ObjCollaborator.prop set to 2")) class SomeException(Exception): pass class Observer(object): def __init__(self): self.state = None def update(self, *args, **kargs): self.state = args[0] class ObjCollaborator(object): def __init__(self): self._propvalue = 1 def no_args(self): return 1 def prop_getter(self): return self._propvalue def prop_setter(self, value): self._propvalue = value prop = property(prop_getter, prop_setter) @property def prop_deco_readonly(self): return 2 class Collaborator: """ The original object we double in tests """ class_attr = "OK" def __init__(self): self.instance_attr = 300 def hello(self): return "hello" def something(self): return "ok" def one_arg_method(self, arg1): return arg1 def two_args_method(self, arg1, arg2): return arg1 + arg2 def three_args_method(self, arg1, arg2, arg3): return arg1 + arg2 + arg3 def kwarg_method(self, key_param=False): return key_param def mixed_method(self, arg1, key_param=False): return key_param + arg1 def void_method(self): pass def method_one(self, arg1): return 1 def varargs(self, *args, **kargs): return len(args) alias_method = one_arg_method doublex-1.8.2/doublex/tracer.py0000644000175000017500000000302712435722065015544 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- from .doubles import Stub from .internal import Method, Property, WrongApiUsage class MethodTracer(object): def __init__(self, logger, method): self.logger = logger self.method = method def __call__(self, *args, **kargs): self.logger(str(self.method._create_invocation(args, kargs))) class PropertyTracer(object): def __init__(self, logger, prop): self.logger = logger self.prop = prop def __call__(self, *args, **kargs): propname = "%s.%s" % (self.prop.double._classname(), self.prop.key) if args: self.logger("%s set to %s" % (propname, args[0])) else: self.logger("%s gotten" % (propname)) class Tracer(object): def __init__(self, logger): self.logger = logger def trace(self, target): if isinstance(target, Method): self.trace_method(target) elif isinstance(target, Stub) or issubclass(target, Stub): self.trace_class(target) else: raise WrongApiUsage('Can not trace %s' % target) def trace_method(self, method): method.attach(MethodTracer(self.logger, method)) def trace_class(self, double): def attach_new_method(attr): if isinstance(attr, Method): attr.attach(MethodTracer(self.logger, attr)) elif isinstance(attr, Property): attr.attach(PropertyTracer(self.logger, attr)) double._new_attr_hooks.append(attach_new_method) doublex-1.8.2/make0000755000175000017500000000143112435722065013110 0ustar piotrpiotr#!/usr/bin/make -f # -*- mode:makefile -*- URL_AUTH=svn+ssh://${ALIOTH_USER}@svn.debian.org/svn/python-modules/packages/doublex/trunk URL_ANON=svn://svn.debian.org/svn/python-modules/packages/doublex/trunk debian: if [ ! -z "$${ALIOTH_USER}" ]; then \ svn co ${URL_AUTH} -N; \ else \ svn co ${URL_ANON} -N; \ fi mv trunk/.svn . rmdir trunk svn up debian .PHONY: docs doctests docs: $(MAKE) -C docs doctests: $(MAKE) -C doctests wiki: hg clone ssh://hg@bitbucket.org/DavidVilla/python-doublex/wiki clean: find . -name *.pyc -delete find . -name *.pyo -delete find . -name *~ -delete $(RM) -r *.egg-info MANIFEST $(RM) -r dist build *.egg-info .tox $(RM) -r slides/reveal.js $(MAKE) -C docs clean $(MAKE) -C doctests clean vclean: clean $(RM) -r .svn debian doublex-1.8.2/pydoubles-site/0000755000175000017500000000000012435722065015216 5ustar piotrpiotrdoublex-1.8.2/pydoubles-site/doublex-documentation0000644000175000017500000000415112435722065021453 0ustar piotrpiotr[migrated] For the time being you can find the doublex API documentation at: https://bitbucket.org/DavidVilla/python-doublex/wiki

What provides doublex respect to pyDoubles?

Respect to pyDoubles, doublex...:
  • Use just hamcrest matchers (for all features).
  • Only ProxySpy requires an instance. Other doubles accept a class too, and they never instantiate it.
  • Stub observers: Notify arbitrary hooks when methods are invoked. Useful to add "side effects".
  • Stub delegates: Use callables, iterables or generators to create stub return values.
  • Mimic doubles: doubles that inherit the same collaborator subclasses. This provides full LSP for code that make strict type checking.
doublex support all the issues notified in the pyDoubles issue tracker: And other features requested in the user group:   doublex-1.8.2/pydoubles-site/downloads0000644000175000017500000000132412435722065017133 0ustar piotrpiotrGet latest release from here
gunzip doublex-X.X.tar.gz
tar xvf doublex-X.X.tar
cd doublex-X.X/
sudo python setup.py install
Or use pip:
$ sudo pip install doubles-X.X.tar.gz
Pydoubles is also available on Pypi:
$ sudo pip install doublex
You can also get the latest source code from the mercurial repository. Check out the project:
$ hg clone https://bitbucket.org/DavidVilla/python-doublex
Browse the source code, get support and notify bugs in the issue tracker. doublex-1.8.2/pydoubles-site/overview0000644000175000017500000001051112435722065017005 0ustar piotrpiotr[migrated]

What is pyDoubles?

pyDoubles is a test doubles framework for the Python platform. Test doubles frameworks are also called mocking frameworks. pyDoubles can be used as a testing tool or as a Test Driven Development tool. It generates stubs, spies, and mock objects using a fluent interface that will make your unit tests more readable. Moreover, it's been designed to make your tests less fragile when possible. The development of pyDoubles has been completely test-driven from scratch. The project is under continuous evolution, but you can extend the framework with your own requirements. The code is simple and well documented with unit tests.

What is doublex?

doublex is a new doubles framework that optionally provides the pyDoubles legacy API. It supports all the pyDoubles features and some more that can not be easely backported. If you are a pyDoubles user you can run your tests using doublex.pyDoubles module. However, we recommed the native doublex API for your new developments.

Supported test doubles

Find out what test doubles are according to Gerard Meszaros. pyDoubles offers mainly three kind of doubles:

Stub

Replaces the implementation of one or more methods in the object instance which plays the role of collaborator or dependency, returning the value that we explicitly write down in the test. A stub is actually a method but it is also common to use the noun stub for a class with stubbed methods. The stub does not have any kind or memory. Stubs are used mainly for state validation or along with spies or mocks.

Spy

Replaces the implementation as a stub does, but it is also able to register and remember what methods are called during the test execution and how they are invoked. They are used for interaction/behavior verification.

Mock

Contains the same features than the Stub and therefore the Spy, but it is very strict in the behavior specification it should expect from the System Under Tests. Before calling any method in the mock object, the framework should be told (in the test) which methods we expect to be called in order for them to succeed. Otherwise, the test will fail with an "UnexpectedBehavior" exception. Mock objects are used when we have to be very precise in the behavior specification. They usually make the tests more fragile than a spy but still are necessary in many cases. It is common to use mock objects together with stubs in tests.

New to test doubles?

A unit test is comprised of three parts: Arrange/Act/Assert or Given/When/Then or whatever you want to call them. The scenario has to be created, exercised, and eventually we verify that the expected behavior happened. The test doubles framework is used to create the scenario (create the objects), and verify behavior after the execution but it does not make sense to invoke test doubles' methods in the test code. If you call the doubles' methods in the test code, you are testing the framework itself, which has been already tested (better than that, we crafted it using TDD). Make sure the calls to the doubles' methods happen in your production code.

Why another framework?

pyDoubles is inspired in mockito and jMock for Java, and also inspired in Rhino.Mocks for .Net. There are other frameworks for Python that work really well, but after some time using them, we were not really happy with the syntax and the readability of the tests. Fragile tests were also a problem. Some well-known frameworks available for Python are: mocker, mockito-python, mock, pymox. pyDoubles is open source and free software, released under the Apache License Version 2.0 Take a look at the project's blog doublex-1.8.2/pydoubles-site/pydoubles-documentation0000644000175000017500000002717712435722065022034 0ustar piotrpiotr[migrated]
class SimpleExample(unittest.TestCase):
   def test_ask_the_sender_to_send_the_report(self):
        sender = spy(Sender())
        service = SavingsService(sender)

        service.analyze_month()
        assert_that_method(sender.send_email).was_called(
                        ).with_args('reports@x.com', ANY_ARG)

Import the framework in your tests

import unittest
from doublex.pyDoubles import *
If you are afraid of importing everything from the pyDoubles.framework module, you can use custom imports, although it has been carefully designed to not conflict with your own classes.
import unittest
from doublex.pyDoubles import stub, spy, mock
from doublex.pyDoubles import when, expect_call, assert_that_method
from doublex.pyDoubles import method_returning, method_raising
You can import Hamcrest matchers which are fully supported:
from hamcrest import *

Which doubles do you need?

You can choose to stub out a method in a regular object instance, to stub the whole object, or to create three types of spies and two types of mock objects.

Stubs

There are several ways to stub out methods.
Stub out a single method
If you just need to replace a single method in the collaborator object and you don't care about the input parameters, you can stub out just that single method:
collaborator = Collaborator() # create the actual object
collaborator.some_calculation = method_returning(10)
Now, when your production code invokes the method "some_calculation" in the collaborator object, the framework will return 10, no matter what parameters are passed in as the input. If you want the method to raise an exception when called use this:
collaborator.some_calculation = method_raising(ApplicationException())
You can pass in any type of exception.
Stub out the whole object
Now the collaborator instance won't be the actual object but a replacement.
collaborator = stub(Collaborator())
Any method will return "None" when called with any input parameters. If you want to change the return value you can use the "when" sentence:
when(collaborator.some_calculation).then_return(10)
Now, when your production code invokes "some_calculation" method, the stub will return 10, no matter what arguments are passed in. You can also specify different return values depending on the input:
when(collaborator.some_calculation).with_args(5).then_return(10)
when(collaborator.some_calculation).with_args(10).then_return(20)
This means that "collaborator.some_calculation(5)" will return 10, and that it will return 20 when the input is 10. You can define as many input/output specifications as you want.
when(collaborator.some_calculation).with_args(5).then_return(10)
when(collaborator.some_calculation).then_return(20)
This time, "collaborator.some_calculation(5)" will return 10, and it will return 20 in any other case.
Any argument matches
The special keyword ANY_ARG is a wildcard for any argument in the stubbed method:
when(collaborator.some_other_method).with_args(5, ANY_ARG).then_return(10)
The method "some_other_method" will return 10 as long as the first parameter is 5, no matter what the second parameter is. You can use any combination of "ANY_ARG" arguments. But remember that if all of them are ANY, you shouldn't specify the arguments, just use this:
when(collaborator.some_other_method).then_return(10)
It is also possible to make the method return exactly the first parameter passed in:
when(collaborator.some_other_method).then_return_input()
So this call: collaborator.some_other_method(10) wil return 10.
Matchers
You can also specify that arguments will match a certain function. Say that you want to return a value only if the input argument contains the substring "abc":
when(collaborator.some_method).with_args(
        str_containing("abc")).then_return(10)
In the last release, pyDoubles matchers are just aliases for the hamcrest counterparts. See release notes.
Hamcrest Matchers
Since pyDoubles v1.2, we fully support Hamcrest matchers. They are used exactly like pyDoubles matchers:
from hamcrest import *
from doublex.pyDoubles import *

    def test_has_entry_matcher(self):
        list = {'one':1, 'two':2}
        when(self.spy.one_arg_method).with_args(
            has_entry(equal_to('two'), 2)).then_return(1000)
        assert_that(1000, equal_to(self.spy.one_arg_method(list)))

    def test_all_of_matcher(self):
        text = 'hello'
        when(self.spy.one_arg_method).with_args(
            all_of(starts_with('h'), instance_of(str))).then_return(1000)
        assert_that(1000, equal_to(self.spy.one_arg_method(text)))
Note that the tests above are just showhing the pyDoubles framework working together with Hamcrest, they are not good examples of unit tests for your production code. The method assert_that comes from Hamcrest, as well as the matchers: has_entry, equal_to, all_of, starts_with, instance_of. Notice that all_of and any_of, allow you to define more than one matcher for a single argument, which is really powerful. For more informacion on matchers, read this blog post.
Stub out the whole unexisting object
If the Collaborator class does not exist yet, or you don't want the framework to check that the call to the stub object method matches the actual API in the actual object, you can use an "empty" stub.
collaborator = empty_stub()
when(collaborator.alpha_operation).then_return("whatever")
The framework is creating the method "alpha_operation" dynamically and making it return "whatever". The use of empty_stub, empty_spy or empty_mock is not recommended because you lose the API match check. We only use them as the construction of the object is too complex among other circumstances.

Spies

Please read the documentation above about stubs, because the API to define method behaviors is the same for stubs and spies. To create the object:
collaborator = spy(Collaborator())
After the execution of the system under test, we want to validate that certain call was made:
assert_that_method(collaborator.send_email).was_called()
That will make the test pass if method "send_email" was invoked one or more times, no matter what arguments were passed in. We can also be precise about the arguments:
assert_that_method(collaborator.send_email).was_called().with_args("example@iexpertos.com")
Notice that you can combine the "when" statement with the called assertion:
def test_sut_asks_the_collaborator_to_send_the_email(self):
   sender = spy(Sender())
   when(sender.send_email).then_return(SUCCESS)
   object_under_test = Sut(sender)

   object_under_test.some_action()

   assert_that_method(
 sender.send_email).was_called().with_args("example@iexpertos.com")
Any other call to any method in the "sender" double will return "None" and will not interrupt the test. We are not telling all that happens between the sender and the SUT, we are just asserting on what we want to verify. The ANY_ARG matcher can be used to verify the call as well:
assert_that_method(collaborator.some_other_method).was_called().with_args(5, ANY_ARG)
Matchers can also be used in the assertion:
assert_that_method(collaborator.some_other_method).was_called().with_args(5, str_containing("abc"))
It is also possible to assert that wasn't called using:
assert_that_method(collaborator.some_method).was_never_called()
You can assert on the number of times a call was made:
assert_that_method(collaborator.some_method).was_called().times(2)
assert_that_method(collaborator.some_method).was_called(
     ).with_args(SOME_VALUE, OTHER_VALUE).times(2)
You can also create an "empty_spy" to not base the object in a certain instance:
sender = empty_spy()
The ProxySpy
There is a special type of spy supported by the framework which is the ProxySpy:
collaborator = proxy_spy(Collaborator())
The proxy spy will record any call made to the object but rather than replacing the actual methods in the actual object, it will execute them. So the actual methods in the Collaborator will be invoked by default. You can replace the methods one by one using the "when" statement:
when(collaborator.some_calculation).then_return(1000)
Now "some_calculation" method will be a stub method but the remaining methods in the class will be the regular implementation. The ProxySpy might be interesting when you don't know what the actual method will return in a given scenario, but still you want to check that some call is made. It can be used for debugging purposes.

Mocks

Before calls are made, they have to be expected:
def test_sut_asks_the_collaborator_to_send_the_email(self):
   sender = mock(Sender())
   expect_call(sender.send_email)
   object_under_test = Sut(sender)

   object_under_test.some_action()

   sender.assert_that_is_satisfied()
The test is quite similar to the one using a spy. However the framework behaves different. If any other call to the sender is made during "some_action", the test will fail. This makes the test more fragile. However, it makes sure that this interaction is the only one between the two objects, and this might be important for you.
More precise expectations
You can also expect the call to have certain input parameters:
expect_call(sender.send_email).with_args("example@iexpertos.com")
Setting the return of the expected call
Additionally, if you want to return anything when the expected call occurs, there are two ways:
expect_call(sender.send_email).returning(SUCCESS)
Which will return SUCCESS whatever arguments you pass in, or
expect_call(sender.send_email).with_args("wrong_email").returning(FAILURE)
Which expects the method to be invoked with "wrong_email" and will return FAILURE. Mocks are strict so if you expect the call to happen several times, be explicit with that:
expect_call(sender.send_email).times(2)
expect_call(sender.send_email).with_args("admin@iexpertos.com").times(2)
Make sure the "times" part is at the end of the sentence:
expect_call(sender.send_email).with_args("admin@iexpertos.com").returning('OK').times(2)
As you might have seen, the "when" statement is not used for mocks, only for stubs and spies. Mock objects use the "expect_call" syntax together with the "assert_that_is_satisfied" (instance method).

More documentation

The best and most updated documentation are the unit tests of the framework itself. We encourage the user to read the tests and see what features are supported in every commit into the source code repository: pyDoublesTests/unit.py You can also read about what's new in every release in the blog doublex-1.8.2/pydoubles-site/release-notes0000644000175000017500000000607212435722065017714 0ustar piotrpiotr

doublex 1.6.6

doublex 1.6.5

doublex 1.6.4

  • Asynchronous spy assertion race condition bug fixed.
  • Reading double attributes returns collaborator.class attribute values by default.

doublex 1.6.2

  • Invocation stubbed return value is now stored.
  • New low level spy API: double method  "calls" property provides access to invocations and their argument values. Each 'call' has an "args" sequence and "kargs dictionary". This provides support to perform individual assertions and direct access to invocation argument values. (see test and doc).

doublex 1.6

  • First release supporting Python-3 (up to Python-3.2) [fixes issue 7].
  • Ad-hoc stub attributes (see test).
  • Partial support for non native Python functions.
  • ProxySpy propagated stubbed invocations too (see test).

doublex 1.5.1

This release includes support for asynchronous spy assertions. See this blog post for the time being, soon in the official documentation.

doublex/pyDoubles 1.5

Since this release the pyDoubles API is provided as a wrapper to doublex. However, there are small differences. pyDoubles matchers are not supported anymore, although you may get the same feature using standard hamcrest matchers. Anyway, legacy pyDoubles matchers are provided as hamcrest aliases. In most cases the only required change in your code is the module name, that change from:
from pyDoubles.framework.*
to:
from doublex.pyDoubles import *
If you have problems migrating to the new 1.5 release or migrating from pyDoubles to doublex, please ask for help in the discussion forum or in the issue tracker. doublex-1.8.2/pydoubles-site/support0000644000175000017500000000115712435722065016661 0ustar piotrpiotr

Free support

Mailing list: http://groups.google.com/group/pydoubles Issue tracker, mercurial repository: https://bitbucket.org/carlosble/pydoubles/overview Thanks to BitBucket!

Commercial support

The development team of pyDoubles is a software company based in Spain. We are happy to help other companies with the usage and extension of pyDoubles. If you want to have custom features or direct support, please contact us at info@iexpertos.com doublex-1.8.2/requirements.txt0000644000175000017500000000001312435722065015524 0ustar piotrpiotrPyHamcrest doublex-1.8.2/setup.py0000755000175000017500000000336012435722065013765 0ustar piotrpiotr#!/usr/bin/python import os import sys from setuptools import setup, find_packages # hack to prevent 'test' target exception: # http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html import multiprocessing, logging def local_open(fname): return open(os.path.join(os.path.dirname(__file__), fname)) config = dict( name = 'doublex', version = '1.8.2', description = 'Python test doubles', keywords = ['unit tests', 'doubles', 'stub', 'spy', 'mock'], author = 'David Villa Alises', author_email = 'David.Villa@gmail.com', url = 'https://bitbucket.org/DavidVilla/python-doublex', packages = find_packages(), data_files = [('', ['README.rst'])], test_suite = 'doublex.test', license = 'GPLv3', long_description = local_open('README.rst').read(), install_requires = local_open('requirements.txt').readlines(), classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', ], ) if sys.version_info >= (3,): config.update(dict( use_2to3=True, )) setup(**config) doublex-1.8.2/slides/0000755000175000017500000000000012435722065013531 5ustar piotrpiotrdoublex-1.8.2/slides/Makefile0000644000175000017500000000031212435722065015165 0ustar piotrpiotr LINKS=css lib plugin js all: reveal.js $(LINKS) reveal.js: git clone --depth 1 https://github.com/hakimel/reveal.js.git $(LINKS): ln -s reveal.js/$@ $@ clean: $(RM) -r reveal.js $(RM) $(LINKS) doublex-1.8.2/slides/beamer/0000755000175000017500000000000012435722065014764 5ustar piotrpiotrdoublex-1.8.2/slides/beamer/Makefile0000644000175000017500000000002612435722065016422 0ustar piotrpiotrinclude arco/latex.mk doublex-1.8.2/slides/beamer/custom.sty0000644000175000017500000000323612435722065017043 0ustar piotrpiotr\usepackage[spanish]{babel} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{times} \usepackage{graphicx} \graphicspath{{figures/}} \usepackage{listings} \newcommand{\lstfont}{\ttfamily\fontfamily{pcr}} \lstset{ % frame frame = Ltb, framerule = 0pt, aboveskip = 0.5cm, framextopmargin = 3pt, framexbottommargin = 3pt, framexleftmargin = 0.4cm, framesep = 0pt, rulesep = .4pt, %-- % caption belowcaptionskip = 5pt, %-- % text style stringstyle = \ttfamily, showstringspaces = false, basicstyle = \scriptsize\lstfont, keywordstyle = \bfseries, %-- % numbers numbers = none, numbersep = 15pt, numberstyle = \scriptsize\lstfont, numberfirstline = false, % breaklines = true, emptylines = 1, % several empty lines are shown as one % literate = % caracteres especiales {á}{{\'a}}1 {Á}{{\'A}}1 {é}{{\'e}}1 {É}{{\'E}}1 {í}{{\'i}}1 {Í}{{\'I}}1 {ó}{{\'o}}1 {Ó}{{\'O}}1 {ú}{{\'u}}1 {Ú}{{\'U}}1 {ñ}{{\~n}}1 {Ñ}{{\~N}}1 {¡}{{!`}}1 {¿}{{?`}}1 } \parskip=10pt \mode { \usetheme{Frankfurt} \setbeamercovered{transparent} % or whatever (possibly just delete it) } % Delete this, if you do not want the table of contents to pop up at % the beginning of each subsection: \AtBeginSubsection[] { \begin{frame}{Outline} \tableofcontents[currentsection,currentsubsection] \end{frame} } % If you wish to uncover everything in a step-wise fashion, uncomment % the following command: %\beamerdefaultoverlayspecification{<+->} doublex-1.8.2/slides/beamer/slides.tex0000644000175000017500000002271412435722065016777 0ustar piotrpiotr\documentclass[11pt]{beamer} \usepackage{custom} \title{doublex: Python test doubles framework} \subtitle{\bfseries\small\url{http://bitbucket.org/DavidVilla/python-doublex}} \author{\bfseries\small\texttt{@david\_vi11a}} %\institute{} \date{} %\subject{} \begin{document} \begin{frame} \titlepage \end{frame} \begin{frame}{Contents} \tableofcontents \end{frame} \section{Intro} \begin{frame}{Another doubles library for Python?} Yes, why not? \end{frame} \begin{frame}{doublex features} \begin{itemize} \item Stubs \item Spies \item Mocks \item ah hoc stub methods \item stub delegates \item stub observers \item properties \item hamcrest matchers for \textbf{all} assertions \item wrapper for legacy pyDoubles API \item doublex never instantiates your classes! \end{itemize} \end{frame} \section{Stubs} \begin{frame}[fragile]{Stubs} \framesubtitle{set fixed return value} \begin{exampleblock}{} \begin{lstlisting}[language=Python] class Collaborator: def add(self, x, y): return x + y with Stub(Collaborator) as stub: stub.add(ANY_ARG).returns(1000) assert_that(stub.add(2, 2), is_(1000)) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Stubs} \framesubtitle{\... by calling arg values} Undefined stub methods returns None. \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Stub(Collaborator) as stub: stub.add(2, 2).returns(1000) stub.add(3, ANY_ARG).returns(0) assert_that(stub.add(1, 1), is_(None)) assert_that(stub.add(2, 2), is_(1000)) assert_that(stub.add(3, 0), is_(0)) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Stubs} \framesubtitle{\... by hamcrest matcher} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Stub(Collaborator) as stub: stub.add(2, greater_than(4)).returns(4) assert_that(stub.add(2, 1), is_(None)) assert_that(stub.add(2, 5), is_(4)) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Stubs} \framesubtitle{\... by composite hamcrest matcher} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Stub(Collaborator) as stub: stub.foo(has_length(all_of( greater_than(4), less_than(8)))).returns(1000) assert_that(stub.add(2, "bad"), is_(None)) assert_that(stub.add(2, "enough"), is_(1000)) \end{lstlisting} \end{exampleblock} \end{frame} \section{Spies} \begin{frame}[fragile]{Spies} \framesubtitle{checking called methods} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy(Collaborator) spy.add(2, 3) spy.add("hi", 3.0) spy.add([1, 2], 'a') assert_that(spy.add, called()) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{collaborator signature checking} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy(Collaborator) spy.add() TypeError: __main__.Collaborator.add() takes exactly 3 arguments (1 given) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{checking called times (with matcher too!)} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy(Collaborator) spy.add(2, 3) spy.add("hi", 3.0) spy.add([1, 2], 'a') assert_that(spy.add, called().times(3)) assert_that(spy.add, called().times(greater_than(2))) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{filter by argument value: \texttt{with\_args()})} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy(Collaborator) spy.add(2, 3) spy.add(2, 8) spy.add("hi", 3.0) assert_that(spy.add, called().with_args(2, ANY_ARG)).times(2) assert_that(spy.add, never(called().with_args(0, 0))) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{filter by key argument (with matcher)} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy() spy.foo(name="Mary") assert_that(spy.foo, called().with_args(name="Mary")) assert_that(spy.foo, called().with_args(name=contains_string("ar"))) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{Verbose meaning-full report messages!} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy() spy.foo(1) spy.bar("hi") assert_that(spy.foo, called().with_args(4)) AssertionError: Expected: these calls: Spy.foo(4) but: calls that actually ocurred were: Spy.foo(1) Spy.bar('hi') \end{lstlisting} \end{exampleblock} \end{frame} \subsection{ProxySpy} \begin{frame}[fragile]{ProxySpy} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with ProxySpy(Collaborator()) as spy: spy.add(2, 2).returns(1000) assert_that(spy.add(2, 2), is_(1000)) assert_that(spy.add(1, 1), is_(2)) \end{lstlisting} \end{exampleblock} \end{frame} \section{Mocks} \begin{frame}[fragile]{Mocks} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Mock() as smtp: smtp.helo() smtp.mail(ANY_ARG) smtp.rcpt("bill@apple.com") smtp.data(ANY_ARG).returns(True).times(2) smtp.helo() smtp.mail("poormen@home.net") smtp.rcpt("bill@apple.com") smtp.data("somebody there?") assert_that(smtp.data("I am afraid.."), is_(True)) assert_that(smtp, verify()) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Mocks} \framesubtitle{invocation order is important} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Mock() as mock: mock.foo() mock.bar() mock.bar() mock.foo() assert_that(mock, verify()) AssertionError: Expected: these calls: Mock.foo() Mock.bar() but: calls that actually ocurred were: Mock.bar() Mock.foo() \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Mocks} \framesubtitle{unless you do not mind: \texttt{any\_order\_verify()}} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Mock() as mock: mock.foo() mock.bar() mock.bar() mock.foo() assert_that(mock, any_order_verify()) \end{lstlisting} \end{exampleblock} \end{frame} \section{ah hoc stub methods} \begin{frame}[fragile]{ah hoc stub methods} \begin{exampleblock}{} \begin{lstlisting}[language=Python] collaborator = Collaborator() collaborator.foo = method_returning('bye') assert_that(self.collaborator.foo(), is_('bye')) collaborator.foo = method_raising(SomeException) collaborator.foo() SomeException: \end{lstlisting} \end{exampleblock} \end{frame} \section{stub observers} \begin{frame}[fragile]{stub observers} \begin{exampleblock}{} \begin{lstlisting}[language=Python] class Observer(object): def __init__(self): self.state = None def update(self, *args, **kargs): self.state = args[0] observer = Observer() stub = Stub() stub.foo.attach(observer.update) stub.foo(2) assert_that(observer.state, is_(2)) \end{lstlisting} \end{exampleblock} \end{frame} \section{stub delegates} \begin{frame}[fragile]{stub delegates} \framesubtitle{delegating to callables} \begin{exampleblock}{} \begin{lstlisting}[language=Python] def get_user(): return "Freddy" with Stub() as stub: stub.user().delegates(get_user) stub.foo().delegates(lambda: "hello") assert_that(stub.user(), is_("Freddy")) assert_that(stub.foo(), is_("hello")) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{stub delegates} \framesubtitle{delegating to iterables} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Stub() as stub: stub.foo().delegates([1, 2, 3]) assert_that(stub.foo(), is_(1)) assert_that(stub.foo(), is_(2)) assert_that(stub.foo(), is_(3)) \end{lstlisting} \end{exampleblock} \end{frame} \section{properties} \begin{frame}[fragile]{stubbing properties} \begin{exampleblock}{} \begin{lstlisting}[language=Python] class Collaborator(object): @property def prop(self): return 1 @prop.setter def prop(self, value): pass with Spy(Collaborator) as spy: spy.prop = 2 assert_that(spy.prop, is_(2)) # double property getter invoked \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{spying properties (with matchers!)} \begin{exampleblock}{} \begin{lstlisting}[language=Python] assert_that(spy, property_got('prop')) spy.prop = 4 # double property setter invoked spy.prop = 5 # -- spy.prop = 5 # -- assert_that(spy, property_set('prop')) # set to any value assert_that(spy, property_set('prop').to(4)) assert_that(spy, property_set('prop').to(5).times(2)) assert_that(spy, never(property_set('prop').to(greater_than(6)))) \end{lstlisting} \end{exampleblock} \end{frame} \section{Mimics} \begin{frame}[fragile]{normal doubles support only duck-typing} \begin{exampleblock}{} \begin{lstlisting}[language=Python] class A(object): pass class B(A): pass >>> spy = Spy(B()) >>> isinstance(spy, Spy) True >>> isinstance(spy, B) False \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Mimics support full LSP} \begin{exampleblock}{} \begin{lstlisting}[language=Python] >>> spy = Mimic(Spy, B) >>> isinstance(spy, B) True >>> isinstance(spy, A) True >>> isinstance(spy, Spy) True >>> isinstance(spy, Stub) True >>> isinstance(spy, object) True \end{lstlisting} \end{exampleblock} \end{frame} \section{Questions} \begin{frame}{} \begin{center} {\huge Questions?} \end{center} \end{frame} \end{document} %% Local Variables: %% coding: utf-8 %% mode: flyspell %% ispell-local-dictionary: "american" %% End: doublex-1.8.2/slides/index.html0000644000175000017500000004371212435722065015535 0ustar piotrpiotr doublex

doublex

Python test doubles framework

@david_vi11a

what are doubles?

Test doubles are atrezzo objects.

why should we use doubles?

Unit tests must isolate the SUT.

So all collaborators should be replaced.

They require (and promote) your classes meets DIP and LSP.

then, instead of production class instances...

 collaborator = Collaborator()

 sut = SUT(collaborator)

 sut.exercise()
	    
...give it doubles

 double = Double(Collaborator)

 sut = SUT(double)

 sut.exercise()
	    

which is the right double?

  • Dummy: a placeholder object, never invoked
  • Fake: Q&D replacement, not suitable for production
  • Stub: returns hardcoded responses: It say you want to hear
  • Spy: Stub that records received invocations
  • Mock: holds and check programmed expectations

[ according to xunitpatterns.com/Test Double.html ]

EXAMPLE
account service

  class AccountService:
      def __init__(self, store, password_service):
	  [...]

      def create_user(self, login):
          [...]
          - raise InvalidPassword()
          - raise AlreadyExists()

      def create_group(self, group_name, user_names):
          [...]
	    

[ slides related to that example
have gray background ]

account service

collaborators


  class AccountStore:
      def save(self, login, password):
          [...]

      def has_user(self, login):
          [...]

  class PasswordService:
      def generate(self):
          [...]
	    

Stub

In a free stub, any method may be invoked:


  class AccountTests(TestCase):
      def test_account_creation(self):
          with Stub() as password_service:
              password_service.generate().returns('secret')

          service = AccountService(store=Stub(), password_service)

          service.create_user('John')
	    

Stub

... you can set return value depending on arguments


 with Stub() as stub:
     stub.foo(2, 2).returns(100)
     stub.foo(3, ANY_ARG).returns(200)

 assert_that(stub.foo(1, 1), is_(None))
 assert_that(stub.foo(2, 2), is_(100))
 assert_that(stub.foo(3, 0), is_(200))
	    

Stub

... or by hamcrest matcher


 with Stub() as stub:
     stub.foo(2, greater_than(4)).returns(100)

 assert_that(stub.foo(2, 1), is_(None))
 assert_that(stub.foo(2, 5), is_(100))
	    

Stub

... or by composite hamcrest matcher


 with Stub() as stub:
     stub.foo(2, has_length(all_of(
         greater_than(4), less_than(8)))).returns(1000)

 assert_that(stub.foo(2, "bad"), is_(None))
 assert_that(stub.foo(2, "enough"), is_(1000))
	    

Stub

interface may be restricted to a given class:


 with Stub(PasswordService) as password_service:
     password_service.generate().returns('secret')

 stub.generate()
 stub.generate(9)
TypeError: PasswordService.generate() takes exactly 1 argument (2 given)

 stub.wrong()
AttributeError: 'PasswordService' object has no attribute 'wrong'
	    

in our AccountService test:


  class AccountTests(TestCase):
      def test_account_creation(self):
          with Stub(PasswordService) as password_service:
              password_service.generate().returns('secret')

          service = AccountService(store=Stub(), password_service)

          service.create_user('John')
    

... is 'store' really called??

we need a spy

Spy

checking double invocations: called()


 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_group('team', ['John', 'Peter', 'Alice'])

 assert_that(store.save, called())
    

but... is really called three times?

Spy

checking called times: times()

(also with matchers)


 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_group('team', ['John', 'Peter', 'Alice'])

 assert_that(store.save, called().times(3))
 assert_that(store.save, called().times(greater_than(2)))
    

but... is really called with the right arguments?

Spy

check argument values: with_args()

(also with matchers)


 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_user('John')

 assert_that(store.save, called().with_args('John', 'secret'))
 assert_that(store.save, called().with_args('John', ANY_ARG))
 assert_that(store.save,
             called().with_args(contains_string('oh'), ANY_ARG))
 assert_that(store.save,
             never(called().with_args('Alice', anything())))
    

Spy

check keyword argument

(also with matcher)


 spy = Spy()
 spy.foo(name="Mary")

 assert_that(spy.foo,
             called().with_args(name="Mary"))

 assert_that(spy.foo,
             called().with_args(name=contains_string("ar")))
    

Spy

meaning-full report messages!


 service.create_group('team', ['John', 'Alice'])

 assert_that(store.save, called().with_args('Peter'))
AssertionError:
Expected: these calls:
          AccountStore.save('Peter')
     but: calls that actually ocurred were:
          AccountStore.has_user('John')
          AccountStore.save('John', 'secret')
          AccountStore.has_user('Alice')
          AccountStore.save('Alice', 'secret')
    

ProxySpy

propagates invocations to the collaborator


 with ProxySpy(AccountStore()) as store:
     store.has_user('John').returns(True)

 service = AccountService(store, password_service)

 with self.assertRaises(AlreadyExists):
     service.create_user('John')
    

CAUTION: ProxySpy is not a true double,
this invokes the actual AccountStore instance!

Mock

programming expectations


        with Mock(AccountStore) as store:
            store.has_user('John')
            store.save('John', anything())
            store.has_user('Peter')
            store.save('Peter', anything())

        service = AccountService(store, password_service)

	service.create_group('team', ['John', 'Peter'])

        assert_that(store, verify())
    

Mock assures these invocations (and only these) are ocurred.

ah hoc stub methods


 collaborator = Collaborator()
 collaborator.foo = method_returning('bye')
 assert_that(self.collaborator.foo(), is_('bye'))

 collaborator.foo = method_raising(SomeException)
 collaborator.foo()
SomeException:
  

stub observers

attach additional behavior


 class Observer(object):
     def __init__(self):
         self.state = None

     def update(self, *args, **kargs):
         self.state = args[0]

 observer = Observer()
 stub = Stub()
 stub.foo.attach(observer.update)
 stub.foo(2)

 assert_that(observer.state, is_(2))
  

stub delegates

delegating to callables


 def get_pass():
     return "12345"

 with Stub(PasswordService) as password_service:
     password_service.generate().delegates(get_pass)

 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_user('John')

 assert_that(store.save, called().with_args('John', '12345'))
    

stub delegates

delegating to iterables/generators


 with Stub(PasswordService) as password_service:
     password_service.generate().delegates(["12345", "mypass", "nope"])

 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_group('team', ['John', 'Peter', 'Alice'])

 assert_that(store.save, called().with_args('John', '12345'))
 assert_that(store.save, called().with_args('Peter', 'mypass'))
 assert_that(store.save, called().with_args('Alice', 'nope'))
    

stubbing properties


 class Collaborator(object):
     @property
     def prop(self):
         return 1

     @prop.setter
     def prop(self, value):
         pass

 with Spy(Collaborator) as spy:
     spy.prop = 2

 assert_that(spy.prop, is_(2))  # double property getter invoked
    

spying properties

(also with matcher)


 assert_that(spy, property_got('prop'))

 spy.prop = 4  # double property setter invoked
 spy.prop = 5  # --
 spy.prop = 5  # --

 assert_that(spy, property_set('prop'))  # set to any value
 assert_that(spy, property_set('prop').to(4))
 assert_that(spy, property_set('prop').to(5).times(2))
 assert_that(spy,
             never(property_set('prop').to(greater_than(6))))
    

Questions?

References

doublex-1.8.2/slides/sample.py0000755000175000017500000001340612435722065015373 0ustar piotrpiotr#!/usr/bin/python # -*- mode:python; coding:utf-8; tab-width:4 -*- from unittest import TestCase from doublex import (Stub, Spy, ProxySpy, Mock, assert_that, called, ANY_ARG, never, verify, any_order_verify) from hamcrest import greater_than, anything, contains_string class AlreadyExists(Exception): pass class InvalidPassword(Exception): pass class AccountStore: def save(self, login, password): pass def has_user(self, login): pass class Group(set): def __init__(self, name): pass class PasswordService: def generate(self): pass class AccountService: def __init__(self, store, password_service): self.store = store self.password_service = password_service def create_user(self, login): if self.store.has_user(login): raise AlreadyExists() password = self.password_service.generate() if not password: raise InvalidPassword() self.store.save(login, password) def create_group(self, group_name, user_names): group = Group(group_name) for name in user_names: try: self.create_user(name) except AlreadyExists: pass group.add(name) class AccountTests(TestCase): def test_account_creation__free_stub(self): with Stub() as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter', 'Alice']) assert_that(store.save, called()) def test_account_creation__restricted_stub(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called()) def test_account_creation__3_accounts(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter', 'Alice']) assert_that(store.save, called().times(3)) assert_that(store.save, called().times(greater_than(2))) def test_account_creation__argument_values(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called().with_args('John', 'some')) assert_that(store.save, called().with_args('John', ANY_ARG)) assert_that(store.save, never(called().with_args('Alice', anything()))) assert_that(store.save, called().with_args(contains_string('oh'), ANY_ARG)) def test_account_creation__report_message(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Alice']) # assert_that(store.save, called().with_args('Peter')) def test_account_already_exists(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') with ProxySpy(AccountStore()) as store: store.has_user('John').returns(True) service = AccountService(store, password_service) with self.assertRaises(AlreadyExists): service.create_user('John') def test_account_behaviour_with_mock(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') with Mock(AccountStore) as store: store.has_user('John') store.save('John', 'some') store.has_user('Peter') store.save('Peter', 'some') service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter']) assert_that(store, verify()) # def test_account_behaviour_with_mock_any_order(self): # with Stub(PasswordService) as password_service: # password_service.generate().returns('some') # # with Mock(AccountStore) as store: # store.has_user('John') # store.has_user('Peter') # store.save('John', 'some') # store.save('Peter', 'some') # # service = AccountService(store, password_service) # # service.create_user('John') # service.create_user('Peter') # # assert_that(store, any_order_verify()) def test_stub_delegates(self): def get_pass(): return "12345" with Stub(PasswordService) as password_service: password_service.generate().delegates(get_pass) store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called().with_args('John', '12345')) def test_stub_delegates_list(self): with Stub(PasswordService) as password_service: password_service.generate().delegates(["12345", "mypass", "nothing"]) store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter', 'Alice']) assert_that(store.save, called().with_args('John', '12345')) assert_that(store.save, called().with_args('Peter', 'mypass')) assert_that(store.save, called().with_args('Alice', 'nothing')) doublex-1.8.2/tox.ini0000644000175000017500000000046712435722065013570 0ustar piotrpiotr[tox] envlist = py27, py32, py34 [testenv] deps=nose commands=python setup.py test [testenv:py26] deps=unittest2 nose # using 2to3 with nose #:https://bitbucket.org/kumar303/fudge/src/9cafce359a21/tox.ini#cl-26 #[testenv:py34] # https://bitbucket.org/hpk42/tox/issue/127/possible-problem-with-python34