diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..8fbf3af --- /dev/null +++ b/.dockerignore @@ -0,0 +1,15 @@ +*.pyc +__pycache__/ +/venv/ +/static/ +/media/ +/pg-data/ +.env +db.sqlite3 +.DS_Store +.idea +.coverage +.vscode +node_modules/ +testy_static/dist/*.html +package-lock.json \ No newline at end of file diff --git a/.env.ci b/.env.ci new file mode 100644 index 0000000..854d791 --- /dev/null +++ b/.env.ci @@ -0,0 +1,11 @@ +POSTGRES_NAME=postgres +POSTGRES_USER=postgres +POSTGRES_USERNAME=postgres +POSTGRES_PASSWORD=postgres +POSTGRES_SERVICE_HOST=127.0.0.1 +POSTGRES_SERVICE_PORT=5435 + +COMPANY_DOMAIN=example.com + +SUPERUSER_USERNAME=admin +SUPERUSER_PASSWORD=password \ No newline at end of file diff --git a/.env.template b/.env.template new file mode 100644 index 0000000..3e330c0 --- /dev/null +++ b/.env.template @@ -0,0 +1,15 @@ +POSTGRES_NAME=postgres +POSTGRES_USER=postgres +POSTGRES_USERNAME=postgres +POSTGRES_PASSWORD=postgres +POSTGRES_SERVICE_HOST=db +POSTGRES_SERVICE_PORT=5432 + +COMPANY_DOMAIN=example.com + +SUPERUSER_USERNAME=admin +SUPERUSER_PASSWORD=password + +SECRET_KEY=12345 + +ALLOWED_HOSTS='["127.0.0.1"]' \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3d2898d --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +*.pyc +__pycache__/ +/venv/ +/static/ +/media/ +/pg-data/ +.env +.env.local +db.sqlite3 +.DS_Store +.idea +.coverage +.vscode +node_modules/ +testy_static/dist/*.html +package-lock.json \ No newline at end of file diff --git a/LICENSE b/LICENSE index 0ad25db..6bb5339 100644 --- a/LICENSE +++ b/LICENSE @@ -1,35 +1,35 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 +GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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. +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 + Preamble - The GNU Affero General Public License is a free, copyleft license for +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. - The licenses for most software and other practical works are designed +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. - When we speak of free software, we are referring to freedom, not +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. - Developers that use our General Public Licenses protect your rights +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. - A secondary benefit of defending all users' freedom is that +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and @@ -39,7 +39,7 @@ The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. - The GNU Affero General Public License is designed specifically to +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the @@ -47,48 +47,48 @@ users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. - An older license, called the Affero General Public License and +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. - The precise terms and conditions for copying, distribution and +The precise terms and conditions for copying, distribution and modification follow. - TERMS AND CONDITIONS + TERMS AND CONDITIONS - 0. Definitions. +0. Definitions. - "This License" refers to version 3 of the GNU Affero General Public License. +"This License" refers to version 3 of the GNU Affero General Public License. - "Copyright" also means copyright-like laws that apply to other kinds of +"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 +"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 +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 +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 +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 +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" +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 @@ -97,18 +97,18 @@ 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. +1. Source Code. - The "source code" for a work means the preferred form of the work +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 +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 +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 @@ -119,7 +119,7 @@ implementation is available to the public in source code form. A (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 "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 @@ -132,16 +132,16 @@ 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 +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 +The Corresponding Source for a work in source code form is that same work. - 2. Basic Permissions. +2. Basic Permissions. - All rights granted under this License are granted for the term of +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 @@ -149,7 +149,7 @@ 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 +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 @@ -160,19 +160,19 @@ 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 +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. +3. Protecting Users' Legal Rights From Anti-Circumvention Law. - No covered work shall be deemed part of an effective technological +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 +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 @@ -180,9 +180,9 @@ 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. +4. Conveying Verbatim Copies. - You may convey verbatim copies of the Program's source code as you +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 @@ -190,37 +190,37 @@ 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, +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. +5. Conveying Modified Source Versions. - You may convey a work based on the Program, or the modifications to +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. +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". +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. +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. +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 +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 @@ -230,59 +230,59 @@ 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. +6. Conveying Non-Source Forms. - You may convey a covered work in object code form under the terms +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 +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 +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, @@ -295,7 +295,7 @@ 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, +"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 @@ -303,7 +303,7 @@ 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 +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 @@ -314,7 +314,7 @@ 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 +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 @@ -322,15 +322,15 @@ 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, +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. +7. Additional Terms. - "Additional permissions" are terms that supplement the terms of this +"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 @@ -339,41 +339,41 @@ 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 +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 +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 +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 +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 +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 +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 +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. +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 +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 @@ -383,46 +383,46 @@ 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 +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 +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. +8. Termination. - You may not propagate or modify a covered work except as expressly +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 +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 +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 +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. +9. Acceptance Not Required for Having Copies. - You are not required to accept this License in order to receive or +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, @@ -431,14 +431,14 @@ 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. +10. Automatic Licensing of Downstream Recipients. - Each time you convey a covered work, the recipient automatically +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 +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 @@ -448,7 +448,7 @@ 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 +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 @@ -456,13 +456,13 @@ rights granted under this License, and you may not initiate litigation any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. - 11. Patents. +11. Patents. - A "contributor" is a copyright holder who authorizes use under this +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 +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, @@ -472,19 +472,19 @@ 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 +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 +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, +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, @@ -498,7 +498,7 @@ 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 +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 @@ -506,7 +506,7 @@ 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 +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 @@ -521,13 +521,13 @@ 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 +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. +12. No Surrender of Others' Freedom. - If conditions are imposed on you (whether by court order, agreement or +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 @@ -537,9 +537,9 @@ 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. Remote Network Interaction; Use with the GNU General Public License. +13. Remote Network Interaction; Use with the GNU General Public License. - Notwithstanding any other provision of this License, if you modify the +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding @@ -550,7 +550,7 @@ shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. - Notwithstanding any other provision of this License, you have +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 General Public License into a single combined work, and to convey the resulting work. The terms of this @@ -558,14 +558,14 @@ License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. - 14. Revised Versions of this License. +14. Revised Versions of this License. - The Free Software Foundation may publish revised and/or new versions of +The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered @@ -574,19 +574,19 @@ Foundation. If the Program does not specify a version number of the GNU Affero 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 +If the Program specifies that a proxy can decide which future versions of the GNU Affero 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 +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. +15. Disclaimer of Warranty. - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +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, @@ -595,9 +595,9 @@ 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. +16. Limitation of Liability. - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +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 @@ -607,47 +607,47 @@ 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. +17. Interpretation of Sections 15 and 16. - If the disclaimer of warranty and limitation of liability provided +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 + END OF TERMS AND CONDITIONS - How to Apply These Terms to Your New Programs +How to Apply These Terms to Your New Programs - If you develop a new program, and you want it to be of the greatest +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 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) + +Copyright (C) - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero 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 free software: you can redistribute it and/or modify +it under the terms of the GNU Affero 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 Affero General Public License for more details. +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 Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. - If your software can interact with users remotely through a computer +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive @@ -655,7 +655,7 @@ of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. - You should also get your employer (if you work as a programmer) or school, +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 AGPL, see -. +. diff --git a/docker-compose-ci.yml b/docker-compose-ci.yml new file mode 100644 index 0000000..4023d48 --- /dev/null +++ b/docker-compose-ci.yml @@ -0,0 +1,6 @@ +version: '3.9' +services: + testy-ci: + build: + context: . + dockerfile: testy/scripts/ci/Dockerfile \ No newline at end of file diff --git a/docker-compose-dev.yml b/docker-compose-dev.yml new file mode 100644 index 0000000..5f13554 --- /dev/null +++ b/docker-compose-dev.yml @@ -0,0 +1,43 @@ +version: '3.9' +services: + testy: + build: + context: testy + dockerfile: scripts/dev/Dockerfile + volumes: + - './testy:/testy' + - './static:/testy/static' + ports: + - "8001:8000" + environment: + - DJANGO_SETTINGS_MODULE=testy.settings.development + - POSTGRES_NAME=${POSTGRES_NAME} + - POSTGRES_USER=${POSTGRES_USERNAME} + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} + - POSTGRES_SERVICE_HOST=${POSTGRES_SERVICE_HOST} + - POSTGRES_SERVICE_PORT=${POSTGRES_SERVICE_PORT} + - COMPANY_DOMAIN=${COMPANY_DOMAIN} + - SUPERUSER_USERNAME=${SUPERUSER_USERNAME} + - SUPERUSER_PASSWORD=${SUPERUSER_PASSWORD} + - ALLOWED_HOSTS=${ALLOWED_HOSTS} + - SECRET_KEY=${SECRET_KEY} + depends_on: + db: + condition: service_healthy + db: + image: postgres:14.5-alpine + volumes: + - ./pg-data:/var/lib/postgresql/data + ports: + - "5435:5432" + environment: + - POSTGRES_USER=${POSTGRES_USERNAME} + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} + - POSTGRES_DB=${POSTGRES_NAME} + healthcheck: + test: [ "CMD-SHELL", "pg_isready -U postgres" ] + interval: 5s + timeout: 5s + retries: 5 +volumes: + react_apps: \ No newline at end of file diff --git a/docker-compose-prod.yml b/docker-compose-prod.yml new file mode 100644 index 0000000..c59c7f5 --- /dev/null +++ b/docker-compose-prod.yml @@ -0,0 +1,43 @@ +version: '3.9' +services: + testy: + build: + context: testy + dockerfile: scripts/prod/Dockerfile + volumes: + - './testy:/testy' + - './static:/testy/static' + ports: + - "8001:8000" + environment: + - DJANGO_SETTINGS_MODULE=testy.settings.production + - POSTGRES_NAME=${POSTGRES_NAME} + - POSTGRES_USER=${POSTGRES_USERNAME} + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} + - POSTGRES_SERVICE_HOST=${POSTGRES_SERVICE_HOST} + - POSTGRES_SERVICE_PORT=${POSTGRES_SERVICE_PORT} + - COMPANY_DOMAIN=${COMPANY_DOMAIN} + - SUPERUSER_USERNAME=${SUPERUSER_USERNAME} + - SUPERUSER_PASSWORD=${SUPERUSER_PASSWORD} + - ALLOWED_HOSTS=${ALLOWED_HOSTS} + - SECRET_KEY=${SECRET_KEY} + depends_on: + db: + condition: service_healthy + db: + image: postgres:14.5-alpine + volumes: + - ./pg-data:/var/lib/postgresql/data + ports: + - "5435:5432" + environment: + - POSTGRES_USER=${POSTGRES_USERNAME} + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} + - POSTGRES_DB=${POSTGRES_NAME} + healthcheck: + test: [ "CMD-SHELL", "pg_isready -U postgres" ] + interval: 5s + timeout: 5s + retries: 5 +volumes: + react_apps: \ No newline at end of file diff --git a/linter-ci.sh b/linter-ci.sh new file mode 100644 index 0000000..f7fe969 --- /dev/null +++ b/linter-ci.sh @@ -0,0 +1,31 @@ +#!/bin/bash + + +fails="" + +inspect() { + # Usage: inspect $? lint + # * param1: job result code + # * param2: job name + if [ $1 -ne 0 ]; then + fails="${fails} $2" + fi +} + +lint() { + docker-compose -f docker-compose-ci.yml up -d --build + docker-compose -f docker-compose-ci.yml run --rm testy-ci flake8 . + inspect $? lint + docker-compose -f docker-compose-ci.yml down -v +} + +echo "Running linter!" +lint + +if [ -n "${fails}" ]; then + echo "Linter failed: ${fails}" + exit 1 +else + echo "Linter passed!" + exit 0 +fi \ No newline at end of file diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..303b4c5 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,60 @@ +[tool:pytest] +DJANGO_SETTINGS_MODULE = testy.settings.development +testpaths = tests +pythonpath = testy +filterwarnings = + ignore::DeprecationWarning + ignore::pytest.PytestCollectionWarning + +[flake8] +show-source = True +max-line-length = 120 +exclude = + .git + __pycache__ + venv + migrations + node_modules + +# settings for flake8_copyright_validator +lines-to-exclude = + '# Generated by Django' + '#!' + +copyright-text = + '# TestY TMS - Test Management System' + '# Copyright (C) 2022 KNS Group LLC (YADRO)' + '#' + '# This program is free software: you can redistribute it and/or modify' + '# it under the terms of the GNU Affero 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 Affero General Public License for more details.' + '#' + '# You should have received a copy of the GNU Affero General Public License' + '# along with this program. If not, see .' + '#' + '# Also add information on how to contact you by electronic and paper mail.' + '#' + '# If your software can interact with users remotely through a computer' + '# network, you should also make sure that it provides a way for users to' + '# get its source. For example, if your program is a web application, its' + '# interface could display a "Source" link that leads users to an archive' + '# of the code. There are many ways you could offer source, and different' + '# solutions will be better for different programs; see section 13 for the' + '# specific requirements.' + '#' + '# 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 AGPL, see' + '# .' + +[isort] +# https://github.com/timothycrosley/isort#multi-line-output-modes +multi_line_output = 3 +include_trailing_comma = true +line_length = 120 \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/tests/commons.py b/tests/commons.py new file mode 100644 index 0000000..9da93ba --- /dev/null +++ b/tests/commons.py @@ -0,0 +1,93 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from enum import Enum +from http import HTTPStatus +from typing import Any, Dict, List, Union + +from django.db.models import QuerySet +from django.forms import model_to_dict +from django.test.client import RequestFactory +from rest_framework.reverse import reverse +from rest_framework.test import APIClient + + +class RequestType(Enum): + POST = 'post' + GET = 'get' + PUT = 'put' + PATCH = 'patch' + DELETE = 'delete' + + +class RequestMock(RequestFactory): + GET = {} + + @staticmethod + def build_absolute_uri(url): + return f'http://testserver{url}' + + +class CustomAPIClient(APIClient): + def send_request( + self, + view_name: str, + data: Dict[str, Any] = None, + expected_status: HTTPStatus = HTTPStatus.OK, + request_type: RequestType = RequestType.GET, + reverse_kwargs: Dict[str, Any] = None, + format='json', + query_params: Dict[str, Any] = None + ): + url = reverse(view_name, kwargs=reverse_kwargs) + if query_params: + url = f'{url}?{"&".join([f"{field}={field_value}" for field, field_value in query_params.items()])}' + http_request = getattr(self, request_type.value, None) + if not http_request: + raise TypeError('Request type is not known') + response = http_request(url, data=data, format=format) + + assert response.status_code == expected_status, f'Expected response code "{expected_status}", ' \ + f'actual: "{response.status_code}"' \ + f'Response content: {response.content}' + return response + + +def model_with_base_to_dict(instance) -> Dict[str, Any]: + instance_dict = model_to_dict(instance) + instance_dict['created_at'] = instance.created_at.strftime("%Y-%m-%dT%H:%M:%S.%fZ") + instance_dict['updated_at'] = instance.updated_at.strftime("%Y-%m-%dT%H:%M:%S.%fZ") + return instance_dict + + +def model_to_dict_via_serializer(instances: Union[QuerySet, Any], serializer_class, many=False) -> List[dict]: + serializer = serializer_class(instances if many else instances[0], many=many, context={'request': RequestMock()}) + return [dict(elem) for elem in serializer.data] if many else dict(serializer.data) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..7cae654 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,119 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import json +from http import HTTPStatus + +import pytest +from pytest_factoryboy import register + +from tests import constants +from tests.commons import CustomAPIClient, RequestType +from tests.factories import ( + GroupFactory, + ParameterFactory, + ProjectFactory, + TestCaseFactory, + TestFactory, + TestPlanFactory, + TestResultFactory, + TestSuiteFactory, + UserFactory, +) + +register(ParameterFactory) +register(ProjectFactory) +register(TestCaseFactory) +register(TestFactory) +register(TestPlanFactory) +register(TestResultFactory) +register(TestSuiteFactory) +register(UserFactory) +register(GroupFactory) + + +@pytest.fixture +def api_client(): + return CustomAPIClient() + + +@pytest.fixture +def superuser(user_factory): + def make_user(**kwargs): + return user_factory(is_staff=True, is_superuser=True, **kwargs) + + return make_user + + +@pytest.fixture +def authorized_superuser(api_client, superuser): + user = superuser() + api_client.force_login(user) + return user + + +@pytest.fixture +def test_plan_from_api(api_client, authorized_superuser, test_plan): + response = api_client.send_request('api:v1:testplan-detail', reverse_kwargs={'pk': test_plan.id}) + return json.loads(response.content) + + +@pytest.fixture +def combined_parameters(number_of_param_groups, number_of_entities_in_group, parameter_factory): + parameters = [] + for _ in range(number_of_param_groups): + src_param = parameter_factory() + parameters.append(src_param.id) + for _ in range(number_of_entities_in_group - 1): + parameters.append(parameter_factory(group_name=src_param.group_name).id) + number_of_combinations = pow(number_of_entities_in_group, number_of_param_groups) + return parameters, number_of_combinations + + +@pytest.fixture +def several_test_plans_from_api(api_client, authorized_superuser, parameter_factory, project): + parameters = [] + for _ in range(3): + parameters.append(parameter_factory().id) + + test_plans = [] + for idx in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + testplan_dict = { + 'name': f'Test plan {idx}', + 'due_date': constants.DATE, + 'started_at': constants.DATE, + 'parameters': parameters, + 'project': project.id + } + response = api_client.send_request('api:v1:testplan-list', testplan_dict, HTTPStatus.CREATED, RequestType.POST) + test_plans.append(json.loads(response.content)[0]) + + return test_plans diff --git a/tests/constants.py b/tests/constants.py new file mode 100644 index 0000000..bc8856d --- /dev/null +++ b/tests/constants.py @@ -0,0 +1,61 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.utils import timezone + +USERNAME = 'test_user' +PASSWORD = '123qweasd123' +NEW_PASSWORD = 'qweasd123qwe' +INVALID_PASSWORD = 'qwerty' +USER_EMAIL = 'user@example.com' +INVALID_EMAIL = 'user@example' +FIRST_NAME = 'TestFirstName' +LAST_NAME = 'TestLastName' +TEST_SUITE_NAME = 'TestSuiteName' +TEST_CASE_NAME = 'TestCaseName' +PROJECT_NAME = 'TestProjectName' +DESCRIPTION = 'TestDescription' +SETUP = '1.Setup\n2.Setup' +SCENARIO = '1.break\n2.break\n3.break' +TEARDOWN = '1.Teardown\n2.Teardown' +ESTIMATE = 12345 +EXECUTION_TIME = 1000000 +DATE = timezone.now() +STATUS_NAME = 'PASSED' +STATUS_CODE = 1 +TEST_COMMENT = 'TestComment' +GROUP_NAME = 'TestGroup' +PARAMETER_GROUP_NAME = 'OS' +PARAMETER_DATA = 'LINUX' +TEST_PLAN_NAME = 'TestPlan' +EXCEEDING_CHAR_FIELD = 't' * 256 + +NUMBER_OF_OBJECTS_TO_CREATE = 10 diff --git a/tests/error_messages.py b/tests/error_messages.py new file mode 100644 index 0000000..df94d04 --- /dev/null +++ b/tests/error_messages.py @@ -0,0 +1,42 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +NOT_NULL_ERR_MSG = 'null value in column "{column}" of relation "{relation}" violates not-null constraint' +CHAR_LENGTH_ERR_MSG = 'value too long for type character varying(255)\n' +ALREADY_EXISTS_ERR_MSG = 'Key ({column_name})=({column_value}) already exists.' +INVALID_EMAIL_MSG = 'Enter a valid email address.' +UNAUTHORIZED_MSG = 'Authentication credentials were not provided.' +REQUIRED_FIELD_MSG = 'This field is required.' +BOOL_VALUE_ERR_MSG = '“{value}” value must be either True or False.' +MODEL_VALUE_ERR_MSG = 'Cannot assign "\'{value}\'": "{model_name}.{column_name}" must be a "{column_model}" instance.' +INT_VALUE_ERR_MSG = "Field '{column}' expected a number but got '{value}'." +ARRAY_VALUE_ERR_MSG = 'Array value must start with "{" or dimension information.' +TYPE_ERR_MSG = 'expected string or bytes-like object' diff --git a/tests/factories.py b/tests/factories.py new file mode 100644 index 0000000..5e04a64 --- /dev/null +++ b/tests/factories.py @@ -0,0 +1,141 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from core.models import Project +from django.contrib.auth import get_user_model +from django.contrib.auth.hashers import make_password +from factory import Sequence, SubFactory +from factory.django import DjangoModelFactory +from tests_description.models import TestCase, TestSuite +from tests_representation.choices import TestStatuses +from tests_representation.models import Parameter, Test, TestPlan, TestResult +from users.models import Group + +import tests.constants as constants + +UserModel = get_user_model() + + +class ProjectFactory(DjangoModelFactory): + class Meta: + model = Project + + name = Sequence(lambda n: f'{constants.PROJECT_NAME}{n}') + description = constants.DESCRIPTION + + +class ParameterFactory(DjangoModelFactory): + class Meta: + model = Parameter + + project = SubFactory(ProjectFactory) + data = Sequence(lambda n: f'{constants.PARAMETER_DATA}{n}') + group_name = Sequence(lambda n: f'{constants.PARAMETER_GROUP_NAME}{n}') + + +class UserFactory(DjangoModelFactory): + class Meta: + model = UserModel + + username = Sequence(lambda n: f'{constants.USERNAME}{n}@yadro.com') + first_name = constants.FIRST_NAME + last_name = constants.LAST_NAME + password = make_password(constants.PASSWORD) + email = username + is_active = True + is_staff = False + + +class GroupFactory(DjangoModelFactory): + class Meta: + model = Group + + name = Sequence(lambda n: f'{constants.GROUP_NAME}{n}') + + +class TestPlanFactory(DjangoModelFactory): + class Meta: + model = TestPlan + + name = Sequence(lambda n: f'{constants.TEST_PLAN_NAME}{n}') + started_at = constants.DATE + due_date = constants.DATE + finished_at = constants.DATE + project = SubFactory(ProjectFactory) + is_archive = False + + +class TestResultsFactory(DjangoModelFactory): + class Meta: + model = TestResult + + +class TestSuiteFactory(DjangoModelFactory): + class Meta: + model = TestSuite + + name = Sequence(lambda n: f'{constants.TEST_SUITE_NAME}{n}') + project = SubFactory(ProjectFactory) + + +class TestCaseFactory(DjangoModelFactory): + class Meta: + model = TestCase + + name = Sequence(lambda n: f'{constants.TEST_CASE_NAME}{n}') + project = SubFactory(ProjectFactory) + suite = SubFactory(TestSuiteFactory) + setup = constants.SETUP + scenario = constants.SCENARIO + teardown = constants.TEARDOWN + estimate = constants.ESTIMATE + + +class TestFactory(DjangoModelFactory): + class Meta: + model = Test + + case = SubFactory(TestCaseFactory) + plan = SubFactory(TestPlanFactory) + user = SubFactory(UserFactory) + project = SubFactory(ProjectFactory) + is_archive = False + + +class TestResultFactory(DjangoModelFactory): + class Meta: + model = TestResult + + test = SubFactory(TestFactory) + status = TestStatuses.UNTESTED + comment = constants.TEST_COMMENT + project = SubFactory(ProjectFactory) + execution_time = constants.EXECUTION_TIME diff --git a/tests/test_api/v1/test_group_endpoints.py b/tests/test_api/v1/test_group_endpoints.py new file mode 100644 index 0000000..ba6e8be --- /dev/null +++ b/tests/test_api/v1/test_group_endpoints.py @@ -0,0 +1,123 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import json +from http import HTTPStatus + +import pytest +from django.forms import model_to_dict +from tests_representation.models import Parameter +from users.models import Group + +from tests import constants +from tests.commons import RequestType +from tests.error_messages import REQUIRED_FIELD_MSG + + +@pytest.mark.django_db +class TestGroupEndpoints: + view_name_list = 'api:v1:group-list' + view_name_detail = 'api:v1:group-detail' + + def test_list(self, api_client, authorized_superuser, group_factory): + expected_instances = [] + for _ in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + expected_instances.append(model_to_dict(group_factory())) + + response = api_client.send_request(self.view_name_list) + for instance in json.loads(response.content): + instance.pop('url') + assert instance in expected_instances + + def test_retrieve(self, api_client, authorized_superuser, group): + expected_dict = model_to_dict(group) + response = api_client.send_request(self.view_name_detail, reverse_kwargs={'pk': group.pk}) + actual_dict = json.loads(response.content) + actual_dict.pop('url') + assert actual_dict == expected_dict + + def test_creation(self, api_client, authorized_superuser): + expected_number_of_parameters = 1 + group_dict = { + 'name': constants.PARAMETER_GROUP_NAME, + 'permissions': [] + } + api_client.send_request(self.view_name_list, group_dict, HTTPStatus.CREATED, RequestType.POST) + assert Group.objects.count() == expected_number_of_parameters, f'Expected number of groups is ' \ + f'"{expected_number_of_parameters}"' \ + f'actual: "{Parameter.objects.count()}"' + + def test_partial_update(self, api_client, authorized_superuser, group): + new_name = 'new_name' + group_dict = { + 'id': group.id, + 'name': new_name, + } + api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': group.pk}, + request_type=RequestType.PATCH, + data=group_dict + ) + actual_name = Group.objects.get(pk=group.id).name + assert actual_name == new_name, f'New name does not match. Expected data "{new_name}", actual: "{actual_name}"' + + @pytest.mark.parametrize('expected_status', [HTTPStatus.OK, HTTPStatus.BAD_REQUEST]) + def test_update(self, api_client, authorized_superuser, group, expected_status): + new_name = 'new_name' + group_dict = { + 'id': group.id, + } + if expected_status == HTTPStatus.OK: + group_dict['name'] = new_name + response = api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': group.pk}, + request_type=RequestType.PUT, + expected_status=expected_status, + data=group_dict + ) + if expected_status == HTTPStatus.OK: + actual_name = Group.objects.get(pk=group.id).name + assert actual_name == new_name, f'Group names do not match. Expected name "{actual_name}", ' \ + f'actual: "{new_name}"' + else: + assert json.loads(response.content)['name'][0] == REQUIRED_FIELD_MSG + + def test_delete(self, api_client, authorized_superuser, group): + assert Group.objects.count() == 1, 'Group was not created' + api_client.send_request( + self.view_name_detail, + expected_status=HTTPStatus.NO_CONTENT, + request_type=RequestType.DELETE, + reverse_kwargs={'pk': group.pk} + ) + assert not Group.objects.count(), f'Group with id "{group.id}" was not deleted.' diff --git a/tests/test_api/v1/test_parameter_endpoints.py b/tests/test_api/v1/test_parameter_endpoints.py new file mode 100644 index 0000000..bf1c1cf --- /dev/null +++ b/tests/test_api/v1/test_parameter_endpoints.py @@ -0,0 +1,127 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import json +from http import HTTPStatus + +import pytest +from django.forms import model_to_dict +from tests_representation.models import Parameter + +from tests import constants +from tests.commons import RequestType +from tests.error_messages import REQUIRED_FIELD_MSG + + +@pytest.mark.django_db +class TestParameterEndpoints: + view_name_list = 'api:v1:parameter-list' + view_name_detail = 'api:v1:parameter-detail' + + def test_list(self, api_client, authorized_superuser, parameter_factory): + expected_instances = [] + for _ in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + expected_instances.append(model_to_dict(parameter_factory())) + + response = api_client.send_request(self.view_name_list) + + for instance in json.loads(response.content): + instance.pop('url') + assert instance in expected_instances + + def test_retrieve(self, api_client, authorized_superuser, parameter): + expected_parameter_dict = model_to_dict(parameter) + response = api_client.send_request(self.view_name_detail, reverse_kwargs={'pk': parameter.pk}) + actual_model_dict = json.loads(response.content) + actual_model_dict.pop('url') + assert actual_model_dict == expected_parameter_dict, 'Actual model dict is different from expected' + + def test_creation(self, api_client, authorized_superuser, project): + expected_number_of_parameters = 1 + parameter_dict = { + 'group_name': constants.PARAMETER_GROUP_NAME, + 'project': project.id, + 'data': constants.PARAMETER_DATA + } + api_client.send_request(self.view_name_list, parameter_dict, HTTPStatus.CREATED, RequestType.POST) + assert Parameter.objects.count() == expected_number_of_parameters, f'Expected number of parameters is ' \ + f'"{expected_number_of_parameters}"' \ + f'actual: "{Parameter.objects.count()}"' + + def test_partial_update(self, api_client, authorized_superuser, parameter): + new_data = 'new_data' + parameter_dict = { + 'id': parameter.id, + 'data': new_data + } + api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': parameter.pk}, + request_type=RequestType.PATCH, + data=parameter_dict + ) + actual_data = Parameter.objects.get(pk=parameter.id).data + assert actual_data == new_data, f'New data does not match. Expected data "{new_data}", actual: "{actual_data}"' + + @pytest.mark.parametrize('expected_status', [HTTPStatus.OK, HTTPStatus.BAD_REQUEST]) + def test_update(self, api_client, authorized_superuser, parameter, expected_status, project): + new_data = 'new_data' + parameter_dict = { + 'id': parameter.id, + 'data': new_data + } + if expected_status == HTTPStatus.OK: + parameter_dict['project'] = project.id + parameter_dict['group_name'] = parameter.group_name + response = api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': parameter.pk}, + request_type=RequestType.PUT, + expected_status=expected_status, + data=parameter_dict + ) + if expected_status == HTTPStatus.OK: + actual_data = Parameter.objects.get(pk=parameter.id).data + assert actual_data == new_data, f'Parameter data do not match. Expected name "{actual_data}", ' \ + f'actual: "{new_data}"' + else: + assert json.loads(response.content)['group_name'][0] == REQUIRED_FIELD_MSG + assert json.loads(response.content)['project'][0] == REQUIRED_FIELD_MSG + + def test_delete(self, api_client, authorized_superuser, parameter): + assert Parameter.objects.count() == 1, 'Parameter was not created' + api_client.send_request( + self.view_name_detail, + expected_status=HTTPStatus.NO_CONTENT, + request_type=RequestType.DELETE, + reverse_kwargs={'pk': parameter.pk} + ) + assert not Parameter.objects.count(), f'Parameter with id "{parameter.id}" was not deleted.' diff --git a/tests/test_api/v1/test_project_endpoints.py b/tests/test_api/v1/test_project_endpoints.py new file mode 100644 index 0000000..b12770c --- /dev/null +++ b/tests/test_api/v1/test_project_endpoints.py @@ -0,0 +1,151 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import json +from http import HTTPStatus + +import pytest +from core.models import Project +from django.forms import model_to_dict +from tests_description.models import TestCase +from tests_representation.choices import TestStatuses +from tests_representation.models import Parameter, TestResult + +from tests import constants +from tests.commons import RequestType +from tests.error_messages import REQUIRED_FIELD_MSG + + +@pytest.mark.django_db +class TestProjectEndpoints: + view_name_list = 'api:v1:project-list' + view_name_detail = 'api:v1:project-detail' + + def test_list(self, api_client, authorized_superuser, project_factory): + expected_instances = [] + for _ in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + expected_instances.append(model_to_dict(project_factory())) + + response = api_client.send_request(self.view_name_list) + for instance in json.loads(response.content): + instance.pop('url') + assert instance in expected_instances + + def test_retrieve(self, api_client, authorized_superuser, project): + expected_dict = model_to_dict(project) + response = api_client.send_request(self.view_name_detail, reverse_kwargs={'pk': project.pk}) + actual_dict = json.loads(response.content) + actual_dict.pop('url') + assert actual_dict == expected_dict + + def test_creation(self, api_client, authorized_superuser): + expected_number_of_parameters = 1 + project_dict = { + 'name': constants.PROJECT_NAME, + 'description': constants.DESCRIPTION + } + api_client.send_request(self.view_name_list, project_dict, HTTPStatus.CREATED, RequestType.POST) + assert Project.objects.count() == expected_number_of_parameters, f'Expected number of projects is ' \ + f'"{expected_number_of_parameters}"' \ + f'actual: "{Parameter.objects.count()}"' + + def test_partial_update(self, api_client, authorized_superuser, project): + new_name = 'new_name' + project_dict = { + 'id': project.id, + 'name': new_name, + } + api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': project.pk}, + request_type=RequestType.PATCH, + data=project_dict + ) + actual_name = Project.objects.get(pk=project.id).name + assert actual_name == new_name, f'New name does not match. Expected name "{new_name}", actual: "{actual_name}"' + + @pytest.mark.parametrize('expected_status', [HTTPStatus.OK, HTTPStatus.BAD_REQUEST]) + def test_update(self, api_client, authorized_superuser, project, expected_status): + new_name = 'new_name' + project_dict = { + 'id': project.id, + } + if expected_status == HTTPStatus.OK: + project_dict['name'] = new_name + response = api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': project.pk}, + request_type=RequestType.PUT, + expected_status=expected_status, + data=project_dict + ) + if expected_status == HTTPStatus.OK: + actual_name = Project.objects.get(pk=project.id).name + assert actual_name == new_name, f'Project name do not match. Expected name "{actual_name}", ' \ + f'actual: "{new_name}"' + else: + assert json.loads(response.content)['name'][0] == REQUIRED_FIELD_MSG + + def test_delete(self, api_client, authorized_superuser, project): + assert Project.objects.count() == 1, 'Project was not created' + api_client.send_request( + self.view_name_detail, + expected_status=HTTPStatus.NO_CONTENT, + request_type=RequestType.DELETE, + reverse_kwargs={'pk': project.pk} + ) + assert not Project.objects.count(), f'Project with id "{project.id}" was not deleted.' + + def test_valid_project_assignation(self, api_client, authorized_superuser, user, test): + result_dict = { + 'status': TestStatuses.UNTESTED, + 'test': test.id, + 'user': user.id, + 'comment': constants.TEST_COMMENT, + } + api_client.send_request( + 'api:v1:results-by-test', + result_dict, + HTTPStatus.CREATED, + RequestType.POST, + reverse_kwargs={'pk': test.id} + ) + + expected_project = TestCase.objects.all()[0].project + + result_project = TestResult.objects.all()[0].project + + assert test.project == expected_project, f'Test was not created with correct project, ' \ + f'expected project: {expected_project}' \ + f'actual project: {test.project}' + assert result_project == expected_project, f'Test result was not created with correct project, ' \ + f'expected project: {expected_project}' \ + f'actual project: {result_project}' diff --git a/tests/test_api/v1/test_test_endpoints.py b/tests/test_api/v1/test_test_endpoints.py new file mode 100644 index 0000000..e86e62f --- /dev/null +++ b/tests/test_api/v1/test_test_endpoints.py @@ -0,0 +1,113 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import json +from http import HTTPStatus + +import pytest +from tests_representation.models import Test + +from tests import constants +from tests.commons import RequestType, model_with_base_to_dict +from tests.error_messages import REQUIRED_FIELD_MSG + + +@pytest.mark.django_db +class TestTestEndpoints: + view_name_list = 'api:v1:test-list' + view_name_detail = 'api:v1:test-detail' + + def test_list(self, api_client, authorized_superuser, test_factory): + expected_instances = [] + for _ in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + expected_instances.append(model_with_base_to_dict(test_factory())) + + response = api_client.send_request(self.view_name_list) + for instance_dict in json.loads(response.content): + instance_dict.pop('url') + assert instance_dict in expected_instances, f'{instance_dict} was not found in expected instances.' + + def test_retrieve(self, api_client, authorized_superuser, test): + expected_dict = model_with_base_to_dict(test) + response = api_client.send_request(self.view_name_detail, reverse_kwargs={'pk': test.pk}) + actual_dict = json.loads(response.content) + actual_dict.pop('url') + assert actual_dict == expected_dict, 'Actual model dict is different from expected' + + def test_partial_update(self, api_client, authorized_superuser, test, user): + result_dict = { + 'id': test.id, + 'user': user.id + } + api_client.send_request( + self.view_name_detail, + result_dict, + request_type=RequestType.PATCH, + reverse_kwargs={'pk': test.pk} + ) + result_user = Test.objects.get(pk=test.id).user + assert result_user == user, f'Test user does not match. Expected user "{user}", ' \ + f'actual: "{result_user}"' + + @pytest.mark.parametrize('expected_status', [HTTPStatus.OK, HTTPStatus.BAD_REQUEST]) + def test_update(self, api_client, authorized_superuser, expected_status, test, user, test_case, test_plan): + result_dict = { + 'id': test.id, + 'user': user.id + } + if expected_status == HTTPStatus.OK: + result_dict['case'] = test_case.id + result_dict['plan'] = test_plan.id + + response = api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': test.pk}, + request_type=RequestType.PUT, + expected_status=expected_status, + data=result_dict + ) + if expected_status == HTTPStatus.OK: + result_user = Test.objects.get(pk=test.id).user + assert result_user == user, f'Test user does not match. Expected user "{user}", ' \ + f'actual: "{result_user}"' + else: + assert json.loads(response.content)['case'][0] == REQUIRED_FIELD_MSG + assert json.loads(response.content)['plan'][0] == REQUIRED_FIELD_MSG + + def test_test_cannot_be_deleted(self, api_client, authorized_superuser, test): + assert Test.objects.count() == 1, 'Test was not created' + api_client.send_request( + self.view_name_detail, + expected_status=HTTPStatus.METHOD_NOT_ALLOWED, + request_type=RequestType.DELETE, + reverse_kwargs={'pk': test.pk} + ) + assert Test.objects.count(), f'Test with id "{test.id}" was not deleted.' diff --git a/tests/test_api/v1/test_testcase_endpoints.py b/tests/test_api/v1/test_testcase_endpoints.py new file mode 100644 index 0000000..333cd72 --- /dev/null +++ b/tests/test_api/v1/test_testcase_endpoints.py @@ -0,0 +1,166 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import json +from http import HTTPStatus + +import pytest +from django.forms import model_to_dict +from tests_description.api.v1.serializers import TestCaseSerializer +from tests_description.models import TestCase + +from tests import constants +from tests.commons import RequestType, model_to_dict_via_serializer +from tests.error_messages import REQUIRED_FIELD_MSG +from tests.factories import ProjectFactory, TestSuiteFactory + + +@pytest.mark.django_db +class TestCaseEndpoints: + view_name_detail = 'api:v1:testcase-detail' + view_name_list = 'api:v1:testcase-list' + + def test_list(self, api_client, authorized_superuser, test_case_factory): + expected_instances = [] + for _ in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + expected_instances.append(model_to_dict(test_case_factory())) + + response = api_client.send_request(self.view_name_list) + + for instance_dict in json.loads(response.content): + instance_dict.pop('url') + assert instance_dict in expected_instances, f'{instance_dict} was not found in expected instances.' + + def test_retrieve(self, api_client, authorized_superuser, test_case): + expected_dict = model_to_dict(test_case) + response = api_client.send_request(self.view_name_detail, reverse_kwargs={'pk': test_case.pk}) + actual_dict = json.loads(response.content) + actual_dict.pop('url') + assert actual_dict == expected_dict, 'Actual model dict is different from expected' + + def test_creation(self, api_client, authorized_superuser, project, test_suite): + expected_number_of_cases = 1 + case_dict = { + 'name': constants.TEST_CASE_NAME, + 'project': project.id, + 'suite': test_suite.id, + 'setup': constants.SETUP, + 'scenario': constants.SCENARIO, + 'teardown': constants.TEARDOWN, + 'estimate': constants.ESTIMATE + } + api_client.send_request(self.view_name_list, case_dict, HTTPStatus.CREATED, RequestType.POST) + assert TestCase.objects.count() == expected_number_of_cases, f'Expected number of users ' \ + f'"{expected_number_of_cases}"' \ + f'actual: "{TestCase.objects.count()}"' + + def test_partial_update(self, api_client, authorized_superuser, test_case): + new_name = 'new_expected_test_case_name' + case_dict = { + 'id': test_case.id, + 'name': new_name + } + api_client.send_request( + self.view_name_detail, + case_dict, + request_type=RequestType.PATCH, + reverse_kwargs={'pk': test_case.pk} + ) + actual_name = TestCase.objects.get(pk=test_case.id).name + assert actual_name == new_name, f'Names do not match. Expected name "{actual_name}", actual: "{new_name}"' + + @pytest.mark.parametrize('expected_status', [HTTPStatus.OK, HTTPStatus.BAD_REQUEST]) + def test_update(self, api_client, authorized_superuser, expected_status, test_case, project, test_suite): + new_name = 'new_expected_test_case_name' + case_dict = { + 'id': test_case.id, + 'name': new_name + } + if expected_status == HTTPStatus.OK: + case_dict['project'] = project.id + case_dict['suite'] = test_suite.id + case_dict['scenario'] = constants.SCENARIO + response = api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': test_case.pk}, + request_type=RequestType.PUT, + expected_status=expected_status, + data=case_dict + ) + if expected_status == HTTPStatus.OK: + actual_name = TestCase.objects.get(pk=test_case.id).name + assert actual_name == new_name, f'Username does not match. Expected name "{actual_name}", ' \ + f'actual: "{new_name}"' + else: + assert json.loads(response.content)['project'][0] == REQUIRED_FIELD_MSG + assert json.loads(response.content)['suite'][0] == REQUIRED_FIELD_MSG + assert json.loads(response.content)['scenario'][0] == REQUIRED_FIELD_MSG + + def test_delete(self, api_client, authorized_superuser, test_case): + assert TestCase.objects.count() == 1, 'Test case was not created' + api_client.send_request( + self.view_name_detail, + expected_status=HTTPStatus.NO_CONTENT, + request_type=RequestType.DELETE, + reverse_kwargs={'pk': test_case.pk} + ) + assert not TestCase.objects.count(), f'TestCase with id "{test_case.id}" was not deleted.' + + +@pytest.mark.django_db +class TestCaseEndpointsQueryParams: + view_name_list = 'api:v1:testcase-list' + + @pytest.mark.parametrize( + 'field_name, factory', + [('project', ProjectFactory), ('suite', TestSuiteFactory)], + ids=['TestCase filter by project query param', 'TestCase filter by suite query param'] + ) + def test_case_filter(self, api_client, authorized_superuser, test_case_factory, field_name, factory): + instances = [factory() for _ in range(3)] + for _ in range(2): + for instance in instances: + test_case_factory(**{field_name: instance}) + for instance in instances: + filtered_instances = TestCase.objects.filter(**{field_name: instance.id}) + expected_dict = model_to_dict_via_serializer( + filtered_instances, + serializer_class=TestCaseSerializer, + many=True + ) + response = api_client.send_request( + self.view_name_list, + expected_status=HTTPStatus.OK, + request_type=RequestType.GET, + query_params={field_name: instance.id} + ) + actual_dict = json.loads(response.content) + assert actual_dict == expected_dict, 'Actual and expected dict are different.' diff --git a/tests/test_api/v1/test_testplan_endpoints.py b/tests/test_api/v1/test_testplan_endpoints.py new file mode 100644 index 0000000..d64593e --- /dev/null +++ b/tests/test_api/v1/test_testplan_endpoints.py @@ -0,0 +1,194 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . +import copy +import json +from http import HTTPStatus + +import pytest +from tests_description.models import TestCase +from tests_representation.models import Test, TestPlan, TestResult + +from tests import constants +from tests.commons import RequestType + + +@pytest.mark.django_db +class TestPlanEndpoints: + view_name_detail = 'api:v1:testplan-detail' + view_name_list = 'api:v1:testplan-list' + + def test_list(self, api_client, authorized_superuser, several_test_plans_from_api): + expected_instances = several_test_plans_from_api + response = api_client.send_request(self.view_name_list) + + for instance_dict in json.loads(response.content): + assert instance_dict in expected_instances, f'{instance_dict} was not found in expected instances.' + + def test_retrieve(self, api_client, authorized_superuser, test_plan_from_api): + response = api_client.send_request(self.view_name_detail, reverse_kwargs={'pk': test_plan_from_api.get('id')}) + actual_dict = json.loads(response.content) + assert actual_dict == test_plan_from_api, 'Actual model dict is different from expected' + + @pytest.mark.parametrize('number_of_param_groups, number_of_entities_in_group', [(1, 3), (2, 2), (3, 4)]) + def test_creation(self, api_client, authorized_superuser, combined_parameters, project): + parameters, expected_number_of_plans = combined_parameters + testplan_dict = { + 'name': 'Test plan', + 'due_date': constants.DATE, + 'started_at': constants.DATE, + 'parameters': parameters, + 'project': project.id + } + response = api_client.send_request(self.view_name_list, testplan_dict, HTTPStatus.CREATED, RequestType.POST) + endpoint_plans = json.loads(response.content) + actual_parameters_combinations = [] + for plan in endpoint_plans: + params_from_plan = plan.get('parameters').sort + assert params_from_plan not in actual_parameters_combinations, 'Found duplicate params in TestPlans' + actual_parameters_combinations.append(plan.get('parameters')) + assert TestPlan.objects.count() == expected_number_of_plans, f'Expected number of test plans ' \ + f'"{expected_number_of_plans}"' \ + f'actual: "{TestPlan.objects.count()}"' + assert len(endpoint_plans) == expected_number_of_plans, f'Expected number of test plans from endpoint ' \ + f'"{expected_number_of_plans}"' \ + f'actual: "{len(endpoint_plans)}"' + + @pytest.mark.parametrize('number_of_param_groups, number_of_entities_in_group', [(1, 3), (2, 2), (3, 4)]) + def test_tests_generated_on_create(self, api_client, authorized_superuser, combined_parameters, test_case_factory, + project): + number_of_cases = 5 + case_ids = [test_case_factory().id for _ in range(number_of_cases)] + parameters, expected_number_of_plans = combined_parameters + number_of_tests = number_of_cases * expected_number_of_plans + testplan_dict = { + 'name': 'Test plan', + 'due_date': constants.DATE, + 'started_at': constants.DATE, + 'parameters': parameters, + 'test_cases': case_ids, + 'project': project.id + } + response = api_client.send_request(self.view_name_list, testplan_dict, HTTPStatus.CREATED, RequestType.POST) + test_plans = json.loads(response.content) + pk = test_plans[0].get('id') + assert Test.objects.count() == number_of_tests + assert TestCase.objects.count() == number_of_cases + update_dict = { + 'test_cases': case_ids[:-1], + } + api_client.send_request( + self.view_name_detail, + update_dict, + HTTPStatus.OK, + RequestType.PATCH, + reverse_kwargs={'pk': pk} + ) + assert Test.objects.count() == number_of_tests - 1, 'More then one test was deleted by updating' + test_ids = [] + for plan in test_plans: + test_ids.extend(test.get('id')for test in plan.get('tests')) + assert len(set(test_ids)) == len(test_ids), 'Test ids from testplans were not unique.' + + @pytest.mark.parametrize( + 'slice_num, expected_number, err_msg', + [ + (None, 5, 'Number of cases should not change'), + (1, 1, 'Number of cases was not decreased'), + (0, 0, 'Cases were found after updating with empty list') + ], + ids=['Update with same cases', 'Update to one case', 'Update to 0 cases'] + ) + def test_tests_generated_deleted_on_partial_update(self, api_client, authorized_superuser, test_plan_from_api, + test_case_factory, slice_num, expected_number, err_msg): + number_of_cases = 5 + case_ids = [test_case_factory().id for _ in range(number_of_cases)] + assert not Test.objects.count() + assert TestCase.objects.count() == number_of_cases + api_client.send_request( + self.view_name_detail, + data={'test_cases': case_ids}, + expected_status=HTTPStatus.OK, + request_type=RequestType.PATCH, + reverse_kwargs={'pk': test_plan_from_api.get('id')} + ) + api_client.send_request( + self.view_name_detail, + data={'test_cases': case_ids[:slice_num]}, + expected_status=HTTPStatus.OK, + request_type=RequestType.PATCH, + reverse_kwargs={'pk': test_plan_from_api.get('id')} + ) + assert Test.objects.count() == expected_number, err_msg + + def test_plan_behaviour_on_update(self, api_client, authorized_superuser, test_case_factory, parameter_factory, + test_result_factory, project): + number_of_cases = 5 + case_ids = [test_case_factory().id for _ in range(number_of_cases)] + parameters = [parameter_factory(group_name='os').id for _ in range(3)] + testplan_dict = { + 'name': 'Test plan', + 'due_date': constants.DATE, + 'started_at': constants.DATE, + 'parameters': parameters, + 'test_cases': case_ids, + 'project': project.id + } + response = api_client.send_request(self.view_name_list, testplan_dict, HTTPStatus.CREATED, RequestType.POST) + test_plans = json.loads(response.content) + test_ids = copy.deepcopy(test_plans[0].get('tests')) + result_ids = [test_result_factory(test_id=test_ids[0]['id']).id for _ in range(3)] + expected_number_of_tests = Test.objects.count() + update_dict = { + 'test_cases': case_ids + } + response = api_client.send_request( + self.view_name_detail, + update_dict, + HTTPStatus.OK, + RequestType.PATCH, + reverse_kwargs={'pk': test_plans[0].get('id')} + ) + plan = json.loads(response.content) + actual_results = [] + for res in TestResult.objects.filter(test=plan.get('tests')[0]['id']): + actual_results.append(res.id) + assert actual_results == result_ids, f'Results changed for test with id: {plan.get("tests")[0]["id"]}' + assert Test.objects.count() == expected_number_of_tests, 'After update number of tests should not change' + + def test_delete(self, api_client, authorized_superuser, test_plan): + assert TestPlan.objects.count() == 1, 'Test case was not created' + api_client.send_request( + self.view_name_detail, + expected_status=HTTPStatus.NO_CONTENT, + request_type=RequestType.DELETE, + reverse_kwargs={'pk': test_plan.pk} + ) + assert not TestPlan.objects.count(), f'Test plan with id "{test_plan.id}" was not deleted.' diff --git a/tests/test_api/v1/test_testresult_endpoints.py b/tests/test_api/v1/test_testresult_endpoints.py new file mode 100644 index 0000000..ccddb71 --- /dev/null +++ b/tests/test_api/v1/test_testresult_endpoints.py @@ -0,0 +1,144 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import json +from http import HTTPStatus + +import pytest +from tests_representation.choices import TestStatuses +from tests_representation.models import TestResult + +from tests import constants +from tests.commons import RequestType, model_with_base_to_dict + + +@pytest.mark.django_db(reset_sequences=True) +class TestResultEndpoints: + view_name_list = 'api:v1:testresult-list' + view_name_detail = 'api:v1:testresult-detail' + + def test_list(self, api_client, authorized_superuser, test_result_factory): + expected_instances = [] + for _ in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + model_dict = model_with_base_to_dict(test_result_factory()) + model_dict['status'] = model_dict['status'].value + expected_instances.append(model_dict) + + response = api_client.send_request(self.view_name_list) + + for instance_dict in json.loads(response.content): + instance_dict.pop('url') + assert instance_dict in expected_instances, f'{instance_dict} was not found in expected instances.' + + def test_retrieve(self, api_client, authorized_superuser, test_result): + expected_dict = model_with_base_to_dict(test_result) + expected_dict['status'] = expected_dict['status'].value + response = api_client.send_request(self.view_name_detail, reverse_kwargs={'pk': test_result.pk}) + actual_dict = json.loads(response.content) + actual_dict.pop('url') + assert actual_dict == expected_dict, 'Actual model dict is different from expected' + + def test_partial_update(self, api_client, authorized_superuser, test_result, user): + result_dict = { + 'id': test_result.id, + 'user': user.id + } + api_client.send_request( + self.view_name_detail, + result_dict, + request_type=RequestType.PATCH, + reverse_kwargs={'pk': test_result.pk} + ) + result_user = TestResult.objects.get(pk=test_result.id).user + assert result_user == user, f'Result users do not match. Expected user "{user}", ' \ + f'actual: "{result_user}"' + + def test_update(self, api_client, authorized_superuser, test_result, user): + result_dict = { + 'id': test_result.id, + 'user': user.id + } + api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': test_result.pk}, + request_type=RequestType.PUT, + expected_status=HTTPStatus.OK, + data=result_dict + ) + result_user = TestResult.objects.get(pk=test_result.id).user + assert result_user == user, f'Result users do not match. Expected user "{user}", actual: "{result_user}"' + + def test_add_results_to_test(self, api_client, authorized_superuser, user, test_factory): + tests = [test_factory(), test_factory()] + for test in tests: + result_dict = { + 'status': TestStatuses.UNTESTED, + 'user': user.id, + 'comment': constants.TEST_COMMENT, + } + api_client.send_request( + 'api:v1:results-by-test', + expected_status=HTTPStatus.CREATED, + request_type=RequestType.POST, + data=result_dict, + reverse_kwargs={'pk': test.id} + ) + assert TestResult.objects.count() == 2, 'Expected number of results was not created.' + assert TestResult.objects.filter(test=tests[0]).count() == 1, f'Only 1 result should be on a test "{tests[0]}"' + assert TestResult.objects.filter(test=tests[1]).count() == 1, f'Only 1 result should be on a test "{tests[1]}"' + + def test_get_results_by_test(self, api_client, test_result_factory, test_factory, authorized_superuser): + test1 = test_factory() + test2 = test_factory() + dicts_test1 = [] + dicts_test2 = [] + for _ in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + dicts_test1.append(model_with_base_to_dict(test_result_factory(test=test1))) + dicts_test2.append(model_with_base_to_dict(test_result_factory(test=test2))) + response_test1 = api_client.send_request( + 'api:v1:results-by-test', + expected_status=HTTPStatus.OK, + request_type=RequestType.GET, + reverse_kwargs={'pk': test1.id} + ) + response_test2 = api_client.send_request( + 'api:v1:results-by-test', + expected_status=HTTPStatus.OK, + request_type=RequestType.GET, + reverse_kwargs={'pk': test2.id} + ) + actual_results1 = json.loads(response_test1.content) + actual_results2 = json.loads(response_test2.content) + for result_test1, result_test2 in zip(actual_results1, actual_results2): + result_test1.pop('url') + result_test2.pop('url') + assert actual_results1 == dicts_test1, 'Response is different from expected one' + assert actual_results2 == dicts_test2, 'Response is different from expected one' diff --git a/tests/test_api/v1/test_testsuite_endpoints.py b/tests/test_api/v1/test_testsuite_endpoints.py new file mode 100644 index 0000000..780d68c --- /dev/null +++ b/tests/test_api/v1/test_testsuite_endpoints.py @@ -0,0 +1,172 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import json +from http import HTTPStatus + +import pytest +from django.forms import model_to_dict +from tests_description.api.v1.serializers import TestSuiteSerializer, TestSuiteTreeSerializer +from tests_description.models import TestSuite + +from tests import constants +from tests.commons import RequestType, model_to_dict_via_serializer +from tests.error_messages import REQUIRED_FIELD_MSG + + +@pytest.mark.django_db +class TestSuiteEndpoints: + view_name_list = 'api:v1:testsuite-list' + view_name_detail = 'api:v1:testsuite-detail' + + def test_list(self, api_client, authorized_superuser, test_suite_factory): + expected_instances = [] + for _ in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + expected_dict = model_to_dict(test_suite_factory()) + expected_dict['test_cases'] = [] + expected_instances.append(expected_dict) + + response = api_client.send_request(self.view_name_list) + for instance_dict in json.loads(response.content): + instance_dict.pop('url') + assert instance_dict in expected_instances, f'{instance_dict} was not found in expected instances.' + + def test_retrieve(self, api_client, authorized_superuser, test_suite): + expected_dict = model_to_dict(test_suite) + expected_dict['test_cases'] = [] + response = api_client.send_request(self.view_name_detail, reverse_kwargs={'pk': test_suite.pk}) + actual_dict = json.loads(response.content) + actual_dict.pop('url') + assert actual_dict == expected_dict, 'Actual model dict is different from expected' + + def test_creation(self, api_client, authorized_superuser, project): + expected_number_of_suites = 1 + suite_dict = { + 'name': constants.TEST_CASE_NAME, + 'project': project.id, + } + api_client.send_request(self.view_name_list, suite_dict, HTTPStatus.CREATED, RequestType.POST) + assert TestSuite.objects.count() == expected_number_of_suites, f'Expected number of users ' \ + f'"{expected_number_of_suites}"' \ + f'actual: "{TestSuite.objects.count()}"' + + def test_partial_update(self, api_client, authorized_superuser, test_suite): + new_name = 'new_expected_test_case_name' + suite_dict = { + 'id': test_suite.id, + 'name': new_name + } + api_client.send_request( + self.view_name_detail, + suite_dict, + request_type=RequestType.PATCH, + reverse_kwargs={'pk': test_suite.pk} + ) + actual_name = TestSuite.objects.get(pk=test_suite.id).name + assert actual_name == new_name, f'Suite names do not match. Expected name "{actual_name}", ' \ + f'actual: "{new_name}"' + + @pytest.mark.parametrize('expected_status', [HTTPStatus.OK, HTTPStatus.BAD_REQUEST]) + def test_update(self, api_client, authorized_superuser, expected_status, test_suite, project): + new_name = 'new_expected_test_case_name' + suite_dict = { + 'id': test_suite.id, + 'name': new_name + } + if expected_status == HTTPStatus.OK: + suite_dict['project'] = project.id + response = api_client.send_request( + self.view_name_detail, + reverse_kwargs={'pk': test_suite.pk}, + request_type=RequestType.PUT, + expected_status=expected_status, + data=suite_dict + ) + if expected_status == HTTPStatus.OK: + actual_name = TestSuite.objects.get(pk=test_suite.id).name + assert actual_name == new_name, f'Suite name does not match. Expected name "{actual_name}", ' \ + f'actual: "{new_name}"' + else: + assert json.loads(response.content)['project'][0] == REQUIRED_FIELD_MSG + + def test_delete(self, api_client, authorized_superuser, test_suite): + assert TestSuite.objects.count() == 1, 'Test suite was not created' + api_client.send_request( + self.view_name_detail, + expected_status=HTTPStatus.NO_CONTENT, + request_type=RequestType.DELETE, + reverse_kwargs={'pk': test_suite.pk} + ) + assert not TestSuite.objects.count(), f'Test suite with id "{test_suite.id}" was not deleted.' + + +@pytest.mark.django_db +class TestSuiteEndpointsQueryParams: + view_name_list = 'api:v1:testsuite-list' + + def test_suite_filter(self, api_client, authorized_superuser, test_suite_factory, project_factory): + projects = [project_factory() for _ in range(3)] + for _ in range(2): + for project in projects: + test_suite_factory(project=project) + + for project in projects: + suites = TestSuite.objects.filter(project=project.id) + expected_dict = model_to_dict_via_serializer(suites, serializer_class=TestSuiteSerializer, many=True) + response = api_client.send_request( + self.view_name_list, + expected_status=HTTPStatus.OK, + request_type=RequestType.GET, + query_params={'project': project.id} + ) + actual_dict = json.loads(response.content) + assert actual_dict == expected_dict, 'Actual and expected dict are different.' + + def test_suite_treeview(self, api_client, authorized_superuser, test_suite_factory, project_factory): + projects = [project_factory() for _ in range(3)] + + for _ in range(2): + for project in projects: + test_suite_factory(project=project) + + for project in projects: + suites = TestSuite.objects.filter(project=project.id) + expected_dict = model_to_dict_via_serializer(suites, serializer_class=TestSuiteTreeSerializer, many=True) + incorrect_dict = model_to_dict_via_serializer(suites, serializer_class=TestSuiteSerializer, many=True) + response = api_client.send_request( + self.view_name_list, + expected_status=HTTPStatus.OK, + request_type=RequestType.GET, + query_params={'project': project.id, 'treeview': 'True'} + ) + actual_dict = json.loads(response.content) + assert actual_dict == expected_dict, 'Actual and expected dict are different.' + assert actual_dict != incorrect_dict, 'SuiteSerializer is used to output suites with treeview param.' diff --git a/tests/test_api/v1/test_user_endpoints.py b/tests/test_api/v1/test_user_endpoints.py new file mode 100644 index 0000000..1effdb7 --- /dev/null +++ b/tests/test_api/v1/test_user_endpoints.py @@ -0,0 +1,175 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import json +from http import HTTPStatus +from typing import Any, Dict + +import pytest +from django.forms import model_to_dict +from users.models import User + +from tests import constants +from tests.commons import RequestType +from tests.error_messages import INVALID_EMAIL_MSG, REQUIRED_FIELD_MSG, UNAUTHORIZED_MSG + + +@pytest.mark.django_db +class TestUserEndpoints: + view_name_list = 'api:v1:user-list' + view_name_detail = 'api:v1:user-detail' + + def test_list(self, api_client, authorized_superuser, user_factory): + expected_instances = [self._form_dict_user_model(authorized_superuser)] + for _ in range(constants.NUMBER_OF_OBJECTS_TO_CREATE): + expected_instances.append(self._form_dict_user_model(user_factory())) + response = api_client.send_request(self.view_name_list) + + for instance_dict in json.loads(response.content): + instance_dict.pop('url') + assert instance_dict in expected_instances, f'{instance_dict} was not found in expected instances.' + + def test_retrieve(self, api_client, authorized_superuser, user): + expected_dict = self._form_dict_user_model(user) + response = api_client.send_request(self.view_name_detail, reverse_kwargs={'pk': user.pk}) + actual_dict = json.loads(response.content) + actual_dict.pop('url') + assert actual_dict == expected_dict, 'Actual model dict is different from expected' + + def test_creation(self, api_client, authorized_superuser): + expected_users_num = 2 + assert User.objects.count() == 1, 'Extra users were found.' + user_dict = { + 'username': constants.USERNAME, + 'first_name': constants.FIRST_NAME, + 'last_name': constants.LAST_NAME, + 'password': constants.PASSWORD, + 'email': constants.USER_EMAIL + } + api_client.send_request(self.view_name_list, user_dict, HTTPStatus.CREATED, RequestType.POST) + assert User.objects.count() == expected_users_num, f'Expected number of users "{expected_users_num}"' \ + f'actual: "{User.objects.count()}"' + + def test_partial_update(self, api_client, authorized_superuser, user): + new_name = 'new_expected_username' + user_dict = { + 'id': user.id, + 'username': new_name, + } + api_client.send_request( + self.view_name_detail, + user_dict, + request_type=RequestType.PATCH, + reverse_kwargs={'pk': user.pk} + ) + actual_name = User.objects.get(pk=user.id).username + assert actual_name == new_name, f'Username does not match. Expected name "{actual_name}", actual: "{new_name}"' + + @pytest.mark.parametrize('expected_status', [HTTPStatus.OK, HTTPStatus.BAD_REQUEST]) + def test_update(self, api_client, authorized_superuser, user, expected_status): + new_name = 'new_expected_username' + user_dict = { + 'id': user.id, + 'username': new_name, + } + if expected_status == HTTPStatus.OK: + user_dict['password'] = user.password + response = api_client.send_request( + self.view_name_detail, + user_dict, + request_type=RequestType.PUT, + expected_status=expected_status, + reverse_kwargs={'pk': user.pk} + ) + if expected_status == HTTPStatus.OK: + actual_name = User.objects.get(pk=user.id).username + assert actual_name == new_name, f'Username does not match. Expected name "{actual_name}", ' \ + f'actual: "{new_name}"' + else: + assert json.loads(response.content)['password'][0] == REQUIRED_FIELD_MSG + + def test_delete(self, api_client, authorized_superuser, user): + assert User.objects.count() == 2, 'User was not created' + api_client.send_request( + self.view_name_detail, + expected_status=HTTPStatus.NO_CONTENT, + request_type=RequestType.DELETE, + reverse_kwargs={'pk': user.pk} + ) + assert User.objects.count() == 1, f'User with id "{user.id}" was not deleted.' + + def test_unauthorized_access(self, api_client): + for request_type in RequestType: + response = api_client.send_request( + self.view_name_list, + expected_status=HTTPStatus.UNAUTHORIZED, + request_type=request_type + ) + received_dict = json.loads(response.content) + assert received_dict['detail'] == UNAUTHORIZED_MSG, 'Expected message was not found in response.' \ + f'Request type: {RequestType.POST.value}' + + def test_email_validation(self, api_client, authorized_superuser, user): + update_types = [RequestType.PUT, RequestType.PATCH] + user_dict = { + 'username': constants.USERNAME, + 'password': constants.PASSWORD, + 'email': constants.INVALID_EMAIL + } + response = api_client.send_request(self.view_name_list, user_dict, HTTPStatus.BAD_REQUEST, RequestType.POST) + received_dict = json.loads(response.content) + assert received_dict['email'][0] == INVALID_EMAIL_MSG, 'Validation email error was not found in response.' \ + f'Request type: {RequestType.POST.value}' + user_dict_update = { + 'username': constants.USERNAME, + 'password': constants.PASSWORD, + 'email': constants.INVALID_EMAIL + } + for request_type in update_types: + response = api_client.send_request( + self.view_name_detail, + data=user_dict_update, + expected_status=HTTPStatus.BAD_REQUEST, + request_type=request_type, + reverse_kwargs={'pk': user.pk} + ) + received_dict = json.loads(response.content) + assert received_dict['email'][0] == INVALID_EMAIL_MSG, 'Validation email error was not found in response.' \ + f'Request type: {request_type.value}' + + @staticmethod + def _form_dict_user_model(user: User) -> Dict[str, Any]: + user_dict = model_to_dict(user) + fields_to_remove = ['is_superuser', 'last_login', 'password', 'user_permissions'] + for field in fields_to_remove: + user_dict.pop(field) + user_dict['date_joined'] = user_dict['date_joined'].strftime("%Y-%m-%dT%H:%M:%S.%fZ") + return user_dict diff --git a/tests/test_models/test_common_model_constraints.py b/tests/test_models/test_common_model_constraints.py new file mode 100644 index 0000000..f5cb2e7 --- /dev/null +++ b/tests/test_models/test_common_model_constraints.py @@ -0,0 +1,94 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import pytest +from django.db import DataError +from tests_description.models import TestCase, TestSuite +from tests_representation.models import Parameter, Test, TestPlan, TestResult + +from tests import constants +from tests.error_messages import CHAR_LENGTH_ERR_MSG +from tests.factories import ( + ParameterFactory, + ProjectFactory, + TestCaseFactory, + TestFactory, + TestPlanFactory, + TestResultFactory, + TestSuiteFactory, +) + + +@pytest.mark.django_db +class TestCommonConstraints: + @pytest.mark.parametrize( + 'instance, column_name', [ + (TestPlanFactory, 'name'), + (TestSuiteFactory, 'name'), + (TestCaseFactory, 'name'), + (TestPlanFactory, 'name'), + (ProjectFactory, 'name'), + (ParameterFactory, 'group_name') + ] + ) + def test_char_length_constraint(self, instance, column_name): + with pytest.raises(DataError) as err: + instance.create(**{column_name: constants.EXCEEDING_CHAR_FIELD}) + assert CHAR_LENGTH_ERR_MSG == str(err.value), f'Char field length was exceeded in model "{instance}".' + + @pytest.mark.parametrize( + 'child_factory, parent_factory, model, parameter_name', [ + (TestSuiteFactory, TestSuiteFactory, TestSuite, 'parent'), + (TestSuiteFactory, ProjectFactory, TestSuite, 'project'), + (TestPlanFactory, TestPlanFactory, TestPlan, 'parent'), + (TestFactory, TestCaseFactory, Test, 'case'), + (TestFactory, TestPlanFactory, Test, 'plan'), + (TestResultFactory, TestFactory, TestResult, 'test'), + (ParameterFactory, ProjectFactory, Parameter, 'project'), + (TestCaseFactory, ProjectFactory, TestCase, 'project'), + (TestCaseFactory, TestSuiteFactory, TestCase, 'suite') + ] + ) + def test_cascade_delete(self, parent_factory, child_factory, model, parameter_name): + expected_number_of_objects = 5 + parent_object = parent_factory.create() + + for _ in range(expected_number_of_objects): + child_factory.create(**{parameter_name: parent_object}) + + objects_number = model.objects.count() + if parent_factory == child_factory: + expected_number_of_objects += 1 + assert objects_number == expected_number_of_objects, f'Expected number of {model} is ' \ + f'"{expected_number_of_objects}"' \ + f'actual number of {model} is "{objects_number}"' + parent_object.delete() + assert not model.objects.count(), 'Parameters were not deleted with project.' diff --git a/tests/test_models/test_group_model.py b/tests/test_models/test_group_model.py new file mode 100644 index 0000000..2f3df46 --- /dev/null +++ b/tests/test_models/test_group_model.py @@ -0,0 +1,51 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import pytest +from django.db import IntegrityError +from users.models import Group + +from tests.error_messages import NOT_NULL_ERR_MSG + + +@pytest.mark.django_db +class TestGroupModel: + + @pytest.mark.parametrize('parameter_name', ['name']) + def test_not_null_constraint(self, parameter_name, group_factory): + with pytest.raises(IntegrityError) as err: + group_factory(**{parameter_name: None}) + assert NOT_NULL_ERR_MSG.format(relation='auth_group', column=parameter_name) in str(err.value), \ + 'Expected error message was not found.' + + def test_valid_model_creation(self, group): + assert Group.objects.count() == 1 + assert Group.objects.get(id=group.id) == group diff --git a/tests/test_models/test_parameter_model.py b/tests/test_models/test_parameter_model.py new file mode 100644 index 0000000..9256eaa --- /dev/null +++ b/tests/test_models/test_parameter_model.py @@ -0,0 +1,68 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import pytest +from django.db import IntegrityError +from tests_representation.models import Parameter + +from tests.error_messages import ALREADY_EXISTS_ERR_MSG, MODEL_VALUE_ERR_MSG, NOT_NULL_ERR_MSG + + +@pytest.mark.django_db +class TestParameterModel: + relation_name = Parameter._meta.label_lower.replace('.', '_') + + @pytest.mark.parametrize('parameter_name', ['project', 'data', 'group_name']) + def test_not_null_constraint(self, parameter_name, parameter_factory): + with pytest.raises(IntegrityError) as err: + parameter_factory(**{parameter_name: None}) + parameter_name = f'{parameter_name}_id' if parameter_name == 'project' else parameter_name + assert NOT_NULL_ERR_MSG.format(relation=self.relation_name, column=parameter_name) in str(err.value), \ + 'Expected error message was not found.' + + def test_fields_type_constraint(self, parameter_factory): + invalid_value = 'abc' + with pytest.raises(ValueError) as err: + parameter_factory(project=invalid_value) + assert MODEL_VALUE_ERR_MSG.format(value=invalid_value, model_name='Parameter', column_name='project', + column_model='Project') == str(err.value) + + def test_valid_model_creation(self, parameter): + assert Parameter.objects.count() == 1 + assert Parameter.objects.get(id=parameter.id) == parameter + + def test_unique_together_constraint(self, parameter, parameter_factory): + with pytest.raises(IntegrityError) as err: + parameter_factory(group_name=parameter.group_name, data=parameter.data) + assert ALREADY_EXISTS_ERR_MSG.format( + column_name='group_name, data', + column_value=f'{parameter.group_name}, {parameter.data}' + ) in str(err.value) diff --git a/tests/test_models/test_test_model.py b/tests/test_models/test_test_model.py new file mode 100644 index 0000000..40b1249 --- /dev/null +++ b/tests/test_models/test_test_model.py @@ -0,0 +1,73 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import pytest +from django.core.exceptions import ValidationError +from django.db import IntegrityError +from tests_representation.models import Test + +from tests.error_messages import BOOL_VALUE_ERR_MSG, MODEL_VALUE_ERR_MSG, NOT_NULL_ERR_MSG + + +@pytest.mark.django_db +class TestTestModel: + relation_name = Test._meta.label_lower.replace('.', '_') + + @pytest.mark.parametrize('parameter_name', ['case', 'plan', 'is_archive']) + def test_not_null_constraint(self, parameter_name, test_factory): + foreign_keys = ['case', 'plan', 'user'] + with pytest.raises(IntegrityError) as err: + test_factory(**{parameter_name: None}) + parameter_name = f'{parameter_name}_id' if parameter_name in foreign_keys else parameter_name + + assert NOT_NULL_ERR_MSG.format( + relation=self.relation_name, column=parameter_name + ) in str(err.value), 'Expected error message was not found.' + + @pytest.mark.parametrize( + 'parameter_name, incorrect_value, error_type, err_msg', [ + ('case', 'abc', ValueError, MODEL_VALUE_ERR_MSG.format(value='abc', model_name='Test', column_name='case', + column_model='TestCase')), + ('plan', 'abc', ValueError, MODEL_VALUE_ERR_MSG.format(value='abc', model_name='Test', column_name='plan', + column_model='TestPlan')), + ('user', 'abc', ValueError, MODEL_VALUE_ERR_MSG.format(value='abc', model_name='Test', column_name='user', + column_model='User')), + ('is_archive', 'abc', ValidationError, BOOL_VALUE_ERR_MSG.format(value='abc')) + ] + ) + def test_fields_type_constraint(self, parameter_name, incorrect_value, error_type, test_factory, err_msg): + with pytest.raises(error_type) as err: + test_factory(**{parameter_name: incorrect_value}) + assert err_msg in str(err.value) + + def test_valid_model_creation(self, test): + assert Test.objects.count() == 1 + assert Test.objects.get(id=test.id) == test diff --git a/tests/test_models/test_testcase_model.py b/tests/test_models/test_testcase_model.py new file mode 100644 index 0000000..4f702db --- /dev/null +++ b/tests/test_models/test_testcase_model.py @@ -0,0 +1,68 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import pytest +from django.db import IntegrityError +from tests_description.models import TestCase + +from tests.error_messages import INT_VALUE_ERR_MSG, MODEL_VALUE_ERR_MSG, NOT_NULL_ERR_MSG + + +@pytest.mark.django_db +class TestCaseModel: + relation_name = TestCase._meta.label_lower.replace('.', '_') + + @pytest.mark.parametrize('parameter_name', ['name', 'project', 'suite', 'setup', 'scenario', 'teardown']) + def test_not_null_constraint(self, parameter_name, test_case_factory): + foreign_keys = ['project', 'suite'] + with pytest.raises(IntegrityError) as err: + test_case_factory(**{parameter_name: None}) + parameter_name = f'{parameter_name}_id' if parameter_name in foreign_keys else parameter_name + assert NOT_NULL_ERR_MSG.format(relation=self.relation_name, column=parameter_name) in str(err.value), \ + 'Expected error message was not found.' + + @pytest.mark.parametrize( + 'parameter_name, incorrect_value, err_msg', [ + ('project', 'abc', MODEL_VALUE_ERR_MSG.format(value='abc', model_name='TestCase', column_name='project', + column_model='Project')), + ('suite', 'abc', MODEL_VALUE_ERR_MSG.format(value='abc', model_name='TestCase', column_name='suite', + column_model='TestSuite')), + ('estimate', 'abc', INT_VALUE_ERR_MSG.format(column='estimate', value='abc')), + ] + ) + def test_fields_type_constraint(self, parameter_name, incorrect_value, err_msg, test_case_factory): + with pytest.raises(ValueError) as err: + test_case_factory(**{parameter_name: incorrect_value}) + assert err_msg == str(err.value) + + def test_valid_model_creation(self, test_case): + assert TestCase.objects.count() == 1 + assert TestCase.objects.get(id=test_case.id) == test_case diff --git a/tests/test_models/test_testplan_model.py b/tests/test_models/test_testplan_model.py new file mode 100644 index 0000000..add57b1 --- /dev/null +++ b/tests/test_models/test_testplan_model.py @@ -0,0 +1,75 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import pytest +from django.core.exceptions import ValidationError +from django.db import DataError, IntegrityError +from tests_representation.models import TestPlan + +from tests.error_messages import ( + ARRAY_VALUE_ERR_MSG, + BOOL_VALUE_ERR_MSG, + MODEL_VALUE_ERR_MSG, + NOT_NULL_ERR_MSG, + TYPE_ERR_MSG, +) + + +@pytest.mark.django_db +class TestPlanModel: + relation_name = TestPlan._meta.label_lower.replace('.', '_') + + @pytest.mark.parametrize('parameter_name', ['started_at', 'name', 'due_date', 'is_archive']) + def test_not_null_constraint(self, parameter_name, test_plan_factory): + with pytest.raises(IntegrityError) as err: + test_plan_factory(**{parameter_name: None}) + assert NOT_NULL_ERR_MSG.format(relation=self.relation_name, column=parameter_name) in str(err.value), \ + 'Expected error message was not found.' + + @pytest.mark.parametrize( + 'parameter_name, incorrect_value, error_type, err_msg', [ + ('parent', 'abc', ValueError, MODEL_VALUE_ERR_MSG.format(value='abc', model_name='TestPlan', + column_name='parent', column_model='TestPlan')), + ('parameters', 'abc', DataError, ARRAY_VALUE_ERR_MSG), + ('started_at', 1, TypeError, TYPE_ERR_MSG), + ('due_date', 1, TypeError, TYPE_ERR_MSG), + ('finished_at', 1, TypeError, TYPE_ERR_MSG), + ('is_archive', 'abc', ValidationError, BOOL_VALUE_ERR_MSG.format(value='abc')) + ] + ) + def test_fields_type_constraint(self, parameter_name, incorrect_value, error_type, err_msg, test_plan_factory): + with pytest.raises(error_type) as err: + test_plan_factory(**{parameter_name: incorrect_value}) + assert err_msg in str(err.value) + + def test_valid_model_creation(self, test_plan): + assert TestPlan.objects.count() == 1 + assert TestPlan.objects.get(id=test_plan.id) == test_plan diff --git a/tests/test_models/test_testresult_model.py b/tests/test_models/test_testresult_model.py new file mode 100644 index 0000000..c9b480f --- /dev/null +++ b/tests/test_models/test_testresult_model.py @@ -0,0 +1,69 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import pytest +from django.core.exceptions import ValidationError +from django.db import IntegrityError +from tests_representation.models import TestResult + +from tests.error_messages import BOOL_VALUE_ERR_MSG, INT_VALUE_ERR_MSG, MODEL_VALUE_ERR_MSG, NOT_NULL_ERR_MSG + + +@pytest.mark.django_db +class TestResultModel: + relation_name = TestResult._meta.label_lower.replace('.', '_') + + @pytest.mark.parametrize('parameter_name', ['status', 'test', 'is_archive']) + def test_not_null_constraint(self, parameter_name, test_result_factory): + with pytest.raises(IntegrityError) as err: + test_result_factory(**{parameter_name: None}) + parameter_name = 'test_id' if parameter_name == 'test' else parameter_name + assert NOT_NULL_ERR_MSG.format(relation=self.relation_name, column=parameter_name) in str(err.value), \ + 'Expected error message was not found.' + + @pytest.mark.parametrize( + 'parameter_name, incorrect_value, error_type, err_msg', [ + ('status', 'abc', ValueError, INT_VALUE_ERR_MSG.format(column='status', value='abc')), + ('test', 'abc', ValueError, MODEL_VALUE_ERR_MSG.format(value='abc', model_name='TestResult', + column_name='test', column_model='Test')), + ('user', 'abc', ValueError, MODEL_VALUE_ERR_MSG.format(value='abc', model_name='TestResult', + column_name='user', column_model='User')), + ('is_archive', 'abc', ValidationError, BOOL_VALUE_ERR_MSG.format(value='abc')) + ] + ) + def test_fields_type_constraint(self, parameter_name, incorrect_value, error_type, err_msg, test_result_factory): + with pytest.raises(error_type) as err: + test_result_factory(**{parameter_name: incorrect_value}) + assert err_msg in str(err.value) + + def test_valid_model_creation(self, test_result): + assert TestResult.objects.count() == 1 + assert TestResult.objects.get(id=test_result.id) == test_result diff --git a/tests/test_models/test_testsuite_model.py b/tests/test_models/test_testsuite_model.py new file mode 100644 index 0000000..db26f9f --- /dev/null +++ b/tests/test_models/test_testsuite_model.py @@ -0,0 +1,69 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import pytest +from django.contrib.auth import get_user_model +from django.db import IntegrityError +from tests_description.models import TestSuite + +from tests.error_messages import MODEL_VALUE_ERR_MSG, NOT_NULL_ERR_MSG + +UserModel = get_user_model() + + +@pytest.mark.django_db +class TestSuiteModel: + relation_name = TestSuite._meta.label_lower.replace('.', '_') + + @pytest.mark.parametrize('parameter_name', ['project', 'name']) + def test_not_null_constraint(self, parameter_name, test_suite_factory): + with pytest.raises(IntegrityError) as err: + test_suite_factory(**{parameter_name: None}) + parameter_name = f'{parameter_name}_id' if parameter_name == 'project' else parameter_name + assert NOT_NULL_ERR_MSG.format(relation=self.relation_name, column=parameter_name) in str(err.value), \ + 'Expected error message was not found.' + + @pytest.mark.parametrize( + 'parameter_name, incorrect_value, err_msg', [ + ('parent', 'abc', MODEL_VALUE_ERR_MSG.format(value='abc', model_name='TestSuite', column_name='parent', + column_model='TestSuite')), + ('project', 'abc', MODEL_VALUE_ERR_MSG.format(value='abc', model_name='TestSuite', column_name='project', + column_model='Project')), + ] + ) + def test_fields_type_constraint(self, parameter_name, incorrect_value, err_msg, test_suite_factory): + with pytest.raises(ValueError) as err: + test_suite_factory(**{parameter_name: incorrect_value}) + assert err_msg in str(err.value) + + def test_valid_model_creation(self, test_suite): + assert TestSuite.objects.count() == 1 + assert TestSuite.objects.get(id=test_suite.id) == test_suite diff --git a/tests/test_models/test_user_model.py b/tests/test_models/test_user_model.py new file mode 100644 index 0000000..0ec79ca --- /dev/null +++ b/tests/test_models/test_user_model.py @@ -0,0 +1,74 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import pytest +from django.contrib.auth import get_user_model +from django.core.exceptions import ValidationError +from django.db import IntegrityError + +from tests.error_messages import ALREADY_EXISTS_ERR_MSG, BOOL_VALUE_ERR_MSG, NOT_NULL_ERR_MSG + +UserModel = get_user_model() + + +@pytest.mark.django_db +class TestUserModel: + relation_name = UserModel._meta.label_lower.replace('.', '_') + + @pytest.mark.parametrize('parameter_name', ['username', 'password', 'is_active', 'is_staff', 'is_superuser']) + def test_not_null_constraint(self, parameter_name, user_factory): + with pytest.raises(IntegrityError) as err: + user_factory(**{parameter_name: None}) + assert NOT_NULL_ERR_MSG.format(relation=self.relation_name, column=parameter_name) in str(err.value), \ + 'Expected error message was not found.' + + @pytest.mark.parametrize( + 'parameter_name, incorrect_value', [ + ('is_superuser', 'abc'), + ('is_active', 'abc'), + ('is_staff', 'abc') + ] + ) + def test_fields_type_constraint(self, parameter_name, incorrect_value, user_factory): + with pytest.raises(ValidationError) as err: + user_factory(**{parameter_name: incorrect_value}) + assert BOOL_VALUE_ERR_MSG.format(value=incorrect_value) in str(err.value) + + def test_duplicate_username_not_allowed(self, user, user_factory): + with pytest.raises(IntegrityError) as err: + user_factory(username=user.username) + assert ALREADY_EXISTS_ERR_MSG.format( + column_name='username', column_value=user.username + ) in str(err.value), f'Expected error message was not found. Expected message: {ALREADY_EXISTS_ERR_MSG}' + + def test_valid_model_creation(self, user): + assert UserModel.objects.count() == 1 + assert UserModel.objects.get(id=user.id) == user diff --git a/tests/test_utils/test_utils.py b/tests/test_utils/test_utils.py new file mode 100644 index 0000000..5b3f435 --- /dev/null +++ b/tests/test_utils/test_utils.py @@ -0,0 +1,47 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . +from utilities.request import get_boolean + +from tests.commons import RequestMock + + +class TestTestyUtilities: + + def test_get_boolean(self): + request = RequestMock() + valid_positive_yes = ['1', 'yes', 'true', 'True', 'YES', 1, 'TRue'] + invalid_yes = ['2', '0', 'ye', 'y', 't', 'truee', 0, ''] + for option in valid_positive_yes: + request.GET = {'treeview': option} + assert get_boolean(request, 'treeview'), f'Valid option "{option}" was recognised as invalid.' + for option in invalid_yes: + request.GET = {'treeview': option} + assert not get_boolean(request, 'treeview'), f'Invalid option "{option}" was recognised as valid.' diff --git a/testy/core/__init__.py b/testy/core/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/core/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/core/admin.py b/testy/core/admin.py new file mode 100644 index 0000000..628f8a9 --- /dev/null +++ b/testy/core/admin.py @@ -0,0 +1,41 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from core.models import Project +from django.contrib import admin + +from testy.admin import BaseAdmin + + +@admin.register(Project) +class ProjectAdmin(BaseAdmin): + list_display = ('name',) + search_fields = ('name',) diff --git a/testy/core/api/v1/__init__.py b/testy/core/api/v1/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/core/api/v1/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/core/api/v1/serializers.py b/testy/core/api/v1/serializers.py new file mode 100644 index 0000000..ec81d4a --- /dev/null +++ b/testy/core/api/v1/serializers.py @@ -0,0 +1,45 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from core.models import Project +from rest_framework.serializers import HyperlinkedIdentityField, ModelSerializer + +__all__ = ( + 'ProjectSerializer' +) + + +class ProjectSerializer(ModelSerializer): + url = HyperlinkedIdentityField(view_name='api:v1:project-detail') + + class Meta: + model = Project + fields = ('id', 'url', 'name', 'description', 'is_archive') diff --git a/testy/core/api/v1/urls.py b/testy/core/api/v1/urls.py new file mode 100644 index 0000000..54886fe --- /dev/null +++ b/testy/core/api/v1/urls.py @@ -0,0 +1,64 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from core.api.v1 import views +from django.urls import path +from rest_framework import routers + +router = routers.SimpleRouter() + +project_list = views.ProjectViewSet.as_view({ + 'get': 'list', + 'post': 'create' +}) +project_detail = views.ProjectViewSet.as_view({ + 'get': 'retrieve', + 'put': 'update', + 'patch': 'partial_update', + 'delete': 'destroy' +}) + +testplans_by_project = views.ProjectViewSet.as_view({ + 'get': 'testplans_by_project' +}) + +parameters_by_project = views.ProjectViewSet.as_view({ + 'get': 'parameters_by_project' +}) + +urlpatterns = [ + path('projects/', project_list, name='project-list'), + path('projects//', project_detail, name='project-detail'), + path('projects//testplans/', testplans_by_project, name='project-testplans'), + path('projects//parameters/', parameters_by_project, name='project-parameters'), +] + +urlpatterns += router.urls diff --git a/testy/core/api/v1/views.py b/testy/core/api/v1/views.py new file mode 100644 index 0000000..cefc4dc --- /dev/null +++ b/testy/core/api/v1/views.py @@ -0,0 +1,56 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from core.api.v1.serializers import ProjectSerializer +from core.selectors.projects import ProjectSelector +from rest_framework.decorators import action +from rest_framework.response import Response +from rest_framework.viewsets import ModelViewSet +from tests_representation.api.v1.serializers import ParameterSerializer, TestPlanTreeSerializer +from tests_representation.selectors.parameters import ParameterSelector +from tests_representation.selectors.testplan import TestPlanSelector + + +class ProjectViewSet(ModelViewSet): + queryset = ProjectSelector.project_list() + serializer_class = ProjectSerializer + + @action(detail=False) + def testplans_by_project(self, request, pk): + qs = TestPlanSelector().testplan_project_root_list(project_id=pk) + serializer = TestPlanTreeSerializer(qs, many=True, context={'request': request}) + return Response(serializer.data) + + @action(detail=False) + def parameters_by_project(self, request, pk): + qs = ParameterSelector().parameter_project_list(project_id=pk) + serializer = ParameterSerializer(qs, many=True, context={'request': request}) + return Response(serializer.data) diff --git a/testy/core/apps.py b/testy/core/apps.py new file mode 100644 index 0000000..1ec35b6 --- /dev/null +++ b/testy/core/apps.py @@ -0,0 +1,39 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class CoreConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'core' + verbose_name = _('core') diff --git a/testy/core/locale/ru/LC_MESSAGES/django.mo b/testy/core/locale/ru/LC_MESSAGES/django.mo new file mode 100644 index 0000000..c14e6da Binary files /dev/null and b/testy/core/locale/ru/LC_MESSAGES/django.mo differ diff --git a/testy/core/locale/ru/LC_MESSAGES/django.po b/testy/core/locale/ru/LC_MESSAGES/django.po new file mode 100644 index 0000000..561eb9b --- /dev/null +++ b/testy/core/locale/ru/LC_MESSAGES/django.po @@ -0,0 +1,41 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2022-09-20 08:55+0000\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n" +"%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n" +"%100>=11 && n%100<=14)? 2 : 3);\n" + +#: testy/core/apps.py:8 +msgid "core" +msgstr "основное" + +#: testy/core/models.py:13 +msgid "name" +msgstr "наименование" + +#: testy/core/models.py:14 +msgid "description" +msgstr "описание" + +#: testy/core/models.py:18 +msgid "project" +msgstr "проект" + +#: testy/core/models.py:19 +msgid "projects" +msgstr "проекты" diff --git a/testy/core/management/commands/seed_db.py b/testy/core/management/commands/seed_db.py new file mode 100644 index 0000000..769634b --- /dev/null +++ b/testy/core/management/commands/seed_db.py @@ -0,0 +1,82 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import logging +import os + +from django.conf import settings +from django.contrib.auth import get_user_model +from django.core.exceptions import ImproperlyConfigured, ValidationError +from django.core.management.base import BaseCommand +from django.core.validators import validate_email + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand): + help = 'Seeding default values in database: default superuser.' + + def handle(self, *args, **options) -> None: + self.create_default_superuser() + + @staticmethod + def create_default_superuser() -> None: + username = os.environ.get("SUPERUSER_USERNAME", "") + if not username: + raise ImproperlyConfigured('Required parameter SUPERUSER_USERNAME is missing.') + + password = os.environ.get("SUPERUSER_PASSWORD", "") + if not password: + raise ImproperlyConfigured('Required parameter SUPERUSER_PASSWORD is missing.') + + company_domain = settings.COMPANY_DOMAIN + if not company_domain: + raise ImproperlyConfigured('Required parameter COMPANY_DOMAIN is missing.') + + email = '{0}@{1}'.format(username, company_domain) + try: + validate_email(email) + except ValidationError as err: + raise ImproperlyConfigured(str(err)) + + User = get_user_model() + if not User.objects.exists(): + logger.info("Creating default superuser") + User.objects.create_superuser(username, email, password) + logger.info( + """ + Default superuser created: + username: '{0}' + email: '{1}' + """.format(username, email) + ) + else: + logger.info("Not creating default superuser") diff --git a/testy/core/migrations/0001_initial.py b/testy/core/migrations/0001_initial.py new file mode 100644 index 0000000..f610843 --- /dev/null +++ b/testy/core/migrations/0001_initial.py @@ -0,0 +1,29 @@ +# Generated by Django 3.2 on 2022-10-06 16:24 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Project', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), + ('name', models.CharField(max_length=255, verbose_name='name')), + ('description', models.TextField(blank=True, verbose_name='description')), + ], + options={ + 'verbose_name': 'project', + 'verbose_name_plural': 'projects', + 'ordering': ('name',), + }, + ), + ] diff --git a/testy/core/migrations/0002_project_is_archive.py b/testy/core/migrations/0002_project_is_archive.py new file mode 100644 index 0000000..567062b --- /dev/null +++ b/testy/core/migrations/0002_project_is_archive.py @@ -0,0 +1,18 @@ +# Generated by Django 3.2 on 2022-11-08 14:54 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('core', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='project', + name='is_archive', + field=models.BooleanField(default=False), + ), + ] diff --git a/testy/core/migrations/__init__.py b/testy/core/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/testy/core/models.py b/testy/core/models.py new file mode 100644 index 0000000..77bf59d --- /dev/null +++ b/testy/core/models.py @@ -0,0 +1,54 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.conf import settings +from django.db import models +from django.utils.translation import gettext_lazy as _ + +from testy.models import BaseModel + +__all__ = ( + 'Project', +) + + +class Project(BaseModel): + name = models.CharField(_('name'), max_length=settings.CHAR_FIELD_MAX_LEN) + description = models.TextField(_('description'), blank=True) + is_archive = models.BooleanField(default=False) + + class Meta: + ordering = ('name',) + verbose_name = _('project') + verbose_name_plural = _('projects') + + def __str__(self) -> str: + return self.name diff --git a/testy/core/selectors/__init__.py b/testy/core/selectors/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/core/selectors/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/core/selectors/projects.py b/testy/core/selectors/projects.py new file mode 100644 index 0000000..5d7f59a --- /dev/null +++ b/testy/core/selectors/projects.py @@ -0,0 +1,44 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from core.models import Project +from django.db.models import QuerySet + + +class ProjectSelector: + + @staticmethod + def project_list() -> QuerySet[Project]: + return QuerySet(model=Project).order_by('name') + + @staticmethod + def project_by_id(project_id: int) -> Project: + return QuerySet(model=Project).get(pk=project_id) diff --git a/testy/core/services/__init__.py b/testy/core/services/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/core/services/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/core/services/projects.py b/testy/core/services/projects.py new file mode 100644 index 0000000..f614828 --- /dev/null +++ b/testy/core/services/projects.py @@ -0,0 +1,51 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import Any, Dict + +from core.models import Project + + +class ProjectService: + non_side_effect_fields = ['name', 'description', 'is_archive'] + + def project_create(self, data: Dict[str, Any]) -> Project: + return Project.model_create( + fields=self.non_side_effect_fields, + data=data, + ) + + def project_update(self, project: Project, data: Dict[str, Any]) -> Project: + project, _ = project.model_update( + fields=self.non_side_effect_fields, + data=data, + ) + return project diff --git a/testy/forms.py b/testy/forms.py new file mode 100644 index 0000000..16df9c7 --- /dev/null +++ b/testy/forms.py @@ -0,0 +1,100 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from crispy_forms.bootstrap import FormActions, UneditableField +from crispy_forms.helper import FormHelper +from crispy_forms.layout import HTML, Div, Layout, Submit +from django import forms +from django.contrib.auth import get_user_model +from django.contrib.auth.forms import PasswordChangeForm + +UserModel = get_user_model() + + +class UserDetailsForm(forms.ModelForm): + username = forms.CharField(disabled=True) + + class Meta: + model = UserModel + fields = ('username', 'first_name', 'last_name', 'email') + help_texts = { + 'username': None, + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.helper = FormHelper() + self.helper.form_class = 'form-horizontal' + self.helper.label_class = 'col-3' + self.helper.field_class = 'col-8' + self.helper.form_tag = False + self.helper.use_custom_control = False + self.helper.layout = Layout( + Div( + Div( + Div(UneditableField('username', css_class='form-control', help_text=None), css_class='row'), + Div('first_name', css_class='row'), + Div('last_name', css_class='row'), + Div('email', css_class='row'), + css_class="col-md-6" + ), + css_class="row justify-content-start" + ), + HTML('
'), + FormActions( + Submit('Save', 'Save changes', css_class='btn-primary'), + ), + ) + + +class ProfilePasswordChangeForm(PasswordChangeForm): + + def __init__(self, user, *args, **kwargs): + super().__init__(user, *args, **kwargs) + self.helper = FormHelper() + self.helper.form_class = 'form-horizontal' + self.helper.label_class = 'col-4' + self.helper.field_class = 'col-7' + self.helper.form_tag = False + self.helper.use_custom_control = False + self.helper.layout = Layout( + Div( + Div( + Div('old_password', css_class='row'), + Div('new_password1', css_class='row'), + Div('new_password2', css_class='row'), + css_class="col-md-6" + ), + css_class="row justify-content-start" + ), + HTML('
'), + FormActions(Submit('Save', 'Change password', css_class='btn-primary'), css_class='mb-0') + ) diff --git a/testy/manage.py b/testy/manage.py new file mode 100644 index 0000000..c65cdec --- /dev/null +++ b/testy/manage.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python + + +"""Django's command-line utility for administrative tasks.""" + +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testy.settings.production') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/testy/requirements/ci-requirements.in b/testy/requirements/ci-requirements.in new file mode 100644 index 0000000..05fc959 --- /dev/null +++ b/testy/requirements/ci-requirements.in @@ -0,0 +1,15 @@ +flake8==5.0.4 +flake8-isort==4.2.0 +ansi2html==1.8.0 +pytest==7.1.3 +pytest-factoryboy==2.5.0 +pytest-django==4.5.2 +django-extensions==3.2.1 +django==3.2 +python-dotenv==0.21.0 +django-mptt==0.13.4 +djangorestframework==3.13.1 +djangorestframework-simplejwt==5.2.0 +django-simple-history==3.1.1 +psycopg2-binary +flake8-copyright-validator==0.0.1 \ No newline at end of file diff --git a/testy/requirements/ci-requirements.txt b/testy/requirements/ci-requirements.txt new file mode 100644 index 0000000..4ede4cf --- /dev/null +++ b/testy/requirements/ci-requirements.txt @@ -0,0 +1,102 @@ +# +# This file is autogenerated by pip-compile with python 3.9 +# To update, run: +# +# pip-compile ci-requirements.in +# +ansi2html==1.8.0 + # via -r ci-requirements.in +asgiref==3.5.2 + # via django +attrs==22.1.0 + # via pytest +django==3.2 + # via + # -r ci-requirements.in + # django-extensions + # django-js-asset + # djangorestframework + # djangorestframework-simplejwt +django-extensions==3.2.1 + # via -r ci-requirements.in +django-js-asset==2.0.0 + # via django-mptt +django-mptt==0.13.4 + # via -r ci-requirements.in +django-simple-history==3.1.1 + # via -r ci-requirements.in +djangorestframework==3.13.1 + # via + # -r ci-requirements.in + # djangorestframework-simplejwt +djangorestframework-simplejwt==5.2.0 + # via -r ci-requirements.in +factory-boy==3.2.1 + # via pytest-factoryboy +faker==15.1.1 + # via factory-boy +flake8==5.0.4 + # via + # -r ci-requirements.in + # flake8-copyright-validator + # flake8-isort +flake8-copyright-validator==0.0.1 + # via -r ci-requirements.in +flake8-isort==4.2.0 + # via -r ci-requirements.in +importlib-metadata==5.0.0 + # via flake8-copyright-validator +inflection==0.5.1 + # via pytest-factoryboy +iniconfig==1.1.1 + # via pytest +isort==5.10.1 + # via flake8-isort +mccabe==0.7.0 + # via flake8 +packaging==21.3 + # via pytest +pluggy==1.0.0 + # via pytest +psycopg2-binary==2.9.5 + # via -r ci-requirements.in +py==1.11.0 + # via pytest +pycodestyle==2.9.1 + # via flake8 +pyflakes==2.5.0 + # via flake8 +pyjwt==2.6.0 + # via djangorestframework-simplejwt +pyparsing==3.0.9 + # via packaging +pytest==7.1.3 + # via + # -r ci-requirements.in + # pytest-django + # pytest-factoryboy +pytest-django==4.5.2 + # via -r ci-requirements.in +pytest-factoryboy==2.5.0 + # via -r ci-requirements.in +python-dateutil==2.8.2 + # via faker +python-dotenv==0.21.0 + # via -r ci-requirements.in +pytz==2022.5 + # via + # django + # djangorestframework +six==1.16.0 + # via python-dateutil +sqlparse==0.4.3 + # via django +tomli==2.0.1 + # via pytest +typing-extensions==4.4.0 + # via pytest-factoryboy +zipp==3.10.0 + # via importlib-metadata + +# The following packages are considered to be unsafe in a requirements file: +# setuptools diff --git a/testy/requirements/dev-requirements.in b/testy/requirements/dev-requirements.in new file mode 100644 index 0000000..a820f3d --- /dev/null +++ b/testy/requirements/dev-requirements.in @@ -0,0 +1,7 @@ +-r requirements.in +-r ci-requirements.in + +pip-tools==6.8.0 +django-extensions==3.2.1 +pytest==7.1.3 +pytest-django==4.5.2 diff --git a/testy/requirements/dev-requirements.txt b/testy/requirements/dev-requirements.txt new file mode 100644 index 0000000..a8c9e75 --- /dev/null +++ b/testy/requirements/dev-requirements.txt @@ -0,0 +1,183 @@ +# +# This file is autogenerated by pip-compile with python 3.9 +# To update, run: +# +# pip-compile dev-requirements.in +# +ansi2html==1.8.0 + # via -r ci-requirements.in +asgiref==3.5.2 + # via django +attrs==22.1.0 + # via pytest +build==0.8.0 + # via pip-tools +certifi==2022.9.24 + # via requests +charset-normalizer==2.1.1 + # via requests +click==8.1.3 + # via pip-tools +coreapi==2.3.3 + # via drf-yasg +coreschema==0.0.4 + # via + # coreapi + # drf-yasg +django==3.2 + # via + # -r ci-requirements.in + # -r requirements.in + # django-cors-headers + # django-extensions + # django-filter + # django-js-asset + # djangorestframework + # djangorestframework-simplejwt + # drf-yasg +django-cors-headers==3.13.0 + # via -r requirements.in +django-extensions==3.2.1 + # via + # -r ci-requirements.in + # -r dev-requirements.in +django-filter==22.1 + # via -r requirements.in +django-js-asset==2.0.0 + # via django-mptt +django-mptt==0.13.4 + # via + # -r ci-requirements.in + # -r requirements.in +django-simple-history==3.1.1 + # via + # -r ci-requirements.in + # -r requirements.in +djangorestframework==3.13.1 + # via + # -r ci-requirements.in + # -r requirements.in + # djangorestframework-simplejwt + # drf-yasg +djangorestframework-simplejwt==5.2.0 + # via + # -r ci-requirements.in + # -r requirements.in +drf-yasg==1.21.4 + # via -r requirements.in +factory-boy==3.2.1 + # via pytest-factoryboy +faker==15.1.1 + # via factory-boy +flake8==5.0.4 + # via + # -r ci-requirements.in + # flake8-copyright-validator + # flake8-isort +flake8-copyright-validator==0.0.1 + # via + # -r ci-requirements.in + # -r requirements.in +flake8-isort==4.2.0 + # via -r ci-requirements.in +gunicorn==20.1.0 + # via -r requirements.in +idna==3.4 + # via requests +importlib-metadata==5.0.0 + # via flake8-copyright-validator +inflection==0.5.1 + # via + # drf-yasg + # pytest-factoryboy +iniconfig==1.1.1 + # via pytest +isort==5.10.1 + # via flake8-isort +itypes==1.2.0 + # via coreapi +jinja2==3.1.2 + # via coreschema +markupsafe==2.1.1 + # via jinja2 +mccabe==0.7.0 + # via flake8 +packaging==21.3 + # via + # build + # drf-yasg + # pytest +pep517==0.13.0 + # via build +pip-tools==6.8.0 + # via -r dev-requirements.in +pluggy==1.0.0 + # via pytest +psycopg2==2.9.3 + # via -r requirements.in +psycopg2-binary==2.9.5 + # via -r ci-requirements.in +py==1.11.0 + # via pytest +pycodestyle==2.9.1 + # via flake8 +pyflakes==2.5.0 + # via flake8 +pyjwt==2.4.0 + # via djangorestframework-simplejwt +pyparsing==3.0.9 + # via packaging +pytest==7.1.3 + # via + # -r ci-requirements.in + # -r dev-requirements.in + # pytest-django + # pytest-factoryboy +pytest-django==4.5.2 + # via + # -r ci-requirements.in + # -r dev-requirements.in +pytest-factoryboy==2.5.0 + # via -r ci-requirements.in +python-dateutil==2.8.2 + # via faker +python-dotenv==0.21.0 + # via + # -r ci-requirements.in + # -r requirements.in +pytz==2022.2.1 + # via + # django + # djangorestframework + # drf-yasg +requests==2.28.1 + # via coreapi +ruamel-yaml==0.17.21 + # via drf-yasg +ruamel-yaml-clib==0.2.7 + # via ruamel-yaml +six==1.16.0 + # via python-dateutil +sqlparse==0.4.2 + # via django +tomli==2.0.1 + # via + # build + # pep517 + # pytest +typing-extensions==4.4.0 + # via pytest-factoryboy +uritemplate==4.1.1 + # via + # coreapi + # drf-yasg +urllib3==1.26.12 + # via requests +wheel==0.37.1 + # via pip-tools +zipp==3.10.0 + # via importlib-metadata + +# The following packages are considered to be unsafe in a requirements file: +# pip +# setuptools diff --git a/testy/requirements/requirements.in b/testy/requirements/requirements.in new file mode 100644 index 0000000..5f5e008 --- /dev/null +++ b/testy/requirements/requirements.in @@ -0,0 +1,13 @@ +django==3.2 +python-dotenv==0.21.0 +django-mptt==0.13.4 +djangorestframework==3.13.1 +djangorestframework-simplejwt==5.2.0 +psycopg2==2.9.3 +django-simple-history==3.1.1 +django_filter==22.1 +drf-yasg==1.21.4 +flake8-copyright-validator==0.0.1 +django-cors-headers==3.13.0 +django-filter==22.1 +gunicorn==20.1.0 \ No newline at end of file diff --git a/testy/requirements/requirements.txt b/testy/requirements/requirements.txt new file mode 100644 index 0000000..afbffdd --- /dev/null +++ b/testy/requirements/requirements.txt @@ -0,0 +1,104 @@ +# +# This file is autogenerated by pip-compile with python 3.9 +# To update, run: +# +# pip-compile requirements.in +# +asgiref==3.5.2 + # via django +certifi==2022.9.24 + # via requests +charset-normalizer==2.1.1 + # via requests +coreapi==2.3.3 + # via drf-yasg +coreschema==0.0.4 + # via + # coreapi + # drf-yasg +django==3.2 + # via + # -r requirements.in + # django-cors-headers + # django-filter + # django-js-asset + # djangorestframework + # djangorestframework-simplejwt + # drf-yasg +django-cors-headers==3.13.0 + # via -r requirements.in +django-filter==22.1 + # via -r requirements.in +django-js-asset==2.0.0 + # via django-mptt +django-mptt==0.13.4 + # via -r requirements.in +django-simple-history==3.1.1 + # via -r requirements.in +djangorestframework==3.13.1 + # via + # -r requirements.in + # djangorestframework-simplejwt + # drf-yasg +djangorestframework-simplejwt==5.2.0 + # via -r requirements.in +drf-yasg==1.21.4 + # via -r requirements.in +flake8==5.0.4 + # via flake8-copyright-validator +flake8-copyright-validator==0.0.1 + # via -r requirements.in +gunicorn==20.1.0 + # via -r requirements.in +idna==3.4 + # via requests +importlib-metadata==5.0.0 + # via flake8-copyright-validator +inflection==0.5.1 + # via drf-yasg +itypes==1.2.0 + # via coreapi +jinja2==3.1.2 + # via coreschema +markupsafe==2.1.1 + # via jinja2 +mccabe==0.7.0 + # via flake8 +packaging==21.3 + # via drf-yasg +psycopg2==2.9.3 + # via -r requirements.in +pycodestyle==2.9.1 + # via flake8 +pyflakes==2.5.0 + # via flake8 +pyjwt==2.4.0 + # via djangorestframework-simplejwt +pyparsing==3.0.9 + # via packaging +python-dotenv==0.21.0 + # via -r requirements.in +pytz==2022.2.1 + # via + # django + # djangorestframework + # drf-yasg +requests==2.28.1 + # via coreapi +ruamel-yaml==0.17.21 + # via drf-yasg +ruamel-yaml-clib==0.2.7 + # via ruamel-yaml +sqlparse==0.4.2 + # via django +uritemplate==4.1.1 + # via + # coreapi + # drf-yasg +urllib3==1.26.12 + # via requests +zipp==3.10.0 + # via importlib-metadata + +# The following packages are considered to be unsafe in a requirements file: +# setuptools diff --git a/testy/scripts/ci/Dockerfile b/testy/scripts/ci/Dockerfile new file mode 100644 index 0000000..7b08120 --- /dev/null +++ b/testy/scripts/ci/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.9.13-alpine + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN mkdir /testy +WORKDIR /testy + +COPY ./testy/requirements/ci-requirements.txt /testy/requirements/ +RUN pip install -r requirements/ci-requirements.txt + +COPY . /testy \ No newline at end of file diff --git a/testy/scripts/dev/Dockerfile b/testy/scripts/dev/Dockerfile new file mode 100644 index 0000000..6c7ce15 --- /dev/null +++ b/testy/scripts/dev/Dockerfile @@ -0,0 +1,23 @@ +FROM python:3.9.13-alpine + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN apk update && \ + apk add --virtual build-deps gcc musl-dev && \ + apk add postgresql-dev && \ + apk add netcat-openbsd + +RUN mkdir /testy +WORKDIR /testy + +COPY ./requirements/dev-requirements.txt /testy/requirements/ + +RUN pip install -r requirements/dev-requirements.txt + +COPY ./scripts/entrypoint.sh /testy/scripts/entrypoint.sh +RUN chmod +x /testy/scripts/entrypoint.sh + +COPY . /testy + +CMD ["/testy/scripts/entrypoint.sh"] \ No newline at end of file diff --git a/testy/scripts/entrypoint.sh b/testy/scripts/entrypoint.sh new file mode 100644 index 0000000..b573005 --- /dev/null +++ b/testy/scripts/entrypoint.sh @@ -0,0 +1,10 @@ +#!/bin/sh +echo "Waiting for postgres..." +while ! nc -z db 5432; do + sleep 0.1 +done +echo "PostgreSQL started" +python manage.py migrate --no-input +python manage.py seed_db +python manage.py collectstatic --no-input +gunicorn testy.wsgi:application -w 4 --bind 0.0.0.0:8000 \ No newline at end of file diff --git a/testy/scripts/prod/Dockerfile b/testy/scripts/prod/Dockerfile new file mode 100644 index 0000000..baaa6bd --- /dev/null +++ b/testy/scripts/prod/Dockerfile @@ -0,0 +1,23 @@ +FROM python:3.9.13-alpine + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN apk update && \ + apk add --virtual build-deps gcc musl-dev && \ + apk add postgresql-dev && \ + apk add netcat-openbsd + +RUN mkdir /testy +WORKDIR /testy + +COPY ./requirements/requirements.txt /testy/requirements/ + +RUN pip install -r requirements/requirements.txt + +COPY ./scripts/entrypoint.sh /testy/scripts/entrypoint.sh +RUN chmod +x /testy/scripts/entrypoint.sh + +COPY . /testy + +CMD ["/testy/scripts/entrypoint.sh"] diff --git a/testy/scripts/tests/Dockerfile b/testy/scripts/tests/Dockerfile new file mode 100644 index 0000000..d04b1d8 --- /dev/null +++ b/testy/scripts/tests/Dockerfile @@ -0,0 +1,16 @@ +FROM python:3.9.13-alpine + +ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE 1 + +RUN apk update && \ + apk add --virtual build-deps gcc musl-dev && \ + apk add postgresql-dev && \ + apk add netcat-openbsd + +RUN mkdir /testy +WORKDIR /testy + +COPY ./requirements/dev-requirements.txt /testy/requirements/ + +RUN pip install -r requirements/dev-requirements.txt diff --git a/testy/templates/testy/admin_page.html b/testy/templates/testy/admin_page.html new file mode 100644 index 0000000..e663f57 --- /dev/null +++ b/testy/templates/testy/admin_page.html @@ -0,0 +1,38 @@ +{% extends 'testy/base_page.html' %} +{% load static %} + +{% block page-content-breadcrumbs %} + +{% endblock %} + +{% block page-content-header %} +
+
+

Administration

+
+
+{% endblock %} + + +{% block page-content-tabs %} + {% include "testy/components/tabs.html" with tabs=tabs active_tab=active_tab %} +{% endblock %} + +{% block page-content %}{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/administration/confirm_deletion.html b/testy/templates/testy/administration/confirm_deletion.html new file mode 100644 index 0000000..df23e69 --- /dev/null +++ b/testy/templates/testy/administration/confirm_deletion.html @@ -0,0 +1,33 @@ +{% extends 'testy/admin_page.html' %} + +{% load crispy_forms_tags %} +{% load static %} + + +{% block breadcrumb %} + {{ block.super }} + + +{% endblock %} + + +{% block page-content %} +
+
+
+
Confirm operation
+

You are going to delete {{ object }}. Are you sure?

+
+
+
+ {% csrf_token %} + Cancel + +
+
+
+
+ +{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/administration/overview.html b/testy/templates/testy/administration/overview.html new file mode 100644 index 0000000..5320606 --- /dev/null +++ b/testy/templates/testy/administration/overview.html @@ -0,0 +1,18 @@ +{% extends 'testy/admin_page.html' %} + +{% block breadcrumb %} + {{ block.super }} + +{% endblock %} + +{% block page-content %} +
+
+
+
+ There will be something. +
+
+
+
+{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/administration/parameter/create.html b/testy/templates/testy/administration/parameter/create.html new file mode 100644 index 0000000..3a277a6 --- /dev/null +++ b/testy/templates/testy/administration/parameter/create.html @@ -0,0 +1,38 @@ +{% extends 'testy/admin_page.html' %} + +{% load render_table from django_tables2 %} +{% load crispy_forms_tags %} + +{% block breadcrumb %} + {{ block.super }} + + + +{% endblock %} + +{% block page-content-header %} +
+
+

New Parameter

+
+
+{% endblock %} + +{% block page-content %} +
+ {% include "testy/components/alerts.html" with messages=messages %} +
+
+
+ {% crispy form form.helper %} +
+ +
+
+
+
+{% endblock %} diff --git a/testy/templates/testy/administration/parameter/edit.html b/testy/templates/testy/administration/parameter/edit.html new file mode 100644 index 0000000..4e8dd05 --- /dev/null +++ b/testy/templates/testy/administration/parameter/edit.html @@ -0,0 +1,42 @@ +{% extends 'testy/admin_page.html' %} + +{% load render_table from django_tables2 %} +{% load crispy_forms_tags %} + +{% block breadcrumb %} + {{ block.super }} + + + + +{% endblock %} + +{% block page-content-header %} +
+
+

{{object}} details

+
+
+{% endblock %} + +{% block page-content %} +
+
+ {% include "testy/components/alerts.html" with messages=messages %} +
+
+
Attributes
+ +
+
+ {% crispy form form.helper %} +
+ +
+
+ +
+
+
+
+{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/administration/project/create.html b/testy/templates/testy/administration/project/create.html new file mode 100644 index 0000000..86b941a --- /dev/null +++ b/testy/templates/testy/administration/project/create.html @@ -0,0 +1,33 @@ +{% extends 'testy/admin_page.html' %} + +{% load render_table from django_tables2 %} +{% load crispy_forms_tags %} + +{% block breadcrumb %} + {{ block.super }} + + +{% endblock %} + +{% block page-content-header %} +
+
+

New project

+
+
+{% endblock %} + +{% block page-content %} +
+ {% include "testy/components/alerts.html" with messages=messages %} +
+
+
+ {% crispy form form.helper %} +
+ +
+
+
+
+{% endblock %} diff --git a/testy/templates/testy/administration/project/edit.html b/testy/templates/testy/administration/project/edit.html new file mode 100644 index 0000000..4e4d305 --- /dev/null +++ b/testy/templates/testy/administration/project/edit.html @@ -0,0 +1,53 @@ +{% extends 'testy/admin_page.html' %} + +{% load render_table from django_tables2 %} +{% load crispy_forms_tags %} + +{% block breadcrumb %} + {{ block.super }} + + +{% endblock %} + +{% block page-content-header %} +
+
+

{{ object }} details

+
+
+{% endblock %} + +{% block page-content %} +
+
+ {% include "testy/components/alerts.html" with messages=messages %} +
+
+
Attributes
+
+
+ {% crispy form form.helper %} +
+ +
+
+
+
+
+
+
+
Parameters
+
+
+ + + Add parameter + + {% render_table parameters_table %} +
+
+
+
+
+{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/administration/project/index.html b/testy/templates/testy/administration/project/index.html new file mode 100644 index 0000000..69a84f5 --- /dev/null +++ b/testy/templates/testy/administration/project/index.html @@ -0,0 +1,35 @@ +{% extends 'testy/admin_page.html' %} + +{% load render_table from django_tables2 %} +{% load crispy_forms_tags %} +{% load static %} + +{% block breadcrumb %} + {{ block.super }} + +{% endblock %} + +{% block page-content-header %} +
+
+

Projects

+
+
+{% endblock %} + +{% block page-content %} +
+ {% include "testy/components/alerts.html" with messages=messages %} + +
+
+ {% render_table table %} +
+
+
+{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/administration/users/create.html b/testy/templates/testy/administration/users/create.html new file mode 100644 index 0000000..4b0fe77 --- /dev/null +++ b/testy/templates/testy/administration/users/create.html @@ -0,0 +1,32 @@ +{% extends 'testy/admin_page.html' %} + +{% load crispy_forms_tags %} + +{% block breadcrumb %} + {{ block.super }} + + +{% endblock %} + +{% block page-content-header %} +
+
+

New user

+
+
+{% endblock %} + +{% block page-content %} +
+ {% include "testy/components/alerts.html" with messages=messages %} +
+
+
+ {% crispy form form.helper %} +
+
+
+
+{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/administration/users/edit.html b/testy/templates/testy/administration/users/edit.html new file mode 100644 index 0000000..34f8b72 --- /dev/null +++ b/testy/templates/testy/administration/users/edit.html @@ -0,0 +1,32 @@ +{% extends 'testy/admin_page.html' %} + +{% load crispy_forms_tags %} + +{% block breadcrumb %} + {{ block.super }} + + +{% endblock %} + +{% block page-content-header %} +
+
+

{{object}} details

+
+
+{% endblock %} + +{% block page-content %} +
+ {% include "testy/components/alerts.html" with messages=messages %} +
+
+
+ {% crispy form form.helper %} +
+
+
+
+{% endblock %} diff --git a/testy/templates/testy/administration/users/index.html b/testy/templates/testy/administration/users/index.html new file mode 100644 index 0000000..9ef9515 --- /dev/null +++ b/testy/templates/testy/administration/users/index.html @@ -0,0 +1,35 @@ +{% extends 'testy/admin_page.html' %} + +{% load render_table from django_tables2 %} +{% load crispy_forms_tags %} +{% load static %} + +{% block breadcrumb %} + {{ block.super }} + +{% endblock %} + +{% block page-content-header %} +
+
+

Users

+
+
+{% endblock %} + +{% block page-content %} +
+ {% include "testy/components/alerts.html" with messages=messages %} + +
+
+ {% render_table table %} +
+
+
+{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/auth.html b/testy/templates/testy/auth.html new file mode 100644 index 0000000..521d0f6 --- /dev/null +++ b/testy/templates/testy/auth.html @@ -0,0 +1,55 @@ +{% extends 'testy/base.html' %} + +{% block content %} +
+
+
+ {% csrf_token %} +
+
+
+
+
+

Test Management System

+ + {% if login_form.non_field_errors %} +
+ {% for error in login_form.non_field_errors %} +

{{ error }}

+ {% endfor %} +
+ {% endif %} + +
+ + {% if login_form.username.errors %} + {% for error in login_form.username.errors %} + {{ error }} + {% endfor %} + {% endif %} +
+
+ + {% if login_form.password.errors %} + {% for error in login_form.password.errors %} + {{ error }} + {% endfor %} + {% endif %} +
+ +
+ +
+
+
+
+
+
+
+
+
+{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/base.html b/testy/templates/testy/base.html new file mode 100644 index 0000000..70a8add --- /dev/null +++ b/testy/templates/testy/base.html @@ -0,0 +1,31 @@ +{% load static %} + + + + + + + + {% block stylesheets %} + + {% endblock %} + + TestY TMS | {% block title %}Base template{% endblock %} + + + +{% block header %}{% endblock %} + +
+ {% block content %}{% endblock %} +
+ +{% block footer %}{% endblock %} + +{% block javascripts %} + +{% endblock %} + + + \ No newline at end of file diff --git a/testy/templates/testy/base_page.html b/testy/templates/testy/base_page.html new file mode 100644 index 0000000..66f9722 --- /dev/null +++ b/testy/templates/testy/base_page.html @@ -0,0 +1,21 @@ +{% extends 'testy/base.html' %} + +{% block header %} + {% include "testy/components/header.html" %} +{% endblock %} + +{% block content %} + + {% block page-content-breadcrumbs %}{% endblock %} + {% block page-content-header %}{% endblock %} + +
+ {% block page-content-tabs %}{% endblock %} + {% block page-content %}{% endblock %} +
+ +{% endblock %} + +{% block footer %} + {% include "testy/components/footer.html" %} +{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/components/alerts.html b/testy/templates/testy/components/alerts.html new file mode 100644 index 0000000..f213efb --- /dev/null +++ b/testy/templates/testy/components/alerts.html @@ -0,0 +1,6 @@ +{% for message in messages %} + +{% endfor %} \ No newline at end of file diff --git a/testy/templates/testy/components/card.html b/testy/templates/testy/components/card.html new file mode 100644 index 0000000..918552f --- /dev/null +++ b/testy/templates/testy/components/card.html @@ -0,0 +1,21 @@ +{% load static %} + +
+
+
+
+ +
+ +
+
{{ project.name }}
+
{{ project.description|linebreaks }}
+ + Test Runs +
+ Test Suites +
+ +
+
+
diff --git a/testy/templates/testy/components/footer.html b/testy/templates/testy/components/footer.html new file mode 100644 index 0000000..b3e383a --- /dev/null +++ b/testy/templates/testy/components/footer.html @@ -0,0 +1,9 @@ +
+
+ +
+
\ No newline at end of file diff --git a/testy/templates/testy/components/header.html b/testy/templates/testy/components/header.html new file mode 100644 index 0000000..47488a1 --- /dev/null +++ b/testy/templates/testy/components/header.html @@ -0,0 +1,46 @@ +{% load static %} + +
+ +
\ No newline at end of file diff --git a/testy/templates/testy/components/tabs.html b/testy/templates/testy/components/tabs.html new file mode 100644 index 0000000..823eb0d --- /dev/null +++ b/testy/templates/testy/components/tabs.html @@ -0,0 +1,13 @@ + \ No newline at end of file diff --git a/testy/templates/testy/dashboard.html b/testy/templates/testy/dashboard.html new file mode 100644 index 0000000..0ef2805 --- /dev/null +++ b/testy/templates/testy/dashboard.html @@ -0,0 +1,62 @@ +{% extends 'testy/base_page.html' %} + +{% block page-content %} + +
+
+ +
+
+
+

{{ projects.count }}

+ +
+
+
+
+

{{ users_count }}

+ +
+
+
+
+

{{ tests_count }}

+ +
+
+
+ +

Projects

+ +
+
    + {% for project in projects %} +
  • +
    +
    + +
    + +
    +
    {{ project.name }}
    +
    {{ project.description|linebreaks }}
    + + + Test Suites + +
    + + Test Plans + +
    + +
    +
  • + {% endfor %} +
+
+ +
+
+ +{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/project/overview.html b/testy/templates/testy/project/overview.html new file mode 100644 index 0000000..82ed5b3 --- /dev/null +++ b/testy/templates/testy/project/overview.html @@ -0,0 +1,18 @@ +{% extends 'testy/project_page.html' %} + +{% block breadcrumb %} + {{ block.super }} + +{% endblock %} + +{% block page-content %} +
+
+
+
+ There will be something. +
+
+
+
+{% endblock %} \ No newline at end of file diff --git a/testy/templates/testy/project/test_runs.html b/testy/templates/testy/project/test_runs.html new file mode 100644 index 0000000..3fea9ac --- /dev/null +++ b/testy/templates/testy/project/test_runs.html @@ -0,0 +1,26 @@ +{% extends 'testy/project_page.html' %} + +{% load static %} + +{% block breadcrumb %} + {{ block.super }} + + +{% endblock %} + +{% block page-content %} +
+
+
+{% endblock %} + +{% block javascripts %} + {{ block.super }} + + + + +{% endblock %} + diff --git a/testy/templates/testy/project/test_suites.html b/testy/templates/testy/project/test_suites.html new file mode 100644 index 0000000..53eb442 --- /dev/null +++ b/testy/templates/testy/project/test_suites.html @@ -0,0 +1,23 @@ +{% extends 'testy/project_page.html' %} +{% load static %} + +{% block breadcrumb %} + {{ block.super }} + + +{% endblock %} + +{% block page-content %} +
+
+
+{% endblock %} + +{% block javascripts %} + {{ block.super }} + + + +{% endblock %} diff --git a/testy/templates/testy/project_page.html b/testy/templates/testy/project_page.html new file mode 100644 index 0000000..9d22918 --- /dev/null +++ b/testy/templates/testy/project_page.html @@ -0,0 +1,32 @@ +{% extends 'testy/base_page.html' %} + +{% load static %} + +{% block page-content-breadcrumbs %} + +{% endblock %} + +{% block page-content-header %} +
+
+

{{ project.name }}

+
+
+{% endblock %} + +{% block page-content-tabs %} + {% include "testy/components/tabs.html" with tabs=tabs active_tab=active_tab %} +{% endblock %} + + +{% block page-content %}{% endblock %} diff --git a/testy/templates/testy/user_profile.html b/testy/templates/testy/user_profile.html new file mode 100644 index 0000000..1514018 --- /dev/null +++ b/testy/templates/testy/user_profile.html @@ -0,0 +1,54 @@ +{% extends 'testy/base_page.html' %} + +{% load crispy_forms_tags %} + +{% block page-content-breadcrumbs %} + +{% endblock %} + +{% block page-content-tabs %} + {% include "testy/components/tabs.html" with tabs=tabs active=active_tab %} +{% endblock %} + +{% block page-content-header %} +
+
+

Profile settings

+
+
+{% endblock %} + +{% block page-content %} +
+ +
+
+ + {% for message in messages %} + + {% endfor %} + +
+ {% crispy form form.helper %} +
+
+
+ +
+{% endblock %} diff --git a/testy/tests_description/__init__.py b/testy/tests_description/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/tests_description/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/tests_description/admin.py b/testy/tests_description/admin.py new file mode 100644 index 0000000..5ed627c --- /dev/null +++ b/testy/tests_description/admin.py @@ -0,0 +1,48 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.contrib import admin +from mptt.admin import MPTTModelAdmin +from tests_description.models import TestCase, TestSuite + +from testy.admin import BaseAdmin + + +@admin.register(TestSuite) +class TestSuiteAdmin(BaseAdmin, MPTTModelAdmin): + list_display = ('name', 'project', 'parent',) + search_fields = ('name',) + + +@admin.register(TestCase) +class TestCaseAdmin(BaseAdmin): + list_display = ('name', 'project', 'suite', ) + search_fields = ('name',) diff --git a/testy/tests_description/api/v1/__init__.py b/testy/tests_description/api/v1/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/tests_description/api/v1/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/tests_description/api/v1/serializers.py b/testy/tests_description/api/v1/serializers.py new file mode 100644 index 0000000..80c0ab1 --- /dev/null +++ b/testy/tests_description/api/v1/serializers.py @@ -0,0 +1,74 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from rest_framework import serializers +from rest_framework.fields import SerializerMethodField +from rest_framework.relations import HyperlinkedIdentityField +from rest_framework.serializers import ModelSerializer +from tests_description.models import TestCase, TestSuite + + +class TestCaseSerializer(ModelSerializer): + url = HyperlinkedIdentityField(view_name='api:v1:testcase-detail') + + class Meta: + model = TestCase + fields = ('id', 'name', 'project', 'suite', 'setup', 'scenario', 'teardown', 'estimate', 'url') + + +class TestSuiteTreeSerializer(ModelSerializer): + children = SerializerMethodField() + test_cases = SerializerMethodField('get_test_case_serializer') + key = serializers.IntegerField(source='id') + value = serializers.IntegerField(source='id') + title = serializers.CharField(source='name') + + class Meta: + model = TestSuite + fields = ('id', 'value', 'name', 'key', 'title', 'level', 'children', 'test_cases') + + def get_children(self, value): + return self.__class__(value.get_children(), many=True).data + + def get_test_case_serializer(self, obj): + serializer_context = {'request': self.context.get('request')} + test_cases = TestCase.objects.all().filter(suite=obj) + serializer = TestCaseSerializer(test_cases, many=True, context=serializer_context) + return serializer.data + + +class TestSuiteSerializer(ModelSerializer): + url = HyperlinkedIdentityField(view_name='api:v1:testsuite-detail') + test_cases = TestCaseSerializer(many=True, read_only=True) + + class Meta: + model = TestSuite + fields = ('id', 'name', 'parent', 'project', 'url', 'test_cases',) diff --git a/testy/tests_description/api/v1/urls.py b/testy/tests_description/api/v1/urls.py new file mode 100644 index 0000000..10916aa --- /dev/null +++ b/testy/tests_description/api/v1/urls.py @@ -0,0 +1,39 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from rest_framework.routers import SimpleRouter +from tests_description.api.v1 import views + +router = SimpleRouter() +router.register('cases', views.TestCaseViewSet) +router.register('suites', views.TestSuiteViewSet, basename='testsuite') + +urlpatterns = router.urls diff --git a/testy/tests_description/api/v1/views.py b/testy/tests_description/api/v1/views.py new file mode 100644 index 0000000..c923b25 --- /dev/null +++ b/testy/tests_description/api/v1/views.py @@ -0,0 +1,74 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . +from django_filters.rest_framework import DjangoFilterBackend +from rest_framework.viewsets import ModelViewSet +from tests_description.api.v1.serializers import TestCaseSerializer, TestSuiteSerializer, TestSuiteTreeSerializer +from tests_description.selectors.cases import TestCaseSelector +from tests_description.selectors.suites import TestSuiteSelector +from tests_description.services.cases import TestCaseService +from tests_description.services.suites import TestSuiteService +from utilities.request import get_boolean + + +class TestCaseViewSet(ModelViewSet): + queryset = TestCaseSelector().case_list() + serializer_class = TestCaseSerializer + filter_backends = [DjangoFilterBackend] + filterset_fields = ['project', 'suite'] + + def perform_create(self, serializer: TestCaseSerializer): + serializer.instance = TestCaseService().case_create(serializer.validated_data) + + def perform_update(self, serializer: TestCaseSerializer): + serializer.instance = TestCaseService().case_update(serializer.instance, serializer.validated_data) + + +class TestSuiteViewSet(ModelViewSet): + queryset = TestSuiteSelector().suite_list() + serializer_class = TestSuiteSerializer + filter_backends = [DjangoFilterBackend] + filterset_fields = ['project'] + + def perform_create(self, serializer: TestSuiteSerializer): + serializer.instance = TestSuiteService().suite_create(serializer.validated_data) + + def perform_update(self, serializer: TestSuiteSerializer): + serializer.instance = TestSuiteService().suite_update(serializer.instance, serializer.validated_data) + + def get_serializer_class(self): + if get_boolean(self.request, 'treeview'): + return TestSuiteTreeSerializer + return TestSuiteSerializer + + def get_queryset(self): + if get_boolean(self.request, 'treeview'): + return TestSuiteSelector().suite_without_parent() + return super().get_queryset() diff --git a/testy/tests_description/apps.py b/testy/tests_description/apps.py new file mode 100644 index 0000000..d5d93c1 --- /dev/null +++ b/testy/tests_description/apps.py @@ -0,0 +1,37 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.apps import AppConfig + + +class TestsDescriptionConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'tests_description' diff --git a/testy/tests_description/migrations/0001_initial.py b/testy/tests_description/migrations/0001_initial.py new file mode 100644 index 0000000..82617ac --- /dev/null +++ b/testy/tests_description/migrations/0001_initial.py @@ -0,0 +1,84 @@ +# Generated by Django 3.2 on 2022-10-07 07:55 + +from django.conf import settings +import django.core.validators +from django.db import migrations, models +import django.db.models.deletion +import mptt.fields +import simple_history.models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('core', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='TestSuite', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), + ('name', models.CharField(max_length=255)), + ('lft', models.PositiveIntegerField(editable=False)), + ('rght', models.PositiveIntegerField(editable=False)), + ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), + ('level', models.PositiveIntegerField(editable=False)), + ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='child_test_suites', to='tests_description.testsuite')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='test_suites', to='core.project')), + ], + options={ + 'default_related_name': 'test_suites', + }, + ), + migrations.CreateModel( + name='TestCase', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), + ('name', models.CharField(max_length=255)), + ('setup', models.TextField(blank=True)), + ('scenario', models.TextField()), + ('teardown', models.TextField(blank=True)), + ('estimate', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='test_cases', to='core.project')), + ('suite', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='test_cases', to='tests_description.testsuite')), + ], + options={ + 'default_related_name': 'test_cases', + }, + ), + migrations.CreateModel( + name='HistoricalTestCase', + fields=[ + ('id', models.BigIntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')), + ('created_at', models.DateTimeField(blank=True, editable=False, verbose_name='created at')), + ('updated_at', models.DateTimeField(blank=True, editable=False, verbose_name='updated at')), + ('name', models.CharField(max_length=255)), + ('setup', models.TextField(blank=True)), + ('scenario', models.TextField()), + ('teardown', models.TextField(blank=True)), + ('estimate', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('history_id', models.AutoField(primary_key=True, serialize=False)), + ('history_date', models.DateTimeField(db_index=True)), + ('history_change_reason', models.CharField(max_length=100, null=True)), + ('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)), + ('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), + ('project', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.project')), + ('suite', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='tests_description.testsuite')), + ], + options={ + 'verbose_name': 'historical test case', + 'verbose_name_plural': 'historical test cases', + 'ordering': ('-history_date', '-history_id'), + 'get_latest_by': ('history_date', 'history_id'), + }, + bases=(simple_history.models.HistoricalChanges, models.Model), + ), + ] diff --git a/testy/tests_description/migrations/__init__.py b/testy/tests_description/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/testy/tests_description/models.py b/testy/tests_description/models.py new file mode 100644 index 0000000..857bf40 --- /dev/null +++ b/testy/tests_description/models.py @@ -0,0 +1,75 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from core.models import Project +from django.conf import settings +from django.core.validators import MinValueValidator +from django.db import models +from mptt.models import MPTTModel, TreeForeignKey +from simple_history.models import HistoricalRecords + +from testy.models import BaseModel + + +class TestSuite(MPTTModel, BaseModel): + parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='child_test_suites') + project = models.ForeignKey(Project, on_delete=models.CASCADE) + name = models.CharField(max_length=settings.CHAR_FIELD_MAX_LEN) + + class Meta: + default_related_name = 'test_suites' + + class MPTTMeta: + order_insertion_by = ('name',) + + def __str__(self): + return self.name + + +class TestCase(BaseModel): + name = models.CharField(max_length=settings.CHAR_FIELD_MAX_LEN) + project = models.ForeignKey(Project, on_delete=models.CASCADE) + suite = models.ForeignKey(TestSuite, on_delete=models.CASCADE, related_name='test_cases') + setup = models.TextField(blank=True) + scenario = models.TextField() + teardown = models.TextField(blank=True) + estimate = models.IntegerField( + null=True, + blank=True, + validators=[MinValueValidator(settings.MIN_VALUE_POSITIVE_INTEGER)] + ) + history = HistoricalRecords() + + class Meta: + default_related_name = 'test_cases' + + def __str__(self): + return self.name diff --git a/testy/tests_description/selectors/__init__.py b/testy/tests_description/selectors/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/tests_description/selectors/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/tests_description/selectors/cases.py b/testy/tests_description/selectors/cases.py new file mode 100644 index 0000000..be9d121 --- /dev/null +++ b/testy/tests_description/selectors/cases.py @@ -0,0 +1,42 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.db.models import QuerySet +from tests_description.models import TestCase + + +class TestCaseSelector: + def case_list(self) -> QuerySet[TestCase]: + return TestCase.objects.all() + + def case_version(self, case: TestCase) -> int: + history = case.history.first() + return history.history_id diff --git a/testy/tests_description/selectors/suites.py b/testy/tests_description/selectors/suites.py new file mode 100644 index 0000000..35f033a --- /dev/null +++ b/testy/tests_description/selectors/suites.py @@ -0,0 +1,41 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.db.models import QuerySet +from tests_description.models import TestSuite + + +class TestSuiteSelector: + def suite_list(self) -> QuerySet[TestSuite]: + return TestSuite.objects.all() + + def suite_without_parent(self) -> QuerySet[TestSuite]: + return QuerySet(model=TestSuite).filter(parent=None).order_by('name') diff --git a/testy/tests_description/services.py b/testy/tests_description/services.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/tests_description/services.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/tests_description/services/__init__.py b/testy/tests_description/services/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/tests_description/services/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/tests_description/services/cases.py b/testy/tests_description/services/cases.py new file mode 100644 index 0000000..170fed8 --- /dev/null +++ b/testy/tests_description/services/cases.py @@ -0,0 +1,51 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import Any, Dict + +from tests_description.models import TestCase + + +class TestCaseService: + non_side_effect_fields = ['name', 'project', 'suite', 'setup', 'scenario', 'teardown', 'estimate'] + + def case_create(self, data: Dict[str, Any]) -> TestCase: + return TestCase.model_create( + fields=self.non_side_effect_fields, + data=data, + ) + + def case_update(self, case: TestCase, data: Dict[str, Any]) -> TestCase: + case, _ = case.model_update( + fields=self.non_side_effect_fields, + data=data, + ) + return case diff --git a/testy/tests_description/services/suites.py b/testy/tests_description/services/suites.py new file mode 100644 index 0000000..673c94e --- /dev/null +++ b/testy/tests_description/services/suites.py @@ -0,0 +1,51 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import Any, Dict + +from tests_description.models import TestSuite + + +class TestSuiteService: + non_side_effect_fields = ['parent', 'project', 'name'] + + def suite_create(self, data: Dict[str, Any]) -> TestSuite: + return TestSuite.model_create( + fields=self.non_side_effect_fields, + data=data, + ) + + def suite_update(self, suite: TestSuite, data: Dict[str, Any]) -> TestSuite: + suite, _ = suite.model_update( + fields=self.non_side_effect_fields, + data=data, + ) + return suite diff --git a/testy/tests_representation/__init__.py b/testy/tests_representation/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/tests_representation/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/tests_representation/admin.py b/testy/tests_representation/admin.py new file mode 100644 index 0000000..9bc6e32 --- /dev/null +++ b/testy/tests_representation/admin.py @@ -0,0 +1,54 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.contrib import admin +from mptt.admin import MPTTModelAdmin +from tests_representation.models import Test, TestPlan, TestResult + +from testy.admin import BaseAdmin + + +@admin.register(TestPlan) +class TestPlanAdmin(BaseAdmin, MPTTModelAdmin): + list_display = ('parent', 'started_at', 'due_date', 'finished_at', 'is_archive') + search_fields = ('id',) + + +@admin.register(Test) +class TestAdmin(BaseAdmin): + list_display = ('case', 'plan', 'user', 'is_archive') + search_fields = ('id',) + + +@admin.register(TestResult) +class TestResultAdmin(BaseAdmin): + list_display = ('test', 'status', 'comment', 'user') + search_fields = ('name',) diff --git a/testy/tests_representation/api/v1/__init__.py b/testy/tests_representation/api/v1/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/tests_representation/api/v1/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/tests_representation/api/v1/serializers.py b/testy/tests_representation/api/v1/serializers.py new file mode 100644 index 0000000..7ad1b8e --- /dev/null +++ b/testy/tests_representation/api/v1/serializers.py @@ -0,0 +1,165 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from rest_framework.fields import SerializerMethodField +from rest_framework.relations import HyperlinkedIdentityField, PrimaryKeyRelatedField +from rest_framework.serializers import ModelSerializer +from tests_description.api.v1.serializers import TestCaseSerializer +from tests_description.selectors.cases import TestCaseSelector +from tests_representation.models import Parameter, Test, TestPlan, TestResult +from tests_representation.selectors.parameters import ParameterSelector +from tests_representation.selectors.results import TestResultSelector + + +class ParameterSerializer(ModelSerializer): + url = HyperlinkedIdentityField(view_name='api:v1:parameter-detail') + + class Meta: + model = Parameter + fields = ('id', 'project', 'data', 'group_name', 'url') + + +class TestPlanUpdateSerializer(ModelSerializer): + test_cases = PrimaryKeyRelatedField(queryset=TestCaseSelector().case_list(), many=True, required=False) + + class Meta: + model = TestPlan + fields = ( + 'id', 'name', 'parent', 'test_cases', 'started_at', 'due_date', 'finished_at', 'is_archive', 'project', + ) + + +class TestPlanInputSerializer(ModelSerializer): + test_cases = PrimaryKeyRelatedField(queryset=TestCaseSelector().case_list(), many=True, required=False) + parameters = PrimaryKeyRelatedField(queryset=ParameterSelector().parameter_list(), many=True, required=False) + + class Meta: + model = TestPlan + fields = ( + 'id', 'name', 'parent', 'test_cases', 'parameters', 'started_at', 'due_date', 'finished_at', 'is_archive', + 'project', + ) + + +class TestSerializer(ModelSerializer): + url = HyperlinkedIdentityField(view_name='api:v1:test-detail') + + class Meta: + model = Test + fields = ('id', 'project', 'case', 'plan', 'user', 'is_archive', 'created_at', 'updated_at', 'url') + + read_only_fields = ('project',) + + +class TestResultSerializer(ModelSerializer): + url = HyperlinkedIdentityField(view_name='api:v1:testresult-detail') + + class Meta: + model = TestResult + fields = ( + 'id', 'project', 'status', 'test', 'user', 'comment', 'is_archive', 'test_case_version', 'created_at', + 'updated_at', 'url', 'execution_time' + ) + + read_only_fields = ('test_case_version', 'project', 'test') + + +class TestPlanTreeSerializer(ModelSerializer): + children = SerializerMethodField() + title = SerializerMethodField() + + class Meta: + model = TestPlan + fields = ('id', 'name', 'level', 'children', 'title') + + def get_title(self, instance): + if instance.parameters is None: + return instance.name + parameters = ParameterSelector().parameter_name_list_by_ids(instance.parameters) + return '{0} [{1}]'.format(instance.name, ', '.join(parameters)) + + def get_children(self, value): + return self.__class__(value.get_children(), many=True).data + + +class TestPlanTestResultSerializer(ModelSerializer): + status = SerializerMethodField() + updated_at = SerializerMethodField() + + class Meta: + model = TestResult + fields = ( + 'id', 'status', 'comment', 'test_case_version', 'created_at', 'updated_at' + ) + + def get_status(self, instance): + return instance.get_status_display() + + def get_updated_at(self, instance): + return instance.updated_at.strftime("%d.%m.%Y %H:%M:%S") + + +class TestPlanTestSerializer(ModelSerializer): + case = TestCaseSerializer() + current_result = SerializerMethodField() + test_results = TestPlanTestResultSerializer(many=True, read_only=True) + + def get_test_results(self, instance): + return TestResultSelector().result_list_by_test_id(instance.id) + + class Meta: + model = Test + fields = ('id', 'case', 'plan', 'is_archive', 'created_at', 'updated_at', 'test_results', + 'current_result') + + def get_current_result(self, instance): + if instance.test_results.last(): + return instance.test_results.last().get_status_display() + return None + + +class TestPlanOutputSerializer(ModelSerializer): + url = HyperlinkedIdentityField(view_name='api:v1:testplan-detail') + tests = TestPlanTestSerializer(many=True, read_only=True) + title = SerializerMethodField() + + class Meta: + model = TestPlan + fields = ( + 'id', 'name', 'parent', 'parameters', 'started_at', 'due_date', 'finished_at', 'is_archive', + 'tests', 'project', 'child_test_plans', 'url', 'title' + ) + + def get_title(self, instance): + if instance.parameters is None: + return instance.name + parameters = ParameterSelector().parameter_name_list_by_ids(instance.parameters) + return '{0} [{1}]'.format(instance.name, ', '.join(parameters)) diff --git a/testy/tests_representation/api/v1/urls.py b/testy/tests_representation/api/v1/urls.py new file mode 100644 index 0000000..45da339 --- /dev/null +++ b/testy/tests_representation/api/v1/urls.py @@ -0,0 +1,76 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.urls import path +from rest_framework.routers import SimpleRouter +from tests_representation.api.v1 import views +from tests_representation.api.v1.views import TestPLanDetailView, TestPLanListView, TestResultChoicesView + +router = SimpleRouter() +router.register('parameters', views.ParameterViewSet) +router.register('results', views.TestResultViewSet) + +test_lists = views.TestListViewSet.as_view({'get': 'list'}) +test_detail = views.TestDetailViewSet.as_view({ + 'get': 'retrieve', + 'put': 'update', + 'patch': 'partial_update', +}) + +result_detail = views.TestResultViewSet.as_view({ + 'get': 'retrieve', + 'put': 'update', + 'patch': 'partial_update' +}) + +result_list = views.TestResultViewSet.as_view({ + 'get': 'list' +}) + +results_by_test = views.TestDetailViewSet.as_view({ + 'post': 'add_result', + 'get': 'results_by_test' +}) + +urlpatterns = [ + path('tests/', test_lists, name='test-list'), + path('tests//', test_detail, name='test-detail'), + path('tests//results/', results_by_test, name='results-by-test'), + + path('testplans/', TestPLanListView.as_view(), name='testplan-list'), + path('testplans//', TestPLanDetailView.as_view(), name='testplan-detail'), + + path('results/', result_list, name='result-list'), + path('results/:pk/', result_detail, name='result-detail'), + + path('test-results/', TestResultChoicesView.as_view(), name='test-results'), +] +urlpatterns += router.urls diff --git a/testy/tests_representation/api/v1/views.py b/testy/tests_representation/api/v1/views.py new file mode 100644 index 0000000..c47362a --- /dev/null +++ b/testy/tests_representation/api/v1/views.py @@ -0,0 +1,173 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.core.exceptions import ObjectDoesNotExist +from django.forms import model_to_dict +from django.http import Http404 +from rest_framework import mixins, status +from rest_framework.decorators import action +from rest_framework.response import Response +from rest_framework.views import APIView +from rest_framework.viewsets import GenericViewSet, ModelViewSet +from tests_representation.api.v1.serializers import ( + ParameterSerializer, + TestPlanInputSerializer, + TestPlanOutputSerializer, + TestPlanUpdateSerializer, + TestResultSerializer, + TestSerializer, +) +from tests_representation.choices import TestStatuses +from tests_representation.selectors.parameters import ParameterSelector +from tests_representation.selectors.results import TestResultSelector +from tests_representation.selectors.testplan import TestPlanSelector +from tests_representation.selectors.tests import TestSelector +from tests_representation.services.parameters import ParameterService +from tests_representation.services.results import TestResultService +from tests_representation.services.testplans import TestPLanService +from tests_representation.services.tests import TestService + + +class ParameterViewSet(ModelViewSet): + queryset = ParameterSelector().parameter_list() + serializer_class = ParameterSerializer + + def perform_create(self, serializer: ParameterSerializer): + serializer.instance = ParameterService().parameter_create(serializer.validated_data) + + def perform_update(self, serializer: ParameterSerializer): + serializer.instance = ParameterService().parameter_update(serializer.instance, serializer.validated_data) + + +class TestPLanListView(APIView): + def get_view_name(self): + return "Test Plan List" + + def get(self, request): + qs = TestPlanSelector().testplan_list() + serializer = TestPlanOutputSerializer(qs, many=True, context={'request': request}) + return Response(serializer.data) + + def post(self, request): + serializer = TestPlanInputSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + test_plans = TestPLanService().testplan_create(serializer.validated_data) + return Response(TestPlanOutputSerializer(test_plans, many=True, context={'request': request}).data, + status=status.HTTP_201_CREATED) + + +class TestPLanDetailView(APIView): + def get_view_name(self): + return "Test Plan Detail" + + def get_object(self, pk): + try: + return TestPlanSelector().testplan_get_by_pk(pk) + except ObjectDoesNotExist: + raise Http404 + + def get(self, request, pk): + test_plan = self.get_object(pk) + serializer = TestPlanOutputSerializer(test_plan, context={"request": request}) + return Response(serializer.data) + + def patch(self, request, pk): + test_plan = self.get_object(pk) + serializer = TestPlanUpdateSerializer(data=request.data, instance=test_plan, context={"request": request}, + partial=True) + serializer.is_valid(raise_exception=True) + test_plan = TestPLanService().testplan_update(test_plan=test_plan, data=serializer.validated_data) + return Response(TestPlanOutputSerializer(test_plan, context={'request': request}).data, + status=status.HTTP_200_OK) + + def delete(self, request, pk): + test_plan = self.get_object(pk) + TestPLanService().testplan_delete(test_plan=test_plan) + return Response(status=status.HTTP_204_NO_CONTENT) + + +class TestListViewSet(mixins.ListModelMixin, GenericViewSet): + queryset = TestSelector().test_list() + serializer_class = TestSerializer + + def get_view_name(self): + return "Test List" + + def perform_update(self, serializer: TestSerializer): + serializer.instance = TestService().test_update(serializer.instance, serializer.validated_data) + + +class TestDetailViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericViewSet): + queryset = TestSelector().test_list() + serializer_class = TestSerializer + + def get_view_name(self): + return "Test Instance" + + def get_serializer_class(self): + if self.action == 'add_result' or self.action == 'results_by_test': + return TestResultSerializer + return TestSerializer + + @action(detail=False, methods=['POST']) + def add_result(self, request, pk): + serializer = self.get_serializer_class() + serializer = serializer(data=request.data, context={'request': request}) + serializer.is_valid(raise_exception=True) + result = TestResultService().result_create(serializer.validated_data, pk) + return Response(model_to_dict(result), status=status.HTTP_201_CREATED) + + @action(detail=False) + def results_by_test(self, request, pk): + queryset = self.filter_queryset(TestResultSelector().result_list_by_test_id(pk)) + page = self.paginate_queryset(queryset) + serializer = self.get_serializer_class() + if page is not None: + serializer = serializer(page, many=True, context={'request': request}) + return self.get_paginated_response(serializer.data) + + serializer = serializer(queryset, many=True, context={'request': request}) + return Response(serializer.data) + + +class TestResultViewSet(mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): + queryset = TestResultSelector().result_list() + serializer_class = TestResultSerializer + + def perform_update(self, serializer: TestResultSerializer): + serializer.instance = TestResultService().result_update(serializer.instance, serializer.validated_data) + + +class TestResultChoicesView(APIView): + + def get(self, request): + choices = [{'id': status_id, 'status': status_name} for status_id, status_name in TestStatuses.choices] + return Response(choices, status=status.HTTP_200_OK) diff --git a/testy/tests_representation/apps.py b/testy/tests_representation/apps.py new file mode 100644 index 0000000..609612b --- /dev/null +++ b/testy/tests_representation/apps.py @@ -0,0 +1,37 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.apps import AppConfig + + +class TestsRepresentationConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'tests_representation' diff --git a/testy/tests_representation/choices.py b/testy/tests_representation/choices.py new file mode 100644 index 0000000..e854c41 --- /dev/null +++ b/testy/tests_representation/choices.py @@ -0,0 +1,42 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.db import models +from django.utils.translation import gettext_lazy as _ + + +class TestStatuses(models.IntegerChoices): + FAILED = 0, _('Failed') + PASSED = 1, _('Passed') + SKIPPED = 2, _('Skipped') + BROKEN = 3, _('Broken') + BLOCKED = 4, _('Blocked') + UNTESTED = 5, _('Untested') diff --git a/testy/tests_representation/migrations/0001_initial.py b/testy/tests_representation/migrations/0001_initial.py new file mode 100644 index 0000000..58ff372 --- /dev/null +++ b/testy/tests_representation/migrations/0001_initial.py @@ -0,0 +1,99 @@ +# Generated by Django 3.2 on 2022-10-10 09:32 + +from django.conf import settings +import django.contrib.postgres.fields +import django.core.validators +from django.db import migrations, models +import django.db.models.deletion +import mptt.fields + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('tests_description', '0001_initial'), + ('core', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Test', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), + ('is_archive', models.BooleanField(default=False)), + ('case', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tests', to='tests_description.testcase')), + ], + options={ + 'default_related_name': 'tests', + }, + ), + migrations.CreateModel( + name='TestResult', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), + ('status', models.IntegerField(choices=[(0, 'Failed'), (1, 'Passed'), (2, 'Skipped'), (3, 'Broken'), (4, 'Blocked'), (5, 'Untested')], default=5)), + ('comment', models.TextField(blank=True)), + ('is_archive', models.BooleanField(default=False)), + ('test_case_version', models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('test', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='test_results', to='tests_representation.test')), + ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='test_results', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'default_related_name': 'test_results', + }, + ), + migrations.CreateModel( + name='TestPlan', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), + ('name', models.CharField(max_length=255)), + ('parameters', django.contrib.postgres.fields.ArrayField(base_field=models.PositiveIntegerField(blank=True, null=True), blank=True, null=True, size=None)), + ('started_at', models.DateTimeField()), + ('due_date', models.DateTimeField()), + ('finished_at', models.DateTimeField(blank=True, null=True)), + ('is_archive', models.BooleanField(default=False)), + ('lft', models.PositiveIntegerField(editable=False)), + ('rght', models.PositiveIntegerField(editable=False)), + ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), + ('level', models.PositiveIntegerField(editable=False)), + ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='child_test_planes', to='tests_representation.testplan')), + ], + options={ + 'default_related_name': 'test_plans', + }, + ), + migrations.AddField( + model_name='test', + name='plan', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tests', to='tests_representation.testplan'), + ), + migrations.AddField( + model_name='test', + name='user', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tests', to=settings.AUTH_USER_MODEL), + ), + migrations.CreateModel( + name='Parameter', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created at')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='updated at')), + ('data', models.TextField()), + ('group_name', models.CharField(max_length=255)), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parameters', to='core.project')), + ], + options={ + 'default_related_name': 'parameters', + 'unique_together': {('group_name', 'data')}, + }, + ), + ] diff --git a/testy/tests_representation/migrations/0002_added_project_fk.py b/testy/tests_representation/migrations/0002_added_project_fk.py new file mode 100644 index 0000000..c62f815 --- /dev/null +++ b/testy/tests_representation/migrations/0002_added_project_fk.py @@ -0,0 +1,33 @@ +# Generated by Django 3.2 on 2022-10-14 09:01 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('core', '0001_initial'), + ('tests_representation', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='test', + name='project', + field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='tests', to='core.project'), + preserve_default=False, + ), + migrations.AddField( + model_name='testplan', + name='project', + field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='test_plans', to='core.project'), + preserve_default=False, + ), + migrations.AddField( + model_name='testresult', + name='project', + field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='test_results', to='core.project'), + preserve_default=False, + ), + ] diff --git a/testy/tests_representation/migrations/0003_make_user_nullable.py b/testy/tests_representation/migrations/0003_make_user_nullable.py new file mode 100644 index 0000000..961965b --- /dev/null +++ b/testy/tests_representation/migrations/0003_make_user_nullable.py @@ -0,0 +1,21 @@ +# Generated by Django 3.2 on 2022-10-18 09:18 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('tests_representation', '0002_added_project_fk'), + ] + + operations = [ + migrations.AlterField( + model_name='test', + name='user', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='tests', to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/testy/tests_representation/migrations/0004_change_testplan_parent_related_name.py b/testy/tests_representation/migrations/0004_change_testplan_parent_related_name.py new file mode 100644 index 0000000..1bbff8e --- /dev/null +++ b/testy/tests_representation/migrations/0004_change_testplan_parent_related_name.py @@ -0,0 +1,20 @@ +# Generated by Django 3.2 on 2022-10-21 05:41 + +from django.db import migrations +import django.db.models.deletion +import mptt.fields + + +class Migration(migrations.Migration): + + dependencies = [ + ('tests_representation', '0003_make_user_nullable'), + ] + + operations = [ + migrations.AlterField( + model_name='testplan', + name='parent', + field=mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='child_test_plans', to='tests_representation.testplan'), + ), + ] diff --git a/testy/tests_representation/migrations/0005_testresult_execution_time.py b/testy/tests_representation/migrations/0005_testresult_execution_time.py new file mode 100644 index 0000000..2382be4 --- /dev/null +++ b/testy/tests_representation/migrations/0005_testresult_execution_time.py @@ -0,0 +1,19 @@ +# Generated by Django 3.2 on 2022-11-08 17:21 + +import django.core.validators +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('tests_representation', '0004_change_testplan_parent_related_name'), + ] + + operations = [ + migrations.AddField( + model_name='testresult', + name='execution_time', + field=models.IntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0)]), + ), + ] diff --git a/testy/tests_representation/migrations/__init__.py b/testy/tests_representation/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/testy/tests_representation/models.py b/testy/tests_representation/models.py new file mode 100644 index 0000000..c9e594a --- /dev/null +++ b/testy/tests_representation/models.py @@ -0,0 +1,105 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from core.models import Project +from django.conf import settings +from django.contrib.auth import get_user_model +from django.contrib.postgres.fields import ArrayField +from django.core.validators import MinValueValidator +from django.db import models +from mptt.models import MPTTModel, TreeForeignKey +from tests_description.models import TestCase +from tests_representation.choices import TestStatuses +from users.models import User + +from testy.models import BaseModel + +UserModel = get_user_model() + + +class Parameter(BaseModel): + project = models.ForeignKey(Project, on_delete=models.CASCADE) + data = models.TextField() + group_name = models.CharField(max_length=settings.CHAR_FIELD_MAX_LEN) + + class Meta: + default_related_name = 'parameters' + unique_together = ('group_name', 'data',) + + def __str__(self): + return f'{self.group_name}: {self.data}' + + +class TestPlan(MPTTModel, BaseModel): + name = models.CharField(max_length=settings.CHAR_FIELD_MAX_LEN) + project = models.ForeignKey(Project, on_delete=models.CASCADE) + parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='child_test_plans') + parameters = ArrayField(models.PositiveIntegerField(null=True, blank=True), null=True, blank=True) + started_at = models.DateTimeField() + due_date = models.DateTimeField() + finished_at = models.DateTimeField(null=True, blank=True) + is_archive = models.BooleanField(default=False) + + class Meta: + default_related_name = 'test_plans' + + +class Test(BaseModel): + project = models.ForeignKey(Project, on_delete=models.CASCADE) + case = models.ForeignKey(TestCase, on_delete=models.CASCADE) + plan = models.ForeignKey(TestPlan, on_delete=models.CASCADE) + user = models.ForeignKey(UserModel, on_delete=models.CASCADE, null=True, blank=True) + is_archive = models.BooleanField(default=False) + + class Meta: + default_related_name = 'tests' + + +class TestResult(BaseModel): + project = models.ForeignKey(Project, on_delete=models.CASCADE) + status = models.IntegerField(choices=TestStatuses.choices, default=TestStatuses.UNTESTED) + test = models.ForeignKey(Test, on_delete=models.CASCADE) + user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) + comment = models.TextField(blank=True) + is_archive = models.BooleanField(default=False) + test_case_version = models.IntegerField( + null=True, + blank=True, + validators=[MinValueValidator(settings.MIN_VALUE_POSITIVE_INTEGER)] + ) + execution_time = models.IntegerField( + null=True, + blank=True, + validators=[MinValueValidator(settings.MIN_VALUE_POSITIVE_INTEGER)] + ) + + class Meta: + default_related_name = 'test_results' diff --git a/testy/tests_representation/selectors/__init__.py b/testy/tests_representation/selectors/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/tests_representation/selectors/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/tests_representation/selectors/parameters.py b/testy/tests_representation/selectors/parameters.py new file mode 100644 index 0000000..ade2e11 --- /dev/null +++ b/testy/tests_representation/selectors/parameters.py @@ -0,0 +1,49 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import List, Optional + +from django.db.models import QuerySet +from tests_representation.models import Parameter + + +class ParameterSelector: + def parameter_list(self) -> QuerySet[Parameter]: + return Parameter.objects.all() + + def parameters_by_project_id(self, project_id: int) -> QuerySet[Parameter]: + return QuerySet(model=Parameter).filter(project=project_id).order_by('group_name') + + def parameter_project_list(self, project_id: int) -> QuerySet[Parameter]: + return QuerySet(model=Parameter).filter(project=project_id).order_by('data') + + def parameter_name_list_by_ids(self, ids: List[int]) -> QuerySet[Optional[List[str]]]: + return QuerySet(model=Parameter).filter(id__in=ids).values_list('data', flat=True).order_by('data') diff --git a/testy/tests_representation/selectors/results.py b/testy/tests_representation/selectors/results.py new file mode 100644 index 0000000..4e97fcb --- /dev/null +++ b/testy/tests_representation/selectors/results.py @@ -0,0 +1,41 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.db.models import QuerySet +from tests_representation.models import TestResult + + +class TestResultSelector: + def result_list(self) -> QuerySet[TestResult]: + return TestResult.objects.all() + + def result_list_by_test_id(self, test_id) -> QuerySet[TestResult]: + return TestResult.objects.select_related('test').filter(test_id=test_id) diff --git a/testy/tests_representation/selectors/testplan.py b/testy/tests_representation/selectors/testplan.py new file mode 100644 index 0000000..465dd4a --- /dev/null +++ b/testy/tests_representation/selectors/testplan.py @@ -0,0 +1,49 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import logging +from typing import Optional + +from django.db.models import QuerySet +from tests_representation.models import TestPlan + +logger = logging.getLogger(__name__) + + +class TestPlanSelector: + def testplan_list(self) -> QuerySet[TestPlan]: + return TestPlan.objects.all() + + def testplan_project_root_list(self, project_id: int) -> QuerySet[TestPlan]: + return QuerySet(model=TestPlan).filter(project=project_id, parent=None).order_by('name') + + def testplan_get_by_pk(self, pk) -> Optional[TestPlan]: + return TestPlan.objects.get(pk=pk) diff --git a/testy/tests_representation/selectors/tests.py b/testy/tests_representation/selectors/tests.py new file mode 100644 index 0000000..5f7a793 --- /dev/null +++ b/testy/tests_representation/selectors/tests.py @@ -0,0 +1,38 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.db.models import QuerySet +from tests_representation.models import Test + + +class TestSelector: + def test_list(self) -> QuerySet[Test]: + return Test.objects.all() diff --git a/testy/tests_representation/services/__init__.py b/testy/tests_representation/services/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/tests_representation/services/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/tests_representation/services/parameters.py b/testy/tests_representation/services/parameters.py new file mode 100644 index 0000000..4591009 --- /dev/null +++ b/testy/tests_representation/services/parameters.py @@ -0,0 +1,51 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import Any, Dict + +from tests_representation.models import Parameter + + +class ParameterService: + non_side_effect_fields = ['project', 'data', 'group_name'] + + def parameter_create(self, data: Dict[str, Any]) -> Parameter: + return Parameter.model_create( + fields=self.non_side_effect_fields, + data=data, + ) + + def parameter_update(self, parameter: Parameter, data: Dict[str, Any]) -> Parameter: + parameter, _ = parameter.model_update( + fields=self.non_side_effect_fields, + data=data, + ) + return parameter diff --git a/testy/tests_representation/services/results.py b/testy/tests_representation/services/results.py new file mode 100644 index 0000000..a0be508 --- /dev/null +++ b/testy/tests_representation/services/results.py @@ -0,0 +1,70 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import Any, Dict + +from django.db import transaction +from tests_description.selectors.cases import TestCaseSelector +from tests_representation.models import Test, TestResult + + +class TestResultService: + non_side_effect_fields = ['status', 'user', 'comment', 'is_archive', 'test_case_version', 'execution_time'] + + @transaction.atomic + def result_create(self, data: Dict[str, Any], test_id: int) -> TestResult: + test_result: TestResult = TestResult.model_create( + fields=self.non_side_effect_fields, + data=data, + commit=False, + ) + test_result.test = Test.objects.get(pk=test_id) + test_result.project = test_result.test.case.project + test_result.test_case_version = TestCaseSelector().case_version(test_result.test.case) + test_result.full_clean() + test_result.save() + + return test_result + + @transaction.atomic + def result_update(self, test_result: TestResult, data: Dict[str, Any]) -> TestResult: + test_result, has_updated = test_result.model_update( + fields=self.non_side_effect_fields, + data=data, + commit=False, + ) + + if has_updated: + test_result.test_case_version = TestCaseSelector().case_version(test_result.test.case) + test_result.full_clean() + test_result.save() + + return test_result diff --git a/testy/tests_representation/services/testplans.py b/testy/tests_representation/services/testplans.py new file mode 100644 index 0000000..c91d0c5 --- /dev/null +++ b/testy/tests_representation/services/testplans.py @@ -0,0 +1,100 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import Any, Dict, List + +from django.db import transaction +from tests_representation.models import TestPlan +from tests_representation.services.tests import TestService +from tests_representation.utils import combination_parameters + + +class TestPLanService: + non_side_effect_fields = ('name', 'parent', 'started_at', 'due_date', 'finished_at', 'is_archive', 'project',) + + def _make_testplan_model(self, data, parameters=None): + testplan = TestPlan.model_create( + fields=self.non_side_effect_fields, + data=data, + commit=False + ) + testplan.lft = 0 + testplan.rght = 0 + testplan.tree_id = 0 + testplan.level = 0 + + if parameters is not None: + testplan.parameters = parameters + + return testplan + + @transaction.atomic + def testplan_create(self, data=Dict[str, Any]) -> List[TestPlan]: + testplan_objects = [] + + if parameters := data.get('parameters', []): + for combine_parameter in combination_parameters(parameters): + testplan_objects.append(self._make_testplan_model(data, combine_parameter)) + else: + testplan_objects.append(self._make_testplan_model(data)) + + test_plans = TestPlan.objects.bulk_create(testplan_objects) + TestPlan.objects.rebuild() + + if test_cases := data.get('test_cases', []): + TestService().bulk_test_create(test_plans, test_cases) + + return test_plans + + @transaction.atomic + def testplan_update(self, *, test_plan: TestPlan, data: dict[str, Any]) -> TestPlan: + test_plan, _ = test_plan.model_update( + fields=self.non_side_effect_fields, + data=data, + ) + + if (test_cases := data.get('test_cases')) is not None: # test_cases may be empty list + old_test_case_ids = set(TestService().get_testcase_ids_by_testplan(test_plan)) + new_test_case_ids = {tc.id for tc in test_cases} + + # deleting tests + if delete_test_case_ids := old_test_case_ids - new_test_case_ids: + TestService().test_delete_by_test_case_ids(test_plan, delete_test_case_ids) + + # creating tests + if create_test_case_ids := new_test_case_ids - old_test_case_ids: + cases = [tc for tc in data['test_cases'] if tc.id in create_test_case_ids] + TestService().bulk_test_create((test_plan,), cases) + + return test_plan + + def testplan_delete(self, *, test_plan) -> None: + test_plan.delete() diff --git a/testy/tests_representation/services/tests.py b/testy/tests_representation/services/tests.py new file mode 100644 index 0000000..d0a34a4 --- /dev/null +++ b/testy/tests_representation/services/tests.py @@ -0,0 +1,79 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import Any, Dict + +from django.db import transaction +from django.db.models import QuerySet +from tests_description.models import TestCase +from tests_representation.models import Test, TestPlan + + +class TestService: + non_side_effect_fields = ['case', 'plan', 'user', 'is_archive', 'project'] + + def _make_test_model(self, data): + return Test.model_create( + fields=self.non_side_effect_fields, + data=data, + commit=False + ) + + def test_create(self, data: Dict[str, Any]) -> Test: + test = Test.model_create( + fields=self.non_side_effect_fields, + data=data, + commit=False + ) + test.project = test.case.project + test.full_clean() + test.save() + return test + + @transaction.atomic + def test_delete_by_test_case_ids(self, test_plan: TestPlan, test_case_ids: list[int]) -> None: + Test.objects.filter(plan=test_plan).filter(case__in=test_case_ids).delete() + + @transaction.atomic + def bulk_test_create(self, test_plans: list[TestPlan], cases: list[TestCase]): + test_objects = [self._make_test_model({'case': case, 'plan': tp, 'project': tp.project}) for tp in test_plans + for case in cases] + return Test.objects.bulk_create(test_objects) + + def test_update(self, test: Test, data: Dict[str, Any]) -> Test: + test, _ = test.model_update( + fields=self.non_side_effect_fields, + data=data, + ) + return test + + def get_testcase_ids_by_testplan(self, test_plan: TestPlan) -> QuerySet[int]: + return test_plan.tests.values_list('case', flat=True) diff --git a/testy/tests_representation/utils.py b/testy/tests_representation/utils.py new file mode 100644 index 0000000..4eff501 --- /dev/null +++ b/testy/tests_representation/utils.py @@ -0,0 +1,47 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from itertools import product +from typing import List, Tuple + +from tests_representation.models import Parameter + + +def combination_parameters(parameters: List[Parameter]) -> List[Tuple[int, ...]]: + """ + Returns all possible combinations of parameters by group name + """ + group_parameters = {} + + for parameter in parameters: + group_parameters.setdefault(parameter.group_name, []).append(parameter.id) + + return list(product(*group_parameters.values())) diff --git a/testy/testy/__init__.py b/testy/testy/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/testy/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/testy/admin.py b/testy/testy/admin.py new file mode 100644 index 0000000..8406b90 --- /dev/null +++ b/testy/testy/admin.py @@ -0,0 +1,42 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.contrib import admin + + +class BaseAdmin(admin.ModelAdmin): + _base_readonly_fields = ("created_at", "updated_at",) + + def get_readonly_fields(self, request, obj=None): + if self.readonly_fields: + return self.readonly_fields + self._base_readonly_fields + else: + return self._base_readonly_fields diff --git a/testy/testy/api/__init__.py b/testy/testy/api/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/testy/api/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/testy/api/urls.py b/testy/testy/api/urls.py new file mode 100644 index 0000000..88c9e76 --- /dev/null +++ b/testy/testy/api/urls.py @@ -0,0 +1,40 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.urls import include, path + +from testy.api.views import APIRootView + +app_name = 'api' +urlpatterns = [ + path('', APIRootView.as_view(), name='api-root'), + path('v1/', include('testy.api.v1.urls', namespace='v1')), +] diff --git a/testy/testy/api/v1/__init__.py b/testy/testy/api/v1/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/testy/api/v1/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/testy/api/v1/urls.py b/testy/testy/api/v1/urls.py new file mode 100644 index 0000000..71bb731 --- /dev/null +++ b/testy/testy/api/v1/urls.py @@ -0,0 +1,48 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.urls import include, path +from rest_framework import routers + +from testy.api.v1 import views + +router = routers.DefaultRouter() +router.APIRootView = views.V1RootView + +app_name = 'v1' +urlpatterns = [ + path('', include('core.api.v1.urls')), + path('', include('tests_description.api.v1.urls')), + path('', include('tests_representation.api.v1.urls')), + path('', include('users.api.v1.urls')), +] + +urlpatterns += router.urls diff --git a/testy/testy/api/v1/views.py b/testy/testy/api/v1/views.py new file mode 100644 index 0000000..4a0dd0e --- /dev/null +++ b/testy/testy/api/v1/views.py @@ -0,0 +1,52 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from rest_framework.response import Response +from rest_framework.reverse import reverse +from rest_framework.routers import APIRootView + + +class V1RootView(APIRootView): + def get_view_name(self): + return 'v1' + + def get(self, request, format=None): + return Response({ + 'projects': reverse('api:v1:project-list', request=request, format=format), + 'suites': reverse('api:v1:testsuite-list', request=request, format=format), + 'cases': reverse('api:v1:testcase-list', request=request, format=format), + 'tests': reverse('api:v1:test-list', request=request, format=format), + 'results': reverse('api:v1:testresult-list', request=request, format=format), + 'testplans': reverse('api:v1:testplan-list', request=request, format=format), + 'parameters': reverse('api:v1:parameter-list', request=request, format=format), + 'users': reverse('api:v1:user-list', request=request, format=format), + 'groups': reverse('api:v1:group-list', request=request, format=format), + }) diff --git a/testy/testy/api/views.py b/testy/testy/api/views.py new file mode 100644 index 0000000..09145d4 --- /dev/null +++ b/testy/testy/api/views.py @@ -0,0 +1,48 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from rest_framework.response import Response +from rest_framework.reverse import reverse +from rest_framework.views import APIView + + +class APIRootView(APIView): + _ignore_model_permissions = True + exclude_from_schema = True + swagger_schema = None + + def get_view_name(self): + return "API Root" + + def get(self, request, format=None): + return Response({ + 'v1': reverse('api:v1:api-root', request=request, format=format), + }) diff --git a/testy/testy/asgi.py b/testy/testy/asgi.py new file mode 100644 index 0000000..ccdc425 --- /dev/null +++ b/testy/testy/asgi.py @@ -0,0 +1,47 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +""" +ASGI config for testy project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testy.settings.production') + +application = get_asgi_application() diff --git a/testy/testy/locale/ru/LC_MESSAGES/django.mo b/testy/testy/locale/ru/LC_MESSAGES/django.mo new file mode 100644 index 0000000..de0ab97 Binary files /dev/null and b/testy/testy/locale/ru/LC_MESSAGES/django.mo differ diff --git a/testy/testy/locale/ru/LC_MESSAGES/django.po b/testy/testy/locale/ru/LC_MESSAGES/django.po new file mode 100644 index 0000000..c41063c --- /dev/null +++ b/testy/testy/locale/ru/LC_MESSAGES/django.po @@ -0,0 +1,37 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2022-09-20 08:55+0000\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n" +"%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n" +"%100>=11 && n%100<=14)? 2 : 3);\n" + +#: testy/testy/models.py:6 +msgid "created at" +msgstr "создано" + +#: testy/testy/models.py:7 +msgid "updated at" +msgstr "обновлено" + +#: testy/testy/settings/common.py:104 +msgid "English" +msgstr "Английский" + +#: testy/testy/settings/common.py:105 +msgid "Russian" +msgstr "Русский" diff --git a/testy/testy/models.py b/testy/testy/models.py new file mode 100644 index 0000000..3e68356 --- /dev/null +++ b/testy/testy/models.py @@ -0,0 +1,84 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import logging +from typing import Any, Dict, List, Tuple + +from django.db import models +from django.utils.translation import gettext_lazy as _ + +from testy.types import DjangoModelType + +logger = logging.getLogger(__name__) + + +class ServiceModelMixin(models.Model): + class Meta: + abstract = True + + @classmethod + def model_create(cls, fields: List[str], data: Dict[str, Any], commit: bool = True) -> DjangoModelType: + actually_fields = {key: data[key] for key in fields if key in data} + instance = cls(**actually_fields) + + if commit: + instance.full_clean() + instance.save() + + return instance + + def model_update( + self, fields: List[str], data: Dict[str, Any], commit: bool = True + ) -> Tuple[DjangoModelType, bool]: + has_updated = False + + for field in fields: + if field not in data: + continue + + if getattr(self, field) != data[field]: + has_updated = True + setattr(self, field, data[field]) + + if has_updated and commit: + self.full_clean() + self.save(update_fields=fields) + if not has_updated: + logger.error('Model was not updated.') + return self, has_updated + + +class BaseModel(ServiceModelMixin, models.Model): + created_at = models.DateTimeField(_('created at'), auto_now_add=True) + updated_at = models.DateTimeField(_('updated at'), auto_now=True) + + class Meta: + abstract = True diff --git a/testy/testy/settings/common.py b/testy/testy/settings/common.py new file mode 100644 index 0000000..c963f4e --- /dev/null +++ b/testy/testy/settings/common.py @@ -0,0 +1,201 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +""" +Django settings for testy project. + +Generated by 'django-admin startproject' using Django 3.2. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.2/ref/settings/ +""" +import json +import os +from pathlib import Path + +from django.utils.translation import gettext_lazy as _ + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent.parent + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ + +VERSION = '0.1.0' + +loaded_hosts = os.environ.get('ALLOWED_HOSTS', []) + +ALLOWED_HOSTS = json.loads(loaded_hosts) if loaded_hosts else loaded_hosts + +# Application definition +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'drf_yasg', + 'mptt', + 'rest_framework', + 'django_filters', + 'corsheaders', + 'simple_history', + 'core', + 'users', + 'tests_description', + 'tests_representation', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + "corsheaders.middleware.CorsMiddleware", + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.middleware.locale.LocaleMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'simple_history.middleware.HistoryRequestMiddleware', +] + +ROOT_URLCONF = 'testy.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [ + os.path.join(BASE_DIR, 'templates'), + ], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'testy.wsgi.application' + +# Database +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': os.environ.get('POSTGRES_NAME'), + 'USER': os.environ.get('POSTGRES_USER'), + 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), + 'HOST': os.environ.get('POSTGRES_SERVICE_HOST'), + 'PORT': os.environ.get('POSTGRES_SERVICE_PORT'), + } +} + +LOGIN_URL = '/' +LOGIN_REDIRECT_URL = '/' +LOGOUT_REDIRECT_URL = '/' + +# Password validation +# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + +# Internationalization +# https://docs.djangoproject.com/en/3.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' +LANGUAGES = [ + ('en', _('English')), + ('ru', _('Russian')), +] + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.2/howto/static-files/ + +STATIC_URL = '/static/' +STATIC_ROOT = 'static' + +# Default primary key field type +# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + +AUTH_USER_MODEL = 'users.User' +CHAR_FIELD_MAX_LEN = 255 +MIN_VALUE_POSITIVE_INTEGER = 0 + +# Django REST framework (API) +REST_FRAMEWORK = { + 'DEFAULT_PERMISSION_CLASSES': [ + 'rest_framework.permissions.IsAuthenticated', + ], + 'DEFAULT_AUTHENTICATION_CLASSES': [ + 'rest_framework_simplejwt.authentication.JWTAuthentication', + 'rest_framework.authentication.SessionAuthentication', + ], + 'DEFAULT_FILTER_BACKENDS': [ + 'django_filters.rest_framework.DjangoFilterBackend' + ], +} + +# Django CORS headers +CORS_ALLOW_CREDENTIALS = True +CORS_ALLOW_ALL_ORIGINS = True + +# Company +COMPANY_DOMAIN = os.environ.get('COMPANY_DOMAIN') diff --git a/testy/testy/settings/development.py b/testy/testy/settings/development.py new file mode 100644 index 0000000..3bbcdd2 --- /dev/null +++ b/testy/testy/settings/development.py @@ -0,0 +1,68 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from testy.settings.common import * # noqa F401, F403 + +DEBUG = True + +SECRET_KEY = 'django-insecure-97ml+ugrkdl6s!h)_5vanzw4%d_lajo6j(08e84e7314*&)s3)' + +INSTALLED_APPS += [ # noqa F405 + 'django_extensions', +] + +log_level = "DEBUG" + +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'formatters': { + 'default': { + 'format': '%(asctime)s - %(module)s - %(levelname)s: %(message)s', + }, + }, + 'handlers': { + 'console': { + 'formatter': 'default', + 'class': 'logging.StreamHandler', + }, + }, + "loggers": { + "django": { + "handlers": ["console"], + "level": os.getenv("DJANGO_LOG_LEVEL", "INFO"), # noqa: F405 + }, + "core": { + "handlers": ["console"], + "level": os.getenv("TESTY_TMS_CORE_LOG_LEVEL", log_level), # noqa: F405 + }, + }, +} diff --git a/testy/testy/settings/local.py b/testy/testy/settings/local.py new file mode 100644 index 0000000..ecbab29 --- /dev/null +++ b/testy/testy/settings/local.py @@ -0,0 +1,34 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . +from dotenv import load_dotenv + +load_dotenv('.env.local') +from testy.settings.development import * # noqa F401, F403 diff --git a/testy/testy/settings/production.py b/testy/testy/settings/production.py new file mode 100644 index 0000000..089a7f0 --- /dev/null +++ b/testy/testy/settings/production.py @@ -0,0 +1,36 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from testy.settings.common import * # noqa F401, F403 + +DEBUG = False + +SECRET_KEY = os.environ.get('SECRET_KEY') # noqa F405 diff --git a/testy/testy/types.py b/testy/testy/types.py new file mode 100644 index 0000000..f228a91 --- /dev/null +++ b/testy/testy/types.py @@ -0,0 +1,35 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . +from typing import TypeVar + +from django.db import models + +DjangoModelType = TypeVar('DjangoModelType', bound=models.Model) diff --git a/testy/testy/urls.py b/testy/testy/urls.py new file mode 100644 index 0000000..5f300c3 --- /dev/null +++ b/testy/testy/urls.py @@ -0,0 +1,83 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +"""testy URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.conf import settings +from django.contrib import admin +from django.contrib.staticfiles.urls import staticfiles_urlpatterns +from django.urls import include, path, re_path +from drf_yasg import openapi +from drf_yasg.views import get_schema_view +from rest_framework import permissions +from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView + +schema_view = get_schema_view( + openapi.Info( + title="testy API", + default_version='v1', + description="testy API v1", + ), + public=True, + permission_classes=[permissions.AllowAny], +) + +urlpatterns = [ + # API + path('api/', include('testy.api.urls', namespace='api')), + path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), + path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), + path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), + + # Admin + path('admin/', admin.site.urls), + + # Swagger + re_path(r'^swagger(?P\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), + re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), + re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), +] + +if settings.DEBUG: + urlpatterns += staticfiles_urlpatterns() diff --git a/testy/testy/wsgi.py b/testy/testy/wsgi.py new file mode 100644 index 0000000..3646d78 --- /dev/null +++ b/testy/testy/wsgi.py @@ -0,0 +1,47 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +""" +WSGI config for testy project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testy.settings.production') + +application = get_wsgi_application() diff --git a/testy/users/__init__.py b/testy/users/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/users/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/users/admin.py b/testy/users/admin.py new file mode 100644 index 0000000..19eb82e --- /dev/null +++ b/testy/users/admin.py @@ -0,0 +1,66 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.contrib import admin +from django.contrib.auth.admin import UserAdmin +from django.contrib.auth.models import Group +from users.models import Group as Group_ +from users.models import User + +admin.site.unregister(Group) + + +@admin.register(Group_) +class GroupAdmin(admin.ModelAdmin): + list_display = ('name', 'user_count') + ordering = ('name',) + search_fields = ('name',) + + @staticmethod + def user_count(obj): + return obj.user_set.count() + + +@admin.register(User) +class UserAdmin(UserAdmin): + list_display = [ + 'username', 'email', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active' + ] + fieldsets = ( + (None, {'fields': ('username', 'password', 'first_name', 'last_name', 'email')}), + ('Groups', {'fields': ('groups',)}), + ('Status', { + 'fields': ('is_active', 'is_staff', 'is_superuser'), + }), + ('Important dates', {'fields': ('last_login', 'date_joined')}), + ) + filter_horizontal = ('groups',) + list_filter = ('is_active', 'is_staff', 'is_superuser', 'groups__name') diff --git a/testy/users/api/v1/__init__.py b/testy/users/api/v1/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/users/api/v1/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/users/api/v1/serializers.py b/testy/users/api/v1/serializers.py new file mode 100644 index 0000000..b92c861 --- /dev/null +++ b/testy/users/api/v1/serializers.py @@ -0,0 +1,60 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.contrib.auth import get_user_model +from rest_framework.serializers import HyperlinkedIdentityField, ModelSerializer +from users.models import Group + +UserModel = get_user_model() + + +class GroupSerializer(ModelSerializer): + url = HyperlinkedIdentityField(view_name='api:v1:group-detail') + + class Meta: + model = Group + fields = ('id', 'name', 'permissions', 'url') + + +class UserSerializer(ModelSerializer): + url = HyperlinkedIdentityField(view_name='api:v1:user-detail') + + class Meta: + model = UserModel + fields = ( + 'id', 'url', 'username', 'password', 'first_name', 'last_name', 'email', 'is_staff', 'is_active', + 'date_joined', 'groups' + ) + + read_only_fields = ('date_joined',) + extra_kwargs = { + 'password': {'write_only': True} + } diff --git a/testy/users/api/v1/urls.py b/testy/users/api/v1/urls.py new file mode 100644 index 0000000..e527851 --- /dev/null +++ b/testy/users/api/v1/urls.py @@ -0,0 +1,40 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from rest_framework.routers import SimpleRouter +from users.api.v1 import views + +router = SimpleRouter() + +router.register('users', views.UserViewSet) +router.register('groups', views.GroupViewSet) + +urlpatterns = router.urls diff --git a/testy/users/api/v1/views.py b/testy/users/api/v1/views.py new file mode 100644 index 0000000..212580c --- /dev/null +++ b/testy/users/api/v1/views.py @@ -0,0 +1,62 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.contrib.auth import get_user_model +from rest_framework.viewsets import ModelViewSet +from users.api.v1.serializers import GroupSerializer, UserSerializer +from users.selectors.groups import GroupSelector +from users.selectors.users import UserSelector +from users.services.groups import GroupService +from users.services.users import UserService + +UserModel = get_user_model() + + +class GroupViewSet(ModelViewSet): + queryset = GroupSelector().group_list() + serializer_class = GroupSerializer + + def perform_create(self, serializer: GroupSerializer): + serializer.instance = GroupService().group_create(serializer.validated_data) + + def perform_update(self, serializer: UserSerializer): + serializer.instance = GroupService().group_update(serializer.instance, serializer.validated_data) + + +class UserViewSet(ModelViewSet): + queryset = UserSelector().user_list() + serializer_class = UserSerializer + + def perform_create(self, serializer: UserSerializer): + serializer.instance = UserService().user_create(serializer.validated_data) + + def perform_update(self, serializer: UserSerializer): + serializer.instance = UserService().user_update(serializer.instance, serializer.validated_data) diff --git a/testy/users/apps.py b/testy/users/apps.py new file mode 100644 index 0000000..f2ca730 --- /dev/null +++ b/testy/users/apps.py @@ -0,0 +1,37 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.apps import AppConfig + + +class UsersConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'users' diff --git a/testy/users/migrations/0001_initial.py b/testy/users/migrations/0001_initial.py new file mode 100644 index 0000000..8b008fd --- /dev/null +++ b/testy/users/migrations/0001_initial.py @@ -0,0 +1,59 @@ +# Generated by Django 3.2 on 2022-10-06 16:24 + +import django.contrib.auth.models +import django.contrib.auth.validators +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0012_alter_user_first_name_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='Group', + fields=[ + ], + options={ + 'verbose_name': 'Group', + 'verbose_name_plural': 'Groups', + 'proxy': True, + 'indexes': [], + 'constraints': [], + }, + bases=('auth.group', models.Model), + managers=[ + ('objects', django.contrib.auth.models.GroupManager()), + ], + ), + migrations.CreateModel( + name='User', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), + ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), + ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), + ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), + ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name': 'User', + 'verbose_name_plural': 'Users', + }, + managers=[ + ('objects', django.contrib.auth.models.UserManager()), + ], + ), + ] diff --git a/testy/users/migrations/__init__.py b/testy/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/testy/users/models.py b/testy/users/models.py new file mode 100644 index 0000000..2ccf418 --- /dev/null +++ b/testy/users/models.py @@ -0,0 +1,47 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.contrib.auth.models import AbstractUser, Group + +from testy.models import ServiceModelMixin + + +class Group(Group, ServiceModelMixin): + class Meta: + verbose_name = 'Group' + verbose_name_plural = 'Groups' + proxy = True + + +class User(AbstractUser, ServiceModelMixin): + class Meta: + verbose_name = 'User' + verbose_name_plural = 'Users' diff --git a/testy/users/selectors/__init__.py b/testy/users/selectors/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/users/selectors/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/users/selectors/groups.py b/testy/users/selectors/groups.py new file mode 100644 index 0000000..7b7752b --- /dev/null +++ b/testy/users/selectors/groups.py @@ -0,0 +1,38 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.db.models import QuerySet +from users.models import Group + + +class GroupSelector: + def group_list(self) -> QuerySet[Group]: + return Group.objects.all() diff --git a/testy/users/selectors/users.py b/testy/users/selectors/users.py new file mode 100644 index 0000000..c17c8a4 --- /dev/null +++ b/testy/users/selectors/users.py @@ -0,0 +1,40 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from django.contrib.auth import get_user_model +from django.db.models import QuerySet + +UserModel = get_user_model() + + +class UserSelector: + def user_list(self) -> QuerySet[UserModel]: + return QuerySet(model=UserModel).prefetch_related('groups').order_by('username') diff --git a/testy/users/services/__init__.py b/testy/users/services/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/users/services/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/users/services/groups.py b/testy/users/services/groups.py new file mode 100644 index 0000000..2f66868 --- /dev/null +++ b/testy/users/services/groups.py @@ -0,0 +1,62 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import Any, Dict + +from users.models import Group + + +class GroupService: + non_side_effect_fields = ['name'] + + def group_create(self, data: Dict[str, Any]) -> Group: + group = Group.model_create( + fields=self.non_side_effect_fields, + data=data, + commit=False + ) + group.full_clean() + group.save() + group.permissions.set(data.get('permissions', [])) + group.full_clean() + group.save() + return group + + def group_update(self, group: Group, data: Dict[str, Any]) -> Group: + group, _ = group.model_update( + fields=self.non_side_effect_fields, + data=data, + commit=False + ) + group.permissions.set(data.get('permissions', [])) + group.full_clean() + group.save() + return group diff --git a/testy/users/services/users.py b/testy/users/services/users.py new file mode 100644 index 0000000..c09b167 --- /dev/null +++ b/testy/users/services/users.py @@ -0,0 +1,64 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +from typing import Any, Dict + +from django.contrib.auth import get_user_model + +UserModel = get_user_model() + + +class UserService: + non_side_effect_fields = ['username', 'first_name', 'last_name', 'email', 'is_staff', 'is_active'] + + def user_create(self, data: Dict[str, Any]) -> UserModel: + user = UserModel.model_create( + fields=self.non_side_effect_fields, + data=data, + commit=False, + ) + user.set_password(data['password']) + user.full_clean() + user.save() + return user + + def user_update(self, user: UserModel, data: Dict[str, Any]) -> UserModel: + user, _ = user.model_update( + fields=self.non_side_effect_fields, + data=data, + commit=False, + ) + password = data.pop('password', None) + if password: + user.set_password(password) + user.full_clean() + user.save() + return user diff --git a/testy/utilities/__init__.py b/testy/utilities/__init__.py new file mode 100644 index 0000000..b0d2609 --- /dev/null +++ b/testy/utilities/__init__.py @@ -0,0 +1,30 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . diff --git a/testy/utilities/request.py b/testy/utilities/request.py new file mode 100644 index 0000000..b2c2c15 --- /dev/null +++ b/testy/utilities/request.py @@ -0,0 +1,43 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . +__all__ = ( + 'get_boolean', +) + + +def get_boolean(request, key, method='GET'): + """ + Gets the value from request and returns it's boolean state + """ + value = getattr(request, method).get(key, False) + if str(value).lower() in ['1', 'yes', 'true']: + return True + return False diff --git a/utils/update_license.py b/utils/update_license.py new file mode 100644 index 0000000..1af2846 --- /dev/null +++ b/utils/update_license.py @@ -0,0 +1,136 @@ +# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . + +import argparse +import difflib +import logging +import os + +logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s') + +__version__ = '0.1' + +EXTENSIONS = ['py'] + +LICENSE_HEADER = """# TestY TMS - Test Management System +# Copyright (C) 2022 KNS Group LLC (YADRO) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Also add information on how to contact you by electronic and paper mail. +# +# If your software can interact with users remotely through a computer +# network, you should also make sure that it provides a way for users to +# get its source. For example, if your program is a web application, its +# interface could display a "Source" link that leads users to an archive +# of the code. There are many ways you could offer source, and different +# solutions will be better for different programs; see section 13 for the +# specific requirements. +# +# 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 AGPL, see +# . +""" + + +def check_ext(name: str): + """ + Check the file extension and return True if the given file should have a license + """ + parts = name.split('.') + if parts[-1] in EXTENSIONS: + return True + return False + + +def main(cmd_args): + found = [] + logging.info(f'Update License version {__version__}') + logging.info(f'Process the extensions {",".join(EXTENSIONS)} in directory {cmd_args.directory}') + # Get all files including nested directories + for path, subdirs, files in os.walk(cmd_args.directory): + for name in files: + if check_ext(name): + found.append(os.path.join(path, name)) + logging.info(f'Found {len(found)} files') + lisense_lines = LICENSE_HEADER.split('\n') + for file in found: + license_required = False + with open(file, 'r+') as w: + content = w.read() + lines = content.split('\n') + if not lines: + continue + if lines[0].startswith('# Generated by Django'): + continue + if lines[0].startswith('#!'): + continue + if lines[0:len(lisense_lines)] != lisense_lines: + diff = '\n'.join([line for line in difflib.unified_diff(lisense_lines, lines[0:len(lisense_lines)])]) + logging.exception(f'No correct license found for {file}:\n{diff}') + license_required = True + if cmd_args.update and license_required: + logging.info(f'Adding the license header for {file}') + content = LICENSE_HEADER + '\n' + content + w.seek(0) + w.write(content) + logging.info(f'The license header added for {file}') + + +if __name__ == '__main__': + # Parse command-line arguments + parser = argparse.ArgumentParser() + parser.add_argument( + '--update', + help='Update files without license', + action='store_true', + default=False + ) + parser.add_argument( + '--directory', + help='Directory for looking files', + type=str, + default=False, + required=True + ) + main(parser.parse_args())