cmdtest-0.10/0000755000175000017500000000000012224016632012757 5ustar jenkinsjenkinscmdtest-0.10/.gitignore0000644000175000017500000000001112224016632014737 0ustar jenkinsjenkins*.py[co] cmdtest-0.10/COPYING0000644000175000017500000010451312224016632014016 0ustar jenkinsjenkins GNU 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. Copyright (C) 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: Copyright (C) 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 . cmdtest-0.10/NEWS0000644000175000017500000000744612224016632013471 0ustar jenkinsjenkinsNEWS for cmdtest ================ This file summarizes changes between releases of cmdtest. Version 0.10, released 2013-10-05 --------------------------------- * Yarn now cleans the environment when it runs shell commands for the implementation steps. The PATH variable is kept from the user's environment, every other variable is either removed or hardcoded to a specific value. More variables can be added explicitly to the test environment with the new `--env NAME=VALUE` option. Additionally yarn sets the `SRCDIR` environment variable to point at the root of the source tree (the directory where yarn was invoked from). * A new option, `--timings`, has been added to yarn to report how long each scenario and each step took. * Yarn now reports scenarios skipped because of ASSUMING failing. * Yarn manual page now documents DATADIR and SRCDIR environment variables. Bug fixes: * Yarn now complains if a scenario has no THEN steps. Suggested by Richard Maw. * Yarn now gives an error if there are no scenarios. Suggested by Daniel Silverstone and others. * Yarn now checks for duplicate scenario names. * Yarn now always checks for IMPLEMENTS sections with case-insensitive matching. Reported, with test case, by Jannis Pohlmann. Version 0.9, released 2013-07-23 -------------------------------- * Yarn now warns if an input file has no code blocks. * There is no a yarn `--shell-library` option for the user to use, which includes a shell library when running any IMPLEMENTS section. * FINALLY always worked in yarn, but has now been added to the manual page as well. * The keyword ASSUMING has been added to yarn. * New yarn option `--run` allows running selected tests only. * New yarn option `--snapshot` makes snapshots of the test working directory after each step in a scenario. Combined with the, also new, option `--tempdir` this makes debugging failed tests easier. * New yarn option `--verbose` (turned on automatically if there is not tty available, e.g., when running from cron), turns off ttystatus progress bar and produces a "wall of text" style output instead. Bug fixes: * Yarn now handles multiple input files correctly. Reported by Daniel Silverstone; fix based on his patch, but rewritten. Version 0.8.3, released 2013-06-21 -------------------------------- * Bug fix: properly install yarnlib. In other news, I hate distutils. Version 0.8.2, released 2013-06-21 -------------------------------- * Bug fix: install the yarnlib library as well. This is embarrassing. Version 0.8.1, released 2013-06-20 -------------------------------- * Bug fix: install the yarn binary in the package. Version 0.8, released 2013-06-19 -------------------------------- * Switch terminology to "scenario testing" from "story testing". Thanks to Rob Kendrick for the suggestion. Doing a quick release so the old terminology doesn't have time to get any use. Version 0.7, released 2013-06-15 -------------------------------- * Added the new tool `yarn`, for doing story testing. It is still fresh and raw, but I want to make it available to get feedback. Version 0.6, released 2013-03-14 -------------------------------- * Fixed cmdtest to diff outputs correctly. Reported by Kevin Lee. Version 0.5, released 2012-09-29 -------------------------------- * Version 0.4 may or may not have released. If it was, it should have had internal changes only. * Add missing copy of GPLv3. Reported by Michel Alexandre Salim. Version 0.3, released 2012-02-24 -------------------------------- * Add `--keep` option to keep the temporary directory for failed tests. * Add `--timings` option to show timings for various tests. Good for when test suites start getting slow and you want to speed them up. Version 0.2, released 2012-02-18 -------------------------------- * The `-t testname` option now works. cmdtest-0.10/README0000644000175000017500000000320212224016632013634 0ustar jenkinsjenkinsREADME for cmdtest ================== This project consists of two programs: the original `cmdtest`, and the newer `yarn`. Both are black box testing tools for Unix command line tools. cmdtest ------- `cmdtest` black box tests Unix command line tools. Given some test scripts, their inputs, and expected outputs, it verifies that the command line produces the expected output. If not, it reports problems, and shows the differences. See the manual page for details on how to use the program. yarn ---- `yarn` also black box tests Unix command line tools, but takes a different approach, where the emphasis is on verifying that the tools works correctly in a sequence of operations, or what we call a "test scenario". `yarn` is inspired [BDD][BDD], behavior-driven development, and some of the implementations made by the Ruby community. See README.yarn for more details. `yarn` has been designed with Daniel Silverstone. [BDD]: https://en.wikipedia.org/wiki/Behavior-driven_development Legalese -------- Copyright 2011-2013 Lars Wirzenius 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 . cmdtest-0.10/README.yarn0000644000175000017500000001777212224016632014625 0ustar jenkinsjenkinsREADME for yarn, a scenario testing tool ======================================== Introduction ------------ `yarn` is a scenario testing tool: you write a scenario describing how a user uses your software and what should happen, and express, using very lightweight syntax, the scenario in such a way that it can be tested automatically. The scenario has a simple, but strict structure: SCENARIO name of scenario GIVEN some setup for the test WHEN thing that is to be tested happens THEN the post-conditions must be true As an example, consider a very short test scenario for verifying that a backup program works, at least for one simple case. SCENARIO basic backup and restore GIVEN some live data in a directory AND an empty backup repository WHEN a backup is made THEN the data can be restored (Note the addition of AND: you can have multiple GIVEN, WHEN, and THEN statements. The AND keyword makes the text be more readable.) Scenarios are meant to be written in mostly human readable language. However, they are not free form text. In addition to the GIVEN/WHEN/THEN structure, the text for each of the steps needs a computer-executable implementation. This is done by using IMPLEMENTS. The backup scenario from above might be implemented as follows: IMPLEMENTS GIVEN some live data in a directory rm -rf "$DATADIR/data" mkdir "$DATADIR/data" echo foo > "$DATADIR/data/foo" IMPLEMENTS GIVEN an empty backup repository rm -rf "$DATADIR/repo" mkdir "$DATADIR/repo" IMPLEMENTS WHEN a backup is made backup-program -r "$DATADIR/repo" "$DATADIR/data" IMPLEMENTS THEN the data can be restored mkdir "$DATADIR/restored" restore-program -r "$DATADIR/repo" "$DATADIR/restored" diff -rq "$DATADIR/data" "$DATADIR/restored" Each "IMPLEMENT GIVEN" (or WHEN, THEN) is followed by a regular expression on the same line, and then a shell script that gets executed to implement any step that matches the regular expression. The implementation can extract data from the match as well: for example, the regular expression might allow a file size to be specified. The above example seems a bit silly, of course: why go to the effort to obfuscate the various steps? The answer is that the various steps, implemented using IMPLEMENTS, can be combined in many ways, to test different aspects of the program being tested. In effect, the IMPLEMENTS sections provide a vocabulary which the scenario writer can use to express a variety of usefully different scenarios, which together test all the aspects of the software that need to be tested. Moreover, by making the step descriptions be human language text, matched by regular expressions, most of the test can hopefully be written, and understood, by non-programmers. Someone who understands what a program should do, could write tests to verify its behaviour. The implementations of the various steps need to be implemented by a programmer, but given a well-designed set of steps, with enough flexibility in their implementation, that quite a good test suite can be written. Test language specification --------------------------- A test document is written in [Markdown][markdown], with block quoted code blocks being interpreted specially. Each block must follow the syntax defined here. * Every step in a scenario is one line, and starts with a keyword. * Each implementation (IMPLEMENTS) starts as a new block, and continues until there is a block that starts with another keyword. The following keywords are defined. * **SCENARIO** starts a new scenario. The rest of the line is the name of the scenario. The name is used for documentation and reporting purposes only and has no semantic meaning. SCENARIO MUST be the first keyword in a scenario, with the exception of IMPLEMENTS. The set of documents passed in a test run may define any number of scenarios between them, but there must be at least one or it is a test failure. The IMPLEMENTS sections are shared between the documents and scenarios. * **ASSUMING** defines a condition for the scenario. The rest of the line is "matched text", which gets implemented by an IMPLEMENTS section. If the code executed by the implementation fails, the scenario is skipped. * **GIVEN** prepares the world for the test to run. If the implementation fails, the scenario fails. * **WHEN** makes the change to the world that is to be tested. If the code fails, the scenario fails. * **THEN** verifies that the changes made by the GIVEN steps did the right thing. If the code fails, the scenario fails. * **FINALLY** specifies how to clean up after a scenario. If the code fails, the scenario fails. All FINALLY blocks get run either when encountered in the scenario flow, or at the end of the scenario, regardless of whether the scenario is failing or not. * **AND** acts as ASSUMING, GIVEN, WHEN, THEN, or FINALLY: whichever was used last. It must not be used unless the previous step was one of those, or another AND. * **IMPLEMENTS** is followed by one of ASSUMING, GIVEN, WHEN, or THEN, and a PCRE regular expression, all on one line, and then further lines of shell commands until the end of the block quoted code block. Markdown is unclear whether an empty line (no characters, not even whitespace) between two block quoted code blocks starts a new one or not, so we resolve the ambiguity by specifiying that a code block directly following a code block is a continuation unless it starts with one of the scenario testing keywords. The shell commands get parenthesised parts of the match of the regular expression as environment variables (`$MATCH_1` etc). For example, if the regexp is "a (\d+) byte file", then `$MATCH_1` gets set to the number matched by `\d+`. The test runner creates a temporary directory, whose name is given to the shell code in the `DATADIR` environment variable. The test runner sets the `SRCDIR` environment variable to the path to the directory it was invoked from (by convention, the root of the source tree of the project). The test runner removes all other environment variables, except `TERM`, `USER`, `USERNAME`, `LOGNAME`, `HOME`, and `PATH`. It also forces `SHELL` set to `/bin/sh`, and `LC_ALL` set to `C`, in order to have as clean an environment as possible for tests to run in. The shell commands get invoked with `/bin/sh -eu`, and need to be written accordingly. Be careful about commands that return a non-zero exit code. There will eventually be a library of shell functions supplied which allow handling the testing of non-zero exit codes cleanly. In addition functions for handling stdout and stderr will be provided. The code block of an IMPLEMENTS block fails if the shell invocation exits with a non-zero exit code. Output to stderr is not an indication of failure. Any output to stdout or stderr may or may not be shown to the user. Semantics: * The name of each scenario (given with SCENARIO) must be unique. * All names of scenarios and steps will be normalised before use (whitespace collapse, leading and trailing whitespace * Every ASSUMING, GIVEN, WHEN, THEN, FINALLY must be matched by exactly one IMPLEMENTS. The test runner checks this before running any code. * Every IMPLEMENTS may match any number of ASSUMING, GIVEN, WHEN, THEN, or FINALLY. The test runner may warn if an IMPLEMENTS is unused. * If ASSUMING fails, that scenario is skipped, and any FINALLY steps are not run. See also -------- Wikipedia has an article on [Behaviour Driven Development][BDD], which can provide background and further explanation to what this tools tries to do. [BDD]: https://en.wikipedia.org/wiki/Behavior-driven_development [Markdown]: http://daringfireball.net/projects/markdown/ TODO ---- * Add DEFINING, PRODUCING, if they turn out to be useful. * Need something like ASSUMING, except fail the scenario if the pre-condition is not true. Useful for testing that you can ssh to localhost when flinging, for example. **DJAS**: We think this might be 'REQUIRING' and it still does not run the FINALLY group. cmdtest-0.10/cmdtest0000755000175000017500000001763612224016632014365 0ustar jenkinsjenkins#!/usr/bin/python # Copyright 2011 Lars Wirzenius # # 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 . import cliapp import glob import logging import os import shutil import sys import tempfile import time import ttystatus import unittest import cmdtestlib ALL_TESTS = '' COMPLETE_TEST = '' class TestFailure(Exception): def __init__(self, test, msg): self.msg = 'FAIL: %s: %s' % (test.name, msg) def __str__(self): return self.msg class CommandTester(cliapp.Application): def add_settings(self): self.settings.string(['command', 'c'], 'ignored for backwards compatibility') self.settings.string_list(['test', 't'], 'run only TEST (can be given many times)', metavar='TEST') self.settings.boolean(['timings'], 'report how long each test takes') self.settings.boolean(['keep', 'k'], 'keep temporary data on failure') def process_args(self, dirnames): self.timings = {} self.timings[ALL_TESTS] = {} suite_started = time.time() td = self.load_tests(dirnames) self.setup_ttystatus(td) errors = 0 self.setup_tempdir() self.run_script(ALL_TESTS, td.setup_once) for test in td.tests: self.timings[test.name] = {} started = time.time() self.ts['test'] = test self.ts['test-name'] = test.name self.run_script(test.name, td.setup) for e in self.run_test(test): logging.error(str(e)) self.ts.clear() self.output.write('%s\n' % str(e)) errors += 1 self.run_script(test.name, td.teardown) self.timings[test.name][COMPLETE_TEST] = time.time() - started self.run_script(ALL_TESTS, td.teardown_once) keep_tempdir = errors and self.settings['keep'] if not keep_tempdir: self.cleanup_tempdir() self.timings[ALL_TESTS][COMPLETE_TEST] = time.time() - suite_started ok = len(td.tests) - errors self.ts.finish() self.output.write('%d/%d tests OK, %d failures\n' % (ok, len(td.tests), errors)) if keep_tempdir: self.output.write('Test work area: %s\n' % self.tempdir) if self.settings['timings']: self.report_timings() if errors: sys.exit(1) def setup_ttystatus(self, td): self.ts = ttystatus.TerminalStatus(period=0.001) self.ts['tests'] = td.tests self.ts.format('test %Index(test,tests): %String(test-name)') def load_tests(self, dirnames): td = cmdtestlib.TestDir() for dirname in dirnames: if self.settings['test']: filenames = self.find_requested_tests(dirname) td.scan(dirname, filenames) else: td.scan(dirname) return td def find_requested_tests(self, dirname): filenames = [] for test in self.settings['test']: matches = glob.glob(os.path.join(dirname, test + '.*')) filenames += [os.path.basename(x) for x in matches] return filenames def setup_tempdir(self): self.tempdir = tempfile.mkdtemp() logging.info('Temporary directory %s' % self.tempdir) self.datadir = os.path.join(self.tempdir, 'data') os.mkdir(self.datadir) def cleanup_tempdir(self): logging.info('Removing temporary directory %s' % self.tempdir) shutil.rmtree(self.tempdir) def run_script(self, test_name, script_name): logging.debug('run_script: test_name=%s script_name=%s' % (test_name, script_name)) if script_name: started = time.time() self.runcmd([script_name], env=self.add_to_env(test_name)) self.timings[test_name][script_name] = time.time() - started def add_to_env(self, test_name): env = dict(os.environ) env['SRCDIR'] = os.getcwd() env['DATADIR'] = self.datadir env['TESTNAME'] = test_name return env def run_test(self, test): logging.info('Test case: %s' % test.name) self.run_script(test.name, test.setup) if test.script: argv = [test.script] else: raise cliapp.AppException('Must have a .script file for test') stdout_name = test.path_prefix + '.stdout-actual' stderr_name = test.path_prefix + '.stderr-actual' with open(stdout_name, 'wb') as stdout: with open(stderr_name, 'wb') as stderr: if test.stdin: stdin = open(test.stdin, 'rb') else: stdin = None env = self.add_to_env(test.name) exit, out, err = self.runcmd_unchecked(argv, env=env, stdin=stdin, stdout=stdout, stderr=stderr) if stdin is not None: stdin.close() self.run_script(test.name, test.teardown) errors = [] stdout_diff_name = test.path_prefix + '.stdout-diff' stdout_diff = self.diff(test.stdout or '/dev/null', stdout_name, stdout_diff_name) if stdout_diff: errors.append(TestFailure(test, 'stdout diff:\n%s' % stdout_diff)) stderr_diff_name = test.path_prefix + '.stderr-diff' stderr_diff = self.diff(test.stderr or '/dev/null', stderr_name, stderr_diff_name) if stderr_diff: errors.append(TestFailure(test, 'stderr diff:\n%s' % stderr_diff)) contents = cmdtestlib.cat(test.exit or '/dev/null') expected_exit = int(contents.strip() or '0') if exit != expected_exit: errors.append(TestFailure(test, 'got exit code %s, expected %s' % (exit, expected_exit))) if not errors: os.remove(stdout_name) os.remove(stderr_name) os.remove(stdout_diff_name) os.remove(stderr_diff_name) return errors def diff(self, expected_name, actual_name, diff_name): argv = ['diff', '-u', expected_name, actual_name] with open(diff_name, 'w') as f: exit, out, err = self.runcmd_unchecked(argv, stdout=f) with open(diff_name, 'r') as f: return f.read() def report_timings(self): def report(key, title): t = self.timings[key] self.output.write(' %s: %.1f s\n' % (title, t[COMPLETE_TEST])) items = [(t[x], x) for x in t.keys() if x != COMPLETE_TEST] for secs, script in sorted(items): self.output.write(' %4.1f %s\n' % (secs, script)) self.output.write('Timings (in seconds):\n') report(ALL_TESTS, 'whole test suite') for name in sorted(x for x in self.timings.keys() if x != ALL_TESTS): report(name, name) if __name__ == '__main__': CommandTester(version=cmdtestlib.__version__).run() cmdtest-0.10/cmdtest.1.in0000644000175000017500000001047712224016632015122 0ustar jenkinsjenkins.\" Copyright 2011 Lars Wirzenius .\" .\" 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 . .\" .TH CMDTEST 1 .SH NAME cmdtest \- blackbox testing of Unix command line tools .SH SYNOPSIS .SH DESCRIPTION .B cmdtest black box tests Unix command line tools. Given some test scripts, their inputs, and expected outputs, it verifies that the command line produces the expected output. If not, it reports problems, and shows the differences. .PP Each test case .I foo consists of the following files: .TP .I foo.script a script to run the test (this is required) .TP .I foo.stdin the file fed to standard input .TP .I foo.stdout the expected output to the standard output .TP .I foo.stderr the expected output to the standard error .TP .I foo.exit the expected exit code .TP .I foo.setup a shell script to run before the test .TP .I foo.teardown a shell script to run after test .PP Usually, a single test is not enough. All tests are put into the same directory, and they may share some setup and teardown code: .TP .I setup-once a shell script to run once, before any tests .TP .I setup a shell script to run before each test .TP .I teardown a shell script to run after each test .TP .I teardown-once a shell script to run once, after all tests .PP .B cmdtest is given the name of the directory with all the tests, or several such directories, and it does the following: .PP .na .nh \(bu execute .I setup-once .PP \(bu for each test case (unique prefix .IR foo ): .RS .HP 2 \(em execute .I setup .HP 2 \(em execute .I foo.setup .HP 2 \(em execute the command, by running .IR foo.script , and redirecting standard input to come from .IR foo.stdin , and capturing standard output and error and exit codes .HP 2 \(em execute .I foo.teardown .HP 2 \(em execute .I teardown .HP 2 \(em report result of test: does exit code match .IR foo.exit , standard output match .IR foo.stdout , and standard error match .IR foo.stderr ? .RE .fi .hy .PP \(bu execute .I teardown-once .PP Except for .IR foo.script , all of these files are optional. If a setup or teardown script is missing, it is simply not executed. If one of the standard input, output, or error files is missing, it is treated as if it were empty. If the exit code file is missing, it is treated as if it specified an exit code of zero. .PP The shell scripts may use the following environment variables: .TP .B DATADIR a temporary directory where files may be created by the test .TP .B TESTNAME name of the current test (will be empty for .B setup-once and .BR teardown-once ) .TP .B SRCDIR directory from which .B cmdtest was launched .SH OPTIONS .SH EXAMPLE To test that the .BR echo (1) command outputs the expected string, create a file called .I echo-tests/hello.script containing the following content: .IP .nf #!/bin/sh echo hello, world .fi .PP Also create the file .I echo-tests/hello.stdout containing: .IP hello, world .PP Then you can run the tests: .IP .nf $ cmdtest echo-tests test 1/1 1/1 tests OK, 0 failures .fi .PP If you change the stdout file to be something else, .B cmdtest will report the differences: .IP .nf $ cmdtest echo-tests FAIL: hello: stdout diff: --- echo-tests/hello.stdout 2011-09-11 19:14:47 +0100 +++ echo-tests/hello.stdout-actual 2011-09-11 19:14:49 +0100 @@ -1 +1 @@ -something else +hello, world test 1/1 0/1 tests OK, 1 failures .fi .PP Furthermore, the .I echo-tests directory will contain the actual output files, and diffs from the expected files. If one of the actual output files is actually correct, you can actualy rename it to be the expected file. Actually, that's a very convenient way of creating the expected output files: you run the test, fixing things, until you've manually checked the actual output is correct, then you rename the file. .SH "SEE ALSO" .BR cliapp (5). cmdtest-0.10/cmdtestlib.py0000644000175000017500000000516412224016632015471 0ustar jenkinsjenkins# Copyright 2011 Lars Wirzenius # # 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 . __version__ = '0.10' import os def cat(filename): '''Return contents of file, or empty string if it doesn't exist.''' if os.path.exists(filename): with open(filename) as f: return f.read() else: return '' class TestCase(object): def __init__(self, name, path_prefix): self.name = name self.path_prefix = path_prefix class TestDir(object): '''Contain information about a directory of test cases.''' per_test_suffixes = ('script', 'stdin', 'stdout', 'stderr', 'exit', 'setup', 'teardown') def __init__(self): self.setup = None self.setup_once = None self.tests = [] self.teardown = None self.teardown_once = None def scan(self, dirname, filenames=None): filenames = os.listdir(dirname) if filenames is None else filenames script_names = ['setup_once', 'setup', 'teardown', 'teardown_once'] for name in script_names: if name in filenames: full_path = os.path.join(dirname, name) setattr(self, name, full_path) prefixes = self.find_prefixes(filenames) for prefix in prefixes: test = TestCase(prefix, os.path.join(dirname, prefix)) for suffix in self.per_test_suffixes: name = '%s.%s' % (prefix, suffix) if name in filenames: value = os.path.join(dirname, name) else: value = None setattr(test, suffix, value) self.tests.append(test) def find_prefixes(self, filenames): prefixes = set() for filename in filenames: for suffix in self.per_test_suffixes: suffix = '.' + suffix if filename.endswith(suffix): prefix = filename[:-len(suffix)] prefixes.add(prefix) return sorted(list(prefixes)) cmdtest-0.10/cmdtestlib_tests.py0000644000175000017500000000564212224016632016714 0ustar jenkinsjenkins# Copyright 2011 Lars Wirzenius # # 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 . import os import shutil import tempfile import unittest from cmdtestlib import TestDir, cat class TestDirTests(unittest.TestCase): def test_finds_nothing_for_empty_directory(self): td = TestDir() td.scan('tests', filenames=[]) self.assertEqual(td.setup_once, None) self.assertEqual(td.setup, None) self.assertEqual(td.tests, []) self.assertEqual(td.teardown, None) self.assertEqual(td.teardown_once, None) def test_finds_setup_and_teardown_files(self): td = TestDir() td.scan('tests', filenames=['setup_once', 'setup', 'teardown', 'teardown_once']) self.assertEqual(td.setup_once, 'tests/setup_once') self.assertEqual(td.setup, 'tests/setup') self.assertEqual(td.tests, []) self.assertEqual(td.teardown, 'tests/teardown') self.assertEqual(td.teardown_once, 'tests/teardown_once') def test_finds_tests(self): td = TestDir() td.scan('tests', filenames=['foo.script']) self.assertEqual(len(td.tests), 1) test = td.tests[0] self.assertEqual(test.name, 'foo') self.assertEqual(test.script, 'tests/foo.script') self.assertEqual(test.stdin, None) def test_finds_no_prefixes_when_there_are_none(self): td = TestDir() self.assertEqual(td.find_prefixes(['setup']), []) def test_finds_single_prefix(self): td = TestDir() self.assertEqual(td.find_prefixes(['setup', 'foo.setup']), ['foo']) def test_finds_two_prefixes(self): td = TestDir() self.assertEqual(td.find_prefixes(['setup', 'foo.setup', 'bar.script']), ['bar', 'foo']) class CatTests(unittest.TestCase): def setUp(self): self.tempdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tempdir) def test_returns_empty_string_for_nonexistent_file(self): filename = os.path.join(self.tempdir, 'file.txt') self.assertEqual(cat(filename), '') def test_returns_contents_of_file(self): filename = os.path.join(self.tempdir, 'file.txt') with open(filename, 'w') as f: f.write('foobar') self.assertEqual(cat(filename), 'foobar') cmdtest-0.10/echo-tests/0000755000175000017500000000000012224016632015035 5ustar jenkinsjenkinscmdtest-0.10/echo-tests/hello.script0000755000175000017500000000003412224016632017366 0ustar jenkinsjenkins#!/bin/sh echo hello, world cmdtest-0.10/echo-tests/hello.setup0000755000175000017500000000004312224016632017222 0ustar jenkinsjenkins#!/bin/sh echo "hello.setup runs" cmdtest-0.10/echo-tests/hello.stdout0000644000175000017500000000001512224016632017400 0ustar jenkinsjenkinshello, world cmdtest-0.10/echo-tests/setup_once0000755000175000017500000000004312224016632017124 0ustar jenkinsjenkins#!/bin/sh echo "setup-once runs" cmdtest-0.10/fail-tests/0000755000175000017500000000000012224016632015032 5ustar jenkinsjenkinscmdtest-0.10/fail-tests/fail.script0000755000175000017500000000015412224016632017176 0ustar jenkinsjenkins#!/bin/sh echo "file used by test" > "$DATADIR/file.txt" echo "this is not empty output to make test fail" cmdtest-0.10/run-yarn0000755000175000017500000000007412224016632014461 0ustar jenkinsjenkins#!/bin/sh set -eu ./yarn --no-default-config --quiet "$@" cmdtest-0.10/setup.py0000644000175000017500000000624612224016632014501 0ustar jenkinsjenkins#!/usr/bin/python # Copyright (C) 2011 Lars Wirzenius # # 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, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from distutils.core import setup, Extension from distutils.cmd import Command from distutils.command.build import build from distutils.command.clean import clean import glob import os import shutil import subprocess import cmdtestlib try: import markdown except ImportError: markdown_version = None else: if (hasattr(markdown, 'extensions') and hasattr(markdown.extensions, 'Extension')): markdown_version = True else: markdown_version = False class GenerateManpage(build): def run(self): build.run(self) print 'building manpages' cmds = ['cmdtest'] if markdown_version: cmds.append('yarn') for x in cmds: with open('%s.1' % x, 'w') as f: subprocess.check_call(['python', x, '--generate-manpage=%s.1.in' % x, '--output=%s.1' % x], stdout=f) class CleanMore(clean): def run(self): clean.run(self) for x in ['.coverage', 'cmdtest.1'] + glob.glob('*.pyc'): if os.path.exists(x): os.remove(x) class Check(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): if markdown_version: subprocess.check_call( ['python', '-m', 'CoverageTestRunner', '--ignore-missing-from', 'without-tests']) os.remove('.coverage') subprocess.check_call(['./cmdtest', 'echo-tests']) subprocess.check_call(['./cmdtest', 'sort-tests']) try: subprocess.check_call(['./cmdtest', 'fail-tests']) except subprocess.CalledProcessError: pass else: raise Exception('fail-tests did not fail, which is a surprise') if markdown_version: subprocess.check_call(['./cmdtest', 'yarn.tests']) setup(name='cmdtest', version=cmdtestlib.__version__, description='blackbox testing of Unix command line tools', author='Lars Wirzenius', author_email='liw@liw.fi', url='http://liw.fi/cmdtest/', scripts=['cmdtest', 'yarn'], py_modules=['cmdtestlib'], packages=['yarnlib'], data_files=[('share/man/man1', glob.glob('*.1'))], cmdclass={ 'build': GenerateManpage, 'check': Check, 'clean': CleanMore, }, ) cmdtest-0.10/shell-lib.sh0000644000175000017500000000011612224016632015164 0ustar jenkinsjenkins# A shell library for the shell-lib.yarn test. implement() { echo "$@" } cmdtest-0.10/shell-lib.yarn0000644000175000017500000000075212224016632015531 0ustar jenkinsjenkinsA simple test scenario with shell libraries ====================== This is a very simple test scenario, which exists only to test the scenario test runner itself. SCENARIO a shell library scenario The following is the actual test in this scenario: GIVEN a given WHEN a when THEN a then And the implementations follow. IMPLEMENTS GIVEN a given implement a given IMPLEMENTS WHEN a when implement a when IMPLEMENTS THEN a then implement a then cmdtest-0.10/simple.scenario0000644000175000017500000000117512224016632016001 0ustar jenkinsjenkinsA simple test scenario ====================== This is a very simple test scenario, which exists only to test the scenario test runner itself. SCENARIO a simple scenario The following is the actual test in this scenario: GIVEN a clean slate WHEN nothing happens THEN everything is OK AND not all is well FINALLY cleanup And the implementations follow. IMPLEMENTS GIVEN a clean slate echo a clean slate! IMPLEMENTS WHEN nothing happens true IMPLEMENTS THEN everything is OK echo OK! IMPLEMENTS THEN not all is well false IMPLEMENTS FINALLY cleanup echo cleaning up cmdtest-0.10/sort-tests/0000755000175000017500000000000012224016632015106 5ustar jenkinsjenkinscmdtest-0.10/sort-tests/empty.script0000755000175000017500000000003312224016632017471 0ustar jenkinsjenkins#!/bin/sh set -e sort "$@" cmdtest-0.10/sort-tests/empty.setup0000755000175000017500000000003212224016632017324 0ustar jenkinsjenkins#!/bin/sh # nothing here cmdtest-0.10/sort-tests/empty.stdin0000644000175000017500000000000012224016632017275 0ustar jenkinsjenkinscmdtest-0.10/sort-tests/empty.stdout0000644000175000017500000000000012224016632017476 0ustar jenkinsjenkinscmdtest-0.10/sort-tests/setup0000755000175000017500000000003212224016632016167 0ustar jenkinsjenkins#!/bin/sh # nothing here cmdtest-0.10/sort-tests/setup_once0000755000175000017500000000003212224016632017173 0ustar jenkinsjenkins#!/bin/sh # nothing here cmdtest-0.10/sort-tests/single-line.script0000755000175000017500000000003312224016632020541 0ustar jenkinsjenkins#!/bin/sh set -e sort "$@" cmdtest-0.10/sort-tests/single-line.stdin0000644000175000017500000000001512224016632020353 0ustar jenkinsjenkinshello, world cmdtest-0.10/sort-tests/single-line.stdout0000644000175000017500000000001512224016632020554 0ustar jenkinsjenkinshello, world cmdtest-0.10/without-tests0000644000175000017500000000006112224016632015542 0ustar jenkinsjenkinsyarnlib/__init__.py setup.py yarnlib/elements.py cmdtest-0.10/yarn0000755000175000017500000004004212224016632013656 0ustar jenkinsjenkins#!/usr/bin/python # Copyright 2013 Lars Wirzenius # # 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 . # # =*= License: GPL-3+ =*= import cliapp import collections import logging import os import re import shutil import sys import tempfile import time import ttystatus import cmdtestlib import yarnlib class YarnRunner(cliapp.Application): def add_settings(self): self.settings.boolean( ['no-act', 'dry-run', 'pretend', 'n'], 'do not actually run any tests, merely print what would be run') self.settings.boolean( ['quiet', 'q'], 'be quiet, avoid progress reporting, only show errors') self.settings.boolean( ['verbose', 'v'], 'make progress reporting be more verbose ("wall of text"), ' 'instead of a one-line status info; this is turned ' 'automatically if there is not terminal') self.settings.string_list( ['shell-library', 's'], 'include a shell library for the IMPLEMENTS sections to use') self.settings.string_list( ['run', 'r'], 'run only TEST (this option can be repeated)', metavar='TEST') self.settings.string( ['tempdir'], 'use DIR as the temporary directory for tests; ' 'it should be empty or not exist', metavar='DIR') self.settings.string_list( ['env'], 'add NAME=VALUE to the environment when tests are run', metavar='NAME=VALUE') self.settings.boolean( ['snapshot'], 'make snapshots of test working directory ' 'after each scenario step; you probably ' 'want to use this with --tempdir') self.settings.boolean( ['timings'], 'report wall clock time for each scenario and step') def info(self, msg): if self.settings['verbose']: logging.info(msg) self.output.write('%s\n' % msg) def warning(self, msg): if self.settings['verbose']: logging.warning(msg) self.output.write('WARNING: %s\n' % msg) elif not self.settings['quiet']: self.ts.notify('WARNING: %s' % msg) def error(self, msg): if self.settings['verbose']: logging.info(msg) sys.stderr.write('%s\n' % msg) elif not self.settings['quiet']: self.ts.error(msg) def process_args(self, args): # Do we have tty? If not, turn on --verbose, unless --quiet. if not self.settings['quiet']: try: open('/dev/tty', 'w') except IOError: self.settings['verbose'] = True self.ts = ttystatus.TerminalStatus(period=0.001) if not self.settings['quiet'] and not self.settings['verbose']: self.ts.format( '%ElapsedTime() %Index(scenario,scenarios): ' '%String(scenario_name): ' 'step %Index(step,steps): %String(step_name)') scenarios, implementations = self.parse_scenarios(args) self.check_there_are_scenarios(scenarios) self.check_for_duplicate_scenario_names(scenarios) self.check_for_thens(scenarios) self.connect_implementations(scenarios, implementations) shell_prelude = self.load_shell_libraries() self.ts['scenarios'] = scenarios self.ts['num_scenarios'] = len(scenarios) self.info('Found %d scenarios' % len(scenarios)) self.scenarios_run = 0 self.steps_run = 0 self.timings = [] start_time = time.time() failed_scenarios = [] for scenario in self.select_scenarios(scenarios): if not self.run_scenario(scenario, shell_prelude): failed_scenarios.append(scenario) duration = time.time() - start_time if not self.settings['quiet']: self.ts.clear() self.ts.finish() if failed_scenarios: raise cliapp.AppException( 'Test suite FAILED in %s scenarios' % len(failed_scenarios)) if not self.settings['quiet']: print ( 'Scenario test suite PASS, with %d scenarios ' '(%d total steps), ' 'in %.1f seconds' % (self.scenarios_run, self.steps_run, duration)) if self.settings['timings']: self.report_timings() def parse_scenarios(self, filenames): mdparser = yarnlib.MarkdownParser() for filename in filenames: self.info('Parsing scenario file %s' % filename) blocks = mdparser.parse_file(filename) if not blocks: self.warning('No scenario code blocks in %s' % filename) block_parser = yarnlib.BlockParser() block_parser.parse_blocks(mdparser.blocks) return block_parser.scenarios, block_parser.implementations def check_there_are_scenarios(self, scenarios): if not scenarios: raise cliapp.AppException( 'There are no scenarios; must have at least one.') def check_for_duplicate_scenario_names(self, scenarios): counts = collections.Counter() for s in scenarios: counts[s.name] += 1 duplicates = [name for name in counts if counts[name] > 1] if duplicates: duplist = ''.join(' %s\n' % name for name in duplicates) raise cliapp.AppException( 'There are scenarios with duplicate names:\n%s' % duplist) def check_for_thens(self, scenarios): no_thens = [] for scenario in scenarios: for step in scenario.steps: if step.what == 'THEN': break else: no_thens.append(scenario) if no_thens: raise cliapp.AppException( 'Some scenarios have no THENs:\n%s' % ''.join(' "%s"\n' % s.name for s in scenarios)) def connect_implementations(self, scenarios, implementations): for scenario in scenarios: for step in scenario.steps: self.connect_implementation(scenario, step, implementations) def connect_implementation(self, scenario, step, implementations): matching = [i for i in implementations if step.what == i.what and self.implements_matches_step(i, step)] if len(matching) == 0: raise cliapp.AppException( 'Scenario "%s", step "%s %s" has no matching ' 'implementation' % (scenario.name, step.what, step.text)) if len(matching) > 1: s = '\n'.join( 'IMPLEMENTS %s %s' % (i.what, i.regexp) for i in matching) raise cliapp.AppException( 'Scenario "%s", step "%s %s" has more than one ' 'matching implementations:\n%s' % (scenario.name, step.what, step.text, s)) assert step.implementation is None step.implementation = matching[0] def load_shell_libraries(self): if not self.settings['shell-library']: self.info('No shell libraries defined') return '' libs = [] for filename in self.settings['shell-library']: self.info('Loading shell library %s' % filename) with open(filename) as f: text = f.read() libs.append('# Loaded from %s\n\n%s\n\n' % (filename, text)) return ''.join(libs) def select_scenarios(self, scenarios): def normalise(s): return ' '.join(s.lower().split()) def matches(a, b): return normalise(a) == normalise(b) if self.settings['run']: result = [] for name in self.settings['run']: for s in scenarios: if matches(s.name, name) and s not in result: result.append(s) break return result return scenarios def run_scenario(self, scenario, shell_prelude): self.start_scenario_timing(scenario.name) started = time.time() self.info('Running scenario %s' % scenario.name) self.ts['scenario'] = scenario self.ts['scenario_name'] = scenario.name self.ts['steps'] = scenario.steps self.scenarios_run += 1 if self.settings['no-act']: self.info('Pretending everything went OK') self.remember_scenario_timing(time.time() - started) return True if self.settings['tempdir']: tempdir = os.path.abspath(self.settings['tempdir']) if not os.path.exists(tempdir): os.mkdir(tempdir) else: tempdir = tempfile.mkdtemp() os.mkdir(self.scenario_dir(tempdir, scenario)) datadir = self.datadir(tempdir, scenario) os.mkdir(datadir) self.info('DATADIR is %s' % datadir) assuming = [s for s in scenario.steps if s.what == 'ASSUMING'] cleanup = [s for s in scenario.steps if s.what == 'FINALLY'] normal = [s for s in scenario.steps if s not in assuming + cleanup] ok = True step_number = 0 for step in assuming: exit = self.run_step(datadir, scenario, step, shell_prelude, False) step_number += 1 self.snapshot_datadir( tempdir, datadir, scenario, step_number, step) if exit != 0: self.ts.notify( 'Skipping "%s" because "%s %s" failed' % (scenario.name, step.what, step.text)) break else: for step in normal: exit = self.run_step( datadir, scenario, step, shell_prelude, True) step_number += 1 self.snapshot_datadir( tempdir, datadir, scenario, step_number, step) if exit != 0: ok = False break for step in cleanup: exit = self.run_step( datadir, scenario, step, shell_prelude, True) step_number += 1 self.snapshot_datadir( tempdir, datadir, scenario, step_number, step) if exit != 0: ok = False break if not self.settings['snapshot']: shutil.rmtree(tempdir) self.remember_scenario_timing(time.time() - started) return ok def clean_env(self): '''Return a clean environment for running tests.''' whitelisted = [ 'PATH', ] hardcoded = { 'TERM': 'dumb', 'SHELL': '/bin/sh', 'LC_ALL': 'C', 'USER': 'tomjon', 'USERNAME': 'tomjon', 'LOGNAME': 'tomjon', 'HOME': '/this/path/does/not/exist', } env = {} for key in whitelisted: if key in os.environ: env[key] = os.environ[key] for key in hardcoded: env[key] = hardcoded[key] for option_arg in self.settings['env']: if '=' not in option_arg: raise cliapp.AppException( '--env argument must contain "=" ' 'to separate environment variable name and value') key, value = option_arg.split('=', 1) env[key] = value return env def run_step(self, datadir, scenario, step, shell_prelude, report_error): started = time.time() self.info('Running step "%s %s"' % (step.what, step.text)) self.ts['step'] = step self.ts['step_name'] = '%s %s' % (step.what, step.text) self.steps_run += 1 m = self.implements_matches_step(step.implementation, step) assert m is not None env = self.clean_env() env['DATADIR'] = datadir env['SRCDIR'] = os.getcwd() for i, match in enumerate(m.groups('')): env['MATCH_%d' % (i+1)] = match shell_script = '%s\n\n%s\n' % ( shell_prelude, step.implementation.shell) exit, stdout, stderr = cliapp.runcmd_unchecked( ['sh', '-xeuc', shell_script], env=env) logging.debug('Exit code: %d' % exit) if stdout: logging.debug('Standard output:\n%s' % self.indent(stdout)) else: logging.debug('Standard output: empty') if stderr: logging.debug('Standard error:\n%s' % self.indent(stderr)) else: logging.debug('Standard error: empty') if exit != 0 and report_error: self.error( 'ERROR: In scenario "%s"\nstep "%s %s" failed,\n' 'with exit code %d:\n' 'Standard output from shell command:\n%s' 'Standard error from shell command:\n%s' % (scenario.name, step.what, step.text, exit, self.indent(stdout), self.indent(stderr))) self.remember_step_timing( '%s %s' % (step.what, step.text), time.time() - started) return exit def scenario_dir(self, tempdir, scenario): return os.path.join(tempdir, self.nice(scenario.name)) def datadir(self, tempdir, scenario): sd = self.scenario_dir(tempdir, scenario) return os.path.join(sd, 'datadir') def snapshot_dir(self, tempdir, scenario, step, step_number): sd = self.scenario_dir(tempdir, scenario) base = '%03d-%s-%s' % (step_number, step.what, self.nice(step.text)) return os.path.join(sd, base) def snapshot_datadir(self, tempdir, datadir, scenario, step_number, step): snapshot = self.snapshot_dir(tempdir, scenario, step, step_number) cliapp.runcmd(['cp', '-a', datadir, snapshot]) def nice(self, name): # Quote a scenario or step name so it forms a nice filename. nice_chars = "abcdefghijklmnopqrstuvwxyz" nice_chars += nice_chars.upper() nice_chars += "0123456789-." nice = [] for c in name: if c in nice_chars: nice.append(c) elif not nice or nice[-1] != '_': nice.append('_') nice = ''.join(nice) return nice def implements_matches_step(self, implements, step): '''Return re.Match if implements matches the step. Otherwise, return None. ''' m = re.match(implements.regexp, step.text, re.I) if m and m.end() != len(step.text): return None return m def indent(self, s): return ''.join(' %s\n' % line for line in s.splitlines()) def start_scenario_timing(self, scenario_name): self.timings.append((scenario_name, None, [])) def remember_scenario_timing(self, duration): scenario_name, _, step_tuples = self.timings[-1] self.timings[-1] = (scenario_name, duration, step_tuples) def remember_step_timing(self, step_name, step_duration): scenario_name, scenario_duration, step_tuples = self.timings[-1] step_tuples = step_tuples + [(step_name, step_duration)] self.timings[-1] = (scenario_name, scenario_duration, step_tuples) def report_timings(self): for scenario_name, scenario_duration, step_tuples in self.timings: print '%5.1f %s' % (scenario_duration, scenario_name) for step_name, step_duration in step_tuples: print ' %5.1f %s' % (step_duration, step_name) YarnRunner(version=cmdtestlib.__version__).run() cmdtest-0.10/yarn.1.in0000644000175000017500000001142612224016632014423 0ustar jenkinsjenkins.\" Copyright 2013 Lars Wirzenius .\" .\" 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 . .\" .TH YARN 1 .SH NAME yarn \- scenario testing of Unix command line tools .SH SYNOPSIS .SH DESCRIPTION .B yarn is a scenario testing tool: you write a scenario describing how a user uses your software and what should happen, and express, using very lightweight syntax, the scenario in such a way that it can be tested automatically. The scenario has a simple, but strict structure: .IP .nf GIVEN some setup for the test WHEN thing that is to be tested happens THEN the post-conditions must be true .fi .PP As an example, consider a very short test scenario for verifying that a backup program works, at least for one simple case. .IP .nf SCENARIO backups can be restored GIVEN some live data in a directory AND an empty backup repository WHEN a backup is made THEN the data case be restored FINALLY cleanup .fi .PP Note the addition of AND: you can have multiple GIVEN, WHEN, and THEN statements. The AND keyword makes the text be more readable. SCENARIO is also necessary, and gives the title. .PP FINALLY is for cleanups. The FINALLY steps will be run regardless of whether the scenario succeeds or not. .PP Scenarios are meant to be written in somewhat human readable language. However, they are not free form text. In addition to the GIVEN/WHEN/THEN structure, the text for each of the steps needs a computer-executable implementation. This is done by using IMPLEMENTS. The backup scenario from above might be implemented as follows: .IP .nf IMPLEMENTS GIVEN some live data in a directory rm -rf "$TESTDIR/data" mkdir "$TESTDIR/data" echo foo > "$TESTDIR/data/foo" .IP IMPLEMENTS GIVEN an empty backup repository rm -rf "$TESTDIR/repo" mkdir "$TESTDIR/repo" .IP IMPLEMENTS WHEN a backup is made backup-program -r "$TESTDIR/repo" "$TESTDIR/data" .IP IMPLEMENTS THEN the data can be restored mkdir "$TESTDIR/restored" restore-program -r "$TESTDIR/repo" "$TESTDIR/restored" diff -rq "$TESTDIR/data" "$TESTDIR/restored" .IP IMPLEMENTS FINALLY cleanup echo nothing to do, actually .fi .PP Each "IMPLEMENTS GIVEN" (or WHEN, THEN, FINALLY) is followed by a regular expression on the same line, and then a shell script that gets executed to implement any step that matches the regular expression. The implementation can extract data from the match as well: for example, the regular expression might allow a file size to be specified. .PP The above example is a bit silly, of course: why go to the effort to obfuscate the various steps? The answer is that the various steps, implemented using IMPLEMENTS, can be combined in many ways, to test different aspects of the program being tested. .PP Moreover, by making the step descriptions be human language text, matched by regular expressions, most of the test can hopefully be written, and understood, by non-programmers. Someone who understands what a program should do, could write tests to verify its behaviour. The implementations of the various steps need to be implemented by a programmer, but given a well-designed set of steps, with enough flexibility in their implementation, that quite a good test suite can be written. .PP The shell commands in an IMPLEMENTS section are run in the directory in which the user ran .BR yarn . The environment variable .B SRCDIR is set to the fully qualified path to that directory. .SH OPTIONS .SH ENVIRONMENT .TP .B DATADIR Fully qualified pathname to a temporary directory, in which the tests can use files. The temporary directory is removed at the end of the test execution, unless the user specifies otherwise with \-\-snapshot. .TP .B SRCDIR Fully qualitifed pathname to the directory in which the user ran .BR yarn . This is useful when the tests want to change the directory. .SH EXAMPLE To run .B yarn on all the scenarios in your current directory: .IP .nf yarn *.scenario .fi .PP All the files will be treated together as if they had been one file. .PP To add a shell library to be included when running any IMPLEMENTS section: .IP .nf yarn \-\-shell\-library mylib.sh *.scenario .fi .PP You can repeat .B \-\-shell\-library as many times as necessary. .SH "SEE ALSO" .BR cmdtest (1), .BR cliapp (5). .PP The README.yarn file has more details on the scenario testing language. cmdtest-0.10/yarn.tests/0000755000175000017500000000000012224016632015071 5ustar jenkinsjenkinscmdtest-0.10/yarn.tests/assuming-failure.script0000755000175000017500000000064412224016632021601 0ustar jenkinsjenkins#!/bin/sh set -eu cat < "$DATADIR/test.yarn" SCENARIO foo ASSUMING something THEN remember FINALLY cleanup IMPLEMENTS ASSUMING something false IMPLEMENTS THEN remember touch "$DATADIR/then-flag" IMPLEMENTS FINALLY cleanup touch "$DATADIR/cleanup-flag" EOF ./run-yarn "$DATADIR/test.yarn" [ ! -e "$DATADIR/then-flag" ] [ ! -e "$DATADIR/cleanup-flag" ] cmdtest-0.10/yarn.tests/assuming-failure.stdout0000644000175000017500000000006312224016632021607 0ustar jenkinsjenkinsSkipping "foo" because "ASSUMING something" failed cmdtest-0.10/yarn.tests/assuming.script0000755000175000017500000000063712224016632020156 0ustar jenkinsjenkins#!/bin/sh set -eu cat < "$DATADIR/test.yarn" SCENARIO foo ASSUMING something THEN remember FINALLY cleanup IMPLEMENTS ASSUMING something true IMPLEMENTS THEN remember touch "$DATADIR/then-flag" IMPLEMENTS FINALLY cleanup touch "$DATADIR/cleanup-flag" EOF ./run-yarn "$DATADIR/test.yarn" [ -e "$DATADIR/then-flag" ] [ -e "$DATADIR/cleanup-flag" ] cmdtest-0.10/yarn.tests/duplicate-scenario-names.exit0000644000175000017500000000000212224016632022630 0ustar jenkinsjenkins1 cmdtest-0.10/yarn.tests/duplicate-scenario-names.script0000755000175000017500000000031712224016632023177 0ustar jenkinsjenkins#!/bin/sh set -eu cat < "$DATADIR/test.yarn" SCENARIO foo THEN nop SCENARIO foo THEN nop IMPLEMENTS THEN nop true EOF ./run-yarn "$DATADIR/test.yarn" cmdtest-0.10/yarn.tests/duplicate-scenario-names.stderr0000644000175000017500000000007012224016632023167 0ustar jenkinsjenkinsERROR: There are scenarios with duplicate names: foo cmdtest-0.10/yarn.tests/env-option.script0000755000175000017500000000033212224016632020416 0ustar jenkinsjenkins#!/bin/sh set -eu cat < "$DATADIR/test.yarn" SCENARIO foo THEN yoyo is set IMPLEMENTS THEN yoyo is set env | grep '^yoyo=' EOF ./run-yarn --env yoyo=something "$DATADIR/test.yarn" cmdtest-0.10/yarn.tests/env.script0000755000175000017500000000052712224016632017116 0ustar jenkinsjenkins#!/bin/sh set -eu cat << 'EOF' > "$DATADIR/env.yarn" SCENARIO check environment THEN DATADIR is set AND SRCDIR is set AND NOTSET is not set IMPLEMENTS THEN (\S+) is set env env | grep "^$MATCH_1=" IMPLEMENTS THEN (\S+) is not set ! env | grep "^$MATCH_1=" EOF NOTSET=foo ./run-yarn "$DATADIR/env.yarn" cmdtest-0.10/yarn.tests/finally.script0000755000175000017500000000062612224016632017764 0ustar jenkinsjenkins#!/bin/sh set -eu cat < "$DATADIR/finally.yarn" SCENARIO finally GIVEN nothing WHEN nothing THEN nothing FINALLY yeehaa IMPLEMENTS GIVEN nothing true IMPLEMENTS WHEN nothing true IMPLEMENTS THEN nothing true IMPLEMENTS FINALLY yeehaa touch "$DATADIR/finally.has.run" EOF ./run-yarn "$DATADIR/finally.yarn" test -e "$DATADIR/finally.has.run" cmdtest-0.10/yarn.tests/multi.script0000755000175000017500000000056512224016632017462 0ustar jenkinsjenkins#!/bin/sh set -eu cat < "$DATADIR/1.yarn" SCENARIO foo GIVEN all is ok WHEN doing ok THEN be ok EOF cat < "$DATADIR/2.yarn" IMPLEMENTS GIVEN all is ok true IMPLEMENTS WHEN doing ok true IMPLEMENTS THEN be ok true EOF ./run-yarn "$DATADIR/1.yarn" "$DATADIR/2.yarn" | sed 's/, in .* seconds$//' cmdtest-0.10/yarn.tests/no-act.script0000755000175000017500000000054512224016632017507 0ustar jenkinsjenkins#!/bin/sh set -eu # Create a scenario that will fail. cat < "$DATADIR/fail.yarn" SCENARIO this will fail GIVEN badness WHEN bad things happen THEN more badness IMPLEMENTS GIVEN badness false IMPLEMENTS WHEN bad things happen false IMPLEMENTS THEN more badness false EOF ./run-yarn -n "$DATADIR/fail.yarn" cmdtest-0.10/yarn.tests/no-scenarios.exit0000644000175000017500000000000212224016632020354 0ustar jenkinsjenkins1 cmdtest-0.10/yarn.tests/no-scenarios.script0000755000175000017500000000013312224016632020717 0ustar jenkinsjenkins#!/bin/sh set -eu cat < "$DATADIR/test.yarn" EOF ./run-yarn "$DATADIR/test.yarn" cmdtest-0.10/yarn.tests/no-scenarios.stderr0000644000175000017500000000006712224016632020721 0ustar jenkinsjenkinsERROR: There are no scenarios; must have at least one. cmdtest-0.10/yarn.tests/no-then.exit0000644000175000017500000000000212224016632017324 0ustar jenkinsjenkins1 cmdtest-0.10/yarn.tests/no-then.script0000755000175000017500000000025112224016632017670 0ustar jenkinsjenkins#!/bin/sh set -eu cat < "$DATADIR/1.yarn" SCENARIO foo WHEN doing ok IMPLEMENTS WHEN doing ok true EOF ./run-yarn "$DATADIR/1.yarn" cmdtest-0.10/yarn.tests/no-then.stderr0000644000175000017500000000005612224016632017667 0ustar jenkinsjenkinsERROR: Some scenarios have no THENs: "foo" cmdtest-0.10/yarn.tests/selected-test.script0000755000175000017500000000044512224016632021072 0ustar jenkinsjenkins#!/bin/sh set -eu cat << EOF > "$DATADIR/test.yarn" SCENARIO bar test THEN do bar SCENARIO foo test THEN do foo IMPLEMENTS THEN do (.*) touch "$DATADIR/\$MATCH_1" EOF ./run-yarn "$DATADIR/test.yarn" --run 'foo test' test -e "$DATADIR/foo" ! test -e "$DATADIR/bar" cmdtest-0.10/yarn.tests/setup0000755000175000017500000000005712224016632016161 0ustar jenkinsjenkins#!/bin/sh find "$DATADIR" -mindepth 1 -delete cmdtest-0.10/yarn.tests/shell-lib.script0000755000175000017500000000011312224016632020170 0ustar jenkinsjenkins#!/bin/sh set -eu ./run-yarn --shell-library shell-lib.sh shell-lib.yarn cmdtest-0.10/yarn.tests/simple.exit0000644000175000017500000000000212224016632017245 0ustar jenkinsjenkins1 cmdtest-0.10/yarn.tests/simple.script0000755000175000017500000000005712224016632017615 0ustar jenkinsjenkins#!/bin/sh set -eu ./run-yarn simple.scenario cmdtest-0.10/yarn.tests/simple.stderr0000644000175000017500000000005012224016632017602 0ustar jenkinsjenkinsERROR: Test suite FAILED in 1 scenarios cmdtest-0.10/yarn.tests/snapshot.script0000755000175000017500000000336512224016632020170 0ustar jenkinsjenkins#!/bin/sh set -eu cat << EOF > "$DATADIR/foo.yarn" SCENARIO foo GIVEN foo WHEN foo THEN foo SCENARIO bar GIVEN bar WHEN bar THEN bar IMPLEMENTS GIVEN (.*) touch "\$DATADIR/\$MATCH_1.given" IMPLEMENTS WHEN (.*) touch "\$DATADIR/\$MATCH_1.when" IMPLEMENTS THEN (.*) touch "\$DATADIR/\$MATCH_1.then" EOF ./run-yarn --snapshot --tempdir "$DATADIR/tmp" "$DATADIR/foo.yarn" test -e "$DATADIR/tmp/bar" test -e "$DATADIR/tmp/bar/datadir" test -e "$DATADIR/tmp/bar/datadir/bar.given" test -e "$DATADIR/tmp/bar/datadir/bar.when" test -e "$DATADIR/tmp/bar/datadir/bar.then" test -e "$DATADIR/tmp/bar/001-GIVEN-bar" test -e "$DATADIR/tmp/bar/001-GIVEN-bar/bar.given" ! test -e "$DATADIR/tmp/bar/001-GIVEN-bar/bar.when" ! test -e "$DATADIR/tmp/bar/001-GIVEN-bar/bar.then" test -e "$DATADIR/tmp/bar/002-WHEN-bar" test -e "$DATADIR/tmp/bar/002-WHEN-bar/bar.given" test -e "$DATADIR/tmp/bar/002-WHEN-bar/bar.when" ! test -e "$DATADIR/tmp/bar/002-WHEN-bar/bar.then" test -e "$DATADIR/tmp/bar/003-THEN-bar" test -e "$DATADIR/tmp/bar/003-THEN-bar/bar.given" test -e "$DATADIR/tmp/bar/003-THEN-bar/bar.when" test -e "$DATADIR/tmp/bar/003-THEN-bar/bar.then" test -e "$DATADIR/tmp/foo/001-GIVEN-foo" test -e "$DATADIR/tmp/foo/001-GIVEN-foo/foo.given" ! test -e "$DATADIR/tmp/foo/001-GIVEN-foo/foo.when" ! test -e "$DATADIR/tmp/foo/001-GIVEN-foo/foo.then" test -e "$DATADIR/tmp/foo/002-WHEN-foo" test -e "$DATADIR/tmp/foo/002-WHEN-foo/foo.given" test -e "$DATADIR/tmp/foo/002-WHEN-foo/foo.when" ! test -e "$DATADIR/tmp/foo/002-WHEN-foo/foo.then" test -e "$DATADIR/tmp/foo/003-THEN-foo" test -e "$DATADIR/tmp/foo/003-THEN-foo/foo.given" test -e "$DATADIR/tmp/foo/003-THEN-foo/foo.when" test -e "$DATADIR/tmp/foo/003-THEN-foo/foo.then" cmdtest-0.10/yarn.tests/warn-if-empty.script0000755000175000017500000000037512224016632021026 0ustar jenkinsjenkins#!/bin/sh set -eu touch "$DATADIR/empty.yarn" # The grep below will fail unless the string exists, thereby failing the # entire test. ./run-yarn --no-quiet --log=/dev/stdout "$DATADIR/empty.yarn" 2>&1 | grep 'No scenario code blocks' > /dev/null cmdtest-0.10/yarnlib/0000755000175000017500000000000012224016632014417 5ustar jenkinsjenkinscmdtest-0.10/yarnlib/__init__.py0000644000175000017500000000151412224016632016531 0ustar jenkinsjenkins# Copyright 2013 Lars Wirzenius # # 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 . # # =*= License: GPL-3+ =*= from mdparser import MarkdownParser from elements import Scenario, ScenarioStep, Implementation from block_parser import BlockParser, BlockError cmdtest-0.10/yarnlib/block_parser.py0000644000175000017500000001051112224016632017435 0ustar jenkinsjenkins# Copyright 2013 Lars Wirzenius # # 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 . # # =*= License: GPL-3+ =*= import cliapp import yarnlib class BlockError(cliapp.AppException): pass # Parse a sequence of textual blocks into scenario and Implementation # objects, and their constituent objects. class BlockParser(object): def __init__(self): self.scenarios = [] self.implementations = [] self.line_parsers = { 'SCENARIO': self.parse_scenario, 'ASSUMING': self.parse_assuming, 'GIVEN': self.parse_given, 'WHEN': self.parse_when, 'THEN': self.parse_then, 'FINALLY': self.parse_finally, 'AND': self.parse_and, 'IMPLEMENTS': self.parse_implementing, } def parse_blocks(self, blocks): while blocks: blocks = self.parse_one(blocks) def parse_one(self, blocks): assert blocks block = blocks[0] assert block t = block.split('\n', 1) assert len(t) in [1,2] if len(t) == 1: line1 = block block = '' else: line1, block = t if block: blocks[0] = block else: del blocks[0] words = line1.split() if not words: return blocks rest = ' '.join(words[1:]) for keyword in self.line_parsers: if words[0] == keyword: return self.line_parsers[keyword](rest, blocks) raise BlockError("Syntax error: unknown step: %s" % line1) def parse_scenario(self, line, blocks): self.scenarios.append(yarnlib.Scenario(line)) return blocks def parse_simple(self, what, line, blocks): if not self.scenarios: raise BlockError('Syntax errror: %s before SCENARIO' % what) step = yarnlib.ScenarioStep(what, line) self.scenarios[-1].steps.append(step) return blocks def parse_assuming(self, line, blocks): return self.parse_simple('ASSUMING', line, blocks) def parse_given(self, line, blocks): return self.parse_simple('GIVEN', line, blocks) def parse_when(self, line, blocks): return self.parse_simple('WHEN', line, blocks) def parse_then(self, line, blocks): return self.parse_simple('THEN', line, blocks) def parse_finally(self, line, blocks): return self.parse_simple('FINALLY', line, blocks) def parse_and(self, line, blocks): if not self.scenarios: raise BlockError('Syntax errror: AND before SCENARIO') scenario = self.scenarios[-1] if not scenario.steps: raise BlockError( 'Syntax errror: AND before what it would continue') step = scenario.steps[-1] assert step.what in self.line_parsers return self.line_parsers[step.what](line, blocks) def parse_implementing(self, line, blocks): words = line.split() if len(words) < 2: raise BlockError( 'Syntax error: IMPLEMENTS must have what and regexp') what = words[0] regexp = ' '.join(words[1:]) if blocks: block = blocks[0] shell = [] rest = [] for block_line in block.splitlines(): if rest or block_line.startswith('IMPLEMENTS'): rest.append(block_line) else: shell.append(block_line) shell = '\n'.join(shell) if rest: blocks[0] = '\n'.join(rest) else: del blocks[0] else: shell = '' implementation = yarnlib.Implementation(what, regexp, shell) self.implementations.append(implementation) return blocks cmdtest-0.10/yarnlib/block_parser_tests.py0000644000175000017500000001175012224016632020665 0ustar jenkinsjenkins# Copyright 2013 Lars Wirzenius # # 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 . # # =*= License: GPL-3+ =*= import unittest import yarnlib class BlockParserTests(unittest.TestCase): def setUp(self): self.parser = yarnlib.BlockParser() def test_is_initially_empty(self): self.assertEqual(self.parser.scenarios, []) self.assertEqual(self.parser.implementations, []) def test_parses_simple_elements(self): self.parser.parse_blocks( ['SCENARIO foo', 'ASSUMING something', 'GIVEN bar', 'WHEN foobar\nTHEN yoyo\nFINALLY yay\nAND yeehaa']) self.assertEqual(len(self.parser.scenarios), 1) self.assertEqual(len(self.parser.implementations), 0) scenario = self.parser.scenarios[0] self.assertEqual(scenario.name, 'foo') self.assertEqual(len(scenario.steps), 6) self.assertEqual(scenario.steps[0].what, 'ASSUMING') self.assertEqual(scenario.steps[0].text, 'something') self.assertEqual(scenario.steps[1].what, 'GIVEN') self.assertEqual(scenario.steps[1].text, 'bar') self.assertEqual(scenario.steps[2].what, 'WHEN') self.assertEqual(scenario.steps[2].text, 'foobar') self.assertEqual(scenario.steps[3].what, 'THEN') self.assertEqual(scenario.steps[3].text, 'yoyo') self.assertEqual(scenario.steps[4].what, 'FINALLY') self.assertEqual(scenario.steps[4].text, 'yay') self.assertEqual(scenario.steps[5].what, 'FINALLY') self.assertEqual(scenario.steps[5].text, 'yeehaa') def test_normalises_whitespace(self): self.parser.parse_blocks(['SCENARIO foo bar ']) self.assertEqual(self.parser.scenarios[0].name, 'foo bar') def test_handles_empty_line(self): self.parser.parse_blocks(['SCENARIO foo\n\nGIVEN bar\nTHEN foobar']) self.assertEqual(len(self.parser.scenarios), 1) def test_raises_error_for_unknown_step(self): self.assertRaises( yarnlib.BlockError, self.parser.parse_blocks, ['SCENARIO foo\nblah']) def test_raises_error_for_step_outside_scenario(self): self.assertRaises( yarnlib.BlockError, self.parser.parse_blocks, ['GIVEN foo']) def test_raises_error_for_AND_before_scenario(self): self.assertRaises( yarnlib.BlockError, self.parser.parse_blocks, ['AND bar']) def test_raises_error_for_AND_before_step(self): self.assertRaises( yarnlib.BlockError, self.parser.parse_blocks, ['SCENARIO foo\nAND bar']) def test_parses_implements_in_a_block_by_itself(self): self.parser.parse_blocks(['IMPLEMENTS GIVEN foo\ntrue']) impls = self.parser.implementations self.assertEqual(len(impls), 1) self.assertEqual(impls[0].what, 'GIVEN') self.assertEqual(impls[0].regexp, 'foo') self.assertEqual(impls[0].shell, 'true') def test_parses_implements_with_empty_shell_text(self): self.parser.parse_blocks(['IMPLEMENTS GIVEN foo']) impls = self.parser.implementations self.assertEqual(len(impls), 1) self.assertEqual(impls[0].what, 'GIVEN') self.assertEqual(impls[0].regexp, 'foo') self.assertEqual(impls[0].shell, '') def test_parses_two_implements_in_a_code_block(self): self.parser.parse_blocks( ['IMPLEMENTS GIVEN foo\ntrue\nIMPLEMENTS WHEN bar\ncat /dev/null']) impls = self.parser.implementations self.assertEqual(len(impls), 2) self.assertEqual(impls[0].what, 'GIVEN') self.assertEqual(impls[0].regexp, 'foo') self.assertEqual(impls[0].shell, 'true') self.assertEqual(impls[1].what, 'WHEN') self.assertEqual(impls[1].regexp, 'bar') self.assertEqual(impls[1].shell, 'cat /dev/null') def test_raises_error_for_implements_with_no_args(self): self.assertRaises( yarnlib.BlockError, self.parser.parse_blocks, ['IMPLEMENTS']) def test_raises_error_for_implements_with_one_args(self): self.assertRaises( yarnlib.BlockError, self.parser.parse_blocks, ['IMPLEMENTS GIVEN']) def test_raises_error_for_implements_with_first_args_not_a_keyword(self): self.assertRaises( yarnlib.BlockError, self.parser.parse_blocks, ['IMPLEMENTS foo']) cmdtest-0.10/yarnlib/elements.py0000644000175000017500000000254612224016632016614 0ustar jenkinsjenkins# Copyright 2013 Lars Wirzenius # # 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 . # # =*= License: GPL-3+ =*= # This is a step in a scenario: GIVEN, WHEN, THEN, etc. class ScenarioStep(object): def __init__(self, what, text): self.what = what self.text = text self.implementation = None # This is the scenario itself. class Scenario(object): def __init__(self, name): self.name = name self.steps = [] # This is an IMPLEMENTS chunk. class Implementation(object): def __init__(self, what, regexp, shell): self.what = what self.regexp = regexp self.shell = shell def execute(self): exit, out, err = cliapp.runcmd_unchecked( ['sh', '-c', 'set -eu\n' + self.shell]) return exit cmdtest-0.10/yarnlib/mdparser.py0000644000175000017500000000466012224016632016614 0ustar jenkinsjenkins# Copyright 2013 Lars Wirzenius # # 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 . # # =*= License: GPL-3+ =*= import logging import markdown import StringIO from markdown.treeprocessors import Treeprocessor # # Classes for Markdown parsing. See python-markdown documentation # for details. We want to find all top level code blocks (indented # four spaces in the Markdown), which we'll parse for scenario test # stuff later on. We create a Python markdown extension and use # "tree processor" to analyse the parsed ElementTree at the right # moment for top level
 blocks.
