pax_global_header00006660000000000000000000000064140113647250014515gustar00rootroot0000000000000052 comment=aa9c27211e05ebff1a259750f092caef8e7fbe12 qtest-2.11.2/000077500000000000000000000000001401136472500127405ustar00rootroot00000000000000qtest-2.11.2/.gitignore000066400000000000000000000001771401136472500147350ustar00rootroot00000000000000*.cmi *.cmx *.cmo *.byte *.opt *.log *.a *.cma *.cmxa *.cmxs qtest qtest.ml *.native _build tests/footest.ml .merlin *.install qtest-2.11.2/.merlin000066400000000000000000000000751401136472500142310ustar00rootroot00000000000000S src S tests B _build/** PKG oUnit PKG bytes FLG -w +a-4-44 qtest-2.11.2/.ocamlinit000066400000000000000000000001721401136472500147200ustar00rootroot00000000000000#use "topfind";; #require "oUnit";; #directory "_build/src";; #load "qcheck.cma";; open QCheck;; (* vim: syntax=ocaml: *) qtest-2.11.2/HOWTO.adoc000066400000000000000000000003541401136472500144720ustar00rootroot00000000000000= HOWTO == Make a release [source,sh] ---- VERSION=42 opam pin add "qtest.$VERSION" . -n opam-publish prepare qtest.$VERSION https://github.com/vincent-hugot/iTeML/archive/$VERSION.tar.gz opam-publish submit ./qtest.$VERSION ---- qtest-2.11.2/LICENSE000066400000000000000000001045151401136472500137530ustar00rootroot00000000000000 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 . qtest-2.11.2/Makefile000066400000000000000000000002561401136472500144030ustar00rootroot00000000000000 build: @dune build @install clean: @dune clean test: build cd tests && ./testfoo.sh || true cd tests && ./testcppo.sh || true cd tests && ./testdirectives.sh || true qtest-2.11.2/README.adoc000066400000000000000000001147751401136472500145440ustar00rootroot00000000000000= qtest v2.2 :toc: macro :toclevels: 4 :source-highlighter: pygments *qtest* is an inline test extraction project, originally developed internally for http://batteries.forge.ocamlcore.org/[the OCaml Batteries Included library] under the name *qtest*. It relies on http://ounit.forge.ocamlcore.org/[oUnit] as a testing framework, though users need not know anything about it for basic usage; it also relies on https://github.com/c-cube/qcheck[Qcheck] for random testing. NOTE: *qtest* stands for _Quick Testing_. * qtest is available for installation as an http://opam.ocaml.org/packages/qtest/qtest.2.2/[OPAM package]. * It has extensive documentation: see section "<>" to get started. * It has good syntax highlighting for Kate (KatePart: KWrite, KDevelop, Konqueror,...) and basic support for Emacs. See the https://github.com/vincent-hugot/qtest/tree/master/editor_support[editor_support] directory *Manual installation:* ./configure make build install To use a custom installation prefix, use ./configure --prefix *Future works:* There are ideas floating around on how to improve qtest2, generally revolving around going from a test "extraction" to an "annotation" model. No timetable is set yet, as all parties involved are busy bees, and qtest2 currently covers most of the needs of the Batteries project and others. *History of the project:* (or at least, what I (VH) can unearth of it thanks to git logs) * 2007--2008 : Ilmari Heikkinen writes _make_suite.rb_ for his Prelude.ml. * Jan 17, 2011: _make_suite.rb_ is copied into Batteries. (=qtest0) * Jan 27, 2011: Kaustuv Chaudhuri writes from scratch an equivalent _make_suite.mll_ to replace the Ruby script. (=qtest1) * Jan 19, 2012: Vincent Hugot writes from scratch a new version, with a lot of new features. Syntax changes a bit. (=qtest2) * Oct 21, 2012: qtest2 moves to its own repository. * Sept. 2015: Simon Cruanes contributes a significant improvement of the random generation process. * March. 2016: Simon Cruanes integrates `qcheck` with `qtest` * Dec. 2016: `qcheck` and `qtest` are split apart again * Feb. 2018: renaming the repository to `qtest` again Over time, the various versions of qtest have received https://github.com/vincent-hugot/qtest/graphs/contributors[contributions] by: Eric Norige, Gabriel Scherer, Cedric Cellier, Valentin Gatien-Baron, Max Mouratov, and Simon Cruanes. *Contact:* The preferred way is to create a https://github.com/vincent-hugot/qtest/issues/new[new issue] on GitHub. Current maintainer: https://github.com/c-cube[Simon Cruanes]. ''' toc::[] [[introduction]] == Introduction: What Is QTest? In a nutshell, qtest is a small program which reads `.ml` and `.mli` source files and extracts inline unit tests from them. It is used internally by the http://batteries.forge.ocamlcore.org[OCaml Batteries] project, and is shipped with it as of version 2.0, but it does not depend on it and can be compiled and used independently. Browse its code in the https://github.com/ocaml-batteries-team/batteries-included/tree/master/qtest[Github Repository]. [[using-a-quick-simple-example]] == Using qtest: a Quick, Simple Example Say that you have a file `foo.ml`, which contains the implementation of your new, shiny function `foo`. [source,OCaml] -------------------------------------- let rec foo x0 f = function | [] -> 0 | x::xs -> f x (foo x0 f xs) -------------------------------------- Maybe you don’t feel confident about that code; or maybe you do, but you know that the function might be re-implemented less trivially in the future and want to prevent potential regressions. Or maybe you simply think unit tests are good practice anyway. In either case, you feel that building a separate test suite for this would be overkill. Using qtest, you can immediately put simple unit tests in comments near `foo`, for instance: [source,OCaml] --------------------------- (*$T foo foo 0 ( + ) [1;2;3] = 6 foo 0 ( * ) [1;2;3] = 0 foo 1 ( * ) [4;5] = 20 foo 12 ( + ) [] = 12 *) --------------------------- the syntax is simple: `(*$` introduces a qtest "pragma", such as `T` in this case. `T` is by far the most common and represents a "simple" unit test. `T` expects a "header", which is most of the time simply the name of the function under test, here `foo`. Following that, each line is a "statement", which must evaluate to `true` for the test to pass. Furthermore, `foo` must appear in each statement. Now, in order to execute those tests, you need to extract them; this is done with the qtest executable. The command ------------------------------------------------------ $ qtest -o footest.ml extract foo.ml Target file: `footest.ml'. Extraction : `foo.ml' Done. ------------------------------------------------------ will create a file `footest.ml`; it’s not terribly human-readable, but you can see that it contains your tests as well as some http://ounit.forge.ocamlcore.org[OUnit] boilerplate. Now you need to compile the tests, for instance with `ocamlbuild`, and assuming OUnit was installed for `ocamlfind`. -------------------------------------------------------------------- $ ocamlbuild -cflags -warn-error,+26 -use-ocamlfind -package oUnit \ footest.native Finished, 10 targets (1 cached) in 00:00:00. -------------------------------------------------------------------- Note that the `-cflags -warn-error,+26` is not indispensable but strongly recommended. Its function will be explained in more detail in the more technical sections of this documentation, but roughly it makes sure that if you write a test for `foo`, via `(*$T foo` for instance, then `foo` is _actually_ tested by each statement – the tests won’t compile if not. *Important note:* in order for this to work, `ocamlbuild` must know where to find `foo.ml`; if `footest.ml` is not in the same directory, you must make provisions to that effect. If `foo.ml` needs some specific flags in order to compile, they must also be passed. Now there only remains to run the tests: ...... $ ./footest.native ..FF ============================================================================== Failure: qtest:0:foo:3:foo.ml:10 OUnit: foo.ml:10::> foo 12 ( + ) [] = 12 ------------------------------------------------------------------------------ ============================================================================== Failure: qtest:0:foo:2:foo.ml:9 OUnit: foo.ml:9::> foo 1 ( * ) [4;5] = 20 ------------------------------------------------------------------------------ Ran: 4 tests in: 0.00 seconds. FAILED: Cases: 4 Tried: 4 Errors: 0 Failures: 2 Skip:0 Todo:0 ...... Oops, something’s wrong… either the tests are incorrect or `foo` is. Finding and fixing the problem is left as an exercise for the reader. When this is done, you get the expected ------------------------------ $ ./footest.native .... Ran: 4 tests in: 0.00 seconds. ------------------------------ TIP: those steps are easy to automate, for instance with a small shell script: ------------------------------------------------------------------------------- set -e # stop on first error qtest -o footest.ml extract foo.ml ocamlbuild -cflags -warn-error,+26 -use-ocamlfind -package oUnit footest.native ./footest.native ------------------------------------------------------------------------------- [[more-qtest-pragmas]] == More qtest Pragmas [[different-kinds-of-tests]] === Different Kinds of Tests [[simple-tests-for-test]] ==== Simple Tests: `T` for "Test" The most common kind of tests is the simple test, an example of which is given above. It is of the form [source,OCaml] ------------- (*$T
... *) ------------- where each _statement_ must be a boolean OCaml expression involving the function (or functions, as we will see when we study headers) referenced in the __header__. The overall test is considered successful if each _statement_ evaluates to `true`. Note that the "close comment" `*)` must appear on a line of its own. *Tip:* if a statement is a bit too long to fit on one line, if can be broken using a backslash (`\`), immediately followed by the carriage return. This also applies to randomised tests. [[equality-tests]] ==== Equality Tests: `=` The vast majority of test cases tend to involve the equality of two expressions; using simple tests, one would write something like: [source,OCaml] ----------------------------------------- (*$T foo foo 1 ( * ) [4;5] = foo 3 ( * ) [1;5;2] *) ----------------------------------------- While this certainly works, the failure report for such a test does not convey any useful information besides the simple fact that the test failed. Wouldn’t it be nice if the report also mentioned the values of the left-hand side and the right-hand side ? Yes it would, and specialised equality tests provide such functionality, at the cost of a little bit of boilerplate code. The bare syntax is: [source,OCaml] ------------- (*$=
... *) ------------- However, used bare, an equality test will not provide much more information than a simple test: just a laconic "not equal". In order for the values to be printed, a "value printer" must be specified for the test. A printer is a function of type `'a -> string`, where `'a` is the type of the expressions on both side of the equality. To pass the printer to the test, we use _parameter injection_ (cf. Section <>); equality tests have an optional argument `printer` for this purpose. In our example, we have `'a = int`, so the test becomes simply: [source,OCaml] ------------------------------------------- (*$= foo & ~printer:string_of_int (foo 1 ( * ) [4;5]) (foo 3 ( * ) [1;5;2]) *) ------------------------------------------- The failure report will now be more explicit, saying `expected: 20 but got: 30`. [[randomized-tests-for-quickcheck]] ==== Randomized Tests: `Q` for "Quickcheck" Quickcheck is a small library useful for randomized unit tests. Using it is a bit more complex, but much more rewarding than simple tests. [source,OCaml] ---------------------------------------------------- (*$Q
(fun -> ) ... *) ---------------------------------------------------- Let us dive into an example straight-away: [source,OCaml] ------------------------------------------------------------------------ (*$Q foo Q.small_int (fun i-> foo i (+) [1;2;3] = List.fold_left (+) i [1;2;3]) *) ------------------------------------------------------------------------ The Quickcheck module is accessible simply as _Q_ within inline tests; `small_int` is a generator, yielding a random, small integer. When the test is run, each statement will be evaluated for a large number of random values – 100 by default. Running this test for the above definition of foo catches the mistake easily: -------------------------------------------------------- law foo.ml:14::> Q.small_int (fun i-> foo i (+) [1;2;3] = List.fold_left (+) i [1;2;3]) failed for 2 -------------------------------------------------------- Note that the random value for which the test failed is provided by the error message – here it is 2. It is also possible to generate several random values simultaneously using tuples. For instance [source,OCaml] ---------------------------------------------------- (Q.pair Q.small_int (Q.list Q.small_int)) \ (fun (i,l)-> foo i (+) l = List.fold_left (+) i l) ---------------------------------------------------- will generate both an integer and a list of small integers randomly. A failure will then look like ----------------------------------------------------------- law foo.ml:15::> (Q.pair Q.small_int (Q.list Q.small_int)) (fun (i,l)-> foo i (+) l = List.fold_left (+) i l) failed for (727, [4; 3; 6; 1; 788; 49]) ----------------------------------------------------------- A generator such as `Q.pair Q.small_int Q.printable_string` is actually a value of type `'a Q.arbitrary` (in this particular case, `(int * string) arbitrary`). It combines a random generation function (`'a Q.Gen.t`), and optional printing, shrinking and size functions that are used to display counter-examples and minimize their size. It is possible, as explained below, to define one's own `'a arbitrary` values, for instance for custom types. *Available Generators:* Simple generators:: `unit`, `bool`, `float`, `pos_float`, `neg_float`, `int`, `int32`, `int64`, `pos_int`, `small_int`, `neg_int`, `char`, `printable_char`, `numeral_char`, `string`, `printable_string`, `numeral_string` Structure generators:: `list` and `array`. They take one generator as their argument. For instance `(Q.list Q.neg_int)` is a generator of lists of (uniformly taken) negative integers. Tuple generators:: `pair` and `triple` are respectively binary and ternary. See above for an example of `pair`. Size-directed generators:: `string`, `numeral_string`, `printable_string`, `list` and `array` all have `*_of_size` variants that take the size of the structure as their first argument. See the https://c-cube.github.io/qcheck/[online documentation of QCheck] for more details. *Tips:* Duplicate Elements in Lists:: When generating lists, avoid `Q.list Q.int` unless you have a good reason to do so. The reason is that, given the size of the `Q.int` space, you are unlikely to generate any duplicate elements. If you wish to test your function’s behaviour with duplicates, prefer `Q.list Q.small_int`. Filtering Inputs:: Rando, inputs can be filtered for a _precondition_ by stating a property `f ==> g`. An input `x` will be tested for the property `g` only if `f x` holds, otherwise it is discarded and a new input is generated. The total number of inputs generated can be capped using the `~max_gen:int` parameter (it should be bigger than `~count`). The system will try to make `count` tests, but stops after `max_gen` inputs are generated to avoid looping forever if acceptable inputs are too rare. Changing Number of Tests:: If you want a specific test to execute each of its statements a specific number of times (deviating from the default of 100), you can specify it explicitly through _parameter injection_ (cf. Section <>) using the `count` : argument. Getting a Better Counterexample:: By default, a random test stops as soon as one of its generated values yields a failure. This first failure value is probably not the best possible counterexample. You can _force_ qtest to generate and test all `count` random values regardless, and to display the value which is smallest with respect to a certain measure which you define. To this end, it suffices to use parameter injection to pass argument `small : 'a -> 'b`, where `'a` is the type of generated values and `'b` is any totally ordered set (wrt. `<`). Typically you will take `'b = int` or `'b = float`. Example: + [source,OCaml] -------------------------------------------------------- let fuz x = x let rec flu = function | [] -> [] | x :: l -> if List.mem x l then flu l else x :: flu l (*$Q fuz; flu & ~small:List.length (Q.list Q.small_int) (fun x -> fuz x = flu x) *) -------------------------------------------------------- + The meaning of `~small:List.length` is therefore simply: "choose the shortest list". For very complicated cases, you can simultaneously increase `count` to yield an even higher-quality counterexample. Shrinking:: A parameter `shrink: ('a -> 'a Q.Iter.t)` can be provided along with a random generator. `'a Q.Iter.t` is an iterator on values of type `'a`. `shrink x` should iterate on a set of values that are smaller than `x` (for instance, if `x: int list`, `shrink x` will remove each element of the list). If a generator (of type `'a arbitrary`) defines a shrink function, then whenever a counter-example is found for a property, the counter-example will be shrunk recursively as long as it continues refuting the property; this allows to find smaller and simpler counter-examples. However, shrinking can be slow. A parameter `~max_fail:int` can be given to the test by writing `(*$Q & ~max_fail:5` to limit the number of counter-examples to find, in case shrinking them is too slow. + The module `Q.Shrink` can be used to combine shrinking functions. + Example: the false property `(Q.list Q.int) (fun l -> not (List.mem 5 l))` might be falsified by the counter-example `[1;2;3;4;5;6;7;8]`. By recursively shrinking the value (trying to remove elements one by one) the minimal counter-example `[5]` will be found and displayed. Raw Random Tests:: Using `(*$QR`, similar to the raw unit test `(*$R`, it is possible to write a random test on multiple lines without the trailing `\` characters. + [source,OCaml] ----------------------------------------------------- (*$QR foo Q.small_int (fun i-> foo i (+) [1;2;3] = List.fold_left (+) i [1;2;3] ) *) ----------------------------------------------------- + The `(*$QR` block needs to contain exactly two values: Random Generator::: of type `'a Quickcheck.arbitrary` Property to test::: of type `'a -> bool` Custom Generators:: For types that are not lists of integers or strings, it can be useful to define one's own `'a arbitrary` instance for the type. The function to use is `Q.make`, it takes a `'a Q.Gen.t` random generator, and optional arguments * `~shrink:('a -> 'a Iter.t)` to define how to shrink counter-examples * `~small:('a -> 'b)` (where `'b` is ordered) to select small counter-examples * `~print:('a -> string)` to print counter-examples * `~collect:('a -> string)` maps inputs to a `string` descriptor and counts how many values belong to each descriptor, for statistics. + Some generators are already defined in `Q.Gen`. Gabriel Scherer's https://github.com/gasche/random-generator[random-generator library] is also a good basis for more advanced generators. + Printers can be defined using `Q.Print`, shrinkers using `Q.Shrink`. [[raw-ounit-tests-for-raw]] ==== Raw OUnit Tests: `R` for "Raw" When more specialised test pragmas are too restrictive, for instance if the test is too complex to reasonably fit on one line, then one can use raw OUnit tests. [source,OCaml] --------------------- (*$R
... ... *) --------------------- Here is a small example, with two tests stringed together: [source,OCaml] -------------------------------------------------------- (*$R foo let thing = foo 1 ( * ) and li = [4;5] in assert_bool "something_witty" (thing li = 20); assert_bool "something_wittier" (foo 12 ( + ) [] = 12) *) -------------------------------------------------------- Note that if the first assertion fails, the second will not be executed; so stringing two assertions in that mode is different in that respect from doing so under a `T` pragma, for instance. That said, raw tests should only be used as a last resort; for instance you don’t automatically get the source file and line number when the test fails. If `T` and `Q` do not satisfy your needs, then it is _probably_ a hint that the test is a bit complex and, maybe, belongs in a separate test suite rather than in the middle of the source code. [[exception-throwing-tests-for-exception]] ==== Exception-Throwing Tests: `E` for "Exception" … not implemented yet… The current usage is to use `(*$T` and the following pattern for function `foo` and exception `Bar`: [source,OCaml] ------------------------------------------ try ignore (foo x); false with Bar -> true ------------------------------------------ If your project uses Batteries and no pattern-matching is needed, then you can also use the following, sexier pattern: [source,OCaml] ---------------------------------- Result.(catch foo x |> is_exn Bar) ---------------------------------- [[manipulation-pragmas]] == Manipulation Pragmas Not all qtest pragmas directly translate into tests; for non-trivial projects, sometimes a little boilerplate code is needed in order to set the tests up properly. The pragmas which do this are collectively called "manipulation pragmas"; they are described in the next section. [[opening-modules-open-pragma-and-option]] === Opening Modules: _open_ Pragma `<...>` and `--preamble` Option The tests should have access to the same values as the code under test; however the generated code for `foo.ml` does not actually live inside that file. Therefore some effort must occasionally be made to synchronise the code’s environment with the tests’. There are three main usecases where you might want to open modules for tests: Project-Wide Global Open:: It may happen that _every single file_ in your project opens a given module. This is the case for Batteries, for instance, where every module opens `Batteries`. In that case simply use the `–preamble` switch. For instance, + ------------------------------------------------------------------------ qtest --preamble "open Batteries;;" extract mod1.ml mod2.ml ... modN.ml ------------------------------------------------------------------------ + Note that you could insert arbitrary code using this switch. c Global Open in a File:: Now, let’s say that `foo.ml` opens `Bar` and `Baz`; you want the tests in `foo.ml` to open them as well. Then you can use the _open_ pragma in its _global_ form: + ----------------- (*$< Bar, Baz >*) ----------------- + The modules will be open for every test in the same `.ml` file, and following the pragma. However, in our example, you will have a duplication of code between the "open" directives of `foo.ml`, and the _open_ pragma of qtest, like so: + --------------------- open Bar;; open Baz;; (*$< Bar, Baz >*) --------------------- + It might therefore be more convenient to use the _code injection_ pragma (see next section) for that purpose, so you would write instead: + ----------------------------------- (*${*) open Bar;; open Baz;; (*$}*) ----------------------------------- + The code between that special markup will simply be duplicated into the tests. The two methods are equivalent, and the second one is recommended, because it reduces the chances of an impedance mismatch between modules open for `foo.ml` and its tests. Therefore, the global form of the _open_ pragma should preferentially be reserved for cases where you _want_ such a mismatch. For instance, if you have special modules useful for tests but useless for the main code, you can easily open then for the tests alone using the pragma. Local Open for a Submodule:: Let’s say we have the following `foo.ml`: + [source,OCaml] ------------------------- let outer x = module Submod = struct let inner y = 2*x (*$T inner inner 2 = 4 *) end ------------------------- + That seems natural enough… but it won’t work, because qtest is not actually aware that the test is "inside" Submod (and making it aware of that would be very problematic). In fact, so long as you use only test pragmas (ie. no manipulation pragma at all), the positions and even the order of the tests – respective to definitions or to each other – are unimportant, because the tests do not actually live in `foo.ml`. So we need to open Submod manually, using the _local_ form of the _open_ pragma: + [source,OCaml] ------------------------------------- module Submod = struct (*$< Submod *) let inner y = 2*x (*$T inner inner 2 = 4 *) end (*$>*) ------------------------------------- + Notice that the `<...>` have simply been split in two, compared to the global form. The effect of that construct is that Submod will be open for every test between `(*$< Submod *)` and `(*$>*)`. Of course, you _could_ also forgo that method entirely and do this: + [source,OCaml] ---------------------- module Submod = struct let inner y = 2*x (*$T & Submod.inner 2 = 4 *) end ---------------------- + … but it is impractical and you are _forced_ to use an empty header because qualified names are not acceptable as headers. The first method is therefore _strongly_ recommended. [[code-injection-pragma]] === Code Injection Pragma: TODO: ocamldoc comments that define unit tests from the offered examples [[technical-considerations-and-other-details]] == Technical Considerations and Other Details What has been said above should suffice to cover at least 90% of use-cases for qtest. This section concerns itself with the remaining 10%. [[function-coverage]] === Function Coverage The headers of a test are not just there for decoration; three properties are enforced when a test, say, `(*$X foo` is compiled, where `X` is `T`, `R`, `Q`, `QR`,… : * `foo` exists; that is to say, it is defined in the scope of the module where the testappears – though one can play with pragmas to relax this condition somewhat. At the very least, it has to be defined __somewhere__. Failure to conform results in an `Error: Unbound value foo`. * `foo` is referenced in _each statement_ of the test: for `T` and `Q`, that means "each line". For `R`, that means "once somewhere in the test’s body". Failure to conform results in a `Warning 26: unused variable foo`, which will be treated as an error if `-warn-error +26` is passed to the compiler. It goes without saying that this is warmly recommended. * the test possesses at least one statement. Those two conditions put together offer a strong guarantee that, if a function is referenced in a test header, then it is actually tested at least once. The list of functions referenced in the headers of extracted tests is written by qtest into `qtest.targets.log`. Each line is of the form ------------------ foo.ml 42 foo ------------------ where `foo.ml` is the file in which the test appears, as passed to `extract`, and `42` is the line number where the test pragma appears in `foo.ml`. Note that a same function can be listed several times for the same source file, if several tests involve it (say, two times if it has both a simple test and a random one). The exact number of statements involving `foo` in each test is currently not taken into account in the logs. [[headers-and-metaheaders]] === Headers and Metaheaders The informal definition of headers given in the above was actually a simplification. In this section we explore two syntaxes available for headers. [[aliases]] ==== Aliases Some functions have exceedingly long names. Case in point : [source,OCaml] --------------------------------------------------- let rec pretentious_drivel x0 f = function | [] -> x0 | x::xs -> pretentious_drivel (f x x0) f xs --------------------------------------------------- [source,OCaml] -------------------------------------------------- (*$T pretentious_drivel pretentious_drivel 1 (+) [4;5] = foo 1 (+) [4;5] ... pretentious_drivel of this and that... *) -------------------------------------------------- The constraint that each statement must fit on one line does not play well with very long function names. Furthermore, you _known_ which function is being tested, it’s right there is the header; no need to repeat it a dozen times. Instead, you can define an __alias__, and write equivalently: [source,OCaml] --------------------------------- (*$T pretentious_drivel as x x 1 (+) [4;5] = foo 1 (+) [4;5] ... x of this and that... *) --------------------------------- …thus saving many keystrokes, thereby contributing to the preservation of the environment. More seriously, aliases have uses beyond just saving a few keystrokes, as we will see in the next sections. [[mutually-tested-functions]] ==== Mutually Tested Functions Most of the time, a test only pertains to one function. There are times, however, when one wishes to test two functions – or more – at the same time. For instance [source,OCaml] --------------------------------- let rec even = function 0 -> true | n -> odd (pred n) and odd = function 0 -> false | n -> even (pred n) --------------------------------- Let us say that we have the following test: [source,OCaml] ---------------------------------------------------- (*$Q
Q.small_int (fun n-> odd (abs n+3) = even (abs n)) *) ---------------------------------------------------- It involves both `even` and `odd`. That question is: "what is a proper header for this test?" One could simply put "even", and thus it would be referenced as being tested in the logs, but `odd` would not, which is unfair. Putting "odd" is symmetrically unfair. The solution is to put both, separated by a semi-colon: [source,OCaml] -------------- (*$Q even; odd -------------- That way _both_ functions are referenced in the logs: ----------------------- foo.ml 37 even foo.ml 37 odd ----------------------- and of course the compiler enforces that both of them are actually referenced in each statement of the test. Of course, each of them can be written under alias, in which case the header could be `even as x; odd as y`. [[testing-functions-by-the-dozen]] ==== Testing Functions by the Dozen Let us come back to our functions `foo` (after correction) and `pretentious_drivel`, as defined above. [source,OCaml] --------------------------------------------------- let rec foo x0 f = function | [] -> x0 | x::xs -> f x (foo x0 f xs) let rec pretentious_drivel x0 f = function | [] -> x0 | x::xs -> pretentious_drivel (f x x0) f xs --------------------------------------------------- You will not have failed to notice that they bear more than a passing resemblance to one another. If you write tests for one, odds are that the same test could be useful verbatim for the other. This is a very common case when you have closely related functions, or even several _implementations_ of the same function, for instance the old, slow, naïve, trustworthy one and the new, fast, arcane, highly optimised version you have just written. The typical case is sorting routines, of which there are many flavours. For our example, recall that we have the following test for `foo`: [source,OCaml] ------------------------------------------------------ (*$Q foo (Q.pair Q.small_int (Q.list Q.small_int)) \ (fun (i,l)-> foo i (+) l = List.fold_left (+) i l) *) ------------------------------------------------------ The same test would apply to `pretentious_drivel`; you could just copy-and-paste the test and change the header, but it’s not terribly elegant. Instead, you can just just add the other function to the header, separating the two by a comma, and defining an alias: [source,OCaml] -------------------------------------------------- (*$Q foo, pretentious_drivel as x (Q.pair Q.small_int (Q.list Q.small_int)) \ (fun (i,l)-> x i (+) l = List.fold_left (+) i l) *) -------------------------------------------------- This same test will be run once for `x = foo`, and once for `x = pretentious_drivel`. Actually, you need not define an alias: if the header is of the form [source,OCaml] ---------------------------- (*$Q foo, pretentious_drivel ---------------------------- then it is equivalent to [source,OCaml] ----------------------------------- (*$Q foo, pretentious_drivel as foo ----------------------------------- so you do not need to alter the body of the test if you subsequently add new functions. A header which combines more than one "version" of a function in this way is called a __metaheader__. [[metaheaders-unleashed]] ==== Metaheaders Unleashed All the constructs above can be combined without constraints: the grammar is as follows: ----------------------------------------------------- Metaheader ::= Binding {";" Binding} Binding ::= Functions [ "as" ID ] Functions ::= ID {"," ID} ID ::= (*OCaml lower-case identifier*) ----------------------------------------------------- [[parameter-injection]] ==== Header Parameters Injection Use `(*$inject foo *)` to inject the piece of code `foo` at the beginning of this module’s tests. This is useful, for instance, to define frequently used random generators, or printers, or to instantiate a functor before testing it. [[warnings-and-exceptions-thrown-by-qtest]] === Warnings and Exceptions Thrown by qtest --------------------------------------------------------------------- Fatal error: exception Failure("Unrecognised qtest pragma: ` T foo'") --------------------------------------------------------------------- You have written something like `(*$ T foo`; there must not be any space between `(*$` and the pragma. ------------------------------------------------------ Warning: likely qtest syntax error: `(* $T foo'. Done. ------------------------------------------------------ Self-explanatory; if `$` is the first real character of a comment, it’s likely a mistyped qtest pragma. This is only a warning though. ----------------------------------------------------------- Fatal error: exception Core.Bad_header_char("M", "Mod.foo") ----------------------------------------------------------- You have used a qualified name in a header, for instance `(*$T Mod.foo`. You cannot do that, the name must be unqualified and defined under the local scope. Furthermore, it must be public, unless you have used pragmas to deal with private functions. --------------------------------------------------- Error: Comment not terminated Fatal error: exception Core.Unterminated_test(_, 0) --------------------------------------------------- Most probably, you forgot the comment-closing `*)` to close some test. --------------------------------------------------------------------- Fatal error: exception Failure("runaway test body terminator: n))*)") --------------------------------------------------------------------- The comment-closing `*)` must be on a line of its own; or, put another way, every statement must be ended by a line break. [[qtest-command-line-options]] === qtest Command-Line Options ------------------------------------------------------------------------ $ qtest --help ** qtest (qtest) USAGE: qtest [options] extract ... OPTIONS: --output (-o) def: standard output Open or create a file for output; the resulting file will be an OCaml source file containing all the tests. --preamble (-p) def: empty Add code to the tests' preamble; typically this will be an instruction of the form 'open Module;;' --help Displays this help page and stops ------------------------------------------------------------------------ [[qtest-runtime-options]] === qtest Runtime Command-Line Options Test files generated by qtest also accept command line options, described by `--help` if needed. ---- $ qtest extract foo.ml -o footest.ml $ ocamlfind ocamlopt -package qcheck -linkpkg footest.ml -o footest $ ./footest --help run qtest suite -v -verbose enable verbose tests -l -list print list of tests (2 lines each). Implies -verbose -s -seed set random seed (to repeat tests) -help Display this list of options --help Display this list of options ---- Currently the options are: - `--verbose`: verbose quick check tests (print statistics, etc.) - `--list`: print a list of tests as they are executed. - `--seed`: force the choice of a random seed. When random tests start, the random seed used by the random generators is displayed; later, providing the same seed with `--seed ` will repeat the same tests. == A few tricks A few useful tricks when writing inline tests: - if possible, favor `(*$= a b *)` over `(*$T (a = b) *)`, because the former makes it possible to add a printer (with `& ~printer:some_printer`) in case the two values are not equal - random tests are useful to check general properties, or compare a complex-but-efficient implementation to a (possibly naive) reference implementation. For instance, if we had implemented a fancy sort function `my_sort` on lists, we could compare it to the stdlib's `List.sort`: + [source,OCaml] ---- (*$Q Q.(list int) (fun l -> \ my_sort compare l = List.sort compare l) *) ---- - to factor some code that is useful in tests, but should not appear in the module (for instance, printers or generators for running complex tests), you can use `(*$inject ... *)` somewhere in the `.ml` file: + [source,OCaml] ---- type foo = { a : int; b : string } (*$inject let pp_foo f = Printf.sprintf "foo{a=%d, b=%s}" f.a f.b *) (*$= & ~printer:pp_foo {a=0; b="b1"} {a=42; b="b2"} *) ---- + here, the test can use a custom printer defined above (and it needs it, for it will fail badly). === Using qtest with dune The simplest way is to use `(inline_tests (backend qtest.lib))` in a `library` statement: [source] ---- (library (name foo) (inline_tests (backend qtest.lib))) ---- And then `dune runtest` should automatically find inline tests in the library's modules. For better control, a rule can be used (adapt to fit your needs): ---- (rule (targets run_qtest.ml) (deps (source_tree src)) ; here is where you need to tell qtest what files to consider (action (run qtest extract src/foo1.ml src/foo2.ml > %{targets}))) (executable (name run_qtest) (modules run_qtest) ; disable some warnings in qtests (flags :standard -warn-error -a -w -33-35-27-39) (libraries qcheck)) (alias (name runtest) (deps run_qtest.exe) (action (run %{deps}))) ---- === Using qtest with OCamlbuild The following snippet, added to `myocamlbuild.ml`, will use `qtest` to extract `foo_tests.ml` from `foo.ml` for any module `foo`. [source,OCaml] ---- open Ocamlbuild_plugin;; rule "qtest extract" ~prod:"%_tests.ml" ~deps:["%.ml"] (fun env build -> Cmd(S[A"qtest"; A"extract"; A"-o"; P(env "%_tests.ml"); P(env "%.ml")])) ---- It is also possible to make a single `all_tests.ml` file from many modules, if they are listed in `all_tests.qtestpack` file (similar to `.mllib`): [source,OCaml] ---- open Ocamlbuild_plugin;; let import_qtestpack build packfile = let tags1 = tags_of_pathname packfile in let files = string_list_of_file packfile in let include_dirs = Pathname.include_dirs_of (Pathname.dirname packfile) in let files_alternatives = List.map begin fun module_name -> expand_module include_dirs module_name ["ml"; "mli"] end files in let files = List.map Outcome.good (build files_alternatives) in let tags2 = List.fold_right (fun file -> Tags.union (tags_of_pathname file)) files tags1 in (tags2, files) let qtest_many target packfile env build = let packfile = env packfile and target = env target in let tags, files = import_qtestpack build packfile in Cmd(S[A "qtest"; A "extract"; T tags; A "-o"; A target; Command.atomize_paths files]);; rule "ocaml: modular qtest (qtestpack)" ~prods:["%.ml"] ~deps:["%.qtestpack"] ~doc:"Qtest supports building a test module by extracting cases directly from several composing several .ml{,i} files together. \ To use that feature with ocamlbuild, you should create a .qtestpack \ file with the same syntax as .mllib or .mlpack files: \ a whitespace-separated list of the capitalized module names \ of the .ml{,i} files you want to combine together." (qtest_many "%.ml" "%.qtestpack"); ---- For instance, `run_tests.qtestpack` might contain ---- src/Foo src/sub/Bar ---- and the target would be [source,Sh] ---- ocamlbuild -use-ocamlfind -package qcheck \ -I src -I src/sub run_tests.native ---- qtest-2.11.2/dune-project000066400000000000000000000000201401136472500152520ustar00rootroot00000000000000(lang dune 1.0) qtest-2.11.2/editor_support/000077500000000000000000000000001401136472500160225ustar00rootroot00000000000000qtest-2.11.2/editor_support/emacs/000077500000000000000000000000001401136472500171125ustar00rootroot00000000000000qtest-2.11.2/editor_support/emacs/batteries_dev.el000066400000000000000000000015531401136472500222600ustar00rootroot00000000000000;; qTest support in emacs ;; ;; * colorizing specially test comments (in orange) ;; ;; To use this file, simply add the following line to your .emacs: ;; (load-file "path/to/batteries/batteries_dev.el") ;; ;; by Valentin Gatien-Baron (defface test-comment-face '((t :foreground "orangered3")) "face for test comments") (add-hook 'tuareg-mode-hook '(lambda () (defun tuareg-font-lock-syntactic-face-function (state) (if (nth 3 state) font-lock-string-face (let ((start (nth 8 state))) (save-excursion (goto-char start) (if (looking-at-p "(\\*\\$[QTRE=]") 'test-comment-face (if (looking-at-p "(\\*\\*[^*]") tuareg-doc-face font-lock-comment-face)))))))) qtest-2.11.2/editor_support/kate_hl/000077500000000000000000000000001401136472500174315ustar00rootroot00000000000000qtest-2.11.2/editor_support/kate_hl/install.sh000066400000000000000000000002161401136472500214320ustar00rootroot00000000000000set -e dir=~/.kde/share/apps/katepart/syntax/ mkdir -pv $dir # cp -iv *.xml $dir for i in ocaml{,yacc,lex}.xml do ln -vs $(pwd)/$i $dir doneqtest-2.11.2/editor_support/kate_hl/ocaml.xml000066400000000000000000000656541401136472500212660ustar00rootroot00000000000000 ]> in as forall and as assert asr begin class closed constraint do done downto else end exception external false for fun function functor if in include inherit land lazy let lor lsl lsr lxor match method mod module mutable new object of open or parser private rec sig struct then to true try type val virtual when while with declare value where abs abs_float acos asin at_exit atan atan2 bool_of_string ceil char_of_int classify_float close_in close_in_noerr close_out close_out_noerr compare cos cosh decr do_at_exit epsilon_float exp float float_of_int float_of_string floor flush flush_all format_of_string frexp fst ignore in_channel_length incr infinity input input_binary_int input_byte input_char input_line input_value int_of_char int_of_float int_of_string ldexp lnot log log10 max max_float max_int min min_float min_int mod_float modf nan neg_infinity not open_in open_in_bin open_in_gen open_out open_out_bin open_out_gen out_channel_length output output_binary_int output_byte output_char output_string output_value pos_in pos_out pred prerr_char prerr_endline prerr_float prerr_int prerr_newline prerr_string print_char print_endline print_float print_int print_newline print_string read_float read_int read_line really_input ref seek_in seek_out set_binary_mode_in set_binary_mode_out sin sinh snd sqrt stderr stdin stdout string_of_bool string_of_float string_of_format string_of_int succ tan tanh truncate unsafe_really_input valid_float_lexem exit failwith invalid_arg raise array bool char exn format4 fpclass in_channel int int32 int64 lazy_t list nativeint open_flag option out_channel real ref string unit FP_infinite FP_nan FP_normal FP_subnormal FP_zero None Open_append Open_append Open_binary Open_binary Open_creat Open_creat Open_excl Open_excl Open_nonblock Open_nonblock Open_rdonly Open_rdonly Open_text Open_text Open_trunc Open_trunc Open_wronly Open_wronly Some Assert_failure Division_by_zero End_of_file Exit Failure Invalid_argument Match_failure Not_found Out_of_memory Stack_overflow Sys_blocked_io Sys_error Undefined_recursive_module Arg Array ArrayLabels Buffer Callback Char Complex Digest Filename Format Gc Genlex Hashtbl Int32 Int64 Lazy Lexing List ListLabels Map Marshal MoreLabels Nativeint Oo Parsing Printexc Printf Queue Random Scanf Set Sort Stack StdLabels Stream String StringLabels Sys Weak qtest-2.11.2/editor_support/kate_hl/ocamllex.xml000066400000000000000000000072461401136472500217700ustar00rootroot00000000000000 ]> and as eof let parse rule shortest qtest-2.11.2/editor_support/kate_hl/ocamlyacc.xml000066400000000000000000000177711401136472500221230ustar00rootroot00000000000000 ]> %token %type %left %right %nonassoc %start %prec error qtest-2.11.2/editor_support/kate_hl/valid.sh000077500000000000000000000002021401136472500210610ustar00rootroot00000000000000xmllint -dtdvalid /usr/share/kde4/apps/katepart/syntax/language.dtd ocaml.xml #> /dev/null cp -i ocaml.xml ocaml--save$RANDOM.xmlqtest-2.11.2/qtest.opam000066400000000000000000000013401401136472500147540ustar00rootroot00000000000000opam-version: "2.0" maintainer: "Simon Cruanes " "Simon Cruanes = "1.1" } "qcheck" { >= "0.14" } "ocaml" { >= "4.03.0" } ] tags: [ "test" "property" "quickcheck" ] qtest-2.11.2/src/000077500000000000000000000000001401136472500135275ustar00rootroot00000000000000qtest-2.11.2/src/META000066400000000000000000000004261401136472500142020ustar00rootroot00000000000000version = "2.2" description = "qTest: inline unit tests extractor, from Batteries." requires = "oUnit unix bytes" archive(byte) = "qcheck.cma" archive(byte, plugin) = "qcheck.cma" archive(native) = "qcheck.cmxa" archive(native, plugin) = "qcheck.cmxs" exists_if = "qcheck.cma" qtest-2.11.2/src/core.ml000066400000000000000000000270371401136472500150220ustar00rootroot00000000000000(* * qTest: quick unit tests: extract oUnit tests from OCaml components * under GNU GPL v3: see qtest.mll *) (**** TOOLKIT ****) module M = Misclex let quiet = ref false let fpf = Printf.fprintf let va = Printf.sprintf let epf = Printf.eprintf let eps = prerr_string let pl = print_endline (** Toggle an option on and off *) let toggle br = br := not !br (** Apply a lexing rule so long as it can be applied. Avoids having to do a bloody recursive call at the end of each action... The rule receives a function terminator() as its last argument; using it lets the rule signify it is done. *) let exhaust_lexer rule lex = let continue = ref true in let term () = toggle continue in while !continue do rule term lex done (** Push a value as head of a list reference *) let push x l = l := x :: !l (** Function application operator (read "of"). This is used to avoid LISP-like parentheses creep; the point of using an [@...] operator is that it has just the right precedence and is right-associative *) let (@@) f x = f x let soi = string_of_int (** Convert a [char] to a [string] *) let soc = String.make 1 let is_blank_char = function ' '|'\t'|'\n'|'\r' -> true | _ -> false let listiteri f l = let c = ref (-1) in let call x = incr c; f !c x in List.iter call l let lex_str lexer s = (* use an ocamllex lexer *) let buff = Lexing.from_string s in lexer buff let trim = lex_str M.trim and normalise = lex_str M.normalise let first_chars s n = let len = min n (String.length s) in String.sub s 0 len let string_after s n = let len = String.length s - n in String.sub s n len let snippet s n = if String.length s <= n then s else first_chars s n ^ "..." let snip lex = (** Snippet of current lexer buffer context *) let curr = max 0 (lex.Lexing.lex_start_pos - 5) in let content = Bytes.to_string lex.Lexing.lex_buffer in let vicinity = string_after content curr in snippet vicinity 70 (*****************) (** output channel *) let outc = ref stdout (** main output function *) let out s = output_string !outc s (** formatted output function *) let outf x = fpf !outc x (** output for targets list *) let outc_target = ref (open_out "qtest.targets.log") (** formatted output for targets list *) let outf_target s = fpf !outc_target s (** indispensable preamble *) let hard_coded_preamble = "open OUnit;;\n\ module Q = QCheck;;let ( ==> ) = Q.( ==> );;\n\ \n\n" (** global preamble, user-definable *) let global_preamble = Buffer.create 100 (** update the buffer to reflect current line number *) let eol lexbuf = Lexing.( let curr = lexbuf.lex_curr_p in lexbuf.lex_curr_p <- { curr with pos_lnum = curr.pos_lnum + 1 ; pos_bol = curr.pos_cnum }) let exhaust = exhaust_lexer (** a simple statement, such as "foo 2 = 4", with line number *) type statement = { ln : int ; code : string } (** foo as bar *) type binding = string * string (** foo, bar as baz *) type metabinding = string list * string (** additional testing parameters: caml code for oUnit *) type param = string (** instantiable header: just a list of bindings *) type header = { hb : binding list; hpar : param; } (** metabindings need to be instanciated before the test can *) type metaheader = { mhb: metabinding list; mhpar : param; } (** what kind of test are we talking about ? *) type kind = | Simple (* statement is asserted to be true *) | Random (* statement is tested on random inputs, using Quickcheck *) | Random_raw (* pair of (arbitrary, invariant) for Quickcheck *) | Raw (* raw oUnit statement *) | Equal (* Equality statement *) (** a test : several statements *) type 'a test = { header : 'a ; (* bindings or metabindings *) kind : kind ; line : int ; (* header line number *) source : string ; (* original source file *) statements : statement list ; (* test code *) } (** what kind of instruction are we talking about ? *) type pragma = | Meta_test of metaheader test (* describes one or several tests *) | Test of header test (* do some testing... *) | Env_begin (* open a test environment, eg. a module or file *) | Env_close (* ... and close it *) | Open of string (* open a module, within the scope of current environment *) | Inject of (string * int) * string (*= (foo.ml ln) code *) (* inject code into test environment *) (** storage facility for all tests in input files *) let suite : pragma list ref = ref [] (** add a pragma to the current suite *) let register prag = push prag suite (** if a test header contains invalid characters *) exception Bad_header_char of string * string (** if a test body is never closed *) exception Unterminated_test of statement list (** a test contains no statement *) exception Empty_test of string (** an "open modules" pragma is invalid at lexing level *) exception Bad_modules_open_char of string (** ... or at parsing level *) exception Modules_syntax_error (** this looks like a qtest pragma, but isn't *) exception Invalid_pragma of string (** human-readable form *) let str_of_metabinding (bind:metabinding) = let targets,alias = bind in String.concat ", " targets ^ if List.length targets > 1 || List.hd targets <> alias then " as " ^ alias else "" let str_of_binding ((f,a):binding) = str_of_metabinding ([f],a) (** lexical closure generation, single binding *) let code_of_binding ((f,a):binding) = va "let %s = %s in" a f (** same, for a list of bindings, ie. a test header *) let code_of_bindings bl = String.concat " " (List.map code_of_binding bl) (** get the functions targeted by a header *) let targets_of_header (hd:header) = match hd.hb with | [] -> ["&empty&"] | l -> let x,_ = List.split l in x (** get an informal "foo, bar as x; a,b as y" string which summarises the metatest *) let get_metatest_name (test : metaheader test) = String.concat "; " (List.map str_of_metabinding test.header.mhb) (** get an informal "foo, bar as x; a,b as y" string which summarises the test *) let get_test_name (test: header test) = String.concat "; " (List.map str_of_binding test.header.hb) (** explode a metaheader into the correponding headers *) let headers_of_metaheader (mh:metaheader) = let rec z = function [] -> assert false | [(foos,x)] -> List.map (fun foo -> [foo,x]) foos | (foos,x) :: mbs -> let rest = z mbs in let combine foo = List.map (fun others ->(foo,x) :: others) rest in List.concat @@ List.map combine foos in match mh.mhb with | [] -> [{hb = []; hpar = mh.mhpar}] | l -> ((List.map (fun b-> {hb = b; hpar = mh.mhpar}) (z l)) : header list) (** break down metatests (tests w/ multiple targets) and enforce that each test is non-empty, ie. has at least one statement. Also, put the statements back in the order they appear in *) let preprocess pragmas = let rec z = function [] -> [] | Meta_test test :: l -> if test.statements = [] then raise @@ Empty_test (get_metatest_name test); let test = {test with statements = List.filter (fun s->s.code <> "") test.statements} in List.map (fun hd -> Test {test with header = hd}) (headers_of_metaheader test.header) @ z l | x :: l -> x :: z l (* leave non-metatest pragmas untouched *) in z pragmas (** get the name of the test function, given its uid *) let test_handle_of_uid uid = "_test_" ^ soi uid (** get a pretty, user-friendly version of the code wrt. whitespace *) let prettify s = if String.contains s '\n' then (* multi-line : as-is *) "\n\n" ^ s ^ "\n\n" else (* single-line: normalise *) trim (normalise s) (** filter tests so that only those which involve a specific function name are kept. Option --run-only *) let _run_only = ref None let retain_test test = match !_run_only with | None -> true | Some pattern -> let targets,_ = List.split test.header.hb in List.mem pattern targets (** execute a pragma; in particular, output the executable version of a test *) let process uid = function | Test test when retain_test test -> let test_handle = test_handle_of_uid uid and targets = targets_of_header test.header in List.iter (fun t-> outf_target "%30s %4d %s\n" test.source test.line t ) targets; outf "let %s = %S >::: [\n" test_handle (get_test_name test); (* handle individual statements *) let do_statement st = let location = va "%s:%d" test.source st.ln in let extended_name = va "\"%s\"" (* pretty, detailed name for the test *) (String.escaped location^": "^String.escaped (prettify st.code)) and lnumdir = va "\n#%d \"%s\"\n" st.ln test.source in let bind = lnumdir ^ code_of_bindings test.header.hb in match test.kind with | Simple -> outf "\"%s\" >:: (%s fun () -> OUnit.assert_bool %s (%s%s%s));\n" location bind extended_name test.header.hpar lnumdir st.code; | Equal -> outf "\"%s\" >:: (%s fun () -> OUnit.assert_equal ~msg:%s %s %s%s);\n" location bind extended_name test.header.hpar lnumdir st.code; | Random -> outf "\"%s\" >:: (%s fun () -> \ let test = Q.Test.make ~name:%s %s %s%s in \n\ try Q.Test.check_exn ~rand:(QCheck_runner.random_state()) test \n\ with Q.Test.Test_fail (a,b) -> OUnit.assert_failure (Q.Test.print_test_fail a b));\n" location bind extended_name test.header.hpar lnumdir st.code; | Raw -> outf "\"%s\" >:: (%s fun () -> (%s%s));\n" location bind lnumdir st.code; | Random_raw -> outf "\"%s\" >:: (%s fun () -> \ let test = Q.Test.make ~name:%s %s %s%s in \n\ try Q.Test.check_exn ~rand:(QCheck_runner.random_state()) test \n\ with Q.Test.Test_fail (a,b) -> OUnit.assert_failure (Q.Test.print_test_fail a b));\n" location bind extended_name test.header.hpar lnumdir st.code; in List.iter do_statement test.statements; outf "];; let _ = ___add %s;;\n" test_handle | Test test -> epf "Skipping `%s'\n" (get_test_name test) | Env_begin -> outf "\n\nmodule Test__environment_%d = struct\n" uid | Env_close -> out "end\n\n" | Open modu -> outf "open %s;;\n" modu | Inject ((modu,ln),cd) -> let lnumdir = va "\n#%d \"%s\"\n" ln modu in out @@ lnumdir ^ " " ^ cd ^ " " (* 4 spaces for column numbers reporting *) | Meta_test _ -> assert false (* metas should have been pre-processed out *) (** Shuffling tests as per --shuffle *) module Shuffle = struct type imbrication = | Env of imbrication list | Prg of pragma (* but without Env_begin and close *) (* turn a raw pragma list into an imbrication *) let input pl = let rec z acc = function | [] -> [], List.rev acc | Env_close :: l -> l, List.rev acc | Env_begin :: l -> let rest, result = z [] l in z (Env result :: acc) rest | p :: l -> z (Prg p :: acc) l in let rest, res = z [] pl in if (rest <> []) then epf "Warning: shuffle has rests: check that every opened module is closed\n"; Env res (* turn an imbrication list back into a raw pragma list *) let output imbl = let rec z = function | Prg p -> [p] | Env il -> Env_begin :: (List.concat @@ List.map z il) @ [Env_close] in z imbl (* Durstenfeld shuffling algorithm *) let durstenfeld l = Array.( let a = of_list l in let ex i j = let oldi = a.(i) in a.(i) <- a.(j); a.(j) <- oldi in for k = length a - 1 downto 1 do ex k (Random.int (succ k)) done; to_list a ) let rec shuffle = function | Prg p -> Prg p | Env (opn::il) -> Env (opn :: if List.exists (function Prg(Inject(_,_)) -> true | _ -> false) il then List.map shuffle il else List.map shuffle (durstenfeld il)) | Env _ -> assert false let exec suite = (* assert (!suite = output (input !suite)); *) suite := output @@ shuffle (input !suite) end (* Shuffle *) qtest-2.11.2/src/dune000066400000000000000000000006531401136472500144110ustar00rootroot00000000000000 (executable (name qtest_bin) (public_name qtest) (libraries bytes) (flags :standard -w +a-4-29-44-50@8 -warn-error -a+8 -safe-string)) (ocamllex (modules qtest_bin misclex)) (ocamlyacc (modules qparse)) (library (public_name qtest.lib) (name qtestlib) (modules) (inline_tests.backend (generate_runner (run qtest extract --quiet %{impl-files} %{intf-files})) (runner_libraries qcheck ounit2 bytes))) qtest-2.11.2/src/misclex.mll000066400000000000000000000010351401136472500157000ustar00rootroot00000000000000{ (* * qTest: quick unit tests: extract oUnit tests from OCaml components * under GNU GPL v3: see qtest.mll *) module B = Buffer let b = B.create 80 } (***************************************************************) let blank = [' ' '\t'] (* remove surrounding whitespace *) rule trim = parse blank* (_* as x) blank* eof { x } (* collapse multiple spaces into one *) and normalise = parse | blank+ { B.add_char b ' '; normalise lexbuf } | _ as c { B.add_char b c ; normalise lexbuf } | eof { let s = B.contents b in B.clear b ; s } qtest-2.11.2/src/qparse.mly000066400000000000000000000022361401136472500155500ustar00rootroot00000000000000%{ (* * qTest: quick unit tests: extract oUnit tests from OCaml components * under GNU GPL v3: see qtest.mll *) open Core %} %token ID PARAM UID %token COMMA AS EOF SEMI IN FORALL LBRACKET RBRACKET %start metaheader_ %type metaheader_ %start modules_ %type modules_ %% /* manipulation pragma */ modules_: | modules EOF { $1 }; modules: | UID { [$1] } | UID COMMA modules { $1 :: $3 } | error { raise Modules_syntax_error }; /* header stuff */ metaheader_ : | metaheader param EOF { {mhb = $1; mhpar = $2} } | metaheader /* */ EOF { {mhb = $1; mhpar = ""} }; param: | PARAM param { $1 ^ " " ^ $2 } | PARAM { $1 }; metaheader: /* x,y,z as target; a,b,c as tata ; ... */ | /* gnu */ { [] } | multibind { [$1] } | multibind SEMI metaheader { $1 :: $3 }; multibind : /* x,y,z as target */ | FORALL ID IN LBRACKET functions RBRACKET { $5, $2 } | ID { [$1], $1 } | ID AS ID { [$1], $3 } | error { failwith "Parser:Multibind" } functions: /* x,y,z */ | ID { [$1] } | ID SEMI functions { $1 :: $3 }; %% qtest-2.11.2/src/qtest_bin.mll000066400000000000000000000252001401136472500162240ustar00rootroot00000000000000{ (* * qtest: quick unit tests: extract oUnit tests from OCaml components * * * Copyright 2012 Vincent Hugot and the "OCaml Batteries Included" team * Copyright 2018 Simon Cruanes * * https://github.com/vincent-hugot/qtest * * 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 . * *) open Core open Qparse module B = Buffer (** the do-it-all buffer; always clear *after* use *) let buffy = B.create 80 (** register a raw metatest from the lexing buffer *) let register_mtest lexbuf lexhead lexbod line kind = let header = metaheader_ lexhead lexbuf in let statements = lexbod lexbuf in Lexing.( register @@ Meta_test { kind; line ; header ; source = lexbuf.lex_curr_p.pos_fname; statements ; }) let lnumof lexbuf = Lexing.(lexbuf.lex_curr_p.pos_lnum) let fileof lexbuf = Lexing.(lexbuf.lex_curr_p.pos_fname) let info lb = fileof lb, lnumof lb (** --shuffle option *) let _shuffle = ref false } (****************************************************************************) let blank = [' ' '\t'] let lowercase = ['a'-'z' '\223'-'\246' '\248'-'\255' '_'] let uppercase = ['A'-'Z' '\192'-'\214' '\216'-'\222'] let identchar = ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '\'' '0'-'9'] let symbolchar = ['!' '$' '%' '&' '*' '+' '-' '.' '/' ':' '<' '=' '>' '?' '@' '^' '|' '~'] let lident = lowercase identchar* | '(' blank* symbolchar+ blank* ')' let uident = uppercase identchar* (** extract tests from ml file *) rule lexml t = parse | "#" [' ' '\t']* (['0'-'9']+ as line) [' ' '\t']* ("\"" ([^ '\010' '\013' '\"' ] * as file) "\"")? [' ' '\t']* '\n' { (* lexer directives *) let file = match file with | Some file -> file | None -> Lexing.(lexbuf.lex_curr_p.pos_fname) in Lexing.(lexbuf.lex_curr_p <- {lexbuf.lex_curr_p with pos_fname = file; pos_lnum = int_of_string line; }) } (* test pragmas *) (****************) | "(*$QR" { (* quickcheck random test, in a raw form *) let lnum = lnumof lexbuf in register_mtest lexbuf lexheader (lexbody_raw (succ lnum) buffy) lnum Random_raw } | "(*$Q" { (* quickcheck (random) test *) let lnum = lnumof lexbuf in register_mtest lexbuf lexheader (lexbody (succ lnum) buffy []) lnum Random } | "(*$T" { (* simple test *) let lnum = lnumof lexbuf in register_mtest lexbuf lexheader (lexbody (succ lnum) buffy []) lnum Simple } | "(*$=" { (* equality test *) let lnum = lnumof lexbuf in register_mtest lexbuf lexheader (lexbody (succ lnum) buffy []) lnum Equal } | "(*$R" { (* raw test *) let lnum = lnumof lexbuf in register_mtest lexbuf lexheader (lexbody_raw (succ lnum) buffy) lnum Raw } (* manipulation pragmas *) (************************) | "(*$<" | "(*$begin:open" { (* local open *) let ctx = snip lexbuf (* save context for error reporting *) and modules = modules_ lexmodules lexbuf and loc_register m = register Env_begin; register @@ Open m in if (List.length modules > 1) then failwith @@ "\n" ^ ctx ^ "\nLocal open cannot take more than one module."; List.iter loc_register modules } | "(*$>*)" | "(*$end:open*)" { register Env_close } | "(*$open" { (* global open *) let modules = modules_ lexmodules lexbuf and glo_register m = register @@ Open m in List.iter glo_register modules } | "(*${*)" | "(*$begin:inject*)" (* copy injection *) { lexinjectcp (info lexbuf) buffy lexbuf } | "(*$inject" (* pure injection *) { lexinjectmv (info lexbuf) buffy lexbuf } (* error cases *) (***************) | "(*$" { raise @@ Invalid_pragma (snip lexbuf) } | "(*" (blank | '*')+ "$" [^'\n']* as y { let f,n = info lexbuf in epf "\nWarning: likely qtest syntax error: `%s' at %s:%d. " y f n } | "(*" { lexcomment 0 lexbuf } | "\\\"" { } | "'" "\\" _ "'" { } | "'" _ "'" { } | "\"" { lexstring lexbuf } | '\n' { eol lexbuf } (* others *) | _ { } | eof {t()} (** body of a test: simply extract lines *) and lexbody ln b acc = parse | "\\\n" { eol lexbuf ; B.add_char b '\n'; lexbody ln b acc lexbuf } | [^'\n'] as c { B.add_char b c; lexbody ln b acc lexbuf } | blank* '\n' { eol lexbuf; let code = B.contents b in B.clear b; lexbody Lexing.(lexbuf.lex_curr_p.pos_lnum) b ({ln ; code} :: acc) lexbuf } | blank* "*)" { List.rev acc } | "(*" { lexcomment 0 lexbuf ; lexbody ln b acc lexbuf } | ([^'\n']#blank)* blank* '*'+ ")" as x { failwith ("runaway test body terminator: " ^ x) } | eof { raise @@ Unterminated_test acc } (** evacuate OCaml comments... *) and lexcomment n = parse | "(*" { lexcomment (succ n) lexbuf } | "\n" { eol lexbuf; lexcomment n lexbuf } | "*)" { if n <= 0 then () else lexcomment (pred n) lexbuf } | _ { lexcomment n lexbuf } | eof { epf "Warning: unterminated comment" } (** ... and strings *) and lexstring = parse | "\\\"" { lexstring lexbuf } | "\\\\" { lexstring lexbuf } | "\"" { } | "\\\n" { eol lexbuf; lexstring lexbuf } | "\n" { eol lexbuf; lexstring lexbuf } | _ { lexstring lexbuf } | eof { epf "Warning: unterminated string" } (** body of a raw test... everything until end comment *) and lexbody_raw ln b = parse | _ as c { if c = '\n' then eol lexbuf; B.add_char b c; lexbody_raw ln b lexbuf } | '\n' blank* "*)" { eol lexbuf; let s = B.contents b in B.clear b; [{ln; code=s}]} (** body of an injection pragma: copy *) and lexinjectcp info b = parse | _ as c { if c = '\n' then eol lexbuf; B.add_char b c; lexinjectcp info b lexbuf } | "(*$}*)" | "(*$end:inject*)" { let code = B.contents b in B.clear b; register @@ Inject (info,code) } (* TODO: eliminate comments *) (** body of an injection pragma: move *) and lexinjectmv info b = parse | _ as c { if c = '\n' then eol lexbuf; B.add_char b c; lexinjectmv info b lexbuf } | "*)" { (* note: the 2 spaces are for column numbers reporting *) let code = " " ^ B.contents b in B.clear b; register @@ Inject (info,code) } (** prepare to parse test header *) and lexheader = parse | blank { lexheader lexbuf } | ";" { SEMI } | "[" { LBRACKET } | "]" { RBRACKET } | "as" { AS } | "in" { IN } | "forall" { FORALL } | lident as x { ID x } | "\\\n" { eol lexbuf ; lexheader lexbuf } | "&" ("" | [^'\n']*[^'\\' '\n'] as x) { PARAM (trim x) } | '\n' { eol lexbuf; EOF } | eof { failwith "unterminated header at end of file" } | _ as c { raise @@ Bad_header_char((soc c), snip lexbuf) } (** parse list of modules *) and lexmodules = parse | blank { lexmodules lexbuf } | "," { COMMA } | "*)" { EOF } (* local open, closed later *) | uident as x { UID x } | _ as c { raise @@ Bad_modules_open_char (soc c) } (**TODO: deal with strings and nested comments *) { (****************************************************************************) (** register all the tests in source file, and register them in the suite *) let extract_from pathin = Lexing.( if not !quiet then epf "`%s' %!" pathin; let chanin = open_in pathin in let lexbuf = from_channel chanin in lexbuf.lex_curr_p <- {lexbuf.lex_curr_p with pos_fname = pathin; pos_lnum = 1; }; (* getting the module *) let mod_name = Filename.( let fn_base = basename pathin in if not (check_suffix fn_base ".ml" || check_suffix fn_base ".mli") then (Printf.eprintf "File %S is not a ML module!\n%!" pathin ; exit 2); String.capitalize_ascii (chop_extension fn_base) ) in (* adding the file's pragmas to the suite *) register Env_begin; register (Open mod_name); exhaust lexml lexbuf; register Env_close; close_in chanin ) (** Generate the test suite from files list on currently selected output *) let generate paths = if not !quiet then eps "Extraction : "; List.iter extract_from paths; out "let ___tests = ref []\nlet ___add test = ___tests := test::!___tests\n"; out hard_coded_preamble; out (Buffer.contents global_preamble); suite := List.rev !suite; (* correct order (suite is built in reverse order) *) if !_shuffle then Shuffle.exec suite; listiteri process (preprocess !suite); out "let _ = try\n\ exit (QCheck_ounit.run (\"\" >::: List.rev !___tests))\n\ with Arg.Bad msg -> print_endline msg; exit 1\n\ | Arg.Help msg -> print_endline msg; exit 0"; if not !quiet then eps "Done.\n" (** Parse command line *) let add_preamble code = Buffer.add_string global_preamble code; Buffer.add_string global_preamble "\n" let add_preamble_file path = let input = open_in path in Buffer.add_channel global_preamble input (in_channel_length input); close_in input let set_output path = if not !quiet then epf "Target file: `%s'. " path; outc := open_out path let options = Arg.align [ "-o", Arg.String set_output, " "; "--output", Arg.String set_output, " (default: standard output) \ Open or create a file for output; the resulting file will be an OCaml source file containing all the tests\ "; "-p", Arg.String add_preamble, " "; "--preamble", Arg.String add_preamble, " (default: empty) \ Add code to the tests preamble; typically this will be an instruction of the form 'open Module'\ "; "--preamble-file", Arg.String add_preamble_file, " \ Add the contents of the given file to the tests preamble\n\ "; "--run-only", Arg.String (fun s->Core._run_only := Some s), " \ Only generate tests pertaining to this function, as indicated by the test header\ "; "--shuffle", Arg.Unit (fun ()->toggle _shuffle; if !_shuffle then epf "!!! SHUFFLE is ON !!!\n"), " (default: turned off) \ Toggle test execution order randomisation; submodules using injection are not shuffled"; "--quiet", Arg.Set quiet, " (default: turned off) \ Suppress output on stderr"; ] let usage_msg = (* OPTIONS: is here to mimick the pre-Arg behavior *) "USAGE: qtest [options] extract ...\n\ \n\ OPTIONS:" let () = Random.self_init(); let rev_anon_args = ref [] in let push_anon arg = (rev_anon_args := arg :: !rev_anon_args) in Arg.parse options push_anon usage_msg; match List.rev !rev_anon_args with | [] -> pl "qtest: use --help for usage notes." | "extract" :: paths -> generate paths | arg :: _ -> Arg.usage options usage_msg; prerr_newline(); failwith @@ "bad argument: " ^ arg } qtest-2.11.2/tests/000077500000000000000000000000001401136472500141025ustar00rootroot00000000000000qtest-2.11.2/tests/Runner_ounit2_test.ml000066400000000000000000000006451401136472500202510ustar00rootroot00000000000000let passing = QCheck.Test.make ~count:1000 ~name:"list_rev_is_involutive" QCheck.(list small_int) (fun l -> List.rev (List.rev l) = l);; let failing = QCheck.(Test.make ~count:10 ~name:"failing_test" (list small_int) (fun l -> l = List.sort compare l));; let () = let open OUnit2 in run_test_tt_main ( "tests" >::: QCheck_runner.to_ounit2_test_list [passing; failing]) qtest-2.11.2/tests/Runner_ounit_test.ml000066400000000000000000000006311401136472500201620ustar00rootroot00000000000000let passing = QCheck.Test.make ~count:1000 ~name:"list_rev_is_involutive" QCheck.(list small_int) (fun l -> List.rev (List.rev l) = l);; let failing = QCheck.(Test.make ~count:10 ~name:"failing_test" (list small_int) (fun l -> l = List.sort compare l));; let () = let open QCheck_runner in let _ = OUnit.run_test_tt_main ("tests" >::: [passing; failing]) in () qtest-2.11.2/tests/Runner_test.ml000066400000000000000000000005641401136472500167510ustar00rootroot00000000000000let passing = QCheck.Test.make ~count:1000 ~name:"list_rev_is_involutive" QCheck.(list small_int) (fun l -> List.rev (List.rev l) = l);; let failing = QCheck.(Test.make ~count:10 ~name:"failing_test" (list small_int) (fun l -> l = List.sort compare l));; let () = let _ = QCheck_runner.run_tests_main [passing; failing] in () qtest-2.11.2/tests/cppo.ml.cppo000066400000000000000000000000531401136472500163330ustar00rootroot00000000000000let included x = x #include "cppo.test.ml" qtest-2.11.2/tests/cppo.test.ml000066400000000000000000000000421401136472500163470ustar00rootroot00000000000000(*$T included included false *) qtest-2.11.2/tests/directives.ml000066400000000000000000000006651401136472500166040ustar00rootroot00000000000000(* first in the original file *) let _id1 x = x;; (*$T _id1 _id1 true _id1 (2 = 2) _id1 (3 + 1 = 4) *) # 8 "another_file.ml" (* then in another file *) let _id2 x = x;; (*$T _id2 _id2 true *) # 3 "with_different_lines.ml" let _id3 x = x;; (*$T _id3 _id3 true _id3 (5 + 1 = 6) *) # 20 "final_file.ml" (* in the middle of things *) let _id4 x = x;; (*$T _id4 _id4 true _id4 (1 = 1) _id4 true _id4 true _id4 true *) qtest-2.11.2/tests/directives.ml.reference000066400000000000000000000046071401136472500205410ustar00rootroot00000000000000let ___tests = ref [] let ___add test = ___tests := test::!___tests open OUnit;; module Q = QCheck;;let ( ==> ) = Q.( ==> );; module Test__environment_0 = struct open Directives;; let _test_2 = "_id1" >::: [ "directives.ml:4" >:: ( #4 "directives.ml" let _id1 = _id1 in fun () -> OUnit.assert_bool "directives.ml:4: _id1 true" ( #4 "directives.ml" _id1 true)); "directives.ml:5" >:: ( #5 "directives.ml" let _id1 = _id1 in fun () -> OUnit.assert_bool "directives.ml:5: _id1 (2 = 2)" ( #5 "directives.ml" _id1 (2 = 2))); "directives.ml:6" >:: ( #6 "directives.ml" let _id1 = _id1 in fun () -> OUnit.assert_bool "directives.ml:6: _id1 (3 + 1 = 4)" ( #6 "directives.ml" _id1 (3 + 1 = 4))); ];; let _ = ___add _test_2;; let _test_3 = "_id2" >::: [ "another_file.ml:11" >:: ( #11 "another_file.ml" let _id2 = _id2 in fun () -> OUnit.assert_bool "another_file.ml:11: _id2 true" ( #11 "another_file.ml" _id2 true)); ];; let _ = ___add _test_3;; let _test_4 = "_id3" >::: [ "with_different_lines.ml:5" >:: ( #5 "with_different_lines.ml" let _id3 = _id3 in fun () -> OUnit.assert_bool "with_different_lines.ml:5: _id3 true" ( #5 "with_different_lines.ml" _id3 true)); "with_different_lines.ml:6" >:: ( #6 "with_different_lines.ml" let _id3 = _id3 in fun () -> OUnit.assert_bool "with_different_lines.ml:6: _id3 (5 + 1 = 6)" ( #6 "with_different_lines.ml" _id3 (5 + 1 = 6))); ];; let _ = ___add _test_4;; let _test_5 = "_id4" >::: [ "final_file.ml:23" >:: ( #23 "final_file.ml" let _id4 = _id4 in fun () -> OUnit.assert_bool "final_file.ml:23: _id4 true" ( #23 "final_file.ml" _id4 true)); "final_file.ml:24" >:: ( #24 "final_file.ml" let _id4 = _id4 in fun () -> OUnit.assert_bool "final_file.ml:24: _id4 (1 = 1)" ( #24 "final_file.ml" _id4 (1 = 1))); "final_file.ml:25" >:: ( #25 "final_file.ml" let _id4 = _id4 in fun () -> OUnit.assert_bool "final_file.ml:25: _id4 true" ( #25 "final_file.ml" _id4 true)); "final_file.ml:26" >:: ( #26 "final_file.ml" let _id4 = _id4 in fun () -> OUnit.assert_bool "final_file.ml:26: _id4 true" ( #26 "final_file.ml" _id4 true)); "final_file.ml:27" >:: ( #27 "final_file.ml" let _id4 = _id4 in fun () -> OUnit.assert_bool "final_file.ml:27: _id4 true" ( #27 "final_file.ml" _id4 true)); ];; let _ = ___add _test_5;; end let _ = try exit (QCheck_ounit.run ("" >::: List.rev !___tests)) with Arg.Bad msg -> print_endline msg; exit 1 | Arg.Help msg -> print_endline msg; exit 0qtest-2.11.2/tests/foo.ml000066400000000000000000000111101401136472500152110ustar00rootroot00000000000000 (** This is the test file to check that qtest works as expected... ... because the tester needs to be tested as well. *) let rec foo x0 f = function [] -> x0 | x::xs -> f x (foo x0 f xs) (*$T foo foo 0 ( + ) [1;2;3] = 6 (* hehe *) foo 0 ( * ) [1;2;3] = 0 (* haha (*hoho *) *) foo 1 ( * ) [4;5] = 20 foo 12 ( + ) [] = 12 *) (*$T foo foo 1 ( * ) [4;5] = foo 2 ( * ) [1;5;2] *) (*$= foo & ~printer:string_of_int (foo 1 ( * ) [4;5]) (foo 2 ( * ) [1;5;2]) *) (*$Q foo Q.small_int (fun i-> foo i (+) [1;2;3] = List.fold_left (+) i [1;2;3]) (Q.pair Q.small_int (Q.list Q.small_int)) (fun (i,l)-> foo i (+) l = List.fold_left (+) i l) *) (*$R foo let thing = foo 1 ( * ) and li = [4;5] in assert_bool "something_witty" (thing li = 20); (* pertinent comment *) assert_bool "something_wittier" (1=1) *) let rec pretentious_drivel x0 f = function [] -> x0 | x::xs -> pretentious_drivel (f x x0) f xs (*$T pretentious_drivel pretentious_drivel 1 (+) [4;5] = foo 1 (+) [4;5] *) (*$T pretentious_drivel as x x 1 (+) [4;5] = foo 1 (+) [4;5] *) let rec even = function 0 -> true | n -> odd (pred n) and odd = function 0 -> false | n -> even (pred n) (*$Q even; odd Q.small_int (fun n-> odd (abs n+3) = even (abs n)) *) (*$Q even as x ; odd as y Q.small_int (fun n-> y (abs n+3) = x (abs n)) *) (*$Q forall x in [foo; pretentious_drivel] (Q.pair Q.small_int (Q.list Q.small_int)) (fun (i,l)-> x i (+) l = List.fold_left (+) i l) *) (*$Q forall foo in [foo; pretentious_drivel] & ~count:500 (Q.pair Q.small_int (Q.list Q.small_int)) (fun (i,l)-> foo i (+) l = List.fold_left (+) i l) *) (*$= pretentious_drivel as x & ~printer:string_of_int (x 1 (+) [4;5]) (foo 1 (+) [4;5]) *) (* first argument to an equality passed in parameter *) (*$= & ~printer:string_of_int 10 (foo 1 (+) [5;4]) (foo 1 (+) [4;5]) *) module Foomod : sig val bar : string (* val baz : string *) end = struct (*$< Foomod *) let bar = "bar" (*$T bar bar.[0] = 'b' *) (* TODO injection numbering is not right... yet it seems to be ?!? *) (*${*) let baz = "baz" (*$}*) (*$begin:inject*) let baz = "boz" (*$end:inject*) (*$T baz baz.[2] = 'z' *) (*$inject let brom = baz *) (*$T brom brom.[2] = 'z' *) (* global open *) (*$open List, Array *) (*${*) open Set;; open Sys;; (*$}*) (*$>*) end (* $T bar bar.[0] = 'b' *) module Tree = struct type t = Leaf of int | Node of t * t let leaf x = Leaf x let node x y = Node(x,y) let rec size = function | Leaf _ -> 1 | Node (x,y) -> 1 + size x + size y (*$< Tree *) (*$inject let rec print = function | Leaf x -> string_of_int x | Node(x,y) -> Printf.sprintf "Node(%s, %s)" (print x)(print y) let shrink = function | Leaf _ -> Q.Iter.empty | Node (x,y) -> Q.Iter.of_list [x;y] let gen = Q.Gen.(sized @@ fix (fun self n st -> match n with | 0 -> map leaf nat st | n -> frequency [1, map leaf nat ; 3, map2 node (self (n/2)) (self (n/2))] st )) let arb_tree = Q.make ~small:size ~shrink ~print gen *) let rec rev = function | Leaf x -> leaf x | Node (x,y) -> node (rev y) (rev x) (*$Q arb_tree (fun t -> rev (rev t) = t) arb_tree (fun t -> size t = size (rev t)) arb_tree (fun t -> (size t > 1) ==> (t = rev t)) *) (*$>*) end module Zooo = struct (*$begin:open Zooo *) let myplus = (+) (*$T myplus myplus 4 9 = 13 *) (*$end:open*) end (*$T & Foomod.bar.[0] = 'b' *) (*$T & 6 = 2*3 4+2 *) (*$= pretentious_drivel as x (x 1 (+) [4;5]) (foo 1 (+) [4;5]) *) (* empty headers: space, nothing, explicit empty param *) (*$T & 2+2 = 4 (* some comment *) *) (*$T 2+1 = 3 *) (*$T & 1 = 2-1 2+3 \ = \ \ 5 1+1=2 *) let fuz x = x let rec flu = function | [] -> [] | x :: l -> if List.mem x l then flu l else x :: flu l (* (*$Q fuz; flu & ~small:List.length\ & ~count:100 \ & (* test *) (Q.list Q.small_int) (fun x -> fuz x = flu x) *) *) let strange_string = " \" (*$Q fuz; flu & ~small:List.length\ & ~count:100 \ & (* test *) (Q.list Q.small_int) (fun x -> fuz x = flu x) *) " (*$T & 6 \ & = 2*3 *) (*$Q & ~count:10 (Q.small_int_corners ()) (fun n-> n+3 -2 -1 = abs n) *) (*$Q & ~max_gen:1000000 ~count:1000000 (Q.make (fun _ -> ())) (fun () -> true) *) (* issue #38 *) (*$Q & ~count:1_000_000 ~max_fail:3_000 (Q.make ~print:string_of_int ~small:(fun i -> i) \ (fun s -> Random.State.int s 1000)) \ (fun i -> i = i + 1) *) qtest-2.11.2/tests/issue_43.ml000066400000000000000000000003471401136472500160760ustar00rootroot00000000000000 (* should always run 100 tests *) open QCheck;; let is_even i = (i mod 2 = 0);; let is_odd i = (i mod 2 = 1);; let t = Test.make pos_int (fun i -> (is_even i) ==> (is_odd (succ i))) in QCheck_runner.run_tests ~verbose:true [t];; qtest-2.11.2/tests/issue_49.ml000066400000000000000000000000361401136472500160770ustar00rootroot00000000000000let x = "\\" (*$T false *) qtest-2.11.2/tests/testcppo.sh000077500000000000000000000006411401136472500163030ustar00rootroot00000000000000set -e # stop on first error echo | cppo > /dev/null \ || (echo "cppo is required to run this test"; exit 1) cppo cppo.ml.cppo > cppo.ml qtest extract cppo.ml -o cppo_test.ml ocamlbuild -cflags -warn-error,+26 -use-ocamlfind -pkg oUnit,qcheck cppo_test.native ./cppo_test.native 2>&1 | grep cppo.test.ml >/dev/null \ || { echo "test failed"; exit 1; } \ && { rm -f cppo.ml cppo_test.ml; echo "test passed"; } qtest-2.11.2/tests/testdirectives.sh000077500000000000000000000003501401136472500175000ustar00rootroot00000000000000set -e # stop on first error qtest extract directives.ml -o directives.ml.result diff -u directives.ml.{result,reference} > /dev/null \ || { echo "test failed"; exit 1; } \ && { rm -f directives.ml.result; echo "test passed"; } qtest-2.11.2/tests/testfoo.sh000077500000000000000000000003141401136472500161220ustar00rootroot00000000000000set -e # stop on first error # ./make.sh rm -rf footest.ml _build qtest -o footest.ml $@ extract foo.ml ocamlbuild -cflags -warn-error,+26 -use-ocamlfind -pkg oUnit,qcheck footest.native ./footest.native