commit 5c3c42d6b3dd1fcf58b8b51a0288e1aca36aede0 Author: Lance Edgar Date: Sat Oct 28 17:48:37 2023 -0500 First commit, basic config (with db) and app handler this has 100% test coverage and i intend to keep it that way. api docs have a good start but still need narrative. several more things must be added before i can seriously consider incorporating into rattail but this seemed a good save point diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fa5423e --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.coverage +docs/_build/ +WuttJamaican.egg-info/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..f0cc3bb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,10 @@ + +# Changelog +All notable changes to WuttJamaican will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [0.1.0] - ?? +### Added +- Initial version (TBD) diff --git a/COPYING.txt b/COPYING.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING.txt @@ -0,0 +1,674 @@ + 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 +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b288e59 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ + +# WuttJamaican + +aka. Whatcha Makin + +Base package for Wutta Framework diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..d4bb2cb --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/api/index.rst b/docs/api/index.rst new file mode 100644 index 0000000..336a1f2 --- /dev/null +++ b/docs/api/index.rst @@ -0,0 +1,12 @@ + +Package API +=========== + +This is the "raw" API documentation for the ``wuttjamaican`` package. It hopefully +contains all pertinent info regarding available functions, classes and their +attributes and method signatures etc. + +.. toctree:: + :maxdepth: 2 + + wuttjamaican/index diff --git a/docs/api/wuttjamaican/app.rst b/docs/api/wuttjamaican/app.rst new file mode 100644 index 0000000..f7368a1 --- /dev/null +++ b/docs/api/wuttjamaican/app.rst @@ -0,0 +1,6 @@ + +``wuttjamaican.app`` +==================== + +.. automodule:: wuttjamaican.app + :members: diff --git a/docs/api/wuttjamaican/conf.rst b/docs/api/wuttjamaican/conf.rst new file mode 100644 index 0000000..cd38c06 --- /dev/null +++ b/docs/api/wuttjamaican/conf.rst @@ -0,0 +1,6 @@ + +``wuttjamaican.conf`` +===================== + +.. automodule:: wuttjamaican.conf + :members: diff --git a/docs/api/wuttjamaican/db.conf.rst b/docs/api/wuttjamaican/db.conf.rst new file mode 100644 index 0000000..8ae273f --- /dev/null +++ b/docs/api/wuttjamaican/db.conf.rst @@ -0,0 +1,6 @@ + +``wuttjamaican.db.conf`` +======================== + +.. automodule:: wuttjamaican.db.conf + :members: diff --git a/docs/api/wuttjamaican/db.rst b/docs/api/wuttjamaican/db.rst new file mode 100644 index 0000000..ef1ddaa --- /dev/null +++ b/docs/api/wuttjamaican/db.rst @@ -0,0 +1,6 @@ + +``wuttjamaican.db`` +=================== + +.. automodule:: wuttjamaican.db + :members: diff --git a/docs/api/wuttjamaican/db.sess.rst b/docs/api/wuttjamaican/db.sess.rst new file mode 100644 index 0000000..2233f88 --- /dev/null +++ b/docs/api/wuttjamaican/db.sess.rst @@ -0,0 +1,6 @@ + +``wuttjamaican.db.sess`` +======================== + +.. automodule:: wuttjamaican.db.sess + :members: diff --git a/docs/api/wuttjamaican/exc.rst b/docs/api/wuttjamaican/exc.rst new file mode 100644 index 0000000..7907af7 --- /dev/null +++ b/docs/api/wuttjamaican/exc.rst @@ -0,0 +1,6 @@ + +``wuttjamaican.exc`` +==================== + +.. automodule:: wuttjamaican.exc + :members: diff --git a/docs/api/wuttjamaican/index.rst b/docs/api/wuttjamaican/index.rst new file mode 100644 index 0000000..68abe0a --- /dev/null +++ b/docs/api/wuttjamaican/index.rst @@ -0,0 +1,16 @@ + +``wuttjaimaican`` +================= + +.. automodule:: wuttjamaican + +.. toctree:: + :maxdepth: 1 + + app + conf + db + db.conf + db.sess + exc + util diff --git a/docs/api/wuttjamaican/util.rst b/docs/api/wuttjamaican/util.rst new file mode 100644 index 0000000..0a16085 --- /dev/null +++ b/docs/api/wuttjamaican/util.rst @@ -0,0 +1,6 @@ + +``wuttjamaican.util`` +===================== + +.. automodule:: wuttjamaican.util + :members: diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..d453db1 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,38 @@ +# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +project = 'WuttJamaican' +copyright = '2023, Lance Edgar' +author = 'Lance Edgar' +release = '0.1' + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration + +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.intersphinx', + 'sphinx.ext.todo', +] + +templates_path = ['_templates'] +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +intersphinx_mapping = { + 'python-configuration': ('https://python-configuration.readthedocs.io/en/latest/', None), + 'rattail': ('https://rattailproject.org/docs/rattail/', None), + 'rattail-manual': ('https://rattailproject.org/docs/rattail-manual/', None), + 'sqlalchemy': ('http://docs.sqlalchemy.org/en/latest/', None), +} + + +# -- Options for HTML output ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +html_theme = 'alabaster' +html_static_path = ['_static'] diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..79b85d2 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,70 @@ + +WuttJamaican +============ + +aka. Whatcha Makin + +This package provides a "base layer" of sorts, for apps built with it. + +It mostly is a distillation of certain patterns developed within the +Rattail Project, which are deemed generally useful. (At least, +according to the author.) It roughly corresponds to the "base layer" +as described in the Rattail Manual (see :doc:`rattail-manual:base/index`). + +Good documentation and 100% test coverage are priorities for this project. + +Much remains to be done, and it may be slow going since I'll be trying +to incorporate this package into the main Rattail package along the +way. So we'll see where this goes... + +At this point the main focus is the configuration interface. + + +Basic Usage +----------- + +Install with: + +.. code-block:: sh + + pip install wuttjamaican + +Create a config file, e.g. ``my.conf``: + +.. code-block:: ini + + [foo] + bar = A + baz = 2 + feature = true + +In your app, load the config and reference its values as needed:: + + import wuttjamaican as wj + + config = wj.make_config('/path/to/my.conf') + + config.get('foo.bar') # returns 'A' + + config.get('foo.baz') # returns '2' + config.get_int('foo.baz') # returns 2 + + config.get('foo.feature') # returns 'true' + config.get_bool('foo.feature') # returns True + + +Contents +-------- + +.. toctree:: + :maxdepth: 3 + + api/index + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..32bb245 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.https://www.sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "" goto help + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..7b0fba0 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,44 @@ +# -*- coding: utf-8; -*- + +[metadata] +name = WuttJamaican +version = attr: wuttjamaican.__version__ +author = Lance Edgar +author_email = lance@edbob.org +url = https://rattailproject.org/ +license = GNU GPL v3 +description = Base package for Wutta Framework +long_description = file: README.md +classifiers = + Development Status :: 4 - Beta + Intended Audience :: Developers + License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) + Natural Language :: English + Operating System :: OS Independent + Programming Language :: Python + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 + Programming Language :: Python :: 3.10 + Programming Language :: Python :: 3.11 + + +[options] +packages = find: +package_dir = + =src +include_package_data = True +python_requires = >=3.6 +install_requires = + python-configuration + + +[options.packages.find] +where = src + + +[options.extras_require] +docs = Sphinx +tests = pytest-cov; SQLAlchemy<2 diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..aa529c4 --- /dev/null +++ b/setup.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8; -*- +################################################################################ +# +# WuttJamaican -- Base package for Wutta Framework +# Copyright © 2023 Lance Edgar +# +# This file is part of Wutta Framework. +# +# Wutta Framework 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. +# +# Wutta Framework 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 +# Wutta Framework. If not, see . +# +################################################################################ +""" +WuttJamaican setup script +""" + +from setuptools import setup + +setup() diff --git a/src/wuttjamaican/__init__.py b/src/wuttjamaican/__init__.py new file mode 100644 index 0000000..e9d5220 --- /dev/null +++ b/src/wuttjamaican/__init__.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8; -*- +################################################################################ +# +# WuttJamaican -- Base package for Wutta Framework +# Copyright © 2023 Lance Edgar +# +# This file is part of Wutta Framework. +# +# Wutta Framework 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. +# +# Wutta Framework 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 +# Wutta Framework. If not, see . +# +################################################################################ +""" +WuttJamaican - base package for Wutta Framework + +There is just one function exposed in the root namespace: +:func:`~wuttjamaican.conf.make_config()` + +Typical usage is something like:: + + import wuttjamaican as wj + + config = wj.make_config(appname='poser') + app = config.get_app() +""" + +from ._version import __version__ + +from .conf import make_config diff --git a/src/wuttjamaican/_version.py b/src/wuttjamaican/_version.py new file mode 100644 index 0000000..e41b669 --- /dev/null +++ b/src/wuttjamaican/_version.py @@ -0,0 +1,3 @@ +# -*- coding: utf-8; -*- + +__version__ = '0.1.0' diff --git a/src/wuttjamaican/app.py b/src/wuttjamaican/app.py new file mode 100644 index 0000000..7eef83e --- /dev/null +++ b/src/wuttjamaican/app.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8; -*- +################################################################################ +# +# WuttJamaican -- Base package for Wutta Framework +# Copyright © 2023 Lance Edgar +# +# This file is part of Wutta Framework. +# +# Wutta Framework 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. +# +# Wutta Framework 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 +# Wutta Framework. If not, see . +# +################################################################################ +""" +WuttJamaican - app handler +""" + +from wuttjamaican.util import load_entry_points + + +class AppHandler: + """ + Base class and default implementation for top-level app handler. + + aka. "the handler to handle all handlers" + + aka. "one handler to bind them all" + + There is normally no need to create one of these yourself; rather + you should call :meth:`~wuttjamaican.conf.WuttaConfig.get_app()` + on the config object if you need the app handler. + + :param config: Config object for the app. This should be an + instance of :class:`~wuttjamaican.conf.WuttaConfig`. + """ + + def __init__(self, config): + self.config = config + self.handlers = {} + + def make_session(self, **kwargs): + """ + Creates a new SQLAlchemy session for the app DB. By default + this will create a new :class:`~wuttjamaican.db.sess.Session` + instance. + + :returns: SQLAlchemy session for the app DB. + """ + from .db import Session + + return Session(**kwargs) + + def short_session(self, **kwargs): + """ + Returns a context manager for a short-lived database session. + + This is a convenience wrapper around + :class:`~wuttjamaican.db.sess.short_session`. + + If caller does not specify ``factory`` nor ``config`` params, + this method will provide a default factory in the form of + :meth:`make_session`. + """ + from .db import short_session + + if 'factory' not in kwargs and 'config' not in kwargs: + kwargs['factory'] = self.make_session + + return short_session(**kwargs) + + def get_setting(self, session, name, **kwargs): + """ + Get a setting value from the DB. + + This does *not* consult the config object directly to + determine the setting value; it always queries the DB. + + Default implementation is just a convenience wrapper around + :func:`~wuttjamaican.db.conf.get_setting()`. + + :param session: App DB session. + + :param name: Name of the setting to get. + + :returns: Setting value as string, or ``None``. + """ + from .db import get_setting + + return get_setting(session, name) diff --git a/src/wuttjamaican/conf.py b/src/wuttjamaican/conf.py new file mode 100644 index 0000000..7922a1f --- /dev/null +++ b/src/wuttjamaican/conf.py @@ -0,0 +1,649 @@ +# -*- coding: utf-8; -*- +################################################################################ +# +# WuttJamaican -- Base package for Wutta Framework +# Copyright © 2023 Lance Edgar +# +# This file is part of Wutta Framework. +# +# Wutta Framework 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. +# +# Wutta Framework 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 +# Wutta Framework. If not, see . +# +################################################################################ +""" +WuttJamaican - app configuration +""" + +import configparser +import importlib +import logging +import os +import sys +import tempfile + +import config as configuration + +from wuttjamaican.util import (load_entry_points, load_object, + parse_bool, parse_list, + UNSPECIFIED) +from wuttjamaican.exc import ConfigurationError + + +log = logging.getLogger(__name__) + + +class WuttaConfig: + """ + Configuration class for Wutta Framework + + A single instance of this class is typically created on app + startup, by calling :func:`make_config()`. + + The global config object is mainly responsible for providing + config values to the app, via :meth:`get()` and similar methods. + + The config object may have more than one place to look when + finding values. This can vary somewhat but often the priority for + lookup is like: + + * settings table in the DB + * one or more INI files + * "defaults" provided by app logic + + :param files: List of file paths from which to read config values. + + :param appname: This string forms the basis of certain other + things, namely some of the config keys which will be checked to + determine default behavior of the config object itself (if they + are not specified via constructor). + + :param usedb: Flag indicating whether config values should ever be + looked up from the DB. Note that you can override this when + calling :meth:`get()`. + + :param preferdb: Flag indicating whether values from DB should be + preferred over the values from INI files or app defaults. Note + that you can override this when calling :meth:`get()`. + + Attributes available on the config instance: + + .. attribute:: configuration + + Reference to the + :class:`python-configuration:config.ConfigurationSet` instance + which houses the full set of config values which are kept in + memory. This does *not* contain settings from DB, but *does* + contain :attr:`defaults` as well as values read from INI files. + + .. attribute:: defaults + + Reference to the + :class:`python-configuration:config.Configuration` instance + containing config *default* values. This is exposed in case + it's useful, but in practice you should not update it directly; + instead use :meth:`setdefault()`. + + .. attribute:: files_read + + List of all INI config files which were read on app startup. + These are listed in the same order as they were read. This + sequence also reflects priority for value lookups, i.e. the + first file with the value wins. + """ + + def __init__( + self, + files=[], + defaults={}, + appname='wutta', + usedb=None, + preferdb=None, + configure_logging=None, + ): + self.appname = appname + configs = [] + + # read all files requested + self.files_read = [] + for path in files: + self._load_ini_configs(path, configs, require=True) + log.debug("config files were: %s", self.files_read) + + # add config for use w/ setdefault() + self.defaults = configuration.Configuration(defaults) + configs.append(self.defaults) + + # master config set + self.configuration = configuration.ConfigurationSet(*configs) + + # establish logging + if configure_logging is None: + configure_logging = self.get_bool(f'{self.appname}.config.configure_logging', + default=False, usedb=False) + if configure_logging: + self._configure_logging() + + # usedb flag + self.usedb = usedb + if self.usedb is None: + self.usedb = self.get_bool(f'{self.appname}.config.usedb', + default=False, usedb=False) + + # preferdb flag + self.preferdb = preferdb + if self.usedb and self.preferdb is None: + self.preferdb = self.get_bool(f'{self.appname}.config.preferdb', + default=False, usedb=False) + + # configure main app DB if applicable, or disable usedb flag + try: + from .db import Session, get_engines + except ImportError: + if self.usedb: + log.warning("config created with `usedb = True`, but can't import " + "DB module(s), so setting `usedb = False` instead", + exc_info=True) + self.usedb = False + self.preferdb = False + else: + self.appdb_engines = get_engines(self, f'{self.appname}.db') + self.appdb_engine = self.appdb_engines.get('default') + Session.configure(bind=self.appdb_engine) + + log.debug("config files read: %s", self.files_read) + + def _load_ini_configs(self, path, configs, require=True): + path = os.path.abspath(path) + + # try to load config from the given path + try: + config = configuration.config_from_ini(path, read_from_file=True) + except FileNotFoundError: + if not require: + log.warning("INI config file not found: %s", path) + return + raise + + # ok add that one to the mix + configs.append(config) + self.files_read.append(path) + + # need parent folder of that path, for %(here)s interpolation + here = os.path.dirname(path) + + # bring in any "required" files + requires = config.get(f'{self.appname}.config.require') + if requires: + for path in parse_list(requires): + path = path % {'here': here} + self._load_ini_configs(path, configs, require=True) + + # bring in any "included" files + includes = config.get(f'{self.appname}.config.include') + if includes: + for path in parse_list(includes): + path = path % {'here': here} + self._load_ini_configs(path, configs, require=False) + + def setdefault( + self, + key, + value): + """ + Establish a default config value for the given key. + + Note that there is only *one* default value per key. If + multiple calls are made with the same key, the first will set + the default and subsequent calls have no effect. + + :returns: The current config value, *outside of the DB*. For + various reasons this method may not be able to lookup + settings from the DB, e.g. during app init. So it can only + determine the value per INI files + config defaults. + """ + # set default value, if not already set + self.defaults.setdefault(key, value) + + # get current value, sans db + return self.get(key, usedb=False) + + def get( + self, + key, + default=UNSPECIFIED, + require=False, + message=None, + usedb=None, + preferdb=None, + session=None, + ): + """ + Retrieve a string value from config. + + .. warning:: + + While the point of this method is to return a *string* + value, it is possible for a key to be present in config + which corresponds to a "subset" of the config, and not a + simple value. For instance with this config file: + + .. code-block:: ini + + [foo] + bar = 1 + bar.baz = 2 + + If you invoke ``config.get('foo.bar')`` the return value + is somewhat ambiguous. At first glance it should return + ``'1'`` - but just as valid would be to return the dict:: + + {'baz': '2'} + + And similarly, if you invoke ``config.get('foo')`` then + the return value "should be" the dict:: + + {'bar': '1', + 'bar.baz': '2'} + + Despite all that ambiguity, again the whole point of this + method is to return a *string* value, only. Therefore in + any case where the return value "should be" a dict, per + logic described above, this method will *ignore* that and + simply return ``None`` (or rather the ``default`` value). + + It is important also to understand that in fact, there is + no "real" ambiguity per se, but rather a dict (subset) + would always get priority over a simple string value. So + in the first example above, ``config.get('foo.bar')`` will + always return the ``default`` value. The string value + ``'1'`` will never be returned since the dict/subset + overshadows it, and this method will only return the + default value in lieu of any dict. + + :param key: String key for which value should be returned. + + :param default: Default value to be returned, if config does + not contain the key. If no default is specified, ``None`` + will be assumed. + + :param require: If set, an error will be raised if config does + not contain the key. If not set, default value is returned + (which may be ``None``). + + Note that it is an error to specify a default value if you + also specify ``require=True``. + + :param message: Optional first part of message to be used, + when raising a "value not found" error. If not specified, + a default error message will be generated. + + :param usedb: Flag indicating whether config values should be + looked up from the DB. The default for this param is + ``None``, in which case the :attr:`usedb` flag determines + the behavior. + + :param preferdb: Flag indicating whether config values from DB + should be preferred over values from INI files and/or app + defaults. The default for this param is ``None``, in which + case the :attr:`preferdb` flag determines the behavior. + + :param session: Optional SQLAlchemy session to use for DB lookups. + NOTE: This param is not yet implemented; currently ignored. + + :returns: Value as string. + + """ + if require and default is not UNSPECIFIED: + raise ValueError("must not specify default value when require=True") + + # should we use/prefer db? + if usedb is None: + usedb = self.usedb + if usedb and preferdb is None: + preferdb = self.preferdb + + # read from db first if so requested + if usedb and preferdb: + value = self.get_from_db(key, session=session) + if value is not None: + return value + + # read from defaults + INI files + value = self.configuration.get(key) + if value is not None: + + # nb. if the "value" corresponding to the given key is in + # fact a subset/dict of more config values, then we must + # "ignore" that. so only return the value if it is *not* + # such a config subset. + if not isinstance(value, configuration.Configuration): + return value + + # read from db last if so requested + if usedb and not preferdb: + value = self.get_from_db(key, session=session) + if value is not None: + return value + + # raise error if required value not found + if require: + message = message or "missing or invalid config" + raise ConfigurationError(f"{message}; please set config value for: {key}") + + # give the default value if specified + if default is not UNSPECIFIED: + return default + + def get_from_db(self, key, session=None): + """ + Retrieve a config value from database settings table. + + This is a convenience wrapper around + :meth:`~wuttjamaican.app.AppHandler.get_setting()`. + """ + app = self.get_app() + with app.short_session(session=session) as s: + return app.get_setting(s, key) + + def require(self, *args, **kwargs): + """ + Retrieve a value from config, or raise error if no value can + be found. This is just a shortcut, so these work the same:: + + config.get('foo', require=True) + + config.require('foo') + """ + kwargs['require'] = True + return self.get(*args, **kwargs) + + def get_bool(self, *args, **kwargs): + """ + Retrieve a boolean value from config. + + Accepts same params as :meth:`get()` but if a value is found, + it will be coerced to boolean via + :func:`~wuttjamaican.util.parse_bool()`. + """ + value = self.get(*args, **kwargs) + return parse_bool(value) + + def get_dict(self, prefix): + """ + Retrieve a particular group of values, as a dictionary. + + Please note, this will only return values from INI files + + defaults. It will *not* return values from DB settings. In + other words it assumes ``usedb=False``. + + For example given this config file: + + .. code-block:: ini + + [wutta.db] + keys = default, host + default.url = sqlite:///tmp/default.sqlite + host.url = sqlite:///tmp/host.sqlite + host.pool_pre_ping = true + + One can get the "dict" for SQLAlchemy engine config via:: + + config.get_dict('wutta.db') + + And the dict would look like:: + + {'keys': 'default, host', + 'default.url': 'sqlite:///tmp/default.sqlite', + 'host.url': 'sqlite:///tmp/host.sqlite', + 'host.pool_pre_ping': 'true'} + + :param prefix: String prefix corresponding to a subsection of + the config. + + :returns: Dictionary containing the config subsection. + """ + try: + values = self.configuration[prefix] + except KeyError: + return {} + + return values.as_dict() + + def _configure_logging(self): + """ + This will save the current config parser defaults to a + temporary file, and use this file to configure Python's + standard logging module. + """ + # write current values to file suitable for logging auto-config + path = self._write_logging_config_file() + try: + logging.config.fileConfig(path, disable_existing_loggers=False) + except configparser.NoSectionError as error: + log.warning("tried to configure logging, but got NoSectionError: %s", error) + else: + log.debug("configured logging") + finally: + os.remove(path) + + def _write_logging_config_file(self): + + # load all current values into configparser + parser = configparser.RawConfigParser() + for section, values in self.configuration.items(): + parser.add_section(section) + for option, value in values.items(): + parser.set(section, option, value) + + # write INI file and return path + fd, path = tempfile.mkstemp(suffix='.conf') + os.close(fd) + with open(path, 'wt') as f: + parser.write(f) + return path + + def get_app(self): + """ + Returns the global :class:`~wuttjamaican.app.AppHandler` + instance, creating it if necessary. + """ + if not hasattr(self, 'app'): + spec = self.get(f'{self.appname}.app.handler', usedb=False, + default='wuttjamaican.app:AppHandler') + factory = load_object(spec) + self.app = factory(self) + return self.app + + +def generic_default_files(appname): + """ + Returns a list of default file paths which might be used for + making a config object. This function does not check if the paths + actually exist. + + :param appname: App name to be used as basis for default filenames. + + :returns: List of default file paths. + """ + if sys.platform == 'win32': + # use pywin32 to fetch official defaults + try: + from win32com.shell import shell, shellcon + except ImportError: + return [] + + return [ + # e.g. C:\..?? TODO: what is the user-specific path on win32? + os.path.join(shell.SHGetSpecialFolderPath( + 0, shellcon.CSIDL_APPDATA), appname, f'{appname}.conf'), + os.path.join(shell.SHGetSpecialFolderPath( + 0, shellcon.CSIDL_APPDATA), f'{appname}.conf'), + + # e.g. C:\ProgramData\wutta\wutta.conf + os.path.join(shell.SHGetSpecialFolderPath( + 0, shellcon.CSIDL_COMMON_APPDATA), appname, f'{appname}.conf'), + os.path.join(shell.SHGetSpecialFolderPath( + 0, shellcon.CSIDL_COMMON_APPDATA), f'{appname}.conf'), + ] + + # default paths for *nix + return [ + f'{sys.prefix}/app/{appname}.conf', + + os.path.expanduser(f'~/.{appname}/{appname}.conf'), + os.path.expanduser(f'~/.{appname}.conf'), + + f'/usr/local/etc/{appname}/{appname}.conf', + f'/usr/local/etc/{appname}.conf', + + f'/etc/{appname}/{appname}.conf', + f'/etc/{appname}.conf', + ] + + +def make_config( + files=None, + plus_files=None, + appname='wutta', + env_files_name=None, + env_plus_files_name=None, + env=None, + default_files=None, + usedb=None, + preferdb=None, + extend=True, + extension_entry_points=None): + """ + Returns a new config object (presumably for global use), + initialized per the given parameters and (usually) further + modified by all registered config extensions. + + :param files: Config file path(s) to be loaded. If not specified, + then some "default" behavior will be attempted. (This will + check for env var or fallback to system default paths. Or you + can override all that by specifying some path(s) here.) + + :param plus_files: Additional config path(s) to be loaded. You + may specify a "config tweak" file(s) here, and leave ``files`` + empty, to get "defaults plus tweak" behavior. + + :param appname: Optional "app name" to use as basis for other + things - namely, constructing the default config file paths + etc. For instance the default ``appname`` value is ``'wutta'`` + which leads to default env vars like ``WUTTA_CONFIG_FILES``. + + :param env_files_name: Name of the environment variable to read, + if ``files`` is not specified. The default is + ``WUTTA_CONFIG_FILES`` unless you override ``appname``. + + :param env_plus_files_name: Name of the environment variable to + read, if ``plus_files`` is not specified. The default is + ``WUTTA_CONFIG_PLUS_FILES`` unless you override ``appname``. + + :param env: Optional override for the ``os.environ`` dict. + + :param default_files: Optional way to identify the "default" file + path(s), if neither ``files`` nor ``env_files_name`` yield + anything. This can be a list of potential file paths, or a + callable which returns such a list. If a callable, it should + accept a single ``appname`` arg. + + :param usedb: Passed to the :class:`WuttaConfig` constructor. + + :param preferdb: Passed to the :class:`WuttaConfig` constructor. + + :param extend: Whether to "auto-extend" the config with all + registered extensions. + + As a general rule, ``make_config()`` should only be called + once, upon app startup. This is because some of the config + extensions may do things which should only happen one time. + However if ``extend=False`` is specified, then no extensions + are invoked, so this may be done multiple times. + + (Why anyone would need this, is another question..maybe only + useful for tests.) + + :param extension_entry_points: Name of the ``setuptools`` entry + points section, used to identify registered config extensions. + The default is ``wutta.config.extensions`` unless you override + ``appname``. + """ + if env is None: + env = os.environ + + # first identify any "primary" config files + if files is None: + if not env_files_name: + env_files_name = f'{appname.upper()}_CONFIG_FILES' + + files = env.get(env_files_name) + if files is not None: + files = files.split(os.pathsep) + + elif default_files: + if callable(default_files): + files = default_files(appname) or [] + elif isinstance(default_files, str): + files = [default_files] + else: + files = list(default_files) + + else: + files = [] + for path in generic_default_files(appname): + if os.path.exists(path): + files.append(path) + + elif isinstance(files, str): + files = [files] + else: + files = list(files) + + # then identify any "plus" (config tweak) files + if plus_files is None: + if not env_plus_files_name: + env_plus_files_name = f'{appname.upper()}_CONFIG_PLUS_FILES' + + plus_files = env.get(env_plus_files_name) + if plus_files is not None: + plus_files = plus_files.split(os.pathsep) + + else: + plus_files = [] + + elif isinstance(plus_files, str): + plus_files = [plus_files] + else: + plus_files = list(plus_files) + + # combine all files + files.extend(plus_files) + + # make config object + config = WuttaConfig(files, appname=appname, + usedb=usedb, preferdb=preferdb) + + # maybe extend config object + if extend: + if not extension_entry_points: + extension_entry_points = f'{appname}.config.extensions' + + # apply all registered extensions + # TODO: maybe let config disable some extensions? + extensions = load_entry_points(extension_entry_points) + for extension in extensions.values(): + log.debug("applying config extension: %s", extension.key) + extension().configure(config) + + return config diff --git a/src/wuttjamaican/db/__init__.py b/src/wuttjamaican/db/__init__.py new file mode 100644 index 0000000..6d95aee --- /dev/null +++ b/src/wuttjamaican/db/__init__.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8; -*- +################################################################################ +# +# WuttJamaican -- Base package for Wutta Framework +# Copyright © 2023 Lance Edgar +# +# This file is part of Wutta Framework. +# +# Wutta Framework 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. +# +# Wutta Framework 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 +# Wutta Framework. If not, see . +# +################################################################################ +""" +WuttJamaican - app database +""" + +from .sess import Session, short_session +from .conf import get_setting, get_engines diff --git a/src/wuttjamaican/db/conf.py b/src/wuttjamaican/db/conf.py new file mode 100644 index 0000000..1d5f497 --- /dev/null +++ b/src/wuttjamaican/db/conf.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8; -*- +################################################################################ +# +# WuttJamaican -- Base package for Wutta Framework +# Copyright © 2023 Lance Edgar +# +# This file is part of Wutta Framework. +# +# Wutta Framework 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. +# +# Wutta Framework 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 +# Wutta Framework. If not, see . +# +################################################################################ +""" +WuttJamaican - database configuration +""" + +from collections import OrderedDict + +import sqlalchemy as sa + +from wuttjamaican.util import load_object, parse_bool, parse_list + + +def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs): + """ + Construct a new DB engine from configuration. + + This is a wrapper around upstream + :func:`sqlalchemy:sqlalchemy.engine_from_config()`. + + The purpose of the customization is to allow certain attributes of + the engine to be driven by config, whereas the upstream function + is more limited in that regard. The following in particular: + + * ``poolclass`` + * ``pool_pre_ping`` + + If these options are present in the configuration dictionary, they + will be coerced to appropriate Python equivalents and then passed + as kwargs to the upstream function. + + An example config file leveraging this feature: + + .. code-block:: ini + + [wutta.db] + sqlalchemy.url = sqlite:///tmp/default.sqlite + sqlalchemy.poolclass = sqlalchemy.pool:NullPool + sqlalchemy.pool_pre_ping = true + + Note that if present, the ``poolclass`` value must be a "spec" + string, as required by :func:`~wuttjamaican.util.load_object()`. + """ + config_dict = dict(configuration) + + # convert 'poolclass' arg to actual class + key = f'{prefix}poolclass' + if key in config_dict: + kwargs.setdefault('poolclass', load_object(config_dict[key])) + del config_dict[key] + + # convert 'pool_pre_ping' arg to boolean + key = f'{prefix}pool_pre_ping' + if key in config_dict: + kwargs.setdefault('pool_pre_ping', parse_bool(config_dict[key])) + del config_dict[key] + + engine = sa.engine_from_config(config_dict, prefix, **kwargs) + + return engine + + +def get_engines(config, prefix): + """ + Construct and return all database engines defined for a given + config prefix. + + For instance if you have a config file with: + + .. code-block:: ini + + [wutta.db] + keys = default, host + default.url = sqlite:///tmp/default.sqlite + host.url = sqlite:///tmp/host.sqlite + + And then you call this function to get those DB engines:: + + get_engines(config, 'wutta.db') + + The result of that will be like:: + + {'default': Engine(bind='sqlite:///tmp/default.sqlite'), + 'host': Engine(bind='sqlite:///tmp/host.sqlite')} + + :param config: App config object. + + :param prefix: Prefix for the config "section" which contains DB + connection info. + + :returns: A dictionary of SQLAlchemy engines, with keys matching + those found in config. + """ + keys = config.get(f'{prefix}.keys', usedb=False) + if keys: + keys = parse_list(keys) + else: + keys = ['default'] + + engines = OrderedDict() + cfg = config.get_dict(prefix) + for key in keys: + key = key.strip() + try: + engines[key] = engine_from_config(cfg, prefix=f'{key}.') + except KeyError: + if key == 'default': + try: + engines[key] = engine_from_config(cfg, prefix='sqlalchemy.') + except KeyError: + pass + return engines + + +def get_setting(session, name): + """ + Get a setting value from the DB. + + Note that this assumes (for now?) the DB contains a table named + ``setting`` with ``(name, value)`` columns. + + :param session: App DB session. + + :param name: Name of the setting to get. + + :returns: Setting value as string, or ``None``. + """ + sql = sa.text("select value from setting where name = :name") + return session.execute(sql, params={'name': name}).scalar() diff --git a/src/wuttjamaican/db/sess.py b/src/wuttjamaican/db/sess.py new file mode 100644 index 0000000..c1597e2 --- /dev/null +++ b/src/wuttjamaican/db/sess.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8; -*- +################################################################################ +# +# WuttJamaican -- Base package for Wutta Framework +# Copyright © 2023 Lance Edgar +# +# This file is part of Wutta Framework. +# +# Wutta Framework 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. +# +# Wutta Framework 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 +# Wutta Framework. If not, see . +# +################################################################################ +""" +WuttJamaican - database sessions + +.. class:: Session + + SQLAlchemy session class used for all (normal) app database + connections. + + See the upstream :class:`sqlalchemy:sqlalchemy.orm.Session` docs + for more info. +""" + +from sqlalchemy import orm + + +Session = orm.sessionmaker() + + +class short_session: + """ + Context manager for a short-lived database session. + + A canonical use case for this is when the config object needs to + grab a single setting value from the DB, but it does not have an + active DB session to do it. This context manager is used to + produce the session, and close it when finished. For example:: + + with short_session(config) as s: + result = s.query("select something from somewhere").scalar() + + How it goes about producing the session instance will depend on + which of the following 3 params are given (explained below): + + * ``config`` + * ``factory`` + * ``session`` + + Note that it is also okay if you provide *none* of the above + params, in which case the main :class:`Session` class will be used + as the factory. + + :param config: Optional app config object. If a new session must + be created, the config will be consulted to determine the + factory which is used to create the new session. + + :param factory: Optional factory to use when making a new session. + If specified, this will override the ``config`` mechanism. + + :param session: Optional SQLAlchemy session instance. If a valid + session is provided here, it will be used instead of creating a + new/temporary session. + + :param commit: Whether the temporary session should be committed + before it is closed. This flag has no effect if a valid + ``session`` instance is provided, since no temporary session + will be created. + """ + + def __init__(self, config=None, factory=None, session=None, commit=False): + self.config = config + self.factory = factory + self.session = session + self.private = not bool(session) + self.commit = commit + + def __enter__(self): + if not self.session: + if not self.factory: + if self.config: + app = self.config.get_app() + self.factory = app.make_session + else: + self.factory = Session + self.session = self.factory() + return self.session + + def __exit__(self, exc_type, exc_value, traceback): + if self.private: + if self.commit: + self.session.commit() + self.session.close() + self.session = None diff --git a/src/wuttjamaican/exc.py b/src/wuttjamaican/exc.py new file mode 100644 index 0000000..7115b85 --- /dev/null +++ b/src/wuttjamaican/exc.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8; -*- +################################################################################ +# +# WuttJamaican -- Base package for Wutta Framework +# Copyright © 2023 Lance Edgar +# +# This file is part of Wutta Framework. +# +# Wutta Framework 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. +# +# Wutta Framework 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 +# Wutta Framework. If not, see . +# +################################################################################ +""" +WuttJamaican - exceptions +""" + + +class WuttaError(Exception): + """ + Base class for all exceptions specific to Wutta Framework. + """ + + +class ConfigurationError(WuttaError): + """ + Generic class for configuration errors. + """ diff --git a/src/wuttjamaican/util.py b/src/wuttjamaican/util.py new file mode 100644 index 0000000..2f7d846 --- /dev/null +++ b/src/wuttjamaican/util.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8; -*- +################################################################################ +# +# WuttJamaican -- Base package for Wutta Framework +# Copyright © 2023 Lance Edgar +# +# This file is part of Wutta Framework. +# +# Wutta Framework 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. +# +# Wutta Framework 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 +# Wutta Framework. If not, see . +# +################################################################################ +""" +WuttJamaican - utilities +""" + +import importlib +import logging +import shlex + + +log = logging.getLogger(__name__) + + +# nb. this is used as default kwarg value in some places, to +# distinguish passing a ``None`` value, vs. *no* value at all +UNSPECIFIED = object() + + +def load_entry_points(group, ignore_errors=False): + """ + Load a set of ``setuptools``-style entry points. + + This is used to locate "plugins" and similar things, e.g. the set + of subcommands which belong to a main command. + + :param group: The group (string name) of entry points to be + loaded. + + :ignore_errors: If false (the default), any errors will be raised + normally. If true, errors will be logged but not raised. + + :returns: A dictionary whose keys are the entry point names, and + values are the loaded entry points. + """ + entry_points = {} + + try: + # nb. this package was added in python 3.8 + import importlib.metadata + + except ImportError: + # older setup, must use pkg_resources + # TODO: remove this section once we require python 3.8 + from pkg_resources import iter_entry_points + + for entry_point in iter_entry_points(group): + try: + ep = entry_point.load() + except: + if not ignore_errors: + raise + log.warning("failed to load entry point: %s", entry_point, + exc_info=True) + else: + entry_points[entry_point.name] = ep + + else: + # newer setup (python >= 3.8); can use importlib + eps = importlib.metadata.entry_points() + for entry_point in eps.select(group=group): + try: + ep = entry_point.load() + except: + if not ignore_errors: + raise + log.warning("failed to load entry point: %s", entry_point, + exc_info=True) + else: + entry_points[entry_point.name] = ep + + return entry_points + + +def load_object(spec): + """ + Load an arbitrary object from a module, according to the spec. + + The spec string should contain a dotted path to an importable module, + followed by a colon (``':'``), followed by the name of the object to be + loaded. For example: + + .. code-block:: none + + wuttjamaican.util:parse_bool + + You'll notice from this example that "object" in this context refers to any + valid Python object, i.e. not necessarily a class instance. The name may + refer to a class, function, variable etc. Once the module is imported, the + ``getattr()`` function is used to obtain a reference to the named object; + therefore anything supported by that approach should work. + + :param spec: Spec string. + + :returns: The specified object. + """ + if not spec: + raise ValueError("no object spec provided") + + module_path, name = spec.split(':') + module = importlib.import_module(module_path) + return getattr(module, name) + + +def parse_bool(value): + """ + Derive a boolean from the given string value. + """ + if value is None: + return None + if isinstance(value, bool): + return value + if str(value).lower() in ('true', 'yes', 'y', 'on', '1'): + return True + return False + + +def parse_list(value): + """ + Parse a configuration value, splitting by whitespace and/or commas + and taking quoting into account etc., yielding a list of strings. + """ + if value is None: + return [] + parser = shlex.shlex(value) + parser.whitespace += ',' + parser.whitespace_split = True + values = list(parser) + for i, value in enumerate(values): + if value.startswith('"') and value.endswith('"'): + values[i] = value[1:-1] + elif value.startswith("'") and value.endswith("'"): + values[i] = value[1:-1] + return values diff --git a/tasks.py b/tasks.py new file mode 100644 index 0000000..e59e973 --- /dev/null +++ b/tasks.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8; -*- +""" +Tasks for WuttJamaican +""" + +import os +import shutil + +from invoke import task + + +here = os.path.abspath(os.path.dirname(__file__)) +exec(open(os.path.join(here, 'wuttjamaican', '_version.py')).read()) + + +@task +def release(c): + """ + Release a new version of WuttJamaican + """ + # rebuild local tar.gz file for distribution + if os.path.exists('WuttJamaican.egg-info'): + shutil.rmtree('WuttJamaican.egg-info') + c.run('python -m build --sdist') + + # upload to PyPI + filename = f'WuttJamaican-{__version__}.tar.gz' + c.run(f'twine upload dist/{filename}') diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/db/__init__.py b/tests/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/db/test_conf.py b/tests/db/test_conf.py new file mode 100644 index 0000000..f2f66b9 --- /dev/null +++ b/tests/db/test_conf.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8; -*- + +import os +import shutil +import tempfile +from unittest import TestCase + +import sqlalchemy as sa +from sqlalchemy import orm +from sqlalchemy.engine import Engine +from sqlalchemy.pool import NullPool + +from wuttjamaican.db import conf +from wuttjamaican.conf import WuttaConfig + + +class TestEngineFromConfig(TestCase): + + def test_basic(self): + engine = conf.engine_from_config({ + 'sqlalchemy.url': 'sqlite://', + }) + self.assertIsInstance(engine, Engine) + + def test_poolclass(self): + + engine = conf.engine_from_config({ + 'sqlalchemy.url': 'sqlite://', + }) + self.assertNotIsInstance(engine.pool, NullPool) + + engine = conf.engine_from_config({ + 'sqlalchemy.url': 'sqlite://', + 'sqlalchemy.poolclass': 'sqlalchemy.pool:NullPool', + }) + self.assertIsInstance(engine.pool, NullPool) + + def test_pool_pre_ping(self): + + engine = conf.engine_from_config({ + 'sqlalchemy.url': 'sqlite://', + }) + self.assertFalse(engine.pool._pre_ping) + + engine = conf.engine_from_config({ + 'sqlalchemy.url': 'sqlite://', + 'sqlalchemy.pool_pre_ping': 'true', + }) + self.assertTrue(engine.pool._pre_ping) + + +class TestGetEngines(TestCase): + + def setUp(self): + self.tempdir = tempfile.mkdtemp() + + def tearDown(self): + shutil.rmtree(self.tempdir) + + def write_file(self, filename, content): + path = os.path.join(self.tempdir, filename) + with open(path, 'wt') as f: + f.write(content) + return path + + def test_no_default(self): + myfile = self.write_file('my.conf', '') + config = WuttaConfig([myfile]) + self.assertEqual(conf.get_engines(config, 'wuttadb'), {}) + + def test_default(self): + myfile = self.write_file('my.conf', """\ +[wuttadb] +default.url = sqlite:// +""") + config = WuttaConfig([myfile]) + result = conf.get_engines(config, 'wuttadb') + self.assertEqual(len(result), 1) + self.assertIn('default', result) + engine = result['default'] + self.assertEqual(engine.dialect.name, 'sqlite') + + def test_default_fallback(self): + myfile = self.write_file('my.conf', """\ +[wuttadb] +sqlalchemy.url = sqlite:// +""") + config = WuttaConfig([myfile]) + result = conf.get_engines(config, 'wuttadb') + self.assertEqual(len(result), 1) + self.assertIn('default', result) + engine = result['default'] + self.assertEqual(engine.dialect.name, 'sqlite') + + def test_other(self): + myfile = self.write_file('my.conf', """\ +[otherdb] +keys = first, second +first.url = sqlite:// +second.url = sqlite:// +""") + config = WuttaConfig([myfile]) + result = conf.get_engines(config, 'otherdb') + self.assertEqual(len(result), 2) + self.assertIn('first', result) + self.assertIn('second', result) + + +class TestGetSetting(TestCase): + + def setUp(self): + Session = orm.sessionmaker() + engine = sa.create_engine('sqlite://') + self.session = Session(bind=engine) + self.session.execute(sa.text(""" + create table setting ( + name varchar(255) primary key, + value text + ); + """)) + + def tearDown(self): + self.session.close() + + def test_basic_value(self): + self.session.execute(sa.text("insert into setting values ('foo', 'bar');")) + value = conf.get_setting(self.session, 'foo') + self.assertEqual(value, 'bar') + + def test_missing_value(self): + value = conf.get_setting(self.session, 'foo') + self.assertIsNone(value) diff --git a/tests/db/test_sess.py b/tests/db/test_sess.py new file mode 100644 index 0000000..d03305b --- /dev/null +++ b/tests/db/test_sess.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8; -*- + +from unittest import TestCase +from unittest.mock import MagicMock + +import sqlalchemy as sa +from sqlalchemy import orm + +from wuttjamaican.db import sess +from wuttjamaican.conf import WuttaConfig + + +class TestShortSession(TestCase): + + def test_none(self): + with sess.short_session() as s: + self.assertIsInstance(s, sess.Session.class_) + + def test_factory(self): + TestSession = orm.sessionmaker() + with sess.short_session(factory=TestSession) as s: + self.assertIsInstance(s, TestSession.class_) + + def test_instance(self): + # nb. nothing really happens if we provide the session instance + session = MagicMock() + with sess.short_session(session=session) as s: + pass + session.commit.assert_not_called() + session.close.assert_not_called() + + def test_config(self): + config = MagicMock() + TestSession = orm.sessionmaker() + config.get_app.return_value.make_session = TestSession + # nb. config may be first arg (or kwarg) + with sess.short_session(config) as s: + self.assertIsInstance(s, TestSession.class_) + + def test_without_commit(self): + session = MagicMock() + TestSession = MagicMock(return_value=session) + with sess.short_session(factory=TestSession, commit=False) as s: + pass + session.commit.assert_not_called() + session.close.assert_called_once_with() + + def test_with_commit(self): + session = MagicMock() + TestSession = MagicMock(return_value=session) + with sess.short_session(factory=TestSession, commit=True) as s: + pass + session.commit.assert_called_once_with() + session.close.assert_called_once_with() diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..c532ade --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8; -*- + +from unittest import TestCase +from unittest.mock import patch, MagicMock + +import sqlalchemy as sa +from sqlalchemy import orm + +from wuttjamaican import app, db + + +class TestAppHandler(TestCase): + + def setUp(self): + self.config = MagicMock() + self.app = app.AppHandler(self.config) + + def test_init(self): + self.assertIs(self.app.config, self.config) + self.assertEqual(self.app.handlers, {}) + + def test_make_session(self): + session = self.app.make_session() + self.assertIsInstance(session, db.Session.class_) + + def test_short_session(self): + short_session = MagicMock() + mockdb = MagicMock(short_session=short_session) + + with patch.dict('sys.modules', **{'wuttjamaican.db': mockdb}): + + with self.app.short_session(foo='bar') as s: + short_session.assert_called_once_with( + foo='bar', factory=self.app.make_session) + + def test_get_setting(self): + Session = orm.sessionmaker() + engine = sa.create_engine('sqlite://') + session = Session(bind=engine) + session.execute(sa.text(""" + create table setting ( + name varchar(255) primary key, + value text + ); + """)) + session.commit() + + value = self.app.get_setting(session, 'foo') + self.assertIsNone(value) + + session.execute(sa.text("insert into setting values ('foo', 'bar');")) + value = self.app.get_setting(session, 'foo') + self.assertEqual(value, 'bar') diff --git a/tests/test_conf.py b/tests/test_conf.py new file mode 100644 index 0000000..213a0e1 --- /dev/null +++ b/tests/test_conf.py @@ -0,0 +1,579 @@ +# -*- coding: utf-8; -*- + +import configparser +import os +import shutil +import tempfile +from unittest import TestCase +from unittest.mock import patch, MagicMock + +import sqlalchemy as sa + +from wuttjamaican import conf +from wuttjamaican.exc import ConfigurationError +from wuttjamaican.db import Session + + +class TestWuttaConfig(TestCase): + + def setUp(self): + self.tempdir = tempfile.mkdtemp() + + def tearDown(self): + shutil.rmtree(self.tempdir) + + def write_file(self, filename, content): + path = os.path.join(self.tempdir, filename) + with open(path, 'wt') as f: + f.write(content) + return path + + def test_contstructor_basic(self): + config = conf.WuttaConfig() + self.assertEqual(config.appname, 'wutta') + self.assertEqual(config.files_read, []) + + def test_constructor_valid_files(self): + myfile = self.write_file('my.conf', '') + config = conf.WuttaConfig(files=[myfile]) + self.assertEqual(len(config.files_read), 1) + self.assertEqual(config.files_read[0], myfile) + + def test_constructor_missing_files(self): + invalid = os.path.join(self.tempdir, 'invalid.conf') + self.assertRaises(FileNotFoundError, conf.WuttaConfig, files=[invalid]) + + def test_constructor_required_files_are_present(self): + first = self.write_file('first.conf', """\ +[foo] +bar = 1 +baz = A +""") + + second = self.write_file('second.conf', """\ +[wutta.config] +require = %(here)s/first.conf + +[foo] +baz = B +""") + + config = conf.WuttaConfig(files=[second]) + self.assertEqual(len(config.files_read), 2) + # nb. files_read listing is in order of "priority" which is + # same the as order in which files were initially read + self.assertEqual(config.files_read[0], second) + self.assertEqual(config.files_read[1], first) + self.assertEqual(config.get('foo.bar'), '1') + self.assertEqual(config.get('foo.baz'), 'B') + + def test_constructor_required_files_are_missing(self): + second = self.write_file('second.conf', """\ +[wutta.config] +require = %(here)s/first.conf + +[foo] +baz = B +""") + + self.assertRaises(FileNotFoundError, conf.WuttaConfig, files=[second]) + + def test_constructor_included_files_are_present(self): + first = self.write_file('first.conf', """\ +[foo] +bar = 1 +baz = A +""") + + second = self.write_file('second.conf', """\ +[wutta.config] +include = %(here)s/first.conf + +[foo] +baz = B +""") + + config = conf.WuttaConfig(files=[second]) + self.assertEqual(len(config.files_read), 2) + # nb. files_read listing is in order of "priority" which is + # same the as order in which files were initially read + self.assertEqual(config.files_read[0], second) + self.assertEqual(config.files_read[1], first) + self.assertEqual(config.get('foo.bar'), '1') + self.assertEqual(config.get('foo.baz'), 'B') + + def test_constructor_included_files_are_missing(self): + second = self.write_file('second.conf', """\ +[wutta.config] +include = %(here)s/first.conf + +[foo] +baz = B +""") + + config = conf.WuttaConfig(files=[second]) + self.assertEqual(len(config.files_read), 1) + self.assertEqual(config.files_read[0], second) + self.assertIsNone(config.get('foo.bar')) + self.assertEqual(config.get('foo.baz'), 'B') + + def test_constructor_defaults(self): + config = conf.WuttaConfig() + self.assertEqual(config.defaults, {}) + self.assertIsNone(config.get('foo')) + + config = conf.WuttaConfig(defaults={'foo': 'bar'}) + self.assertEqual(config.defaults, {'foo': 'bar'}) + self.assertEqual(config.get('foo'), 'bar') + + def test_constructor_db_flags(self): + myfile = self.write_file('my.conf', """\ +[wutta.config] +usedb = true +preferdb = true +""") + + # flags are off by default + config = conf.WuttaConfig() + self.assertFalse(config.usedb) + self.assertFalse(config.preferdb) + + # but may override via constructor + config = conf.WuttaConfig(usedb=True, preferdb=True) + self.assertTrue(config.usedb) + self.assertTrue(config.preferdb) + + # and also may override via config file + config = conf.WuttaConfig(files=[myfile]) + self.assertTrue(config.usedb) + self.assertTrue(config.preferdb) + + def test_constructor_db_not_supported(self): + + # flags are off by default + config = conf.WuttaConfig() + self.assertFalse(config.usedb) + self.assertFalse(config.preferdb) + + # but caller may enable the flags (if sqlalchemy available) + config = conf.WuttaConfig(usedb=True, preferdb=True) + self.assertTrue(config.usedb) + self.assertTrue(config.preferdb) + + # but db flags are force-disabled if sqlalchemy not available, + # regardless of flag values caller provides... + + orig_import = __import__ + + def mock_import(name, *args, **kwargs): + if name == 'db': + raise ImportError + return orig_import(name, *args, **kwargs) + + with patch('builtins.__import__', side_effect=mock_import): + config = conf.WuttaConfig(usedb=True, preferdb=True) + self.assertFalse(config.usedb) + self.assertFalse(config.preferdb) + + def test_constructor_may_configure_logging(self): + myfile = self.write_file('my.conf', """\ +[wutta.config] +configure_logging = true +""") + + with patch.object(conf.WuttaConfig, '_configure_logging') as method: + + # no logging config by default + config = conf.WuttaConfig() + method.assert_not_called() + + # but may override via constructor + method.reset_mock() + config = conf.WuttaConfig(configure_logging=True) + method.assert_called_once() + + # and also may override via config file + method.reset_mock() + config = conf.WuttaConfig(files=[myfile]) + method.assert_called_once() + + def test_constructor_configures_logging(self): + myfile = self.write_file('my.conf', """\ +[wutta] +timezone.default = America/Chicago + +[wutta.config] +configure_logging = true +""") + + with patch('wuttjamaican.conf.logging') as logging: + + # basic constructor attempts logging config + config = conf.WuttaConfig(configure_logging=True) + logging.config.fileConfig.assert_called_once() + + # if logging config fails, error is *not* raised + logging.config.fileConfig.reset_mock() + logging.config.fileConfig.side_effect = configparser.NoSectionError('logging') + config = conf.WuttaConfig(configure_logging=True) + logging.config.fileConfig.assert_called_once() + + # and it works if we specify config file + logging.config.fileConfig.reset_mock() + config = conf.WuttaConfig(files=[myfile]) + logging.config.fileConfig.assert_called_once() + + def test_setdefault(self): + config = conf.WuttaConfig() + + # value is empty by default + self.assertIsNone(config.get('foo')) + + # but we can change that by setting default + config.setdefault('foo', 'bar') + self.assertEqual(config.get('foo'), 'bar') + + # also, value is returned when we set default + self.assertIsNone(config.get('baz')) + self.assertEqual(config.setdefault('baz', 'blarg'), 'blarg') + + def test_get_require_with_default(self): + config = conf.WuttaConfig() + self.assertRaises(ValueError, config.get, 'foo', require=True, default='bar') + + def test_get_require_missing(self): + config = conf.WuttaConfig() + self.assertRaises(ConfigurationError, config.get, 'foo', require=True) + + def test_get_with_default(self): + config = conf.WuttaConfig() + # nb. returns None if no default specified + self.assertIsNone(config.get('foo')) + self.assertEqual(config.get('foo', default='bar'), 'bar') + + def test_get_from_db(self): + # minimal config, but at least it needs db cxn info + config = conf.WuttaConfig(defaults={'wutta.db.default.url': 'sqlite://'}) + + session = Session() + + # setup table for testing + session.execute(sa.text(""" + create table setting ( + name varchar(255) primary key, + value text + ); + """)) + session.commit() + + # setting not yet defined + self.assertIsNone(config.get_from_db('foo')) + + # insert setting value to db + session.execute(sa.text("insert into setting values ('foo', 'bar')")) + session.commit() + + # now setting returns a value + self.assertEqual(config.get_from_db('foo'), 'bar') + + # also works if we provide the session + self.assertEqual(config.get_from_db('foo', session=session), 'bar') + + session.close() + + def test_get_default(self): + config = conf.WuttaConfig() + self.assertIsNone(config.get('foo')) + self.assertEqual(config.get('foo', default='bar'), 'bar') + + def test_get_require(self): + config = conf.WuttaConfig() + self.assertIsNone(config.get('foo')) + self.assertRaises(ConfigurationError, config.get, 'foo', require=True) + + def test_get_require_message(self): + config = conf.WuttaConfig() + self.assertIsNone(config.get('foo')) + try: + config.get('foo', require=True, message="makin stuff up") + except ConfigurationError as error: + self.assertIn("makin stuff up", str(error)) + + def test_get_preferdb(self): + + # start out with a default value + config = conf.WuttaConfig(defaults={'wutta.db.default.url': 'sqlite://', + 'foo': 'bar'}) + self.assertEqual(config.get('foo'), 'bar') + + session = Session() + + # setup table for testing + session.execute(sa.text(""" + create table setting ( + name varchar(255) primary key, + value text + ); + """)) + session.execute(sa.text("insert into setting values ('foo', 'baz')")) + session.commit() + + # we did not specify usedb=True, so original default is still returned + self.assertFalse(config.usedb) + self.assertEqual(config.get('foo'), 'bar') + + # usedb but no preferdb means original default is still returned + self.assertEqual(config.get('foo', usedb=True), 'bar') + + # but preferdb should mean newer db value is returned + self.assertEqual(config.get('foo', usedb=True, preferdb=True), 'baz') + + # try a different key to ensure db fallback works if no default present + session.execute(sa.text("insert into setting values ('blarg', 'blitz')")) + session.commit() + self.assertIsNone(config.get('blarg')) + self.assertEqual(config.get('blarg', usedb=True), 'blitz') + + session.close() + + def test_require(self): + config = conf.WuttaConfig() + self.assertRaises(ConfigurationError, config.require, 'foo') + + +class TestGenericDefaultFiles(TestCase): + + def test_linux(self): + files = conf.generic_default_files('wuttatest') + self.assertIsInstance(files, list) + self.assertTrue(len(files) > 1) + self.assertIn('/etc/wuttatest.conf', files) + + def test_win32(self): + win32com = MagicMock() + win32com.shell.SHGetSpecialFolderPath.return_value = r'C:' + os.sep + with patch.dict('sys.modules', **{'win32com.shell': win32com}): + with patch('wuttjamaican.conf.sys', platform='win32'): + + files = conf.generic_default_files('wuttatest') + self.assertIsInstance(files, list) + self.assertTrue(len(files) > 1) + self.assertIn(os.path.join('C:', 'wuttatest.conf'), files) + + def test_win32_broken(self): + orig_import = __import__ + + def mock_import(name, *args, **kwargs): + if name == 'win32com.shell': + raise ImportError + return orig_import(name, *args, **kwargs) + + with patch('builtins.__import__', side_effect=mock_import): + with patch('wuttjamaican.conf.sys', platform='win32'): + + files = conf.generic_default_files('wuttatest') + self.assertIsInstance(files, list) + self.assertEqual(len(files), 0) + + +class TestMakeConfig(TestCase): + + # nb. we use appname='wuttatest' in this suite to avoid any + # "valid" default config files, env vars etc. which may be present + # on the dev machine + + def setUp(self): + self.tempdir = tempfile.mkdtemp() + + def tearDown(self): + shutil.rmtree(self.tempdir) + + def write_file(self, filename, content): + path = os.path.join(self.tempdir, filename) + with open(path, 'wt') as f: + f.write(content) + return path + + def test_generic_default_files(self): + generic = self.write_file('generic.conf', '') + + with patch('wuttjamaican.conf.generic_default_files') as generic_default_files: + with patch('wuttjamaican.conf.WuttaConfig') as WuttaConfig: + + # generic files are used if nothing is specified + generic_default_files.return_value = [generic] + config = conf.make_config(appname='wuttatest') + generic_default_files.assert_called_once_with('wuttatest') + WuttaConfig.assert_called_once_with([generic], appname='wuttatest', + usedb=None, preferdb=None) + + # make sure empty defaults works too + generic_default_files.reset_mock() + generic_default_files.return_value = [] + WuttaConfig.reset_mock() + config = conf.make_config(appname='wuttatest') + generic_default_files.assert_called_once_with('wuttatest') + WuttaConfig.assert_called_once_with([], appname='wuttatest', + usedb=None, preferdb=None) + + def test_specify_default_files(self): + generic = self.write_file('generic.conf', '') + myfile = self.write_file('my.conf', '') + + with patch('wuttjamaican.conf.generic_default_files') as generic_default_files: + with patch('wuttjamaican.conf.WuttaConfig') as WuttaConfig: + + # generic defaults are used if nothing specified + generic_default_files.return_value = [generic] + config = conf.make_config(appname='wuttatest') + generic_default_files.assert_called_once_with('wuttatest') + WuttaConfig.assert_called_once_with([generic], appname='wuttatest', + usedb=None, preferdb=None) + + # can specify single default file + generic_default_files.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(appname='wuttatest', default_files=myfile) + generic_default_files.assert_not_called() + WuttaConfig.assert_called_once_with([myfile], appname='wuttatest', + usedb=None, preferdb=None) + + # can specify default files as list + generic_default_files.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(appname='wuttatest', default_files=[myfile]) + generic_default_files.assert_not_called() + WuttaConfig.assert_called_once_with([myfile], appname='wuttatest', + usedb=None, preferdb=None) + + # can specify default files as callable + generic_default_files.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(appname='wuttatest', default_files=lambda appname: [myfile]) + generic_default_files.assert_not_called() + WuttaConfig.assert_called_once_with([myfile], appname='wuttatest', + usedb=None, preferdb=None) + + def test_specify_plus_files(self): + generic = self.write_file('generic.conf', '') + myfile = self.write_file('my.conf', '') + + with patch('wuttjamaican.conf.generic_default_files') as generic_default_files: + with patch('wuttjamaican.conf.WuttaConfig') as WuttaConfig: + + generic_default_files.return_value = [generic] + + # no plus files by default + config = conf.make_config(appname='wuttatest') + generic_default_files.assert_called_once_with('wuttatest') + WuttaConfig.assert_called_once_with([generic], appname='wuttatest', + usedb=None, preferdb=None) + + # can specify single plus file + generic_default_files.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(appname='wuttatest', plus_files=myfile) + generic_default_files.assert_called_once_with('wuttatest') + WuttaConfig.assert_called_once_with([generic, myfile], appname='wuttatest', + usedb=None, preferdb=None) + + # can specify plus files as list + generic_default_files.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(appname='wuttatest', plus_files=[myfile]) + generic_default_files.assert_called_once_with('wuttatest') + WuttaConfig.assert_called_once_with([generic, myfile], appname='wuttatest', + usedb=None, preferdb=None) + + # can specify plus files via env + generic_default_files.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(appname='wuttatest', + env={'WUTTATEST_CONFIG_PLUS_FILES': myfile}) + generic_default_files.assert_called_once_with('wuttatest') + WuttaConfig.assert_called_once_with([generic, myfile], appname='wuttatest', + usedb=None, preferdb=None) + + def test_specify_primary_files(self): + generic = self.write_file('generic.conf', '') + myfile = self.write_file('my.conf', '') + + with patch('wuttjamaican.conf.generic_default_files') as generic_default_files: + with patch('wuttjamaican.conf.WuttaConfig') as WuttaConfig: + + generic_default_files.return_value = [generic] + + # generic files by default + config = conf.make_config(appname='wuttatest') + generic_default_files.assert_called_once_with('wuttatest') + WuttaConfig.assert_called_once_with([generic], appname='wuttatest', + usedb=None, preferdb=None) + + # can specify single primary file (nb. no default files) + generic_default_files.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(myfile, appname='wuttatest') + generic_default_files.assert_not_called() + WuttaConfig.assert_called_once_with([myfile], appname='wuttatest', + usedb=None, preferdb=None) + + # can specify primary files as list + generic_default_files.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config([myfile], appname='wuttatest') + generic_default_files.assert_not_called() + WuttaConfig.assert_called_once_with([myfile], appname='wuttatest', + usedb=None, preferdb=None) + + # can specify primary files via env + generic_default_files.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(appname='wuttatest', + env={'WUTTATEST_CONFIG_FILES': myfile}) + generic_default_files.assert_not_called() + WuttaConfig.assert_called_once_with([myfile], appname='wuttatest', + usedb=None, preferdb=None) + + def test_extensions(self): + generic = self.write_file('generic.conf', '') + myfile = self.write_file('my.conf', '') + + with patch('wuttjamaican.conf.WuttaConfig') as WuttaConfig: + with patch('wuttjamaican.conf.load_entry_points') as load_entry_points: + + # no entry points loaded if extend=False + config = conf.make_config(appname='wuttatest', extend=False) + WuttaConfig.assert_called_once_with([], appname='wuttatest', + usedb=None, preferdb=None) + load_entry_points.assert_not_called() + + # confirm entry points for default appname + load_entry_points.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(appname='wutta') + WuttaConfig.assert_called_once_with([], appname='wutta', + usedb=None, preferdb=None) + load_entry_points.assert_called_once_with('wutta.config.extensions') + + # confirm entry points for custom appname + load_entry_points.reset_mock() + WuttaConfig.reset_mock() + config = conf.make_config(appname='wuttatest') + WuttaConfig.assert_called_once_with([], appname='wuttatest', + usedb=None, preferdb=None) + load_entry_points.assert_called_once_with('wuttatest.config.extensions') + + # confirm extensions are invoked + load_entry_points.reset_mock() + foo_obj = MagicMock() + foo_cls = MagicMock(return_value=foo_obj) + load_entry_points.return_value = {'foo': foo_cls} + WuttaConfig.reset_mock() + testconfig = MagicMock() + WuttaConfig.return_value = testconfig + config = conf.make_config(appname='wuttatest') + WuttaConfig.assert_called_once_with([], appname='wuttatest', + usedb=None, preferdb=None) + load_entry_points.assert_called_once_with('wuttatest.config.extensions') + foo_cls.assert_called_once_with() + foo_obj.configure.assert_called_once_with(testconfig) diff --git a/tests/test_util.py b/tests/test_util.py new file mode 100644 index 0000000..d424376 --- /dev/null +++ b/tests/test_util.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8; -*- + +from unittest import TestCase +from unittest.mock import patch, MagicMock + +# nb. setuptools must be imported before distutils, else weird +# behavior may ensue within some of the tests below +import setuptools + +from wuttjamaican import util + + +class TestLoadEntryPoints(TestCase): + + def test_empty(self): + # empty set returned for unknown group + result = util.load_entry_points('this_should_never_exist!!!!!!') + self.assertEqual(result, {}) + + def test_basic(self): + # load some entry points which should "always" be present, + # even in a testing environment. basic sanity check + result = util.load_entry_points('console_scripts') + self.assertTrue(len(result) >= 1) + self.assertIn('pip', result) + + def test_error(self): + + entry_point = MagicMock() + entry_point.load.side_effect = NotImplementedError("just a testin") + + entry_points = MagicMock() + entry_points.select.return_value = [entry_point] + + importlib = MagicMock() + importlib.metadata.entry_points.return_value = entry_points + + with patch.dict('sys.modules', **{'importlib': importlib}): + + # empty set returned if errors suppressed + result = util.load_entry_points('wuttatest.thingers', ignore_errors=True) + self.assertEqual(result, {}) + importlib.metadata.entry_points.assert_called_once_with() + entry_points.select.assert_called_once_with(group='wuttatest.thingers') + entry_point.load.assert_called_once_with() + + # error is raised, if not suppressed + importlib.metadata.entry_points.reset_mock() + entry_points.select.reset_mock() + entry_point.load.reset_mock() + self.assertRaises(NotImplementedError, util.load_entry_points, 'wuttatest.thingers') + importlib.metadata.entry_points.assert_called_once_with() + entry_points.select.assert_called_once_with(group='wuttatest.thingers') + entry_point.load.assert_called_once_with() + + def test_pkg_resources_empty(self): + orig_import = __import__ + + def mock_import(name, *args, **kwargs): + if name == 'importlib.metadata': + raise ImportError + return orig_import(name, *args, **kwargs) + + with patch('builtins.__import__', side_effect=mock_import): + + # empty set returned for unknown group + result = util.load_entry_points('this_should_never_exist!!!!!!') + self.assertEqual(result, {}) + + def test_pkg_resources_basic(self): + orig_import = __import__ + + def mock_import(name, *args, **kwargs): + if name == 'importlib.metadata': + raise ImportError + return orig_import(name, *args, **kwargs) + + with patch('builtins.__import__', side_effect=mock_import): + + # load some entry points which should "always" be present, + # even in a testing environment. basic sanity check + result = util.load_entry_points('console_scripts') + self.assertTrue(len(result) >= 1) + self.assertIn('pip', result) + + def test_pkg_resources_error(self): + orig_import = __import__ + + entry_point = MagicMock() + entry_point.load.side_effect = NotImplementedError("just a testin") + + iter_entry_points = MagicMock(return_value=[entry_point]) + pkg_resources = MagicMock(iter_entry_points=iter_entry_points) + + def mock_import(name, *args, **kwargs): + if name == 'importlib.metadata': + raise ImportError + return orig_import(name, *args, **kwargs) + + with patch('builtins.__import__', side_effect=mock_import): + with patch.dict('sys.modules', **{'pkg_resources': pkg_resources}): + + # empty set returned if errors suppressed + result = util.load_entry_points('wuttatest.thingers', ignore_errors=True) + self.assertEqual(result, {}) + iter_entry_points.assert_called_once_with('wuttatest.thingers') + entry_point.load.assert_called_once_with() + + # error is raised, if not suppressed + iter_entry_points.reset_mock() + entry_point.load.reset_mock() + self.assertRaises(NotImplementedError, util.load_entry_points, 'wuttatest.thingers') + iter_entry_points.assert_called_once_with('wuttatest.thingers') + entry_point.load.assert_called_once_with() + + +class TestLoadObject(TestCase): + + def test_missing_spec(self): + self.assertRaises(ValueError, util.load_object, None) + + def test_basic(self): + result = util.load_object('unittest:TestCase') + self.assertIs(result, TestCase) + + +class TestParseBool(TestCase): + + def test_null(self): + self.assertIsNone(util.parse_bool(None)) + + def test_bool(self): + self.assertTrue(util.parse_bool(True)) + self.assertFalse(util.parse_bool(False)) + + def test_string_true(self): + self.assertTrue(util.parse_bool('true')) + self.assertTrue(util.parse_bool('yes')) + self.assertTrue(util.parse_bool('y')) + self.assertTrue(util.parse_bool('on')) + self.assertTrue(util.parse_bool('1')) + + def test_string_false(self): + self.assertFalse(util.parse_bool('false')) + self.assertFalse(util.parse_bool('no')) + self.assertFalse(util.parse_bool('n')) + self.assertFalse(util.parse_bool('off')) + self.assertFalse(util.parse_bool('0')) + # nb. assume false for unrecognized input + self.assertFalse(util.parse_bool('whatever-else')) + + +class TestParseList(TestCase): + + def test_null(self): + value = util.parse_list(None) + self.assertIsInstance(value, list) + self.assertEqual(len(value), 0) + + def test_single_value(self): + value = util.parse_list('foo') + self.assertEqual(len(value), 1) + self.assertEqual(value[0], 'foo') + + def test_single_value_padded_by_spaces(self): + value = util.parse_list(' foo ') + self.assertEqual(len(value), 1) + self.assertEqual(value[0], 'foo') + + def test_slash_is_not_a_separator(self): + value = util.parse_list('/dev/null') + self.assertEqual(len(value), 1) + self.assertEqual(value[0], '/dev/null') + + def test_multiple_values_separated_by_whitespace(self): + value = util.parse_list('foo bar baz') + self.assertEqual(len(value), 3) + self.assertEqual(value[0], 'foo') + self.assertEqual(value[1], 'bar') + self.assertEqual(value[2], 'baz') + + def test_multiple_values_separated_by_commas(self): + value = util.parse_list('foo,bar,baz') + self.assertEqual(len(value), 3) + self.assertEqual(value[0], 'foo') + self.assertEqual(value[1], 'bar') + self.assertEqual(value[2], 'baz') + + def test_multiple_values_separated_by_whitespace_and_commas(self): + value = util.parse_list(' foo, bar baz') + self.assertEqual(len(value), 3) + self.assertEqual(value[0], 'foo') + self.assertEqual(value[1], 'bar') + self.assertEqual(value[2], 'baz') + + def test_multiple_values_separated_by_whitespace_and_commas_with_some_quoting(self): + value = util.parse_list(""" + foo + "C:\\some path\\with spaces\\and, a comma", + baz + """) + self.assertEqual(len(value), 3) + self.assertEqual(value[0], 'foo') + self.assertEqual(value[1], 'C:\\some path\\with spaces\\and, a comma') + self.assertEqual(value[2], 'baz') + + def test_multiple_values_separated_by_whitespace_and_commas_with_single_quotes(self): + value = util.parse_list(""" + foo + 'C:\\some path\\with spaces\\and, a comma', + baz + """) + self.assertEqual(len(value), 3) + self.assertEqual(value[0], 'foo') + self.assertEqual(value[1], 'C:\\some path\\with spaces\\and, a comma') + self.assertEqual(value[2], 'baz')