#

# This is a Treeprocessor that iterates over the parsed Markdown,
# as an ElementTree, and finds all top level code blocks.

class GatherCodeBlocks(Treeprocessor):

    def __init__(self, blocks):
        self.blocks = blocks

    def run(self, root):
        for child in root.getchildren():
            if child.tag == 'pre':
                code = child.find('code')
                self.blocks.append(code.text)
        return root

# This is the Python Markdown extension to call the code block
# gatherer at the right time. It stores the list of top level
# code blocks as the blocks attribute.

class ParseScenarioTestBlocks(markdown.extensions.Extension):

    def extendMarkdown(self, md, md_globals):
        self.blocks = []
        self.gatherer = GatherCodeBlocks(self.blocks)
        md.treeprocessors.add('gathercode', self.gatherer, '_end')


class MarkdownParser(object):

    def __init__(self):
        self.blocks = []

    def parse_string(self, text):
        ext = ParseScenarioTestBlocks()
        f = StringIO.StringIO()
        markdown.markdown(text, output=f, extensions=[ext])
        self.blocks.extend(ext.blocks)
        return ext.blocks

    def parse_file(self, filename): # pragma: no cover
        with open(filename) as f:
            return self.parse_string(f.read())

cmdtest-0.10/yarnlib/mdparser_tests.py0000644000175000017500000000462712224016632020041 0ustar  jenkinsjenkins# Copyright 2013  Lars Wirzenius
#
# 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 .
#
# =*= License: GPL-3+ =*=


import unittest

import yarnlib


class MarkdownParserTests(unittest.TestCase):

    def setUp(self):
        self.parser = yarnlib.MarkdownParser()

    def test_finds_code_block(self):
        result = self.parser.parse_string('''
This is blah blah text.

    this is a code block

More text.
''')
        self.assertEqual(self.parser.blocks, ['this is a code block\n'])
        self.assertEqual(result, ['this is a code block\n'])

    def test_finds_consecutive_code_blocks_as_one(self):
        self.parser.parse_string('''
This is blah blah text.

    this is a code block

    this is a second code block

More text.
''')
        self.assertEqual(
            self.parser.blocks,
            ['this is a code block\n\nthis is a second code block\n'])

    def test_finds_code_blocks_with_text_in_between_as_two_blocks(self):
        self.parser.parse_string('''
This is blah blah text.

    this is a code block

Blah.

    this is a second code block

More text.
''')
        self.assertEqual(
            self.parser.blocks,
            ['this is a code block\n', 'this is a second code block\n'])

    def test_only_finds_top_level_code_blocks(self):
        self.parser.parse_string('''
This is blah blah text.

    this is a code block

And now a list:

*   list item

        this is a second level code block

More text.
''')
        self.assertEqual(self.parser.blocks, ['this is a code block\n'])

    def test_parses_multiple_files(self):
        result1 = self.parser.parse_string('''
    block 1
''')
        result2 = self.parser.parse_string('''
    block 2
''')
        self.assertEqual(result1, ['block 1\n'])
        self.assertEqual(result2, ['block 2\n'])
        self.assertEqual(self.parser.blocks, ['block 1\n', 'block 2\n'])