diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 31bd6c3d..00000000 --- a/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -*.pyc -*.sw? -*~ -.coverage -.eggs/ -__pycache__ -*.egg-info/ -version.txt -/analysis.org -/swh/deposit/fixtures/private_data.yaml -/swh/deposit.json -/test.json -/swh/test -db.sqlite3 -/.noseids -*.tgz -*.zip -*.tar.gz -*.tar.bz2 -*.tar.lzma diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 7a5c79d9..00000000 --- a/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -Copyright (C) 2015-2016 The Software Heritage developers - -See http://www.softwareheritage.org/ for more information. diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 94a9ed02..00000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/Makefile.local b/Makefile.local deleted file mode 100644 index a0cda2c3..00000000 --- a/Makefile.local +++ /dev/null @@ -1,30 +0,0 @@ -FLAKEFLAGS='--exclude=swh/manage.py,swh/deposit/settings.py,swh/deposit/migrations/' - -MANAGE=python3 -m swh.manage - -db-drop: - dropdb swh-deposit-dev || return 0 - -db-create: db-drop - createdb swh-deposit-dev - -db-prepare: - $(MANAGE) makemigrations - -db-migrate: - $(MANAGE) migrate - -db-load-data: - $(MANAGE) loaddata deposit_data - -db-load-private-data: db-load-data - $(MANAGE) loaddata ../private_data.yaml - -run-dev: - $(MANAGE) runserver - -run: - gunicorn3 -b 127.0.0.1:5006 swh.deposit.wsgi - -test: - ./swh/manage.py test diff --git a/PKG-INFO b/PKG-INFO index d4d2aa01..7fb5a638 100644 --- a/PKG-INFO +++ b/PKG-INFO @@ -1,10 +1,34 @@ -Metadata-Version: 1.0 +Metadata-Version: 2.1 Name: swh.deposit -Version: 0.0.63 +Version: 0.0.65 Summary: Software Heritage Deposit Server Home-page: https://forge.softwareheritage.org/source/swh-deposit/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN -Description: UNKNOWN +Project-URL: Funding, https://www.softwareheritage.org/donate +Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest +Project-URL: Source, https://forge.softwareheritage.org/source/swh-deposit +Description: # swh-deposit + + This is [Software Heritage](https://www.softwareheritage.org)'s + [SWORD 2.0](http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html) Server + implementation. + + **S.W.O.R.D** (**S**imple **W**eb-Service **O**ffering **R**epository + **D**eposit) is an interoperability standard for digital file deposit. + + This implementation will permit interaction between a client (a + repository) and a server (SWH repository) to permit deposits of + software source code archives and associated metadata. + + The documentation is at ./docs/README-specification.md + Platform: UNKNOWN +Classifier: Programming Language :: Python :: 3 +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) +Classifier: Operating System :: OS Independent +Classifier: Development Status :: 5 - Production/Stable +Description-Content-Type: text/markdown +Provides-Extra: testing diff --git a/bin/Makefile b/bin/Makefile deleted file mode 100644 index 7a8898ff..00000000 --- a/bin/Makefile +++ /dev/null @@ -1,45 +0,0 @@ -DEPOSIT_ID=1 -ARCHIVE=../../swh-deposit.zip -ARCHIVE2=../../swh-model.zip -STATUS=--no-partial -PARTIAL_STATUS=--partial -UPDATE_STATUS='done' -ATOM_ENTRY=../../atom-entry.xml -EXTERNAL_ID='external-id' - -create-archives: - 7z a $(ARCHIVE) $(FOLDER) - 7z a $(ARCHIVE2) $(FOLDER2) - -new: - ./create_deposit.sh $(ARCHIVE) $(STATUS) - -new-complete: - ./create_deposit_with_metadata.sh $(ARCHIVE) $(ATOM_ENTRY) $(STATUS) $(EXTERNAL_ID) - -new-partial: - make new STATUS=$(PARTIAL_STATUS) ARCHIVE=$(ARCHIVE) - -update: - ./update-deposit-with-another-archive.sh $(DEPOSIT_ID) $(ARCHIVE2) $(STATUS) - -update-partial: - make update DEPOSIT_ID=$(DEPOSIT_ID) ARCHIVE2=$(ARCHIVE2) STATUS=$(PARTIAL_STATUS) - -replace: - ./replace-deposit-archive.sh $(ARCHIVE2) $(DEPOSIT_ID) - -download: - ./download-deposit-archive.sh $(DEPOSIT_ID) - -status: - ./status.sh $(DEPOSIT_ID) - -service-document: - ./service-document.sh - -home: - ./home.sh - -update-status: - ./update-status.sh $(DEPOSIT_ID) $(UPDATE_STATUS) diff --git a/bin/content.sh b/bin/content.sh deleted file mode 100755 index 08012f94..00000000 --- a/bin/content.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -DEPOSIT_ID=${1-1} - -curl -i -u "${CREDS}" ${SERVER}/1/${COLLECTION}/${DEPOSIT_ID}/content/ diff --git a/bin/create_deposit.sh b/bin/create_deposit.sh deleted file mode 100755 index 41e4010b..00000000 --- a/bin/create_deposit.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -ARCHIVE=${1-'../../deposit.zip'} - -STATUS=${2-'--no-partial'} - -./swh-deposit \ - --username ${USER} \ - --password ${PASSWORD} \ - --collection ${COLLECTION} \ - --archive-deposit \ - --archive ${ARCHIVE} \ - ${STATUS} \ - --url ${SERVER}/1 diff --git a/bin/create_deposit_atom.sh b/bin/create_deposit_atom.sh deleted file mode 100755 index db0c92d5..00000000 --- a/bin/create_deposit_atom.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -ATOM=${1-'../../atom.xml'} -PROGRESS=${2-'false'} - -curl -i -u "$CREDS" \ - --data-binary @${ATOM} \ - -X POST \ - -H "In-Progress: ${PROGRESS}" \ - -H 'Content-Type: application/atom+xml;type=entry' \ - -H 'Slug: external-id' \ - -H 'Packaging: http://purl.org/net/sword/package/SimpleZip' \ - ${SERVER}/1/${COLLECTION}/ diff --git a/bin/create_deposit_with_metadata.sh b/bin/create_deposit_with_metadata.sh deleted file mode 100755 index d93a85bc..00000000 --- a/bin/create_deposit_with_metadata.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -ARCHIVE=${1-'../../swh-deposit.zip'} -ATOM_ENTRY=${2-'../../atom-entry.xml'} - -STATUS=${3-'--no-partial'} -EXTERNAL_ID=${4-'external-id'} - -./swh-deposit \ - --username ${USER} \ - --password ${PASSWORD} \ - --collection ${COLLECTION} \ - --archive-deposit \ - --archive ${ARCHIVE} \ - --metadata-deposit \ - --metadata ${ATOM_ENTRY} \ - --slug ${EXTERNAL_ID} \ - ${STATUS} \ - --url ${SERVER}/1 diff --git a/bin/default-setup b/bin/default-setup deleted file mode 100644 index c27054f9..00000000 --- a/bin/default-setup +++ /dev/null @@ -1,5 +0,0 @@ -SERVER=http://127.0.0.1:5006 -USER='hal' -PASSWORD='hal' -COLLECTION=hal -CREDS="$USER:$PASSWORD" diff --git a/bin/download-deposit-archive.sh b/bin/download-deposit-archive.sh deleted file mode 100755 index 2b875e31..00000000 --- a/bin/download-deposit-archive.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -DEPOSIT_ID=${1-1} - -curl ${SERVER}/1/${COLLECTION}/${DEPOSIT_ID}/raw/ diff --git a/bin/home.sh b/bin/home.sh deleted file mode 100755 index d3cf2df4..00000000 --- a/bin/home.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -curl ${SERVER} -echo diff --git a/bin/replace-deposit-archive.sh b/bin/replace-deposit-archive.sh deleted file mode 100755 index 5b2b50d2..00000000 --- a/bin/replace-deposit-archive.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -ARCHIVE=${1-'../../swh-model.zip'} -NAME=$(basename ${ARCHIVE}) - -MD5=$(md5sum ${ARCHIVE} | cut -f 1 -d' ') - -DEPOSIT_ID=${2-1} - -curl -i -u "$CREDS" \ - -X PUT \ - --data-binary @${ARCHIVE} \ - -H "In-Progress: false" \ - -H "Content-MD5: ${MD5}" \ - -H "Content-Disposition: attachment; filename=${NAME}" \ - -H 'Slug: external-id' \ - -H 'Packaging: http://purl.org/net/sword/package/SimpleZip' \ - -H 'Content-type: application/zip' \ - ${SERVER}/1/${COLLECTION}/${DEPOSIT_ID}/media/ diff --git a/bin/service-document.sh b/bin/service-document.sh deleted file mode 100755 index f7818a11..00000000 --- a/bin/service-document.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -curl -i -u "${CREDS}" ${SERVER}/1/servicedocument/ diff --git a/bin/status.sh b/bin/status.sh deleted file mode 100755 index 6d3662d1..00000000 --- a/bin/status.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -DEPOSIT_ID=${1-1} - -./swh-deposit \ - --username ${USER} \ - --password ${PASSWORD} \ - --collection ${COLLECTION} \ - --status \ - --deposit-id ${DEPOSIT_ID} \ - --url ${SERVER}/1 diff --git a/bin/update-deposit-with-another-archive.sh b/bin/update-deposit-with-another-archive.sh deleted file mode 100755 index 644e7b80..00000000 --- a/bin/update-deposit-with-another-archive.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -DEPOSIT_ID=${1-1} -ARCHIVE=${2-'../../swh-core.zip'} - -NAME=$(basename ${ARCHIVE}) -MD5=$(md5sum ${ARCHIVE} | cut -f 1 -d' ') -PROGRESS=${3-'false'} - -curl -i -u "${CREDS}" \ - -X POST \ - --data-binary @${ARCHIVE} \ - -H "In-Progress: ${PROGRESS}" \ - -H "Content-MD5: ${MD5}" \ - -H "Content-Disposition: attachment; filename=${NAME}" \ - -H 'Slug: external-id-2' \ - -H 'Packaging: http://purl.org/net/sword/package/SimpleZip' \ - -H 'Content-type: application/zip' \ - ${SERVER}/1/${COLLECTION}/${DEPOSIT_ID}/media/ diff --git a/bin/update-status.sh b/bin/update-status.sh deleted file mode 100755 index c5925a41..00000000 --- a/bin/update-status.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -. ./default-setup - -DEPOSIT_ID=${1-1} -UPDATE_STATUS=${2-'done'} - -curl -i \ - -X PUT \ - -H 'Content-Type: application/json' \ - -d "{\"status\": \"${UPDATE_STATUS}\"}" \ - ${SERVER}/1/${COLLECTION}/${DEPOSIT_ID}/update/ diff --git a/debian/changelog b/debian/changelog deleted file mode 100644 index c1deebce..00000000 --- a/debian/changelog +++ /dev/null @@ -1,5 +0,0 @@ -swh-deposit (0.0.1-1) unstable; urgency=low - - * Bootstrap version - - -- Antoine R. Dumont (@ardumont) Mon, 22 May 2017 20:14:03 +0200 diff --git a/debian/compat b/debian/compat deleted file mode 100644 index ec635144..00000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -9 diff --git a/debian/control b/debian/control deleted file mode 100644 index aeb529bc..00000000 --- a/debian/control +++ /dev/null @@ -1,55 +0,0 @@ -Source: swh-deposit -Maintainer: Software Heritage developers -Section: python -Priority: optional -Build-Depends: debhelper (>= 9), - dh-python (>= 2), - python3-setuptools, - python3-all, - python3-nose, - python3-django-nose, - python3-vcversioner, - python3-swh.core (>= 0.0.36~), - python3-swh.model (>= 0.0.26~), - python3-swh.loader.core (>= 0.0.32~), - python3-swh.loader.tar (>= 0.0.35~), - python3-swh.scheduler (>= 0.0.26~), - python3-django, - python3-click, - python3-vcversioner, - python3-djangorestframework, - python3-requests, - python3-xmltodict, - patool -Standards-Version: 3.9.6 -Homepage: https://forge.softwareheritage.org/source/swh-deposit/ - -Package: python3-swh.deposit -Architecture: all -Depends: python3-swh.core (>= 0.0.36~), - python3-swh.model (>= 0.0.26~), - python3-swh.scheduler (>= 0.0.26~), - patool, - ${misc:Depends}, ${python3:Depends} -Description: Software Heritage Deposit Server - -Package: python3-swh.deposit.client -Architecture: all -Depends: python3-swh.core (>= 0.0.36~), - python3-swh.model (>= 0.0.26~), - python3-requests, - python3-xmltodict, - ${misc:Depends}, ${python3:Depends} -Description: Software Heritage Deposit Api Client - -Package: python3-swh.deposit.loader -Conflict: python3-swh.deposit.injection -Architecture: all -Depends: python3-swh.deposit.client (= ${binary:Version}), - python3-swh.core (>= 0.0.36~), - python3-swh.model (>= 0.0.26~), - python3-swh.loader.core (>= 0.0.32~), - python3-swh.loader.tar (>= 0.0.35~), - python3-swh.scheduler (>= 0.0.26~), - ${misc:Depends}, ${python3:Depends} -Description: Software Heritage Deposit Loader diff --git a/debian/copyright b/debian/copyright deleted file mode 100644 index 81d037db..00000000 --- a/debian/copyright +++ /dev/null @@ -1,22 +0,0 @@ -Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ - -Files: * -Copyright: 2015 The Software Heritage developers -License: GPL-3+ - -License: GPL-3+ - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - . - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - . - You should have received a copy of the GNU General Public License - along with this program. If not, see . - . - On Debian systems, the complete text of the GNU General Public - License version 3 can be found in `/usr/share/common-licenses/GPL-3'. diff --git a/debian/rules b/debian/rules deleted file mode 100755 index 77f54459..00000000 --- a/debian/rules +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/make -f - -export PYBUILD_NAME=swh.deposit -export PYBUILD_TEST_ARGS=--with-doctest -sv -a !db,!fs - -%: - dh $@ --with python3 --buildsystem=pybuild - - -override_dh_install: - dh_install - rm -v $(CURDIR)/debian/python3-*/usr/lib/python*/dist-packages/swh/__init__.py - for pyvers in $(shell py3versions -vr); do \ - mkdir -p $(CURDIR)/debian/python3-swh.deposit.loader/usr/lib/python$$pyvers/dist-packages/swh/deposit/loader ; \ - mv $(CURDIR)/debian/python3-swh.deposit/usr/lib/python$$pyvers/dist-packages/swh/deposit/loader/* \ - $(CURDIR)/debian/python3-swh.deposit.loader/usr/lib/python$$pyvers/dist-packages/swh/deposit/loader/ ; \ - mkdir -p $(CURDIR)/debian/python3-swh.deposit.client/usr/lib/python$$pyvers/dist-packages/swh/deposit/client ; \ - mv $(CURDIR)/debian/python3-swh.deposit/usr/lib/python$$pyvers/dist-packages/swh/deposit/client/* \ - $(CURDIR)/debian/python3-swh.deposit.client/usr/lib/python$$pyvers/dist-packages/swh/deposit/client/ ; \ - done - -override_dh_auto_test: diff --git a/debian/source/format b/debian/source/format deleted file mode 100644 index 163aaf8d..00000000 --- a/debian/source/format +++ /dev/null @@ -1 +0,0 @@ -3.0 (quilt) diff --git a/docs/.gitignore b/docs/.gitignore deleted file mode 100644 index e379dea1..00000000 --- a/docs/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -_build/ -apidoc/ -*-stamp - diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index c30c50ab..00000000 --- a/docs/Makefile +++ /dev/null @@ -1 +0,0 @@ -include ../../swh-docs/Makefile.sphinx diff --git a/docs/_static/.placeholder b/docs/_static/.placeholder deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/_templates/.placeholder b/docs/_templates/.placeholder deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index cab6f17a..00000000 --- a/docs/conf.py +++ /dev/null @@ -1,8 +0,0 @@ -import os -import django - -os.environ.setdefault("DJANGO_SETTINGS_MODULE", - "swh.deposit.settings.development") -django.setup() - -from swh.docs.sphinx.conf import * # NoQA diff --git a/docs/dev-info.rst b/docs/dev-info.rst deleted file mode 100644 index 6e0a02bc..00000000 --- a/docs/dev-info.rst +++ /dev/null @@ -1,174 +0,0 @@ -Hacking on swh-deposit -====================== - -There are multiple modes to run and test the server locally: - -* development-like (automatic reloading when code changes) -* production-like (no reloading) -* integration tests (no side effects) - -Except for the tests which are mostly side effects free (except for the -database access), the other modes will need some configuration files (up to 2) -to run properly. - -Database --------- - -swh-deposit uses a database to store the state of a deposit. The default -db is expected to be called swh-deposit-dev. - -To simplify the use, the following makefile targets can be used: - -schema -~~~~~~ - -.. code:: shell - - make db-create db-prepare db-migrate - -data -~~~~ - -Once the db is created, you need some data to be injected (request -types, client, collection, etc...): - -.. code:: shell - - make db-load-data db-load-private-data - -The private data are about having a user (``hal``) with a password -(``hal``) who can access a collection (``hal``). - -Add the following to ``../private-data.yaml``: - -.. code:: yaml - - - model: deposit.depositclient - fields: - user_ptr_id: 1 - collections: - - 1 - - model: auth.User - pk: 1 - fields: - first_name: hal - last_name: hal - username: hal - password: "pbkdf2_sha256$30000$8lxjoGc9PiBm$DO22vPUJCTM17zYogBgBg5zr/97lH4pw10Mqwh85yUM=" - - model: deposit.depositclient - fields: - user_ptr_id: 1 - collections: - - 1 - url: https://hal.inria.fr - -drop -~~~~ - -For information, you can drop the db: - -.. code:: shell - - make db-drop - -Development-like environment ----------------------------- - -Development-like environment needs one configuration file to work -properly. - -Configuration -~~~~~~~~~~~~~ - -**``{/etc/softwareheritage | ~/.config/swh | ~/.swh}``/deposit/server.yml**: - -.. code:: yaml - - # dev option for running the server locally - host: 127.0.0.1 - port: 5006 - - # production - authentication: - activated: true - white-list: - GET: - - / - - # 20 Mib max size - max_upload_size: 20971520 - -Run -~~~ - -Run the local server, using the default configuration file: - -.. code:: shell - - make run-dev - -Production-like environment ---------------------------- - -Production-like environment needs two configuration files to work -properly. - -This is more close to what's actually running in production. - -Configuration -~~~~~~~~~~~~~ - -This expects the same file describes in the previous chapter. Plus, an -additional private **settings.yml** file containing secret information -that is not in the source code repository. - -**``{/etc/softwareheritage | ~/.config/swh | ~/.swh}``/deposit/private.yml**: - -.. code:: yaml - - secret_key: production-local - db: - name: swh-deposit-dev - -A production configuration file would look like: - -.. code:: yaml - - secret_key: production-secret-key - db: - name: swh-deposit-dev - host: db - port: 5467 - user: user - password: user-password - -Run -~~~ - -.. code:: shell - - make run - -Note: This expects gunicorn3 package installed on the system - -Tests ------ - -To run the tests: - -.. code:: shell - - make test - -As explained, those tests are mostly side-effect free. The db part is -dealt with by django. The remaining part which patches those side-effect -behavior is dealt with in the ``swh/deposit/tests/__init__.py`` module. - -Sum up ------- - -Prepare everything for your user to run: - -.. code:: shell - - make db-drop db-create db-prepare db-migrate db-load-private-data run-dev diff --git a/docs/endpoints/collection.rst b/docs/endpoints/collection.rst deleted file mode 100644 index 7debb7f2..00000000 --- a/docs/endpoints/collection.rst +++ /dev/null @@ -1,73 +0,0 @@ -Create deposit -^^^^^^^^^^^^^^^ - -.. http:post:: /1// - - Create deposit in a collection. - - The client sends a deposit request to a specific collection with: - - * an archive holding the software source code (binary upload) - * an envelop with metadata describing information regarding a deposit (atom - entry deposit) - - Also known as: COL-IRI - - :param text : the client's credentials - :param text Content-Type: accepted mimetype - :param int Content-Length: tarball size - :param text Content-MD5: md5 checksum hex encoded of the tarball - :param text Content-Disposition: attachment; filename=[filename]; the filename - parameter must be text (ascii) - :param text Content-Disposition: for the metadata file set name parameter - to 'atom'. - :param bool In-progress: true if not final; false when final request. - :statuscode 201: success for deposit on POST - :statuscode 401: Unauthorized - :statuscode 404: access to an unknown collection - :statuscode 415: unsupported media type - -Sample request -~~~~~~~~~~~~~~~ -.. code:: shell - - curl -i -u hal: \ - -F "file=@../deposit.json;type=application/zip;filename=payload" \ - -F "atom=@../atom-entry.xml;type=application/atom+xml;charset=UTF-8" \ - -H 'In-Progress: false' \ - -H 'Slug: some-external-id' \ - -XPOST https://deposit.softwareheritage.org/1/hal/ - -Sample response -~~~~~~~~~~~~~~~ - -.. code:: shell - - HTTP/1.0 201 Created - Date: Tue, 26 Sep 2017 10:32:35 GMT - Server: WSGIServer/0.2 CPython/3.5.3 - Vary: Accept, Cookie - Allow: GET, POST, PUT, DELETE, HEAD, OPTIONS - Location: /1/hal/10/metadata/ - X-Frame-Options: SAMEORIGIN - Content-Type: application/xml - - - 10 - Sept. 26, 2017, 10:32 a.m. - None - deposited - - - - - - - - - - - http://purl.org/net/sword/package/SimpleZip - diff --git a/docs/endpoints/content.rst b/docs/endpoints/content.rst deleted file mode 100644 index ef89d1e9..00000000 --- a/docs/endpoints/content.rst +++ /dev/null @@ -1,14 +0,0 @@ -Display content -^^^^^^^^^^^^^^^^ - -.. http:get:: /1///content/ - - Display information on the content's representation in the sword - server. - - - Also known as: CONT-FILE-IRI - - :param text : the client's credentials - :statuscode 200: no error - :statuscode 401: Unauthorized diff --git a/docs/endpoints/service-document.rst b/docs/endpoints/service-document.rst deleted file mode 100644 index 97a7af19..00000000 --- a/docs/endpoints/service-document.rst +++ /dev/null @@ -1,48 +0,0 @@ -Service document -^^^^^^^^^^^^^^^^^ - -.. http:get:: /1/servicedocument/ - - This is the starting endpoint for the client to discover its initial - collection. The answer to this query will describes: - - * the server's abilities - * connected client's collection information - - Also known as: SD-IRI - The Service Document IRI - - :param text : the client's credentials - :statuscode 200: no error - :statuscode 401: Unauthorized - - - -Sample response -~~~~~~~~~~~~~~~ - .. code:: xml - - - - - 2.0 - 20971520 - - - The Software Heritage (SWH) archive - - SWH Software Archive - application/zip - application/x-tar - Collection Policy - Software Heritage Archive - false - false - Collect, Preserve, Share - http://purl.org/net/sword/package/SimpleZip - https://deposit.softwareheritage.org/1/hal/ - - - diff --git a/docs/endpoints/status.rst b/docs/endpoints/status.rst deleted file mode 100644 index ed17ac87..00000000 --- a/docs/endpoints/status.rst +++ /dev/null @@ -1,76 +0,0 @@ -Retrieve status -^^^^^^^^^^^^^^^^ - -.. http:get:: /1/// - - Returns deposit's status. - - The different statuses: - - - **partial**: multipart deposit is still ongoing - - **deposited**: deposit completed, ready for checks - - **rejected**: deposit failed the checks - - **verified**: content and metadata verified, ready for loading - - **loading**: loading in-progress - - **done**: loading completed successfully - - **failed**: the deposit loading has failed - - Also known as STATE-IRI - - :param text : the client's credentials - :statuscode 201: with the deposit's status - :statuscode 401: Unauthorized - :statuscode 404: access to an unknown deposit - - -Rejected deposit -~~~~~~~~~~~~~~~~ - -It so happens that deposit could be rejected. In that case, the -`deposit_status_detail` entry will explain failed checks. - -Many reasons are possibles, here are some: - -- Deposit without software archive (main goal of the deposit is to - deposit software source code) - -- Deposit with malformed software archive (i.e archive within archive) - -- Deposit with invalid software archive (corrupted archive, although, - this one should happen during upload and not during checks) - -- Deposit with unsupported archive format - -- Deposit with missing metadata - - -Sample response -~~~~~~~~~~~~~~~ - - Successful deposit: - - .. code:: xml - - - 160 - done - The deposit has been successfully loaded into the Software Heritage archive - swh:1:dir:d83b7dda887dc790f7207608474650d4344b8df9 - swh:1:dir:d83b7dda887dc790f7207608474650d4344b8df9;origin=https://forge.softwareheritage.org/source/jesuisgpl/ - swh:1:rev:e76ea49c9ffbb7f73611087ba6e999b19e5d71eb - swh:1:rev:e76ea49c9ffbb7f73611087ba6e999b19e5d71eb;origin=https://forge.softwareheritage.org/source/jesuisgpl/ - - - Rejected deposit: - - .. code:: xml - - - 148 - rejected - - At least one url field must be compatible with the client's domain name (codemeta:url) - diff --git a/docs/endpoints/update-media.rst b/docs/endpoints/update-media.rst deleted file mode 100644 index de32634c..00000000 --- a/docs/endpoints/update-media.rst +++ /dev/null @@ -1,27 +0,0 @@ -Update content -^^^^^^^^^^^^^^^ - -.. http:post:: /1///media/ - - Add archive(s) to a deposit. Only possible if the deposit's status - is partial. - -.. http:put:: /1///media/ - - Replace all content by submitting a new archive. Only possible if - the deposit's status is partial. - - - Also known as: *update iri* (EM-IRI) - - :param text : the client's credentials - :param text Content-Type: accepted mimetype - :param int Content-Length: tarball size - :param text Content-MD5: md5 checksum hex encoded of the tarball - :param text Content-Disposition: attachment; filename=[filename] ; the filename - parameter must be text (ascii) - :param bool In-progress: true if not final; false when final request. - :statuscode 204: success without payload on PUT - :statuscode 201: success for deposit on POST - :statuscode 401: Unauthorized - :statuscode 415: unsupported media type diff --git a/docs/endpoints/update-metadata.rst b/docs/endpoints/update-metadata.rst deleted file mode 100644 index 661d7516..00000000 --- a/docs/endpoints/update-metadata.rst +++ /dev/null @@ -1,24 +0,0 @@ -Update metadata -^^^^^^^^^^^^^^^^ - -.. http:post:: /1///metadata/ - - Add metadata to a deposit. Only possible if the deposit's status - is partial. - -.. http:put:: /1///metadata/ - - Replace all metadata by submitting a new metadata file. Only possible if - the deposit's status is partial. - - - Also known as: *update iri* (SE-IRI) - - :param text : the client's credentials - :param text Content-Disposition: attachment; filename=[filename] ; the filename - parameter must be text (ascii), with a name parameter set to 'atom'. - :param bool In-progress: true if not final; false when final request. - :statuscode 204: success without payload on PUT - :statuscode 201: success for deposit on POST - :statuscode 401: Unauthorized - :statuscode 415: unsupported media type diff --git a/docs/getting-started.rst b/docs/getting-started.rst deleted file mode 100644 index 59d7f858..00000000 --- a/docs/getting-started.rst +++ /dev/null @@ -1,309 +0,0 @@ -Getting Started -=============== - -This is a guide for how to prepare and push a software deposit with -the swh-deposit commands. - -The api is rooted at https://deposit.softwareheritage.org/1. - -For more details, see the `main documentation <./index.html>`__. - -Requirements ------------- - -You need to be referenced on SWH's client list to have: - -* credentials (needed for the basic authentication step) - - - in this document we reference ```` as the client's name and - ```` as its associated authentication password. - -* an associated collection - - -`Contact us for more -information. `__ - -Prepare a deposit ------------------ -* compress the files in a supported archive format: - - - zip: common zip archive (no multi-disk zip files). - - tar: tar archive without compression or optionally any of the - following compression algorithm gzip (.tar.gz, .tgz), bzip2 - (.tar.bz2) , or lzma (.tar.lzma) -* prepare a metadata file (`more details <./metadata.html>`__.): - - - specify metadata schema/vocabulary (CodeMeta is recommended) - - specify *MUST* metadata (url, authors, software name and - the external\_identifier) - - add all available information under the compatible metadata term - - An example of an atom entry file with CodeMeta terms: - -.. code:: xml - - - - Je suis GPL - swh - je-suis-gpl - https://forge.softwareheritage.org/source/jesuisgpl/ - 2018-01-05 - Je suis GPL is a modified version of GNU Hello whose - sole purpose is to showcase the usage of - Software Heritage for license compliance purposes. - 0.1 - GNU/Linux - stable - C - - - GNU General Public License v3.0 or later - https://spdx.org/licenses/GPL-3.0-or-later.html - - - Stefano Zacchiroli - Maintainer - - - - - -Push deposit ------------- -You can push a deposit with: - -* a single deposit (archive + metadata): - - The user posts in one query a software - source code archive and associated metadata. - The deposit is directly marked with status ``deposited``. - -* a multisteps deposit: - - 1. Create an incomplete deposit (marked with status ``partial``) - 2. Add data to a deposit (in multiple requests if needed) - 3. Finalize deposit (the status becomes ``deposited``) - - -Single deposit -^^^^^^^^^^^^^^ - - -Once the files are ready for deposit, we want to do the actual deposit -in one shot, sending exactly one POST query: - -* 1 archive (content-type ``application/zip`` or ``application/x-tar``) -* 1 metadata file in atom xml format (``content-type: application/atom+xml;type=entry``) - -For this, we need to provide the: - -* arguments: ``--username 'name' --password 'pass'`` as credentials -* archive's path (example: ``--archive path/to/archive-name.tgz``) : -* (optionally) metadata file's path ``--metadata - path/to/file.metadata.xml``. If not provided, the archive's filename - will be used to determine the metadata file, e.g: - ``path/to/archive-name.tgz.metadata.xml`` -* (optionally) ``--slug 'your-id'`` argument, a reference to a - unique identifier the client uses for the software object. - -You can do this with the following command: - -minimal deposit - -.. code:: shell - - $ swh-deposit ---username name --password secret \ - --archive je-suis-gpl.tgz - -with client's external identifier (``slug``) - -.. code:: shell - - $ swh-deposit --username name --password secret \ - --archive je-suis-gpl.tgz \ - --slug je-suis-gpl - -to a specific client's collection - -.. code:: shell - - $ swh-deposit --username name --password secret \ - --archive je-suis-gpl.tgz \ - --collection 'second-collection' - - - -You just posted a deposit to your collection on Software Heritage - - -If everything went well, the successful response will contain the -elements below: - -.. code:: shell - - { - 'deposit_status': 'deposited', - 'deposit_id': '7', - 'deposit_date': 'Jan. 29, 2018, 12:29 p.m.' - } - -Note: As the deposit is in ``deposited`` status, you can no longer -update the deposit after this query. It will be answered with a 403 -forbidden answer. - -If something went wrong, an equivalent response will be given with the -`error` and `detail` keys explaining the issue, e.g.: - -.. code:: shell - - { - 'error': 'Unknown collection name xyz', - 'detail': None, - 'deposit_status': None, - 'deposit_status_detail': None, - 'deposit_swh_id': None, - 'status': 404 - } - - - -multisteps deposit -^^^^^^^^^^^^^^^^^^^^^^^^^ -The steps to create a multisteps deposit: - -1. Create an incomplete deposit -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -First use the ``--partial`` argument to declare there is more to come - -.. code:: shell - - $ swh-deposit --username name --password secret \ - --archive foo.tar.gz \ - --partial - - -2. Add content or metadata to the deposit -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Continue the deposit by using the ``--deposit-id`` argument given as a response -for the first step. You can continue adding content or metadata while you use -the ``--partial`` argument. - -.. code:: shell - - $ swh-deposit --username name --password secret \ - --archive add-foo.tar.gz \ - --deposit-id 42 \ - --partial - - -In case you want to add only one new archive without metadata: - -.. code:: shell - - $ swh-deposit --username name --password secret \ - --archive add-foo.tar.gz \ - --archive-deposit \ - --deposit-id 42 \ - --partial \ - -If you want to add only metadata, use: - -.. code:: shell - - $ swh-deposit --username name --password secret \ - --metadata add-foo.tar.gz.metadata.xml \ - --metadata-deposit \ - --deposit-id 42 \ - --partial - -3. Finalize deposit -~~~~~~~~~~~~~~~~~~~ -On your last addition, by not declaring it as ``--partial``, the -deposit will be considered as completed and its status will be changed -to ``deposited``. - - - -Update deposit ----------------- -* replace deposit: - - - only possible if the deposit status is ``partial`` and - ``--deposit-id `` is provided - - - by using the ``--replace`` flag - - - ``--metadata-deposit`` replaces associated existing metadata - - ``--archive-deposit`` replaces associated archive(s) - - by default, with no flag or both, you'll replace associated - metadata and archive(s) - -.. code:: shell - - $ swh-deposit --username name --password secret \ - --deposit-id 11 \ - --archive updated-je-suis-gpl.tgz \ - --replace - -* update a loaded deposit with a new version: - - - by using the external-id with the ``--slug`` argument, you will - link the new deposit with its parent deposit - -.. code:: shell - - $ swh-deposit --username name --password secret \ - --archive je-suis-gpl-v2.tgz \ - --slug 'je-suis-gpl' \ - - - -Check the deposit's status --------------------------- - -You can check the status of the deposit by using the ``--deposit-id`` argument: - -.. code:: shell - - $ swh-deposit --username name --password secret --deposit-id '11' --status - -.. code:: json - - { - 'deposit_id': '11', - 'deposit_status': 'deposited', - 'deposit_swh_id': None, - 'deposit_status_detail': 'Deposit is ready for additional checks \ - (tarball ok, metadata, etc...)' - } - -The different statuses: - -- **partial**: multipart deposit is still ongoing -- **deposited**: deposit completed -- **rejected**: deposit failed the checks -- **verified**: content and metadata verified -- **loading**: loading in-progress -- **done**: loading completed successfully -- **failed**: the deposit loading has failed - -When the deposit has been loaded into the archive, the status will be -marked ``done``. In the response, will also be available the -, , , -. For example: - -.. code:: json - - { - 'deposit_id': '11', - 'deposit_status': 'done', - 'deposit_swh_id': 'swh:1:dir:d83b7dda887dc790f7207608474650d4344b8df9', - 'deposit_swh_id_context': 'swh:1:dir:d83b7dda887dc790f7207608474650d4344b8df9;origin=https://forge.softwareheritage.org/source/jesuisgpl/', - 'deposit_swh_anchor_id': 'swh:1:rev:e76ea49c9ffbb7f73611087ba6e999b19e5d71eb', - 'deposit_swh_anchor_id_context': 'swh:1:rev:e76ea49c9ffbb7f73611087ba6e999b19e5d71eb;origin=https://forge.softwareheritage.org/source/jesuisgpl/', - 'deposit_status_detail': 'The deposit has been successfully \ - loaded into the Software Heritage archive' - } diff --git a/docs/images/deposit-create-chart.png b/docs/images/deposit-create-chart.png deleted file mode 100644 index 97c4eb45..00000000 Binary files a/docs/images/deposit-create-chart.png and /dev/null differ diff --git a/docs/images/deposit-delete-chart.png b/docs/images/deposit-delete-chart.png deleted file mode 100644 index d9ba8ec4..00000000 Binary files a/docs/images/deposit-delete-chart.png and /dev/null differ diff --git a/docs/images/deposit-update-chart.png b/docs/images/deposit-update-chart.png deleted file mode 100644 index d84eb52f..00000000 Binary files a/docs/images/deposit-update-chart.png and /dev/null differ diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index e8ffe3ef..00000000 --- a/docs/index.rst +++ /dev/null @@ -1,22 +0,0 @@ -.. _swh-deposit: - -Software Heritage Deposit -========================= - -.. toctree:: - :maxdepth: 1 - :caption: Contents: - - getting-started.rst - spec-api.rst - metadata.rst - dev-info.rst - sys-info.rst - specs/specs.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/metadata.rst b/docs/metadata.rst deleted file mode 100644 index 52d9cedc..00000000 --- a/docs/metadata.rst +++ /dev/null @@ -1,187 +0,0 @@ -Deposit metadata -================ - -When making a software deposit into the SWH archive, one can add -information describing the software artifact and the software project. - - -Metadata requirements ---------------------- - -- **the schema/vocabulary** used *MUST* be specified with a persistent url - (DublinCore, DOAP, CodeMeta, etc.) - - .. code:: xml - - - or - - or - - -- **the url** representing the location of the source *MUST* be provided under - the url tag. The url will be used for creating an origin object in the - archive. - - .. code:: xml - - www.url-example.com - or - www.url-example.com - or - www.url-example.com - -- **the external\_identifier** *MUST* be provided as an identifier - -- **the name** of the software deposit *MUST* be provided [atom:title, - codemeta:name, dcterms:title] - -- **the authors** of the software deposit *MUST* be provided - -- **the external\_identifier** *SHOULD* match the Slug external-identifier in - the header - -- **the description** of the software deposit *SHOULD* be provided - [codemeta:description]: short or long description of the software - -- **the license/s** of the software - deposit *SHOULD* be provided [codemeta:license] - -- other metadata *MAY* be added with terms defined by the schema in use. - -Examples --------- - -Using only Atom -~~~~~~~~~~~~~~~ - -.. code:: xml - - - - Awesome Compiler - urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a - 1785io25c695 - 2017-10-07T15:17:08Z - some awesome author - - -Using Atom with CodeMeta -~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: xml - - - - Awesome Compiler - urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a - 1785io25c695 - 1785io25c695 - origin url - other identifier, DOI, ARK - Domain - - description - key-word 1 - key-word 2 - creation date - publication date - comment - - article name - article id - - - Collaboration/Projet - project name - id - - see also - Sponsor A - Sponsor B - Platform/OS - dependencies - Version - active - - license - url spdx - - .Net Framework 3.0 - Python2.3 - - author1 - Inria - UPMC - - - author2 - Inria - UPMC - - http://code.com - language 1 - language 2 - http://issuetracker.com - - -Using Atom with DublinCore and CodeMeta (multi-schema entry) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: xml - - - - Awesome Compiler - hal - urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a - %s - hal-01587361 - doi:10.5281/zenodo.438684 - The assignment problem - AffectationRO - author - [INFO] Computer Science [cs] - [INFO.INFO-RO] Computer Science [cs]/Operations Research [cs.RO] - SOFTWARE - Project in OR: The assignment problemA java implementation for the assignment problem first release - description fr - 2015-06-01 - 2017-10-19 - en - - - origin url - - 1.0.0 - key word - Comment - Rfrence interne - - link - Sponsor - - Platform/OS - dependencies - Ended - - license - url spdx - - - http://code.com - language 1 - language 2 - - -Note ----- -We aim on harmonizing the metadata from different origins and thus -metadata will be translated to the `CodeMeta -v.2 `__ vocabulary if -possible. diff --git a/docs/spec-api.rst b/docs/spec-api.rst deleted file mode 100644 index 4a6b3cc2..00000000 --- a/docs/spec-api.rst +++ /dev/null @@ -1,112 +0,0 @@ -API Specification -================= - -This is `Software Heritage `__'s -`SWORD -2.0 `__ -Server implementation. - -**S.W.O.R.D** (**S**\ imple **W**\ eb-Service **O**\ ffering -**R**\ epository **D**\ eposit) is an interoperability standard for -digital file deposit. - -This implementation will permit interaction between a client (a repository) and -a server (SWH repository) to push deposits of software source code archives -with associated metadata. - -*Note:* - -* In the following document, we will use the ``archive`` or ``software source - code archive`` interchangeably. -* The supported archive formats are: - - * zip: common zip archive (no multi-disk zip files). - * tar: tar archive without compression or optionally any of the following - compression algorithm gzip (.tar.gz, .tgz), bzip2 (.tar.bz2) , or lzma - (.tar.lzma) - -Collection ----------- - -SWORD defines a ``collection`` concept. In SWH's case, this collection -refers to a group of deposits. A ``deposit`` is some form of software -source code archive(s) associated with metadata. -By default the client's collection will have the client's name. - -Limitations ------------ -* upload limitation of 100Mib -* no mediation - -API overview ------------- - -API access is over HTTPS. - -The API is protected through basic authentication. - - -Endpoints ---------- - -The API endpoints are rooted at https://deposit.softwareheritage.org/1/. - -Data is sent and received as XML (as specified in the SWORD 2.0 -specification). - -.. include:: endpoints/service-document.rst - -.. include:: endpoints/collection.rst - -.. include:: endpoints/update-media.rst - -.. include:: endpoints/update-metadata.rst - -.. include:: endpoints/status.rst - -.. include:: endpoints/content.rst - - -Possible errors: ----------------- - -* common errors: - - * 401 (unauthenticated) if a client does not provide credential or provide - wrong ones - * 403 (forbidden) if a client tries access to a collection it does not own - * 404 (not found) if a client tries access to an unknown collection - * 404 (not found) if a client tries access to an unknown deposit - * 415 (unsupported media type) if a wrong media type is provided to the - endpoint - -* archive/binary deposit: - - * 403 (forbidden) if the length of the archive exceeds the max size - configured - * 412 (precondition failed) if the length or hash provided mismatch the - reality of the archive. - * 415 (unsupported media type) if a wrong media type is provided - -* multipart deposit: - - * 412 (precondition failed) if the md5 hash provided mismatch the reality of - the archive - * 415 (unsupported media type) if a wrong media type is provided - -* Atom entry deposit: - - * 400 (bad request) if the request's body is empty (for creation only) - - - - -Sources -------- - -* `SWORD v2 specification - `__ -* `arxiv documentation `__ -* `Dataverse example `__ -* `SWORD used on HAL `__ -* `xml examples for CCSD `__ diff --git a/docs/specs/blueprint.rst b/docs/specs/blueprint.rst deleted file mode 100644 index e0b93e8f..00000000 --- a/docs/specs/blueprint.rst +++ /dev/null @@ -1,114 +0,0 @@ -Use cases ---------- - - -Deposit creation -~~~~~~~~~~~~~~~~ - -From client's deposit repository server to SWH's repository server: - -1. The client requests for the server's abilities and its associated collection - (GET query to the *SD/service document uri*) - -2. The server answers the client with the service document which gives the - *collection uri* (also known as *COL/collection IRI*). - -3. The client sends a deposit (optionally a zip archive, some metadata or both) - through the *collection uri*. - - This can be done in: - - * one POST request (metadata + archive). - * one POST request (metadata or archive) + other PUT or POST request to the - *update uris* (*edit-media iri* or *edit iri*) - - a. Server validates the client's input or returns detailed error if any - - b. Server stores information received (metadata or software archive source - code or both) - -4. The server notifies the client it acknowledged the client's request. An - ``http 201 Created`` response with a deposit receipt in the body response is - sent back. That deposit receipt will hold the necessary information to - eventually complete the deposit later on if it was incomplete (also known as - status ``partial``). - -Schema representation -^^^^^^^^^^^^^^^^^^^^^ - -.. raw:: html - - - -.. figure:: /images/deposit-create-chart.png - :alt: - - -Updating an existing deposit -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -5. Client updates existing deposit through the *update uris* (one or more POST - or PUT requests to either the *edit-media iri* or *edit iri*). - - 1. Server validates the client's input or returns detailed error if any - - 2. Server stores information received (metadata or software archive source - code or both) - - This would be the case for example if the client initially posted a - ``partial`` deposit (e.g. only metadata with no archive, or an archive - without metadata, or a splitted archive because the initial one exceeded - the limit size imposed by swh repository deposit) - -Schema representation -^^^^^^^^^^^^^^^^^^^^^ - -.. raw:: html - - - -.. figure:: /images/deposit-update-chart.png - :alt: - -Deleting deposit (or associated archive, or associated metadata) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -6. Deposit deletion is possible as long as the deposit is still in ``partial`` - state. - - 1. Server validates the client's input or returns detailed error if any - 2. Server actually delete information according to request - -Schema representation -^^^^^^^^^^^^^^^^^^^^^ - -.. raw:: html - - - -.. figure:: /images/deposit-delete-chart.png - :alt: - -Client asks for operation status -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -7. Operation status can be read through a GET query to the *state iri*. - -Server: Triggering deposit checks -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Once the status ``deposited`` is reached for a deposit, checks for the -associated archive(s) and metadata will be triggered. If those checks -fail, the status is changed to ``rejected`` and nothing more happens -there. Otherwise, the status is changed to ``verified``. - -Server: Triggering deposit load -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Once the status ``verified`` is reached for a deposit, loading the -deposit with its associated metadata will be triggered. - -The loading will result on status update, either ``done`` or ``failed`` -(depending on the loading's status). - -This is described in the `loading document <./spec-loading.html>`__. diff --git a/docs/specs/metadata_example.xml b/docs/specs/metadata_example.xml deleted file mode 100644 index 7ae6c8e4..00000000 --- a/docs/specs/metadata_example.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - HAL - hal@ccsd.cnrs.fr - - hal - hal-01243573 - The assignment problem - https://hal.archives-ouvertes.fr/hal-01243573 - other identifier, DOI, ARK - Domain - description - - author1 - Inria - UPMC - - - author2 - Inria - UPMC - - - - - - - diff --git a/docs/specs/spec-loading.rst b/docs/specs/spec-loading.rst deleted file mode 100644 index 21c7a0f1..00000000 --- a/docs/specs/spec-loading.rst +++ /dev/null @@ -1,222 +0,0 @@ -Loading specification (draft) -============================= - -This part discusses the deposit loading part on the server side. - -Tarball Loading ---------------- - -The ``swh-loader-tar`` module is already able to inject tarballs in swh -with very limited metadata (mainly the origin). - -The loading of the deposit will use the deposit's associated data: - -* the metadata -* the archive(s) - -We will use the ``synthetic`` revision notion. - -To that revision will be associated the metadata. Those will be included -in the hash computation, thus resulting in a unique identifier. - -Loading mapping -~~~~~~~~~~~~~~~ - -Some of those metadata will also be included in the ``origin_metadata`` -table. - -:: - - origin | https://hal.inria.fr/hal-id | - ------------------------------------|----------------------------------------| - origin_visit | 1 :reception_date | - origin_metadata | aggregated metadata | - occurrence & occurrence_history | branch: client's version n° (e.g hal) | - revision | synthetic_revision (tarball) | - directory | upper level of the uncompressed archive| - -Questions raised concerning loading -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -- A deposit has one origin, yet an origin can have multiple deposits? - -No, an origin can have multiple requests for the same deposit. Which -should end up in one single deposit (when the client pushes its final -request saying deposit 'done' through the header In-Progress). - -Only update of existing 'partial' deposit is permitted. Other than that, -the deposit 'update' operation. - -To create a new version of a software (already deposited), the client -must prior to this create a new deposit. - -Illustration First deposit loading: - -HAL's deposit 01535619 = SWH's deposit **01535619-1** - -:: - - + 1 origin with url:https://hal.inria.fr/medihal-01535619 - - + 1 synthetic revision - - + 1 directory - -HAL's update on deposit 01535619 = SWH's deposit **01535619-2** - -(\*with HAL updates can only be on the metadata and a new version is -required if the content changes) - -:: - - + 1 origin with url:https://hal.inria.fr/medihal-01535619 - - + new synthetic revision (with new metadata) - - + same directory - -HAL's deposit 01535619-v2 = SWH's deposit **01535619-v2-1** - -:: - - + same origin - - + new revision - - + new directory - -Technical details ------------------ - -Requirements -~~~~~~~~~~~~ - -* one dedicated database to store the deposit's state - swh-deposit -* one dedicated temporary objstorage to store archives before loading -* one client to test the communication with SWORD protocol - -Deposit reception schema -~~~~~~~~~~~~~~~~~~~~~~~~ - -* SWORD imposes the use of basic authentication, so we need a way to - authenticate client. Also, a client can access collections: - - **deposit\_client** table: - id (bigint): Client's identifier - username - (str): Client's username - password (pass): Client's crypted password - - collections ([id]): List of collections the client can access - -* Collections group deposits together: - - **deposit\_collection** table: - id (bigint): Collection's identifier - name - (str): Collection's human readable name - -* A deposit is the main object the repository is all about: - - **deposit** table: - - * id (bigint): deposit's identifier - * reception\_date (date): First deposit's reception date - * complete\_data (date): Date when the deposit is deemed complete and ready - for loading - * collection (id): The collection the deposit belongs to - * external id (text): client's internal identifier (e.g hal's id, etc...). - * client\_id (id) : Client which did the deposit - * swh\_id (str) : swh identifier result once the loading is complete - * status (enum): The deposit's current status - -- As mentioned, a deposit can have a status, whose possible values are: - - .. code:: text - - 'partial', -- the deposit is new or partially received since it - -- can be done in multiple requests - 'expired', -- deposit has been there too long and is now deemed - -- ready to be garbage collected - 'deposited' -- deposit complete, it is ready to be checked to ensure data consistency - 'verified', -- deposit is fully received, checked, and ready for loading - 'loading', -- loading is ongoing on swh's side - 'done', -- loading is successful - 'failed' -- loading is a failure - -* A deposit is stateful and can be made in multiple requests: - - **deposit\_request** table: - * id (bigint): identifier - * type (id): deposit request's type (possible values: 'archive', 'metadata') - * deposit\_id (id): deposit whose request belongs to - * metadata: metadata associated to the request - * date (date): date of the requests - - Information sent along a request are stored in a ``deposit_request`` row. - - They can be either of type ``metadata`` (atom entry, multipart's atom entry - part) or of type ``archive`` (binary upload, multipart's binary upload part). - - When the deposit is complete (status ``deposited``), those ``metadata`` and - ``archive`` deposit requests will be read and aggregated. They will then be - sent as parameters to the loading routine. - - During loading, some of those metadata are kept in the ``origin_metadata`` - table and some other are stored in the ``revision`` table (see `metadata - loading <#metadata-loading>`__). - - The only update actions occurring on the deposit table are in regards of: - - status changing: - ``partial`` -> {``expired``/``deposited``}, - - ``deposited`` -> {``rejected``/``verified``}, - ``verified`` -> ``loading`` - - ``loading`` -> {``done``/``failed``} - ``complete_date`` when the deposit is - finalized (when the status is changed to ``deposited``) - ``swh-id`` is - populated once we have the loading result - -SWH Identifier returned -^^^^^^^^^^^^^^^^^^^^^^^ - -:: - - The synthetic revision id - - e.g.: swh:1:rev:47dc6b4636c7f6cba0df83e3d5490bf4334d987e - -Scheduling loading -~~~~~~~~~~~~~~~~~~ - -All ``archive`` and ``metadata`` deposit requests should be aggregated before -loading. - -The loading should be scheduled via the scheduler's api. - -Only ``deposited`` deposit are concerned by the loading. - -When the loading is done and successful, the deposit entry is updated: - -``status`` is updated to ``done`` - ``swh-id`` is populated with the resulting -hash (cf. `swh identifier <#swh-identifier-returned>`__) - ``complete_date`` is -updated to the loading's finished time - -When the loading is failed, the deposit entry is updated: - ``status`` is -updated to ``failed`` - ``swh-id`` and ``complete_data`` remains as is - -*Note:* As a further improvement, we may prefer having a retry policy with -graceful delays for further scheduling. - -Metadata loading -~~~~~~~~~~~~~~~~ - -- the metadata received with the deposit should be kept in the - ``origin_metadata`` table before translation as part of the loading process - and an indexation process should be scheduled. - -- provider\_id and tool\_id are resolved by the prepare\_metadata method in the - loader-core - -- the origin\_metadata entry is sent to storage by the send\_origin\_metadata - in the loader-core - -origin\_metadata table: - -:: - - id bigint PK - origin bigint - discovery_date date - provider_id bigint FK // (from provider table) - tool_id bigint FK // indexer_configuration_id tool used for extraction - metadata jsonb // before translation diff --git a/docs/specs/spec-meta-deposit.rst b/docs/specs/spec-meta-deposit.rst deleted file mode 100644 index 887baef2..00000000 --- a/docs/specs/spec-meta-deposit.rst +++ /dev/null @@ -1,98 +0,0 @@ -The metadata-deposit -==================== - -Goal ----- -A client wishes to deposit only metadata about an object in the Software -Heritage archive. - -The metadata-deposit is a special deposit where no content is -provided and the data transfered to Software Heritage is only -the metadata about an object or several objects in the archive. - -Requirements ------------- -The scope of the meta-deposit is different than the -sparse-deposit. While a sparse-deposit creates a revision with referenced -directories and content files, the metadata-deposit references one of the -following: - -- origin -- snapshot -- revision -- release - - -A complete metadata example ---------------------------- -The reference element is included in the metadata xml atomEntry under the -swh namespace (a link for the published schema will be provided during -the implementation of the metadata deposit): - -.. code:: xml - - - - - HAL - hal@ccsd.cnrs.fr - - hal - hal-01243573 - The assignment problem - https://hal.archives-ouvertes.fr/hal-01243573 - other identifier, DOI, ARK - Domain - description - - author1 - Inria - UPMC - - - author2 - Inria - UPMC - - - - - - - - -Examples by target type -^^^^^^^^^^^^^^^^^^^^^^^ -Reference an origin: - -.. code:: xml - - - - - - - - -Reference a snapshot, revision or release: - -.. code:: xml - - With ${type} in {snp (snapshot), rev (revision), rel (release) }: - - - - - - - - -Loading procedure ------------------- - -In this case, the metadata-deposit will be injected as a metadata entry at the -appropriate level (origin_metadata, revision_metadata, etc.) with the information -about the contributor of the deposit. Contrary to the complete and sparse -deposit, there will be no object creation. diff --git a/docs/specs/spec-sparse-deposit.rst b/docs/specs/spec-sparse-deposit.rst deleted file mode 100644 index ffa001ae..00000000 --- a/docs/specs/spec-sparse-deposit.rst +++ /dev/null @@ -1,102 +0,0 @@ -The sparse-deposit -================== - -Goal ----- -A client wishes to transfer a tarball for which part of the content is -already in the SWH archive. - -Requirements ------------- -To do so, a list of paths with targets must be provided in the metadata and -the paths to the missing directories/content should not be included -in the tarball. The list will be referred to -as the manifest list using the entry name 'bindings' in the metadata. - -+----------------------+-------------------------------------+ -| path | swh-id | -+======================+=====================================+ -| path/to/file.txt | swh:1:cnt:aaaaaaaaaaaaaaaaaaaaa... | -+----------------------+-------------------------------------+ -| path/to/dir/ | swh:1:dir:aaaaaaaaaaaaaaaaaaaaa... | -+----------------------+-------------------------------------+ - -Note: the *name* of the file or the directory is given by the path and is not -part of the identified object. - -A concrete example ------------------- -The manifest list is included in the metadata xml atomEntry under the -swh namespace (a link for the published schema will be provided during -the implementation of the sparse deposit): - -.. code:: xml - - - - - HAL - hal@ccsd.cnrs.fr - - hal - hal-01243573 - The assignment problem - https://hal.archives-ouvertes.fr/hal-01243573 - other identifier, DOI, ARK - Domain - description - - author1 - Inria - UPMC - - - author2 - Inria - UPMC - - - - - - - - - - - - -Deposit verification --------------------- - -After checking the integrity of the deposit content and -metadata, the following checks should be added: - -1. validate the manifest list structure with a correct swh-id for each path (syntax check on the swh-id format) -2. verify that the path name corresponds to the object type -3. locate the identifiers in the SWH archive - -Each failing check should return a different error with the deposit -and result in a 'rejected' deposit. - -Loading procedure ------------------- -The injection procedure should include: - -- load the tarball new data -- create new objects using the path name and create links from the path to the - SWH object using the identifier -- calculate identifier of the new objects at each level -- return final swh-id of the new revision - -Invariant: the same content should yield the same swh-id, -that's why a complete deposit with all the content and -a sparse-deposit with the correct links will result -with the same root directory swh-id. -The same is expected with the revision swh-id if the metadata provided is -identical. diff --git a/docs/specs/specs.rst b/docs/specs/specs.rst deleted file mode 100644 index bb86993d..00000000 --- a/docs/specs/specs.rst +++ /dev/null @@ -1,13 +0,0 @@ -.. _swh-deposit-specs: - -Blueprint Specifications -========================= - -.. toctree:: - :maxdepth: 1 - :caption: Contents: - - blueprint.rst - spec-loading.rst - spec-sparse-deposit.rst - spec-meta-deposit.rst diff --git a/docs/specs/swh.xsd b/docs/specs/swh.xsd deleted file mode 100644 index 4dbf0ac6..00000000 --- a/docs/specs/swh.xsd +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/sys-info.rst b/docs/sys-info.rst deleted file mode 100644 index 582fbc7c..00000000 --- a/docs/sys-info.rst +++ /dev/null @@ -1,51 +0,0 @@ -Deployment of the swh-deposit -============================= - -As usual, the debian packaged is created and uploaded to the swh debian -repository. Once the package is installed, we need to do a few things in -regards to the database. - -Prepare the database setup (existence, connection, etc...). ------------------------------------------------------------ - -This is defined through the packaged ``swh.deposit.settings.production`` -module and the expected **/etc/softwareheritage/deposit/private.yml**. - -As usual, the expected configuration files are deployed through our -puppet manifest (cf. puppet-environment/swh-site, -puppet-environment/swh-role, puppet-environment/swh-profile) - -Migrate/bootstrap the db schema -------------------------------- - -.. code:: shell - - sudo django-admin migrate --settings=swh.deposit.settings.production - -Load minimum defaults data --------------------------- - -.. code:: shell - - sudo django-admin loaddata --settings=swh.deposit.settings.production deposit_data - -This adds the minimal: - deposit request type 'archive' and 'metadata' - -'hal' collection - -Note: swh.deposit.fixtures.deposit\_data is packaged - -Add client and collection -------------------------- - -.. code:: shell - - python3 -m swh.deposit.create_user --platform production \ - --collection \ - --username \ - --password - -This adds a user ```` which can access the collection -````. The password will be used for the authentication -access to the deposit api. - -Note: This creation procedure needs to be improved. diff --git a/requirements-swh.txt b/requirements-swh.txt index 5dde0cd2..dc3f43fe 100644 --- a/requirements-swh.txt +++ b/requirements-swh.txt @@ -1,5 +1,5 @@ swh.core >= 0.0.36 -swh.loader.tar >= 0.0.35 +swh.loader.tar >= 0.0.37 swh.loader.core >= 0.0.32 -swh.scheduler >= 0.0.26 +swh.scheduler >= 0.0.39 swh.model >= 0.0.26 diff --git a/requirements-test.txt b/requirements-test.txt deleted file mode 100644 index f3c7e8e6..00000000 --- a/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -nose diff --git a/requirements.txt b/requirements.txt index 40c6d884..8bf3155c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,5 @@ vcversioner click -Django +Django < 2.0 djangorestframework xmltodict diff --git a/resources/deposit/server.yml b/resources/deposit/server.yml deleted file mode 100644 index b7dbba1f..00000000 --- a/resources/deposit/server.yml +++ /dev/null @@ -1,2 +0,0 @@ -# 200 Mib max size -max_upload_size: 209715200 diff --git a/setup.py b/setup.py index 3824b5d4..52090e35 100755 --- a/setup.py +++ b/setup.py @@ -1,41 +1,66 @@ #!/usr/bin/env python3 - -import os +# Copyright (C) 2015-2018 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information from setuptools import setup, find_packages +from os import path +from io import open + +here = path.abspath(path.dirname(__file__)) + +# Get the long description from the README file +with open(path.join(here, 'README.md'), encoding='utf-8') as f: + long_description = f.read() + def parse_requirements(name=None): if name: reqf = 'requirements-%s.txt' % name else: reqf = 'requirements.txt' requirements = [] - if not os.path.exists(reqf): + if not path.exists(reqf): return requirements with open(reqf) as f: for line in f.readlines(): line = line.strip() if not line or line.startswith('#'): continue requirements.append(line) return requirements setup( name='swh.deposit', description='Software Heritage Deposit Server', + long_description=long_description, + long_description_content_type='text/markdown', author='Software Heritage developers', author_email='swh-devel@inria.fr', url='https://forge.softwareheritage.org/source/swh-deposit/', packages=find_packages(), scripts=['bin/swh-deposit'], # scripts to package install_requires=parse_requirements() + parse_requirements('swh'), - test_requires=parse_requirements('test'), - extras_require={}, + tests_require=parse_requirements('test'), setup_requires=['vcversioner'], + extras_require={'testing': parse_requirements('test')}, vcversioner={}, include_package_data=True, + classifiers=[ + "Programming Language :: Python :: 3", + "Intended Audience :: Developers", + "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "Operating System :: OS Independent", + "Development Status :: 5 - Production/Stable", + ], + project_urls={ + 'Bug Reports': 'https://forge.softwareheritage.org/maniphest', + 'Funding': 'https://www.softwareheritage.org/donate', + 'Source': 'https://forge.softwareheritage.org/source/swh-deposit', + }, ) diff --git a/swh.deposit.egg-info/PKG-INFO b/swh.deposit.egg-info/PKG-INFO index d4d2aa01..7fb5a638 100644 --- a/swh.deposit.egg-info/PKG-INFO +++ b/swh.deposit.egg-info/PKG-INFO @@ -1,10 +1,34 @@ -Metadata-Version: 1.0 +Metadata-Version: 2.1 Name: swh.deposit -Version: 0.0.63 +Version: 0.0.65 Summary: Software Heritage Deposit Server Home-page: https://forge.softwareheritage.org/source/swh-deposit/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN -Description: UNKNOWN +Project-URL: Funding, https://www.softwareheritage.org/donate +Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest +Project-URL: Source, https://forge.softwareheritage.org/source/swh-deposit +Description: # swh-deposit + + This is [Software Heritage](https://www.softwareheritage.org)'s + [SWORD 2.0](http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html) Server + implementation. + + **S.W.O.R.D** (**S**imple **W**eb-Service **O**ffering **R**epository + **D**eposit) is an interoperability standard for digital file deposit. + + This implementation will permit interaction between a client (a + repository) and a server (SWH repository) to permit deposits of + software source code archives and associated metadata. + + The documentation is at ./docs/README-specification.md + Platform: UNKNOWN +Classifier: Programming Language :: Python :: 3 +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) +Classifier: Operating System :: OS Independent +Classifier: Development Status :: 5 - Production/Stable +Description-Content-Type: text/markdown +Provides-Extra: testing diff --git a/swh.deposit.egg-info/SOURCES.txt b/swh.deposit.egg-info/SOURCES.txt index 3745fa2f..8e1e6b79 100644 --- a/swh.deposit.egg-info/SOURCES.txt +++ b/swh.deposit.egg-info/SOURCES.txt @@ -1,168 +1,117 @@ -.gitignore -AUTHORS -LICENSE MANIFEST.in Makefile -Makefile.local README.md requirements-swh.txt -requirements-test.txt requirements.txt setup.py version.txt -bin/Makefile -bin/content.sh -bin/create_deposit.sh -bin/create_deposit_atom.sh -bin/create_deposit_with_metadata.sh -bin/default-setup -bin/download-deposit-archive.sh -bin/home.sh -bin/replace-deposit-archive.sh -bin/service-document.sh -bin/status.sh bin/swh-deposit -bin/update-deposit-with-another-archive.sh -bin/update-status.sh -debian/changelog -debian/compat -debian/control -debian/copyright -debian/rules -debian/source/format -docs/.gitignore -docs/Makefile -docs/conf.py -docs/dev-info.rst -docs/getting-started.rst -docs/index.rst -docs/metadata.rst -docs/spec-api.rst -docs/sys-info.rst -docs/_static/.placeholder -docs/_templates/.placeholder -docs/endpoints/collection.rst -docs/endpoints/content.rst -docs/endpoints/service-document.rst -docs/endpoints/status.rst -docs/endpoints/update-media.rst -docs/endpoints/update-metadata.rst -docs/images/deposit-create-chart.png -docs/images/deposit-delete-chart.png -docs/images/deposit-update-chart.png -docs/specs/blueprint.rst -docs/specs/metadata_example.xml -docs/specs/spec-loading.rst -docs/specs/spec-meta-deposit.rst -docs/specs/spec-sparse-deposit.rst -docs/specs/specs.rst -docs/specs/swh.xsd -resources/deposit/server.yml swh/__init__.py swh/manage.py swh.deposit.egg-info/PKG-INFO swh.deposit.egg-info/SOURCES.txt swh.deposit.egg-info/dependency_links.txt swh.deposit.egg-info/requires.txt swh.deposit.egg-info/top_level.txt swh/deposit/__init__.py swh/deposit/apps.py swh/deposit/auth.py swh/deposit/config.py swh/deposit/create_user.py swh/deposit/errors.py swh/deposit/models.py swh/deposit/parsers.py swh/deposit/signals.py swh/deposit/urls.py swh/deposit/utils.py swh/deposit/wsgi.py swh/deposit/api/__init__.py swh/deposit/api/common.py swh/deposit/api/converters.py swh/deposit/api/deposit.py swh/deposit/api/deposit_content.py swh/deposit/api/deposit_status.py swh/deposit/api/deposit_update.py swh/deposit/api/service_document.py swh/deposit/api/urls.py swh/deposit/api/private/__init__.py swh/deposit/api/private/deposit_check.py swh/deposit/api/private/deposit_list.py swh/deposit/api/private/deposit_read.py swh/deposit/api/private/deposit_update_status.py swh/deposit/api/private/urls.py swh/deposit/client/__init__.py swh/deposit/client/cli.py swh/deposit/fixtures/__init__.py swh/deposit/fixtures/deposit_data.yaml swh/deposit/loader/__init__.py swh/deposit/loader/checker.py swh/deposit/loader/loader.py -swh/deposit/loader/scheduler.py swh/deposit/loader/tasks.py swh/deposit/migrations/0001_initial.py swh/deposit/migrations/0002_depositrequest_archive.py swh/deposit/migrations/0003_temporaryarchive.py swh/deposit/migrations/0004_delete_temporaryarchive.py swh/deposit/migrations/0005_auto_20171019_1436.py swh/deposit/migrations/0006_depositclient_url.py swh/deposit/migrations/0007_auto_20171129_1609.py swh/deposit/migrations/0008_auto_20171130_1513.py swh/deposit/migrations/0009_deposit_parent.py swh/deposit/migrations/0010_auto_20180110_0953.py swh/deposit/migrations/0011_auto_20180115_1510.py swh/deposit/migrations/0012_deposit_status_detail.py swh/deposit/migrations/0013_depositrequest_raw_metadata.py swh/deposit/migrations/0014_auto_20180720_1221.py swh/deposit/migrations/__init__.py swh/deposit/settings/__init__.py swh/deposit/settings/common.py swh/deposit/settings/development.py swh/deposit/settings/production.py swh/deposit/settings/testing.py swh/deposit/static/robots.txt swh/deposit/static/css/bootstrap-responsive.min.css swh/deposit/static/css/style.css swh/deposit/static/img/arrow-up-small.png swh/deposit/static/img/swh-logo-deposit.png swh/deposit/static/img/swh-logo-deposit.svg swh/deposit/static/img/icons/swh-logo-32x32.png swh/deposit/static/img/icons/swh-logo-deposit-180x180.png swh/deposit/static/img/icons/swh-logo-deposit-192x192.png swh/deposit/static/img/icons/swh-logo-deposit-270x270.png swh/deposit/templates/__init__.py swh/deposit/templates/homepage.html swh/deposit/templates/layout.html swh/deposit/templates/deposit/__init__.py swh/deposit/templates/deposit/content.xml swh/deposit/templates/deposit/deposit_receipt.xml swh/deposit/templates/deposit/error.xml swh/deposit/templates/deposit/service_document.xml swh/deposit/templates/deposit/status.xml swh/deposit/templates/rest_framework/api.html swh/deposit/tests/__init__.py swh/deposit/tests/common.py swh/deposit/tests/test_utils.py swh/deposit/tests/api/__init__.py swh/deposit/tests/api/test_common.py swh/deposit/tests/api/test_converters.py swh/deposit/tests/api/test_deposit.py swh/deposit/tests/api/test_deposit_atom.py swh/deposit/tests/api/test_deposit_binary.py swh/deposit/tests/api/test_deposit_check.py swh/deposit/tests/api/test_deposit_delete.py swh/deposit/tests/api/test_deposit_list.py swh/deposit/tests/api/test_deposit_multipart.py swh/deposit/tests/api/test_deposit_read_archive.py swh/deposit/tests/api/test_deposit_read_metadata.py swh/deposit/tests/api/test_deposit_status.py swh/deposit/tests/api/test_deposit_update.py swh/deposit/tests/api/test_deposit_update_status.py swh/deposit/tests/api/test_parser.py swh/deposit/tests/api/test_service_document.py swh/deposit/tests/loader/__init__.py swh/deposit/tests/loader/common.py +swh/deposit/tests/loader/conftest.py swh/deposit/tests/loader/test_checker.py swh/deposit/tests/loader/test_client.py -swh/deposit/tests/loader/test_loader.py \ No newline at end of file +swh/deposit/tests/loader/test_loader.py +swh/deposit/tests/loader/test_tasks.py \ No newline at end of file diff --git a/swh.deposit.egg-info/requires.txt b/swh.deposit.egg-info/requires.txt index fcdfc32c..3a09e20b 100644 --- a/swh.deposit.egg-info/requires.txt +++ b/swh.deposit.egg-info/requires.txt @@ -1,10 +1,15 @@ -Django +vcversioner click +Django<2.0 djangorestframework +xmltodict swh.core>=0.0.36 +swh.loader.tar>=0.0.37 swh.loader.core>=0.0.32 -swh.loader.tar>=0.0.35 +swh.scheduler>=0.0.39 swh.model>=0.0.26 -swh.scheduler>=0.0.26 -vcversioner -xmltodict + +[testing] +pytest<4 +pytest-django +swh.scheduler[testing] diff --git a/swh/deposit/api/converters.py b/swh/deposit/api/converters.py index 928fb248..6707f9ba 100644 --- a/swh/deposit/api/converters.py +++ b/swh/deposit/api/converters.py @@ -1,58 +1,57 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information def convert_status_detail(status_detail): - """Given a status_detail dict, transforms it into a human readable - string. - - Dict has the following form (all first level keys are optional): - { - 'url': { - 'summary': , - 'fields': - }, - 'metadata': [{ - 'summary': , - 'fields': , - }], - 'archive': [{ - 'summary': , - 'fields': , - }] - - - } + """Given a status_detail dict, transforms it into a human readable string. + + Dict has the following form (all first level keys are optional):: + + { + 'url': { + 'summary': "summary-string", + 'fields': [impacted-fields-list] + }, + 'metadata': [{ + 'summary': "summary-string", + 'fields': [impacted-fields-list], + }], + 'archive': [{ + 'summary': "summary-string", + 'fields': [impacted-fields-list], + }] + } Args: - status_detail (dict): + status_detail (dict): The status detail dict with the syntax + mentioned Returns: - Status detail as inlined string. + the status detail as inlined string """ if not status_detail: return None def _str_fields(data): fields = data.get('fields') if not fields: return '' return ' (%s)' % ', '.join(map(str, fields)) msg = [] for key in ['metadata', 'archive']: _detail = status_detail.get(key) if _detail: for data in _detail: msg.append('- %s%s\n' % (data['summary'], _str_fields(data))) _detail = status_detail.get('url') if _detail: msg.append('- %s%s\n' % (_detail['summary'], _str_fields(_detail))) if not msg: return None return ''.join(msg) diff --git a/swh/deposit/api/deposit_update.py b/swh/deposit/api/deposit_update.py index 42af22e0..109902a7 100644 --- a/swh/deposit/api/deposit_update.py +++ b/swh/deposit/api/deposit_update.py @@ -1,155 +1,148 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from rest_framework import status from .common import SWHPostDepositAPI, SWHPutDepositAPI, SWHDeleteDepositAPI from .common import ACCEPT_ARCHIVE_CONTENT_TYPES from ..config import CONT_FILE_IRI, EDIT_SE_IRI, EM_IRI from ..errors import make_error_dict, BAD_REQUEST from ..parsers import SWHFileUploadZipParser, SWHFileUploadTarParser from ..parsers import SWHAtomEntryParser from ..parsers import SWHMultiPartParser class SWHUpdateArchiveDeposit(SWHPostDepositAPI, SWHPutDepositAPI, SWHDeleteDepositAPI): """Deposit request class defining api endpoints for sword deposit. - What's known as 'EM IRI' in the sword specification. + What's known as 'EM IRI' in the sword specification. - HTTP verbs supported: PUT, POST, DELETE + HTTP verbs supported: PUT, POST, DELETE """ parser_classes = (SWHFileUploadZipParser, SWHFileUploadTarParser, ) def process_put(self, req, headers, collection_name, deposit_id): """Replace existing content for the existing deposit. - source: http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html - #protocoloperations_editingcontent_binary + source: http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_editingcontent_binary # noqa Returns: 204 No content """ if req.content_type not in ACCEPT_ARCHIVE_CONTENT_TYPES: msg = 'Packaging format supported is restricted to %s' % ( ', '.join(ACCEPT_ARCHIVE_CONTENT_TYPES)) return make_error_dict(BAD_REQUEST, msg) return self._binary_upload(req, headers, collection_name, deposit_id=deposit_id, replace_archives=True) def process_post(self, req, headers, collection_name, deposit_id): """Add new content to the existing deposit. - source: http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html - #protocoloperations_addingcontent_mediaresource + source: http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_addingcontent_mediaresource # noqa Returns: 201 Created Headers: Location: [Cont-File-IRI] Body: [optional Deposit Receipt] """ if req.content_type not in ACCEPT_ARCHIVE_CONTENT_TYPES: msg = 'Packaging format supported is restricted to %s' % ( ', '.join(ACCEPT_ARCHIVE_CONTENT_TYPES)) return 'unused', 'unused', make_error_dict(BAD_REQUEST, msg) return (status.HTTP_201_CREATED, CONT_FILE_IRI, self._binary_upload(req, headers, collection_name, deposit_id)) def process_delete(self, req, collection_name, deposit_id): """Delete content (archives) from existing deposit. - source: http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html - #protocoloperations_deletingcontent + source: http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_deletingcontent # noqa Returns: 204 Created """ return self._delete_archives(collection_name, deposit_id) class SWHUpdateMetadataDeposit(SWHPostDepositAPI, SWHPutDepositAPI, SWHDeleteDepositAPI): """Deposit request class defining api endpoints for sword deposit. - What's known as 'Edit IRI' (and SE IRI) in the sword specification. + What's known as 'Edit IRI' (and SE IRI) in the sword specification. - HTTP verbs supported: POST (SE IRI), PUT (Edit IRI), DELETE + HTTP verbs supported: POST (SE IRI), PUT (Edit IRI), DELETE """ parser_classes = (SWHMultiPartParser, SWHAtomEntryParser) def process_put(self, req, headers, collection_name, deposit_id): """Replace existing deposit's metadata/archive with new ones. - source: - - http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html - #protocoloperations_editingcontent_metadata - - http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html - #protocoloperations_editingcontent_multipart + source: + - http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_editingcontent_metadata # noqa + - http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_editingcontent_multipart # noqa Returns: 204 No content """ if req.content_type.startswith('multipart/'): return self._multipart_upload(req, headers, collection_name, deposit_id=deposit_id, replace_archives=True, replace_metadata=True) return self._atom_entry(req, headers, collection_name, deposit_id=deposit_id, replace_metadata=True) def process_post(self, req, headers, collection_name, deposit_id): """Add new metadata/archive to existing deposit. - source: - - http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html - #protocoloperations_addingcontent_metadata - - http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html - #protocoloperations_addingcontent_multipart + source: + - http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_addingcontent_metadata # noqa + - http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_addingcontent_multipart # noqa This also deals with an empty post corner case to finalize a deposit. Returns: In optimal case for a multipart and atom-entry update, a 201 Created response. The body response will hold a deposit. And the response headers will contain an entry 'Location' with the EM-IRI. For the empty post case, this returns a 200. """ if req.content_type.startswith('multipart/'): return (status.HTTP_201_CREATED, EM_IRI, self._multipart_upload(req, headers, collection_name, deposit_id=deposit_id)) # check for final empty post # source: http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html # #continueddeposit_complete if headers['content-length'] == 0 and headers['in-progress'] is False: data = self._empty_post(req, headers, collection_name, deposit_id) return (status.HTTP_200_OK, EDIT_SE_IRI, data) return (status.HTTP_201_CREATED, EM_IRI, self._atom_entry(req, headers, collection_name, deposit_id=deposit_id)) def process_delete(self, req, collection_name, deposit_id): """Delete the container (deposit). - Source: http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html - #protocoloperations_deleteconteiner + source: http://swordapp.github.io/SWORDv2-Profile/SWORDProfile.html#protocoloperations_deleteconteiner # noqa + """ return self._delete_deposit(collection_name, deposit_id) diff --git a/swh/deposit/api/private/deposit_read.py b/swh/deposit/api/private/deposit_read.py index 833dcf29..6d28f106 100644 --- a/swh/deposit/api/private/deposit_read.py +++ b/swh/deposit/api/private/deposit_read.py @@ -1,209 +1,209 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import json import os import shutil import tempfile from contextlib import contextmanager from django.http import FileResponse from rest_framework import status from swh.core import tarball from swh.model import identifiers from . import DepositReadMixin from ...config import SWH_PERSON, ARCHIVE_TYPE from ..common import SWHGetDepositAPI, SWHPrivateAPIView from ...models import Deposit @contextmanager def aggregate_tarballs(extraction_dir, archive_paths): """Aggregate multiple tarballs into one and returns this new archive's path. Args: extraction_dir (path): Path to use for the tarballs computation archive_paths ([str]): Deposit's archive paths Returns: Tuple (directory to clean up, archive path (aggregated or not)) """ - if len(archive_paths) > 1: # need to rebuild one archive - # from multiple ones + if len(archive_paths) > 1: + # need to rebuild one archive from multiple ones os.makedirs(extraction_dir, 0o755, exist_ok=True) dir_path = tempfile.mkdtemp(prefix='swh.deposit-', dir=extraction_dir) # root folder to build an aggregated tarball aggregated_tarball_rootdir = os.path.join(dir_path, 'aggregate') os.makedirs(aggregated_tarball_rootdir, 0o755, exist_ok=True) # uncompress in a temporary location all archives for archive_path in archive_paths: tarball.uncompress(archive_path, aggregated_tarball_rootdir) # Aggregate into one big tarball the multiple smaller ones temp_tarpath = tarball.compress( aggregated_tarball_rootdir + '.zip', nature='zip', dirpath_or_files=aggregated_tarball_rootdir) # can already clean up temporary directory shutil.rmtree(aggregated_tarball_rootdir) try: yield temp_tarpath finally: shutil.rmtree(dir_path) else: # only 1 archive, no need to do fancy actions (and no cleanup step) yield archive_paths[0] class SWHDepositReadArchives(SWHGetDepositAPI, SWHPrivateAPIView, DepositReadMixin): """Dedicated class to read a deposit's raw archives content. Only GET is supported. """ ADDITIONAL_CONFIG = { 'extraction_dir': ('str', '/tmp/swh-deposit/archive/'), } def __init__(self): super().__init__() self.extraction_dir = self.config['extraction_dir'] if not os.path.exists(self.extraction_dir): os.makedirs(self.extraction_dir) def process_get(self, req, collection_name, deposit_id): """Build a unique tarball from the multiple received and stream that content to the client. Args: req (Request): collection_name (str): Collection owning the deposit deposit_id (id): Deposit concerned by the reading Returns: Tuple status, stream of content, content-type """ archive_paths = [r.archive.path for r in self._deposit_requests( deposit_id, request_type=ARCHIVE_TYPE)] with aggregate_tarballs(self.extraction_dir, archive_paths) as path: return FileResponse(open(path, 'rb'), status=status.HTTP_200_OK, content_type='application/octet-stream') class SWHDepositReadMetadata(SWHGetDepositAPI, SWHPrivateAPIView, DepositReadMixin): """Class in charge of aggregating metadata on a deposit. """ ADDITIONAL_CONFIG = { 'provider': ('dict', { # 'provider_name': '', # those are not set since read from the # 'provider_url': '', # deposit's client 'provider_type': 'deposit_client', 'metadata': {} }), 'tool': ('dict', { 'name': 'swh-deposit', 'version': '0.0.1', 'configuration': { 'sword_version': '2' } }) } def __init__(self): super().__init__() self.provider = self.config['provider'] self.tool = self.config['tool'] def _retrieve_url(self, deposit, metadata): client_domain = deposit.client.domain for field in metadata: if 'url' in field: if client_domain in metadata[field]: return metadata[field] def metadata_read(self, deposit): """Read and aggregate multiple data on deposit into one unified data dictionary. Args: deposit (Deposit): Deposit concerned by the data aggregation. Returns: Dictionary of data representing the deposit to inject in swh. """ data = {} metadata = self._metadata_get(deposit) # create origin_url from metadata only after deposit_check validates it origin_url = self._retrieve_url(deposit, metadata) # Read information metadata data['origin'] = { 'type': 'deposit', 'url': origin_url } # revision fullname = deposit.client.username author_committer = SWH_PERSON # metadata provider self.provider['provider_name'] = deposit.client.last_name self.provider['provider_url'] = deposit.client.provider_url revision_type = 'tar' revision_msg = '%s: Deposit %s in collection %s' % ( fullname, deposit.id, deposit.collection.name) complete_date = identifiers.normalize_timestamp(deposit.complete_date) data['revision'] = { 'synthetic': True, 'date': complete_date, 'committer_date': complete_date, 'author': author_committer, 'committer': author_committer, 'type': revision_type, 'message': revision_msg, 'metadata': metadata, } if deposit.parent: swh_persistent_id = deposit.parent.swh_id persistent_identifier = identifiers.parse_persistent_identifier( swh_persistent_id) parent_revision = persistent_identifier.object_id data['revision']['parents'] = [parent_revision] data['branch_name'] = 'master' data['origin_metadata'] = { 'provider': self.provider, 'tool': self.tool, 'metadata': metadata } return data def process_get(self, req, collection_name, deposit_id): deposit = Deposit.objects.get(pk=deposit_id) data = self.metadata_read(deposit) d = {} if data: d = json.dumps(data) return status.HTTP_200_OK, d, 'application/json' diff --git a/swh/deposit/api/urls.py b/swh/deposit/api/urls.py index 1aba2429..cc516092 100644 --- a/swh/deposit/api/urls.py +++ b/swh/deposit/api/urls.py @@ -1,68 +1,57 @@ -# Copyright (C) 2017 The Software Heritage developers +# Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information """swh URL Configuration -The `urlpatterns` list routes URLs to views. For more information please see: - https://docs.djangoproject.com/en/1.10/topics/http/urls/ -Examples: -Function views - 1. Add an import: from my_app import views - 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') -Class-based views - 1. Add an import: from other_app.views import Home - 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') -Including another URLconf - 1. Import the include() function: from django.conf.urls import url, include - 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ + from django.conf.urls import url from ..config import EDIT_SE_IRI, EM_IRI, CONT_FILE_IRI from ..config import SD_IRI, COL_IRI, STATE_IRI from .deposit import SWHDeposit from .deposit_status import SWHDepositStatus from .deposit_update import SWHUpdateMetadataDeposit from .deposit_update import SWHUpdateArchiveDeposit from .deposit_content import SWHDepositContent from .service_document import SWHServiceDocument urlpatterns = [ # PUBLIC API # SD IRI - Service Document IRI # -> GET url(r'^servicedocument/', SWHServiceDocument.as_view(), name=SD_IRI), # Col IRI - Collection IRI # -> POST url(r'^(?P[^/]+)/$', SWHDeposit.as_view(), name=COL_IRI), # EM IRI - Atom Edit Media IRI (update archive IRI) # -> PUT (update-in-place existing archive) # -> POST (add new archive) url(r'^(?P[^/]+)/(?P[^/]+)/media/$', SWHUpdateArchiveDeposit.as_view(), name=EM_IRI), # Edit IRI - Atom Entry Edit IRI (update metadata IRI) # SE IRI - Sword Edit IRI ;; possibly same as Edit IRI # -> PUT (update in place) # -> POST (add new metadata) url(r'^(?P[^/]+)/(?P[^/]+)/metadata/$', SWHUpdateMetadataDeposit.as_view(), name=EDIT_SE_IRI), # State IRI # -> GET url(r'^(?P[^/]+)/(?P[^/]+)/status/$', SWHDepositStatus.as_view(), name=STATE_IRI), # Cont/File IRI # -> GET url(r'^(?P[^/]+)/(?P[^/]+)/content/$', SWHDepositContent.as_view(), name=CONT_FILE_IRI), # specification is not clear about # FILE-IRI, we assume it's the same as # the CONT-IRI one ] diff --git a/swh/deposit/loader/loader.py b/swh/deposit/loader/loader.py index d640bfbb..95ca7a43 100644 --- a/swh/deposit/loader/loader.py +++ b/swh/deposit/loader/loader.py @@ -1,141 +1,141 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import os import tempfile from swh.model import hashutil from swh.loader.tar import loader -from swh.loader.core.loader import SWHLoader +from swh.loader.core.loader import BufferedLoader from ..client import PrivateApiDepositClient -class DepositLoader(loader.TarLoader): +class DepositLoader(loader.LegacyLocalTarLoader): """Deposit loader implementation. This is a subclass of the :class:TarLoader as the main goal of this class is to first retrieve the deposit's tarball contents as one and its associated metadata. Then provide said tarball to be loaded by the TarLoader. This will: - retrieves the deposit's archive locally - provide the archive to be loaded by the tar loader - clean up the temporary location used to retrieve the archive locally - update the deposit's status accordingly """ CONFIG_BASE_FILENAME = 'loader/deposit' ADDITIONAL_CONFIG = { 'extraction_dir': ('str', '/tmp/swh.deposit.loader/'), } def __init__(self, client=None): super().__init__( logging_class='swh.deposit.loader.loader.DepositLoader') - self.client = client if client else PrivateApiDepositClient() + self.deposit_client = client if client else PrivateApiDepositClient() def load(self, *, archive_url, deposit_meta_url, deposit_update_url): - return SWHLoader.load( + return BufferedLoader.load( self, archive_url=archive_url, deposit_meta_url=deposit_meta_url, deposit_update_url=deposit_update_url) def prepare_origin_visit(self, *, deposit_meta_url, **kwargs): - self.metadata = self.client.metadata_get( + self.metadata = self.deposit_client.metadata_get( deposit_meta_url, log=self.log) self.origin = self.metadata['origin'] self.visit_date = None def prepare(self, *, archive_url, deposit_meta_url, deposit_update_url): """Prepare the loading by first retrieving the deposit's raw archive content. """ self.deposit_update_url = deposit_update_url - self.client.status_update(deposit_update_url, 'loading') + self.deposit_client.status_update(deposit_update_url, 'loading') temporary_directory = tempfile.TemporaryDirectory() self.temporary_directory = temporary_directory archive_path = os.path.join(temporary_directory.name, 'archive.zip') - archive = self.client.archive_get( + archive = self.deposit_client.archive_get( archive_url, archive_path, log=self.log) metadata = self.metadata revision = metadata['revision'] branch_name = metadata['branch_name'] self.origin_metadata = metadata['origin_metadata'] self.prepare_metadata() super().prepare(tar_path=archive, origin=self.origin, revision=revision, branch_name=branch_name) def store_metadata(self): """Storing the origin_metadata during the load processus. Provider_id and tool_id are resolved during the prepare() method. """ origin_id = self.origin_id visit_date = self.visit_date provider_id = self.origin_metadata['provider']['provider_id'] tool_id = self.origin_metadata['tool']['tool_id'] metadata = self.origin_metadata['metadata'] try: self.send_origin_metadata(origin_id, visit_date, provider_id, tool_id, metadata) except Exception: self.log.exception('Problem when storing origin_metadata') raise def post_load(self, success=True): """Updating the deposit's status according to its loading status. If not successful, we update its status to 'failed'. Otherwise, we update its status to 'done' and pass along its associated revision. """ try: if not success: - self.client.status_update(self.deposit_update_url, - status='failed') + self.deposit_client.status_update(self.deposit_update_url, + status='failed') return revisions = self.objects['revision'] # Retrieve the revision [rev_id] = revisions.keys() rev = revisions[rev_id] if rev_id: rev_id = hashutil.hash_to_hex(rev_id) dir_id = rev['directory'] if dir_id: dir_id = hashutil.hash_to_hex(dir_id) # update the deposit's status to success with its # revision-id and directory-id - self.client.status_update( + self.deposit_client.status_update( self.deposit_update_url, status='done', revision_id=rev_id, directory_id=dir_id, origin_url=self.origin['url']) except Exception: self.log.exception( 'Problem when trying to update the deposit\'s status') def cleanup(self): """Clean up temporary directory where we retrieved the tarball. """ super().cleanup() self.temporary_directory.cleanup() diff --git a/swh/deposit/loader/scheduler.py b/swh/deposit/loader/scheduler.py deleted file mode 100644 index bc2713c6..00000000 --- a/swh/deposit/loader/scheduler.py +++ /dev/null @@ -1,219 +0,0 @@ -# Copyright (C) 2017-2018 The Software Heritage developers -# See the AUTHORS file at the top-level directory of this distribution -# License: GNU General Public License version 3, or any later version -# See top-level LICENSE file for more information - -"""Module in charge of sending deposit loading/checking as either -celery task or scheduled one-shot tasks. - -""" - -import click -import logging - -from abc import ABCMeta, abstractmethod -from celery import group - -from swh.core import utils -from swh.core.config import SWHConfig -from swh.deposit.config import setup_django_for, DEPOSIT_STATUS_VERIFIED -from swh.deposit.config import DEPOSIT_STATUS_DEPOSITED -from swh.scheduler.utils import get_task, create_oneshot_task_dict - - -class SWHScheduling(SWHConfig, metaclass=ABCMeta): - """Base swh scheduling class to aggregate the schedule deposit - loading. - - """ - CONFIG_BASE_FILENAME = 'deposit/server' - - DEFAULT_CONFIG = { - 'dry_run': ('bool', False), - } - - ADDITIONAL_CONFIG = {} - - def __init__(self): - super().__init__() - self.config = self.parse_config_file( - additional_configs=[self.ADDITIONAL_CONFIG]) - self.log = logging.getLogger('swh.deposit.scheduling') - - @abstractmethod - def schedule(self, deposits): - """Schedule the new deposit loading. - - Args: - data (dict): Deposit aggregated data - - Returns: - None - - """ - pass - - -class SWHCeleryScheduling(SWHScheduling): - """Deposit loading as Celery task scheduling. - - """ - def __init__(self, config=None): - super().__init__() - if config: - self.config.update(**config) - self.dry_run = self.config['dry_run'] - self.check = self.config['check'] - if self.check: - task_name = 'swh.deposit.loader.tasks.ChecksDepositTsk' - else: - task_name = 'swh.deposit.loader.tasks.LoadDepositArchiveTsk' - self.task = get_task(task_name) - - def _convert(self, deposits): - """Convert tuple to celery task signature. - - """ - task = self.task - for archive_url, meta_url, update_url, check_url in deposits: - if self.check: - yield task.s(deposit_check_url=check_url) - else: - yield task.s(archive_url=archive_url, - deposit_meta_url=meta_url, - deposit_update_url=update_url) - - def schedule(self, deposits): - """Schedule the new deposit loading directly through celery. - - Args: - depositdata (dict): Deposit aggregated information. - - Returns: - None - - """ - if self.dry_run: - return - - return group(self._convert(deposits)).delay() - - -class SWHSchedulerScheduling(SWHScheduling): - """Deposit loading through SWH's task scheduling interface. - - """ - ADDITIONAL_CONFIG = { - 'scheduler': ('dict', { - 'cls': 'remote', - 'args': { - 'url': 'http://localhost:5008', - } - }) - } - - def __init__(self, config=None): - super().__init__() - from swh.scheduler import get_scheduler - if config: - self.config.update(**config) - self.dry_run = self.config['dry_run'] - self.scheduler = get_scheduler(**self.config['scheduler']) - self.check = self.config['check'] - - def _convert(self, deposits): - """Convert tuple to one-shot scheduling tasks. - - """ - for archive_url, meta_url, update_url, check_url in deposits: - if self.check: - task = create_oneshot_task_dict( - 'swh-deposit-archive-checks', - deposit_check_url=check_url) - else: - task = create_oneshot_task_dict( - 'swh-deposit-archive-loading', - archive_url=archive_url, - deposit_meta_url=meta_url, - deposit_update_url=update_url) - - yield task - - def schedule(self, deposits): - """Schedule the new deposit loading through swh.scheduler's api. - - Args: - deposits (dict): Deposit aggregated information. - - """ - if self.dry_run: - return - - self.scheduler.create_tasks(self._convert(deposits)) - - -def get_deposit_by(status): - """Filter deposit given a specific status. - - """ - from swh.deposit.models import Deposit - yield from Deposit.objects.filter(status=status) - - -def prepare_task_arguments(check): - """Convert deposit to argument for task to be executed. - - """ - from swh.deposit.config import PRIVATE_GET_RAW_CONTENT - from swh.deposit.config import PRIVATE_GET_DEPOSIT_METADATA - from swh.deposit.config import PRIVATE_PUT_DEPOSIT - from swh.deposit.config import PRIVATE_CHECK_DEPOSIT - from django.core.urlresolvers import reverse - - if check: - status = DEPOSIT_STATUS_DEPOSITED - else: - status = DEPOSIT_STATUS_VERIFIED - - for deposit in get_deposit_by(status): - args = [deposit.collection.name, deposit.id] - archive_url = reverse(PRIVATE_GET_RAW_CONTENT, args=args) - meta_url = reverse(PRIVATE_GET_DEPOSIT_METADATA, args=args) - update_url = reverse(PRIVATE_PUT_DEPOSIT, args=args) - check_url = reverse(PRIVATE_CHECK_DEPOSIT, args=args) - yield archive_url, meta_url, update_url, check_url - - -@click.command( - help='Schedule one-shot deposit loadings') -@click.option('--platform', default='development', - help='development or production platform') -@click.option('--scheduling-method', default='celery', - help='Scheduling method') -@click.option('--batch-size', default=1000, type=click.INT, - help='Task batch size') -@click.option('--dry-run/--no-dry-run', is_flag=True, default=False, - help='Dry run') -@click.option('--check', is_flag=True, default=False) -def main(platform, scheduling_method, batch_size, dry_run, check): - setup_django_for(platform) - - override_config = {} - if dry_run: - override_config['dry_run'] = dry_run - override_config['check'] = check - - if scheduling_method == 'celery': - scheduling = SWHCeleryScheduling(override_config) - elif scheduling_method == 'swh-scheduler': - scheduling = SWHSchedulerScheduling(override_config) - else: - raise ValueError( - 'Only `celery` or `swh-scheduler` values are accepted') - - for deposits in utils.grouper(prepare_task_arguments(check), batch_size): - scheduling.schedule(deposits) - - -if __name__ == '__main__': - main() diff --git a/swh/deposit/loader/tasks.py b/swh/deposit/loader/tasks.py index 770df259..ad7e7ebd 100644 --- a/swh/deposit/loader/tasks.py +++ b/swh/deposit/loader/tasks.py @@ -1,50 +1,36 @@ # Copyright (C) 2015-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information -from swh.scheduler.task import Task -from swh.deposit.loader import loader, checker +from celery import current_app as app +from swh.deposit.loader.loader import DepositLoader +from swh.deposit.loader.checker import DepositChecker -class LoadDepositArchiveTsk(Task): + +@app.task(name=__name__ + '.LoadDepositArchiveTsk') +def load_deposit_archive(archive_url, deposit_meta_url, deposit_update_url): """Deposit archive loading task described by the following steps: 1. Retrieve tarball from deposit's private api and store locally in a temporary directory 2. Trigger the loading 3. clean up the temporary directory 4. Update the deposit's status according to result using the deposit's private update status api """ - task_queue = 'swh_loader_deposit' - - def run_task(self, *, archive_url, deposit_meta_url, deposit_update_url): - """Import a deposit tarball into swh. - - Args: see :func:`DepositLoader.load`. - - """ - _loader = loader.DepositLoader() - _loader.log = self.log - return _loader.load(archive_url=archive_url, - deposit_meta_url=deposit_meta_url, - deposit_update_url=deposit_update_url) + return DepositLoader().load( + archive_url=archive_url, + deposit_meta_url=deposit_meta_url, + deposit_update_url=deposit_update_url) -class ChecksDepositTsk(Task): - """Deposit checks task. +@app.task(name=__name__ + '.ChecksDepositTsk') +def check_deposit(deposit_check_url): + """Check a deposit's status + Args: see :func:`DepositChecker.check`. """ - task_queue = 'swh_checker_deposit' - - def run_task(self, deposit_check_url): - """Check a deposit's status - - Args: see :func:`DepositChecker.check`. - - """ - _checker = checker.DepositChecker() - _checker.log = self.log - return _checker.check(deposit_check_url) + return DepositChecker().check(deposit_check_url) diff --git a/swh/deposit/settings/production.py b/swh/deposit/settings/production.py index 1427d079..e8a99bee 100644 --- a/swh/deposit/settings/production.py +++ b/swh/deposit/settings/production.py @@ -1,91 +1,91 @@ # Copyright (C) 2017 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from .common import * # noqa from .common import ALLOWED_HOSTS from swh.core import config ALLOWED_HOSTS += ['deposit.softwareheritage.org'] # Setup support for proxy headers USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') DEBUG = False # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases # https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-DATABASES # https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/#databases DEFAULT_PATH = 'deposit/private' private_conf = config.load_named_config(DEFAULT_PATH) if not private_conf: raise ValueError('Cannot run in production, missing private data file.') -SECRET_KEY = private_conf['secret_key'] +SECRET_KEY = private_conf.get('secret_key', 'change me') # https://docs.djangoproject.com/en/1.10/ref/settings/#logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", # noqa 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, }, } # database -db_conf = private_conf['db'] +db_conf = private_conf.get('db', {'name': 'unset'}) db = { 'ENGINE': 'django.db.backends.postgresql', 'NAME': db_conf['name'], } db_user = db_conf.get('user') if db_user: db['USER'] = db_user db_pass = db_conf.get('password') if db_pass: db['PASSWORD'] = db_pass db_host = db_conf.get('host') if db_host: db['HOST'] = db_host db_port = db_conf.get('port') if db_port: db['PORT'] = db_port # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': db, } # Upload user directory # https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-MEDIA_ROOT -MEDIA_ROOT = private_conf['media_root'] +MEDIA_ROOT = private_conf.get('media_root') diff --git a/swh/deposit/settings/testing.py b/swh/deposit/settings/testing.py index 45ee6873..c35631b3 100644 --- a/swh/deposit/settings/testing.py +++ b/swh/deposit/settings/testing.py @@ -1,50 +1,47 @@ # Copyright (C) 2017 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from .common import * # noqa from .common import ALLOWED_HOSTS from .development import * # noqa from .development import INSTALLED_APPS -# django-nose setup +# django setup ALLOWED_HOSTS += ['testserver'] -INSTALLED_APPS += ['django_nose'] - -TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' -NOSE_ARGS = ['--verbosity=3', '-s'] # to see test pass +INSTALLED_APPS += ['pytest_django'] # https://docs.djangoproject.com/en/1.10/ref/settings/#logging LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", # noqa 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'console': { 'level': 'ERROR', 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'swh.deposit': { 'handlers': ['console'], 'level': 'ERROR', }, } } # https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-MEDIA_ROOT # SECURITY WARNING: Override this in the production.py module MEDIA_ROOT = '/tmp/swh-deposit/test/uploads/' FILE_UPLOAD_HANDLERS = [ "django.core.files.uploadhandler.MemoryFileUploadHandler", ] diff --git a/swh/deposit/tests/__init__.py b/swh/deposit/tests/__init__.py index de3abb55..af3302c5 100644 --- a/swh/deposit/tests/__init__.py +++ b/swh/deposit/tests/__init__.py @@ -1,71 +1,73 @@ # Copyright (C) 2017 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from swh.deposit.config import setup_django_for from swh.deposit.config import SWHDefaultConfig # noqa -from swh.loader.core.loader import SWHLoader +from swh.loader.core.loader import BufferedLoader TEST_CONFIG = { 'max_upload_size': 500, 'extraction_dir': '/tmp/swh-deposit/test/extraction-dir', 'checks': False, 'provider': { 'provider_name': '', 'provider_type': 'deposit_client', 'provider_url': '', 'metadata': { } }, 'tool': { - 'tool_name': 'swh-deposit', - 'tool_version': '0.0.1', - 'tool_configuration': { + 'name': 'swh-deposit', + 'version': '0.0.1', + 'configuration': { 'sword_version': '2' } } } def parse_deposit_config_file(base_filename=None, config_filename=None, additional_configs=None, global_config=True): return TEST_CONFIG TEST_LOADER_CONFIG = { 'extraction_dir': '/tmp/swh-loader-tar/test/', + 'working_dir': '/tmp/swh-loader-tar/test/working-dir', + 'debug': False, 'storage': { - 'cls': 'remote', + 'cls': 'memory', 'args': { - 'url': 'http://localhost:unexisting-port/', } }, - 'send_contents': False, - 'send_directories': False, - 'send_revisions': False, - 'send_releases': False, - 'send_snapshot': False, + 'send_contents': True, + 'send_directories': True, + 'send_revisions': True, + 'send_releases': True, + 'send_snapshot': True, + 'content_size_limit': 100 * 1024 * 1024, 'content_packet_size': 10, 'content_packet_size_bytes': 100 * 1024 * 1024, 'directory_packet_size': 10, 'revision_packet_size': 10, 'release_packet_size': 10, } def parse_loader_config_file(base_filename=None, config_filename=None, additional_configs=None, global_config=True): return TEST_LOADER_CONFIG # monkey patch classes method permits to override, for tests purposes, # the default configuration without side-effect, i.e do not load the # configuration from disk SWHDefaultConfig.parse_config_file = parse_deposit_config_file -SWHLoader.parse_config_file = parse_loader_config_file +BufferedLoader.parse_config_file = parse_loader_config_file setup_django_for('testing') diff --git a/swh/deposit/tests/api/test_common.py b/swh/deposit/tests/api/test_common.py index 12585229..74bc0b8b 100644 --- a/swh/deposit/tests/api/test_common.py +++ b/swh/deposit/tests/api/test_common.py @@ -1,42 +1,39 @@ # Copyright (C) 2017 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.urlresolvers import reverse -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase from ..common import BasicTestCase, WithAuthTestCase class IndexNoAuthCase(APITestCase, BasicTestCase): """Access to main entry point is ok without authentication """ - @istest - def get_home_is_ok(self): + def test_get_home_is_ok(self): """Without authentication, endpoint refuses access with 401 response """ url = reverse('home') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIn(b'The Software Heritage Deposit', response.content) class IndexWithAuthCase(WithAuthTestCase, APITestCase, BasicTestCase): """Access to main entry point is ok with authentication as well """ - @istest - def get_home_is_ok_2(self): + def test_get_home_is_ok_2(self): """Without authentication, endpoint refuses access with 401 response """ url = reverse('home') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIn(b'The Software Heritage Deposit', response.content) diff --git a/swh/deposit/tests/api/test_converters.py b/swh/deposit/tests/api/test_converters.py index f02b43a2..3d2a4888 100644 --- a/swh/deposit/tests/api/test_converters.py +++ b/swh/deposit/tests/api/test_converters.py @@ -1,138 +1,132 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information -from nose.tools import istest from rest_framework.test import APITestCase from swh.deposit.api.converters import convert_status_detail class ConvertersTestCase(APITestCase): - @istest - def convert_status_detail_empty(self): + def test_convert_status_detail_empty(self): actual_status_detail = convert_status_detail({}) self.assertIsNone(actual_status_detail) actual_status_detail = convert_status_detail({'dummy-keys': []}) self.assertIsNone(actual_status_detail) actual_status_detail = convert_status_detail(None) self.assertIsNone(actual_status_detail) - @istest - def convert_status_detail(self): + def test_convert_status_detail(self): status_detail = { 'url': { 'summary': "At least one url field must be compatible with the client\'s domain name. The following url fields failed the check", # noqa 'fields': ['blahurl', 'testurl'], }, 'metadata': [ { 'summary': 'Mandatory fields missing', 'fields': ['url', 'title'], }, { 'summary': 'Alternate fields missing', 'fields': ['name or title', 'url or badurl'] } ], 'archive': [{ 'summary': 'Unreadable archive', 'fields': ['1'], }], } expected_status_detail = '''- Mandatory fields missing (url, title) - Alternate fields missing (name or title, url or badurl) - Unreadable archive (1) - At least one url field must be compatible with the client's domain name. The following url fields failed the check (blahurl, testurl) ''' # noqa actual_status_detail = convert_status_detail(status_detail) self.assertEqual(actual_status_detail, expected_status_detail) - @istest - def convert_status_detail_2(self): + def test_convert_status_detail_2(self): status_detail = { 'url': { 'summary': 'At least one compatible url field. Failed', 'fields': ['testurl'], }, 'metadata': [ { 'summary': 'Mandatory fields missing', 'fields': ['name'], }, ], 'archive': [ { 'summary': 'Invalid archive', 'fields': ['2'], }, { 'summary': 'Unsupported archive', 'fields': ['1'], } ], } expected_status_detail = '''- Mandatory fields missing (name) - Invalid archive (2) - Unsupported archive (1) - At least one compatible url field. Failed (testurl) ''' actual_status_detail = convert_status_detail(status_detail) self.assertEqual(actual_status_detail, expected_status_detail) - @istest - def convert_status_detail_3(self): + def test_convert_status_detail_3(self): status_detail = { 'url': { 'summary': 'At least one compatible url field', }, } expected_status_detail = '- At least one compatible url field\n' actual_status_detail = convert_status_detail(status_detail) self.assertEqual(actual_status_detail, expected_status_detail) - @istest - def convert_status_detail_edge_case(self): + def test_convert_status_detail_edge_case(self): status_detail = { 'url': { 'summary': 'At least one compatible url field. Failed', 'fields': ['testurl'], }, 'metadata': [ { 'summary': 'Mandatory fields missing', 'fields': ['9', 10, 1.212], }, ], 'archive': [ { 'summary': 'Invalid archive', 'fields': ['3'], }, { 'summary': 'Unsupported archive', 'fields': [2], } ], } expected_status_detail = '''- Mandatory fields missing (9, 10, 1.212) - Invalid archive (3) - Unsupported archive (2) - At least one compatible url field. Failed (testurl) ''' actual_status_detail = convert_status_detail(status_detail) self.assertEqual(actual_status_detail, expected_status_detail) diff --git a/swh/deposit/tests/api/test_deposit.py b/swh/deposit/tests/api/test_deposit.py index 507bafdd..fcfac4e9 100644 --- a/swh/deposit/tests/api/test_deposit.py +++ b/swh/deposit/tests/api/test_deposit.py @@ -1,167 +1,160 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import hashlib from django.core.urlresolvers import reverse from io import BytesIO -from nose.tools import istest, nottest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.config import COL_IRI, EDIT_SE_IRI, DEPOSIT_STATUS_REJECTED from swh.deposit.config import DEPOSIT_STATUS_PARTIAL from swh.deposit.config import DEPOSIT_STATUS_LOAD_SUCCESS from swh.deposit.config import DEPOSIT_STATUS_LOAD_FAILURE from swh.deposit.models import Deposit, DepositClient, DepositCollection from swh.deposit.parsers import parse_xml from ..common import BasicTestCase, WithAuthTestCase, CommonCreationRoutine class DepositNoAuthCase(APITestCase, BasicTestCase): """Deposit access are protected with basic authentication. """ - @istest - def post_will_fail_with_401(self): + def test_post_will_fail_with_401(self): """Without authentication, endpoint refuses access with 401 response """ url = reverse(COL_IRI, args=[self.collection.name]) # when response = self.client.post(url) # then self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) class DepositFailuresTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine): """Deposit access are protected with basic authentication. """ def setUp(self): super().setUp() # Add another user _collection2 = DepositCollection(name='some') _collection2.save() _user = DepositClient.objects.create_user(username='user', password='user') _user.collections = [_collection2.id] self.collection2 = _collection2 - @istest - def access_to_another_user_collection_is_forbidden(self): + def test_access_to_another_user_collection_is_forbidden(self): """Access to another user collection should return a 403 """ url = reverse(COL_IRI, args=[self.collection2.name]) response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertRegex(response.content.decode('utf-8'), 'Client hal cannot access collection %s' % ( self.collection2.name, )) - @istest - def delete_on_col_iri_not_supported(self): + def test_delete_on_col_iri_not_supported(self): """Delete on col iri should return a 405 response """ url = reverse(COL_IRI, args=[self.collection.name]) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) self.assertRegex(response.content.decode('utf-8'), 'DELETE method is not supported on this endpoint') - @nottest def create_deposit_with_rejection_status(self): url = reverse(COL_IRI, args=[self.collection.name]) data = b'some data which is clearly not a zip file' md5sum = hashlib.md5(data).hexdigest() external_id = 'some-external-id-1' # when response = self.client.post( url, content_type='application/zip', # as zip data=data, # + headers CONTENT_LENGTH=len(data), # other headers needs HTTP_ prefix to be taken into account HTTP_SLUG=external_id, HTTP_CONTENT_MD5=md5sum, HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') - self.assertEquals(response.status_code, status.HTTP_201_CREATED) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) actual_state = response_content['deposit_status'] - self.assertEquals(actual_state, DEPOSIT_STATUS_REJECTED) + self.assertEqual(actual_state, DEPOSIT_STATUS_REJECTED) - @istest - def act_on_deposit_rejected_is_not_permitted(self): + def test_act_on_deposit_rejected_is_not_permitted(self): deposit_id = self.create_deposit_with_status(DEPOSIT_STATUS_REJECTED) deposit = Deposit.objects.get(pk=deposit_id) assert deposit.status == DEPOSIT_STATUS_REJECTED response = self.client.post( reverse(EDIT_SE_IRI, args=[self.collection.name, deposit_id]), content_type='application/atom+xml;type=entry', data=self.atom_entry_data1, HTTP_SLUG='external-id') - self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertRegex( response.content.decode('utf-8'), "You can only act on deposit with status '%s'" % ( DEPOSIT_STATUS_PARTIAL, )) - @istest - def add_deposit_with_parent(self): + def test_add_deposit_with_parent(self): # given multiple deposit already loaded deposit_id = self.create_deposit_with_status( status=DEPOSIT_STATUS_LOAD_SUCCESS, external_id='some-external-id') deposit1 = Deposit.objects.get(pk=deposit_id) self.assertIsNotNone(deposit1) - self.assertEquals(deposit1.external_id, 'some-external-id') - self.assertEquals(deposit1.status, DEPOSIT_STATUS_LOAD_SUCCESS) + self.assertEqual(deposit1.external_id, 'some-external-id') + self.assertEqual(deposit1.status, DEPOSIT_STATUS_LOAD_SUCCESS) deposit_id2 = self.create_deposit_with_status( status=DEPOSIT_STATUS_LOAD_SUCCESS, external_id='some-external-id') deposit2 = Deposit.objects.get(pk=deposit_id2) self.assertIsNotNone(deposit2) - self.assertEquals(deposit2.external_id, 'some-external-id') - self.assertEquals(deposit2.status, DEPOSIT_STATUS_LOAD_SUCCESS) + self.assertEqual(deposit2.external_id, 'some-external-id') + self.assertEqual(deposit2.status, DEPOSIT_STATUS_LOAD_SUCCESS) deposit_id3 = self.create_deposit_with_status( status=DEPOSIT_STATUS_LOAD_FAILURE, external_id='some-external-id') deposit3 = Deposit.objects.get(pk=deposit_id3) self.assertIsNotNone(deposit3) - self.assertEquals(deposit3.external_id, 'some-external-id') - self.assertEquals(deposit3.status, DEPOSIT_STATUS_LOAD_FAILURE) + self.assertEqual(deposit3.external_id, 'some-external-id') + self.assertEqual(deposit3.status, DEPOSIT_STATUS_LOAD_FAILURE) # when deposit_id3 = self.create_simple_deposit_partial( external_id='some-external-id') # then deposit4 = Deposit.objects.get(pk=deposit_id3) self.assertIsNotNone(deposit4) - self.assertEquals(deposit4.external_id, 'some-external-id') - self.assertEquals(deposit4.status, DEPOSIT_STATUS_PARTIAL) - self.assertEquals(deposit4.parent, deposit2) + self.assertEqual(deposit4.external_id, 'some-external-id') + self.assertEqual(deposit4.status, DEPOSIT_STATUS_PARTIAL) + self.assertEqual(deposit4.parent, deposit2) diff --git a/swh/deposit/tests/api/test_deposit_atom.py b/swh/deposit/tests/api/test_deposit_atom.py index b4096b80..2f50f050 100644 --- a/swh/deposit/tests/api/test_deposit_atom.py +++ b/swh/deposit/tests/api/test_deposit_atom.py @@ -1,538 +1,528 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.urlresolvers import reverse from io import BytesIO -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.config import COL_IRI, DEPOSIT_STATUS_DEPOSITED from swh.deposit.models import Deposit, DepositRequest from swh.deposit.parsers import parse_xml from ..common import BasicTestCase, WithAuthTestCase class DepositAtomEntryTestCase(APITestCase, WithAuthTestCase, BasicTestCase): """Try and post atom entry deposit. """ def setUp(self): super().setUp() self.atom_entry_data0 = b""" Awesome Compiler hal urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a %s 2017-10-07T15:17:08Z some awesome author something awesome-compiler This is an awesome compiler destined to awesomely compile stuff and other stuff compiler,programming,language 2005-10-07T17:17:08Z 2005-10-07T17:17:08Z release note related link Awesome https://hoster.org/awesome-compiler GNU/Linux 0.0.1 running all """ self.atom_entry_data1 = b""" hal urn:uuid:2225c695-cfb8-4ebb-aaaa-80da344efa6a 2017-10-07T15:17:08Z some awesome author something awesome-compiler This is an awesome compiler destined to awesomely compile stuff and other stuff compiler,programming,language 2005-10-07T17:17:08Z 2005-10-07T17:17:08Z release note related link Awesome https://hoster.org/awesome-compiler GNU/Linux 0.0.1 running all """ self.atom_entry_data2 = b""" %s """ self.atom_entry_data_empty_body = b""" """ self.atom_entry_data3 = b""" something """ self.atom_entry_data_atom_only = b""" Awesome Compiler urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 1785io25c695 2017-10-07T15:17:08Z some awesome author """ self.atom_entry_data_codemeta = b""" Awesome Compiler urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 1785io25c695 1785io25c695 origin url other identifier, DOI, ARK Domain description key-word 1 key-word 2 creation date publication date comment article name article id Collaboration/Projet project name id see also Sponsor A Sponsor B Platform/OS dependencies Version active license url spdx .Net Framework 3.0 Python2.3 author1 Inria UPMC author2 Inria UPMC http://code.com language 1 language 2 http://issuetracker.com """ # noqa self.atom_entry_data_dc_codemeta = b""" %s hal-01587361 https://hal.inria.fr/hal-01587361 https://hal.inria.fr/hal-01587361/document https://hal.inria.fr/hal-01587361/file/AffectationRO-v1.0.0.zip doi:10.5281/zenodo.438684 The assignment problem AffectationRO Gruenpeter, Morane [INFO] Computer Science [cs] [INFO.INFO-RO] Computer Science [cs]/Operations Research [cs.RO] SOFTWARE Project in OR: The assignment problemA java implementation for the assignment problem first release description fr 2015-06-01 2017-10-19 en url stable Version sur hal Version entre par lutilisateur Mots-cls Commentaire Rfrence interne Collaboration/Projet nom du projet id Voir aussi Financement Projet ANR Projet Europen Platform/OS Dpendances Etat du dveloppement license url spdx Outils de dveloppement- outil no1 Outils de dveloppement- outil no2 http://code.com language 1 language 2 """ # noqa self.atom_entry_tei = b"""HAL TEI export of hal-01587083CCSDDistributed under a Creative Commons Attribution 4.0 International License

HAL API platform

questionnaire software metadataMoraneGruenpeter7de56c632362954fa84172cad80afe4einria.fr1556733MoraneGruenpeterf85a43a5fb4a2e0778a77e017f28c8fdgmail.com2017-09-29 11:21:322017-10-03 17:20:132017-10-03 17:20:132017-09-292017-09-29contributorMoraneGruenpeterf85a43a5fb4a2e0778a77e017f28c8fdgmail.comCCSDhal-01587083https://hal.inria.fr/hal-01587083gruenpeter:hal-0158708320172017questionnaire software metadataMoraneGruenpeter7de56c632362954fa84172cad80afe4einria.fr1556733EnglishComputer Science [cs]SoftwareIRILLInitiative pour la Recherche et l'Innovation sur le Logiciel Libre
https://www.irill.org/
Universite Pierre et Marie Curie - Paris 6UPMC
4 place Jussieu - 75005 Paris
http://www.upmc.fr/
Institut National de Recherche en Informatique et en AutomatiqueInria
Domaine de VoluceauRocquencourt - BP 10578153 Le Chesnay Cedex
http://www.inria.fr/en/
Universite Paris Diderot - Paris 7UPD7
5 rue Thomas-Mann - 75205 Paris cedex 13
http://www.univ-paris-diderot.fr
""" # noqa self.atom_entry_data_badly_formatted = b""" """ self.atom_error_with_decimal = b""" Composing a Web of Audio Applications hal hal-01243065 hal-01243065 https://hal-test.archives-ouvertes.fr/hal-01243065 test DSP programming,Web,Composability,Faust 2017-05-03T16:08:47+02:00 The Web offers a great opportunity to share, deploy and use programs without installation difficulties. In this article we explore the idea of freely combining/composing real-time audio applications deployed on the Web using Faust audio DSP language. 1 10.4 phpstorm stable linux php python C GNU General Public License v3.0 only CeCILL Free Software License Agreement v1.1 HAL hal@ccsd.cnrs.fr Someone Nice someone@nice.fr FFJ """ # noqa - @istest - def post_deposit_atom_entry_serialization_error(self): + def test_post_deposit_atom_entry_serialization_error(self): """Posting an initial atom entry should return 201 with deposit receipt """ # given # when response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/atom+xml;type=entry', data=self.atom_error_with_decimal, HTTP_SLUG='external-id', HTTP_IN_PROGRESS='false') # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) dr = DepositRequest.objects.get(deposit=deposit) self.assertIsNotNone(dr.metadata) sw_version = dr.metadata.get('codemeta:softwareVersion') - self.assertEquals(sw_version, '10.4') + self.assertEqual(sw_version, '10.4') - @istest - def post_deposit_atom_empty_body_request(self): + def test_post_deposit_atom_empty_body_request(self): """Posting empty body request should return a 400 response """ response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/atom+xml;type=entry', data=self.atom_entry_data_empty_body) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) - @istest - def post_deposit_atom_badly_formatted_is_a_bad_request(self): + def test_post_deposit_atom_badly_formatted_is_a_bad_request(self): """Posting a badly formatted atom should return a 400 response """ response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/atom+xml;type=entry', data=self.atom_entry_data_badly_formatted) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) - @istest - def post_deposit_atom_without_slug_header_is_bad_request(self): + def test_post_deposit_atom_without_slug_header_is_bad_request(self): """Posting an atom entry without a slug header should return a 400 """ url = reverse(COL_IRI, args=[self.collection.name]) # when response = self.client.post( url, content_type='application/atom+xml;type=entry', data=self.atom_entry_data0, # + headers HTTP_IN_PROGRESS='false') self.assertIn(b'Missing SLUG header', response.content) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) - @istest - def post_deposit_atom_unknown_collection(self): + def test_post_deposit_atom_unknown_collection(self): """Posting an atom entry to an unknown collection should return a 404 """ response = self.client.post( reverse(COL_IRI, args=['unknown-one']), content_type='application/atom+xml;type=entry', data=self.atom_entry_data3, HTTP_SLUG='something') self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) - @istest - def post_deposit_atom_entry_initial(self): + def test_post_deposit_atom_entry_initial(self): """Posting an initial atom entry should return 201 with deposit receipt """ # given external_id = 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a' with self.assertRaises(Deposit.DoesNotExist): Deposit.objects.get(external_id=external_id) atom_entry_data = self.atom_entry_data0 % external_id.encode('utf-8') # when response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/atom+xml;type=entry', data=atom_entry_data, HTTP_SLUG='external-id', HTTP_IN_PROGRESS='false') # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.client, self.user) # one associated request to a deposit deposit_request = DepositRequest.objects.get(deposit=deposit) self.assertIsNotNone(deposit_request.metadata) - self.assertEquals( + self.assertEqual( deposit_request.raw_metadata, atom_entry_data.decode('utf-8')) self.assertFalse(bool(deposit_request.archive)) - @istest - def post_deposit_atom_entry_with_codemeta(self): + def test_post_deposit_atom_entry_with_codemeta(self): """Posting an initial atom entry should return 201 with deposit receipt """ # given external_id = 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a' with self.assertRaises(Deposit.DoesNotExist): Deposit.objects.get(external_id=external_id) atom_entry_data = self.atom_entry_data_dc_codemeta % ( external_id.encode('utf-8'), ) # when response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/atom+xml;type=entry', data=atom_entry_data, HTTP_SLUG='external-id', HTTP_IN_PROGRESS='false') # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.client, self.user) # one associated request to a deposit deposit_request = DepositRequest.objects.get(deposit=deposit) self.assertIsNotNone(deposit_request.metadata) - self.assertEquals( + self.assertEqual( deposit_request.raw_metadata, atom_entry_data.decode('utf-8')) self.assertFalse(bool(deposit_request.archive)) - @istest def test_post_deposit_atom_entry_tei(self): """Posting initial atom entry as TEI should return 201 with receipt """ # given external_id = 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a' with self.assertRaises(Deposit.DoesNotExist): Deposit.objects.get(external_id=external_id) atom_entry_data = self.atom_entry_tei # when response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/atom+xml;type=entry', data=atom_entry_data, HTTP_SLUG=external_id, HTTP_IN_PROGRESS='false') # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.client, self.user) # one associated request to a deposit deposit_request = DepositRequest.objects.get(deposit=deposit) self.assertIsNotNone(deposit_request.metadata) - self.assertEquals( + self.assertEqual( deposit_request.raw_metadata, atom_entry_data.decode('utf-8')) self.assertFalse(bool(deposit_request.archive)) - @istest - def post_deposit_atom_entry_multiple_steps(self): + def test_post_deposit_atom_entry_multiple_steps(self): """After initial deposit, updating a deposit should return a 201 """ # given external_id = 'urn:uuid:2225c695-cfb8-4ebb-aaaa-80da344efa6a' with self.assertRaises(Deposit.DoesNotExist): deposit = Deposit.objects.get(external_id=external_id) # when response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/atom+xml;type=entry', data=self.atom_entry_data1, HTTP_IN_PROGRESS='True', HTTP_SLUG=external_id) # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = int(response_content['deposit_id']) deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.status, 'partial') self.assertEqual(deposit.client, self.user) # one associated request to a deposit deposit_requests = DepositRequest.objects.filter(deposit=deposit) self.assertEqual(len(deposit_requests), 1) atom_entry_data = self.atom_entry_data2 % external_id.encode('utf-8') update_uri = response._headers['location'][1] # when updating the first deposit post response = self.client.post( update_uri, content_type='application/atom+xml;type=entry', data=atom_entry_data, HTTP_IN_PROGRESS='False') # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = int(response_content['deposit_id']) deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.client, self.user) self.assertEqual(len(Deposit.objects.all()), 1) # now 2 associated requests to a same deposit deposit_requests = DepositRequest.objects.filter( deposit=deposit).order_by('id') self.assertEqual(len(deposit_requests), 2) expected_meta = [ { 'metadata': parse_xml(self.atom_entry_data1), 'raw_metadata': self.atom_entry_data1.decode('utf-8'), }, { 'metadata': parse_xml(atom_entry_data), 'raw_metadata': atom_entry_data.decode('utf-8'), } ] for i, deposit_request in enumerate(deposit_requests): actual_metadata = deposit_request.metadata - self.assertEquals(actual_metadata, - expected_meta[i]['metadata']) - self.assertEquals(deposit_request.raw_metadata, - expected_meta[i]['raw_metadata']) + self.assertEqual(actual_metadata, + expected_meta[i]['metadata']) + self.assertEqual(deposit_request.raw_metadata, + expected_meta[i]['raw_metadata']) self.assertFalse(bool(deposit_request.archive)) diff --git a/swh/deposit/tests/api/test_deposit_binary.py b/swh/deposit/tests/api/test_deposit_binary.py index 73734396..f2549e7a 100644 --- a/swh/deposit/tests/api/test_deposit_binary.py +++ b/swh/deposit/tests/api/test_deposit_binary.py @@ -1,656 +1,645 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.files.uploadedfile import InMemoryUploadedFile from django.core.urlresolvers import reverse from io import BytesIO -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.tests import TEST_CONFIG from swh.deposit.config import COL_IRI, EM_IRI from swh.deposit.config import DEPOSIT_STATUS_DEPOSITED from swh.deposit.models import Deposit, DepositRequest from swh.deposit.parsers import parse_xml from ..common import ( BasicTestCase, WithAuthTestCase, create_arborescence_archive, FileSystemCreationRoutine ) class DepositTestCase(APITestCase, WithAuthTestCase, BasicTestCase, FileSystemCreationRoutine): """Try and upload one single deposit """ def setUp(self): super().setUp() self.atom_entry_data0 = b""" Awesome Compiler hal urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a %s 2017-10-07T15:17:08Z some awesome author something awesome-compiler This is an awesome compiler destined to awesomely compile stuff and other stuff compiler,programming,language 2005-10-07T17:17:08Z 2005-10-07T17:17:08Z release note related link Awesome https://hoster.org/awesome-compiler GNU/Linux 0.0.1 running all """ self.atom_entry_data1 = b""" hal urn:uuid:2225c695-cfb8-4ebb-aaaa-80da344efa6a 2017-10-07T15:17:08Z some awesome author something awesome-compiler This is an awesome compiler destined to awesomely compile stuff and other stuff compiler,programming,language 2005-10-07T17:17:08Z 2005-10-07T17:17:08Z release note related link Awesome https://hoster.org/awesome-compiler GNU/Linux 0.0.1 running all """ self.atom_entry_data2 = b""" %s """ self.atom_entry_data_empty_body = b""" """ self.atom_entry_data3 = b""" something """ self.data_atom_entry_ok = b""" Title urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2005-10-07T17:17:08Z Contributor The abstract The abstract Access Rights Alternative Title Date Available Bibliographic Citation # noqa Contributor Description Has Part Has Version Identifier Is Part Of Publisher References Rights Holder Source Title Type """ - @istest - def post_deposit_binary_without_slug_header_is_bad_request(self): + def test_post_deposit_binary_without_slug_header_is_bad_request(self): """Posting a binary deposit without slug header should return 400 """ url = reverse(COL_IRI, args=[self.collection.name]) # when response = self.client.post( url, content_type='application/zip', # as zip data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') self.assertIn(b'Missing SLUG header', response.content) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) - @istest - def post_deposit_binary_upload_final_and_status_check(self): + def test_post_deposit_binary_upload_final_and_status_check(self): """Binary upload with correct headers should return 201 with receipt """ # given url = reverse(COL_IRI, args=[self.collection.name]) external_id = 'some-external-id-1' # when response = self.client.post( url, content_type='application/zip', # as zip data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], # other headers needs HTTP_ prefix to be taken into account HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=%s' % ( self.archive['name'], )) # then response_content = parse_xml(BytesIO(response.content)) self.assertEqual(response.status_code, status.HTTP_201_CREATED) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.client, self.user) self.assertIsNone(deposit.swh_id) deposit_request = DepositRequest.objects.get(deposit=deposit) - self.assertEquals(deposit_request.deposit, deposit) + self.assertEqual(deposit_request.deposit, deposit) self.assertRegex(deposit_request.archive.name, self.archive['name']) self.assertIsNone(deposit_request.metadata) self.assertIsNone(deposit_request.raw_metadata) response_content = parse_xml(BytesIO(response.content)) self.assertEqual(response_content['deposit_archive'], self.archive['name']) self.assertEqual(int(response_content['deposit_id']), deposit.id) self.assertEqual(response_content['deposit_status'], deposit.status) edit_se_iri = reverse('edit_se_iri', args=[self.collection.name, deposit.id]) self.assertEqual(response._headers['location'], ('Location', 'http://testserver' + edit_se_iri)) - @istest - def post_deposit_binary_upload_supports_zip_or_tar(self): + def test_post_deposit_binary_upload_supports_zip_or_tar(self): """Binary upload with content-type not in [zip,x-tar] should return 415 """ # given url = reverse(COL_IRI, args=[self.collection.name]) external_id = 'some-external-id-1' # when response = self.client.post( url, content_type='application/octet-stream', data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') # then self.assertEqual(response.status_code, status.HTTP_415_UNSUPPORTED_MEDIA_TYPE) with self.assertRaises(Deposit.DoesNotExist): Deposit.objects.get(external_id=external_id) - @istest - def post_deposit_binary_fails_if_unsupported_packaging_header( + def test_post_deposit_binary_fails_if_unsupported_packaging_header( self): """Bin deposit without supported content_disposition header returns 400 """ # given url = reverse(COL_IRI, args=[self.collection.name]) external_id = 'some-external-id' # when response = self.client.post( url, content_type='application/zip', data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='something-unsupported', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') # then self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) with self.assertRaises(Deposit.DoesNotExist): Deposit.objects.get(external_id=external_id) - @istest - def post_deposit_binary_upload_fail_if_no_content_disposition_header( + def test_post_deposit_binary_upload_fail_if_no_content_disposition_header( self): """Binary upload without content_disposition header should return 400 """ # given url = reverse(COL_IRI, args=[self.collection.name]) external_id = 'some-external-id' # when response = self.client.post( url, content_type='application/zip', data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false') # then self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) with self.assertRaises(Deposit.DoesNotExist): Deposit.objects.get(external_id=external_id) - @istest - def post_deposit_mediation_not_supported(self): + def test_post_deposit_mediation_not_supported(self): """Binary upload with mediation should return a 412 response """ # given url = reverse(COL_IRI, args=[self.collection.name]) external_id = 'some-external-id-1' # when response = self.client.post( url, content_type='application/zip', data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_ON_BEHALF_OF='someone', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') # then self.assertEqual(response.status_code, status.HTTP_412_PRECONDITION_FAILED) with self.assertRaises(Deposit.DoesNotExist): Deposit.objects.get(external_id=external_id) - @istest - def post_deposit_binary_upload_fail_if_upload_size_limit_exceeded( + def test_post_deposit_binary_upload_fail_if_upload_size_limit_exceeded( self): """Binary upload must not exceed the limit set up... """ # given url = reverse(COL_IRI, args=[self.collection.name]) archive = create_arborescence_archive( self.root_path, 'archive2', 'file2', b'some content in file', up_to_size=TEST_CONFIG['max_upload_size']) external_id = 'some-external-id' # when response = self.client.post( url, content_type='application/zip', data=archive['data'], # + headers CONTENT_LENGTH=archive['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') # then self.assertEqual(response.status_code, status.HTTP_413_REQUEST_ENTITY_TOO_LARGE) self.assertRegex(response.content, b'Upload size limit exceeded') with self.assertRaises(Deposit.DoesNotExist): Deposit.objects.get(external_id=external_id) - @istest - def post_deposit_2_post_2_different_deposits(self): + def test_post_deposit_2_post_2_different_deposits(self): """2 posting deposits should return 2 different 201 with receipt """ url = reverse(COL_IRI, args=[self.collection.name]) # when response = self.client.post( url, content_type='application/zip', # as zip data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_SLUG='some-external-id-1', HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) deposits = Deposit.objects.all() self.assertEqual(len(deposits), 1) self.assertEqual(deposits[0], deposit) # second post response = self.client.post( url, content_type='application/x-tar', # as zip data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_SLUG='another-external-id', HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=filename1') self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id2 = response_content['deposit_id'] deposit2 = Deposit.objects.get(pk=deposit_id2) self.assertNotEqual(deposit, deposit2) deposits = Deposit.objects.all().order_by('id') self.assertEqual(len(deposits), 2) self.assertEqual(list(deposits), [deposit, deposit2]) - @istest - def post_deposit_binary_and_post_to_add_another_archive(self): + def test_post_deposit_binary_and_post_to_add_another_archive(self): """Updating a deposit should return a 201 with receipt """ # given url = reverse(COL_IRI, args=[self.collection.name]) external_id = 'some-external-id-1' # when response = self.client.post( url, content_type='application/zip', # as zip data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='true', HTTP_CONTENT_DISPOSITION='attachment; filename=%s' % ( self.archive['name'], )) # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.status, 'partial') self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.client, self.user) self.assertIsNone(deposit.swh_id) deposit_request = DepositRequest.objects.get(deposit=deposit) - self.assertEquals(deposit_request.deposit, deposit) - self.assertEquals(deposit_request.type.name, 'archive') + self.assertEqual(deposit_request.deposit, deposit) + self.assertEqual(deposit_request.type.name, 'archive') self.assertRegex(deposit_request.archive.name, self.archive['name']) # 2nd archive to upload archive2 = create_arborescence_archive( self.root_path, 'archive2', 'file2', b'some other content in file') # uri to update the content update_uri = reverse(EM_IRI, args=[self.collection.name, deposit_id]) # adding another archive for the deposit and finalizing it response = self.client.post( update_uri, content_type='application/zip', # as zip data=archive2['data'], # + headers CONTENT_LENGTH=archive2['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=archive2['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_CONTENT_DISPOSITION='attachment; filename=%s' % ( archive2['name'])) self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.client, self.user) self.assertIsNone(deposit.swh_id) deposit_requests = list(DepositRequest.objects.filter(deposit=deposit). order_by('id')) # 2 deposit requests for the same deposit - self.assertEquals(len(deposit_requests), 2) - self.assertEquals(deposit_requests[0].deposit, deposit) - self.assertEquals(deposit_requests[0].type.name, 'archive') + self.assertEqual(len(deposit_requests), 2) + self.assertEqual(deposit_requests[0].deposit, deposit) + self.assertEqual(deposit_requests[0].type.name, 'archive') self.assertRegex(deposit_requests[0].archive.name, self.archive['name']) - self.assertEquals(deposit_requests[1].deposit, deposit) - self.assertEquals(deposit_requests[1].type.name, 'archive') + self.assertEqual(deposit_requests[1].deposit, deposit) + self.assertEqual(deposit_requests[1].type.name, 'archive') self.assertRegex(deposit_requests[1].archive.name, archive2['name']) # only 1 deposit in db deposits = Deposit.objects.all() self.assertEqual(len(deposits), 1) - @istest - def post_deposit_then_post_or_put_is_refused_when_status_ready(self): + def test_post_deposit_then_post_or_put_is_refused_when_status_ready(self): """Updating a deposit with status 'ready' should return a 400 """ url = reverse(COL_IRI, args=[self.collection.name]) external_id = 'some-external-id-1' # when response = self.client.post( url, content_type='application/zip', # as zip data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.client, self.user) self.assertIsNone(deposit.swh_id) deposit_request = DepositRequest.objects.get(deposit=deposit) - self.assertEquals(deposit_request.deposit, deposit) + self.assertEqual(deposit_request.deposit, deposit) self.assertRegex(deposit_request.archive.name, 'filename0') # updating/adding is forbidden # uri to update the content edit_se_iri = reverse( 'edit_se_iri', args=[self.collection.name, deposit_id]) em_iri = reverse( 'em_iri', args=[self.collection.name, deposit_id]) # Testing all update/add endpoint should fail # since the status is ready archive2 = create_arborescence_archive( self.root_path, 'archive2', 'file2', b'some content in file 2') # replacing file is no longer possible since the deposit's # status is ready r = self.client.put( em_iri, content_type='application/zip', data=archive2['data'], CONTENT_LENGTH=archive2['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=archive2['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') - self.assertEquals(r.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual(r.status_code, status.HTTP_400_BAD_REQUEST) # adding file is no longer possible since the deposit's status # is ready r = self.client.post( em_iri, content_type='application/zip', data=archive2['data'], CONTENT_LENGTH=archive2['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=archive2['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') - self.assertEquals(r.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual(r.status_code, status.HTTP_400_BAD_REQUEST) # replacing metadata is no longer possible since the deposit's # status is ready r = self.client.put( edit_se_iri, content_type='application/atom+xml;type=entry', data=self.data_atom_entry_ok, CONTENT_LENGTH=len(self.data_atom_entry_ok), HTTP_SLUG=external_id) - self.assertEquals(r.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual(r.status_code, status.HTTP_400_BAD_REQUEST) # adding new metadata is no longer possible since the # deposit's status is ready r = self.client.post( edit_se_iri, content_type='application/atom+xml;type=entry', data=self.data_atom_entry_ok, CONTENT_LENGTH=len(self.data_atom_entry_ok), HTTP_SLUG=external_id) - self.assertEquals(r.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual(r.status_code, status.HTTP_400_BAD_REQUEST) archive_content = b'some content representing archive' archive = InMemoryUploadedFile( BytesIO(archive_content), field_name='archive0', name='archive0', content_type='application/zip', size=len(archive_content), charset=None) atom_entry = InMemoryUploadedFile( BytesIO(self.data_atom_entry_ok), field_name='atom0', name='atom0', content_type='application/atom+xml; charset="utf-8"', size=len(self.data_atom_entry_ok), charset='utf-8') # replacing multipart metadata is no longer possible since the # deposit's status is ready r = self.client.put( edit_se_iri, format='multipart', data={ 'archive': archive, 'atom_entry': atom_entry, }) - self.assertEquals(r.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual(r.status_code, status.HTTP_400_BAD_REQUEST) # adding new metadata is no longer possible since the # deposit's status is ready r = self.client.post( edit_se_iri, format='multipart', data={ 'archive': archive, 'atom_entry': atom_entry, }) - self.assertEquals(r.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual(r.status_code, status.HTTP_400_BAD_REQUEST) diff --git a/swh/deposit/tests/api/test_deposit_check.py b/swh/deposit/tests/api/test_deposit_check.py index 9ce5d1c5..1b9c5d2d 100644 --- a/swh/deposit/tests/api/test_deposit_check.py +++ b/swh/deposit/tests/api/test_deposit_check.py @@ -1,246 +1,236 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import unittest from django.core.urlresolvers import reverse -from nose.tools import istest -from nose.plugins.attrib import attr +import pytest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.config import ( DEPOSIT_STATUS_VERIFIED, PRIVATE_CHECK_DEPOSIT, DEPOSIT_STATUS_DEPOSITED, DEPOSIT_STATUS_REJECTED ) from swh.deposit.api.private.deposit_check import ( SWHChecksDeposit, MANDATORY_ARCHIVE_INVALID, MANDATORY_FIELDS_MISSING, INCOMPATIBLE_URL_FIELDS, MANDATORY_ARCHIVE_UNSUPPORTED, ALTERNATE_FIELDS_MISSING, MANDATORY_ARCHIVE_MISSING ) from swh.deposit.models import Deposit from ..common import BasicTestCase, WithAuthTestCase, CommonCreationRoutine from ..common import FileSystemCreationRoutine -@attr('fs') +@pytest.mark.fs class CheckDepositTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine, FileSystemCreationRoutine): """Check deposit endpoints. """ def setUp(self): super().setUp() - @istest - def deposit_ok(self): + def test_deposit_ok(self): """Proper deposit should succeed the checks (-> status ready) """ deposit_id = self.create_simple_binary_deposit(status_partial=True) deposit_id = self.update_binary_deposit(deposit_id, status_partial=False) deposit = Deposit.objects.get(pk=deposit_id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_DEPOSITED) + self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) url = reverse(PRIVATE_CHECK_DEPOSIT, args=[self.collection.name, deposit.id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json() self.assertEqual(data['status'], DEPOSIT_STATUS_VERIFIED) deposit = Deposit.objects.get(pk=deposit.id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_VERIFIED) + self.assertEqual(deposit.status, DEPOSIT_STATUS_VERIFIED) - @istest - def deposit_invalid_tarball(self): + def test_deposit_invalid_tarball(self): """Deposit with tarball (of 1 tarball) should fail the checks: rejected """ for archive_extension in ['zip', 'tar', 'tar.gz', 'tar.bz2', 'tar.xz']: deposit_id = self.create_deposit_archive_with_archive( archive_extension) deposit = Deposit.objects.get(pk=deposit_id) - self.assertEquals(DEPOSIT_STATUS_DEPOSITED, deposit.status) + self.assertEqual(DEPOSIT_STATUS_DEPOSITED, deposit.status) url = reverse(PRIVATE_CHECK_DEPOSIT, args=[self.collection.name, deposit.id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json() self.assertEqual(data['status'], DEPOSIT_STATUS_REJECTED) details = data['details'] # archive checks failure self.assertEqual(len(details['archive']), 1) self.assertEqual(details['archive'][0]['summary'], MANDATORY_ARCHIVE_INVALID) deposit = Deposit.objects.get(pk=deposit.id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_REJECTED) + self.assertEqual(deposit.status, DEPOSIT_STATUS_REJECTED) - @istest - def deposit_ko_missing_tarball(self): + def test_deposit_ko_missing_tarball(self): """Deposit without archive should fail the checks: rejected """ deposit_id = self.create_deposit_ready() # no archive, only atom deposit = Deposit.objects.get(pk=deposit_id) - self.assertEquals(DEPOSIT_STATUS_DEPOSITED, deposit.status) + self.assertEqual(DEPOSIT_STATUS_DEPOSITED, deposit.status) url = reverse(PRIVATE_CHECK_DEPOSIT, args=[self.collection.name, deposit.id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json() self.assertEqual(data['status'], DEPOSIT_STATUS_REJECTED) details = data['details'] # archive checks failure self.assertEqual(len(details['archive']), 1) self.assertEqual(details['archive'][0]['summary'], MANDATORY_ARCHIVE_MISSING) deposit = Deposit.objects.get(pk=deposit.id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_REJECTED) + self.assertEqual(deposit.status, DEPOSIT_STATUS_REJECTED) - @istest - def deposit_ko_unsupported_tarball(self): + def test_deposit_ko_unsupported_tarball(self): """Deposit with an unsupported tarball should fail the checks: rejected """ deposit_id = self.create_deposit_with_invalid_archive() deposit = Deposit.objects.get(pk=deposit_id) - self.assertEquals(DEPOSIT_STATUS_DEPOSITED, deposit.status) + self.assertEqual(DEPOSIT_STATUS_DEPOSITED, deposit.status) url = reverse(PRIVATE_CHECK_DEPOSIT, args=[self.collection.name, deposit.id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json() self.assertEqual(data['status'], DEPOSIT_STATUS_REJECTED) details = data['details'] # archive checks failure self.assertEqual(len(details['archive']), 1) self.assertEqual(details['archive'][0]['summary'], MANDATORY_ARCHIVE_UNSUPPORTED) # metadata check failure self.assertEqual(len(details['metadata']), 2) mandatory = details['metadata'][0] self.assertEqual(mandatory['summary'], MANDATORY_FIELDS_MISSING) self.assertEqual(set(mandatory['fields']), set(['url', 'external_identifier', 'author'])) alternate = details['metadata'][1] self.assertEqual(alternate['summary'], ALTERNATE_FIELDS_MISSING) self.assertEqual(alternate['fields'], ['name or title']) # url check failure self.assertEqual(details['url']['summary'], INCOMPATIBLE_URL_FIELDS) deposit = Deposit.objects.get(pk=deposit.id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_REJECTED) + self.assertEqual(deposit.status, DEPOSIT_STATUS_REJECTED) - @istest - def check_deposit_metadata_ok(self): + def test_check_deposit_metadata_ok(self): """Proper deposit should succeed the checks (-> status ready) with all **MUST** metadata using the codemeta metadata test set """ deposit_id = self.create_simple_binary_deposit(status_partial=True) deposit_id_metadata = self.add_metadata_to_deposit(deposit_id) - self.assertEquals(deposit_id, deposit_id_metadata) + self.assertEqual(deposit_id, deposit_id_metadata) deposit = Deposit.objects.get(pk=deposit_id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_DEPOSITED) + self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) url = reverse(PRIVATE_CHECK_DEPOSIT, args=[self.collection.name, deposit.id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json() self.assertEqual(data['status'], DEPOSIT_STATUS_VERIFIED) deposit = Deposit.objects.get(pk=deposit.id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_VERIFIED) + self.assertEqual(deposit.status, DEPOSIT_STATUS_VERIFIED) class CheckMetadata(unittest.TestCase, SWHChecksDeposit): - @istest - def check_metadata_ok(self): + def test_check_metadata_ok(self): actual_check, detail = self._check_metadata({ 'url': 'something', 'external_identifier': 'something-else', 'name': 'foo', 'author': 'someone', }) self.assertTrue(actual_check) self.assertIsNone(detail) - @istest - def check_metadata_ok2(self): + def test_check_metadata_ok2(self): actual_check, detail = self._check_metadata({ 'url': 'something', 'external_identifier': 'something-else', 'title': 'bar', 'author': 'someone', }) self.assertTrue(actual_check) self.assertIsNone(detail) - @istest - def check_metadata_ko(self): + def test_check_metadata_ko(self): """Missing optional field should be caught """ actual_check, error_detail = self._check_metadata({ 'url': 'something', 'external_identifier': 'something-else', 'author': 'someone', }) expected_error = { 'metadata': [{ 'summary': 'Mandatory alternate fields are missing', 'fields': ['name or title'], }] } self.assertFalse(actual_check) self.assertEqual(error_detail, expected_error) - @istest - def check_metadata_ko2(self): + def test_check_metadata_ko2(self): """Missing mandatory fields should be caught """ actual_check, error_detail = self._check_metadata({ 'url': 'something', 'external_identifier': 'something-else', 'title': 'foobar', }) expected_error = { 'metadata': [{ 'summary': 'Mandatory fields are missing', 'fields': ['author'], }] } self.assertFalse(actual_check) self.assertEqual(error_detail, expected_error) diff --git a/swh/deposit/tests/api/test_deposit_delete.py b/swh/deposit/tests/api/test_deposit_delete.py index 721d3128..9bf963cc 100644 --- a/swh/deposit/tests/api/test_deposit_delete.py +++ b/swh/deposit/tests/api/test_deposit_delete.py @@ -1,119 +1,113 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.urlresolvers import reverse -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.config import EDIT_SE_IRI, EM_IRI, ARCHIVE_KEY, METADATA_KEY from swh.deposit.config import DEPOSIT_STATUS_DEPOSITED from swh.deposit.models import Deposit, DepositRequest from ..common import BasicTestCase, WithAuthTestCase, CommonCreationRoutine class DepositDeleteTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine): - @istest - def delete_archive_on_partial_deposit_works(self): + def test_delete_archive_on_partial_deposit_works(self): """Removing partial deposit's archive should return a 204 response """ # given deposit_id = self.create_deposit_partial() deposit = Deposit.objects.get(pk=deposit_id) deposit_requests = DepositRequest.objects.filter(deposit=deposit) - self.assertEquals(len(deposit_requests), 2) + self.assertEqual(len(deposit_requests), 2) for dr in deposit_requests: if dr.type.name == ARCHIVE_KEY: continue elif dr.type.name == METADATA_KEY: continue else: self.fail('only archive and metadata type should exist ' 'in this test context') # when update_uri = reverse(EM_IRI, args=[self.collection.name, deposit_id]) response = self.client.delete(update_uri) # then self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) deposit = Deposit.objects.get(pk=deposit_id) requests = list(DepositRequest.objects.filter(deposit=deposit)) - self.assertEquals(len(requests), 2) - self.assertEquals(requests[0].type.name, 'metadata') - self.assertEquals(requests[1].type.name, 'metadata') + self.assertEqual(len(requests), 2) + self.assertEqual(requests[0].type.name, 'metadata') + self.assertEqual(requests[1].type.name, 'metadata') - @istest - def delete_archive_on_undefined_deposit_fails(self): + def test_delete_archive_on_undefined_deposit_fails(self): """Delete undefined deposit returns a 404 response """ # when update_uri = reverse(EM_IRI, args=[self.collection.name, 999]) response = self.client.delete(update_uri) # then self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) - @istest - def delete_archive_on_non_partial_deposit_fails(self): + def test_delete_archive_on_non_partial_deposit_fails(self): """Delete !partial status deposit should return a 400 response""" deposit_id = self.create_deposit_ready() deposit = Deposit.objects.get(pk=deposit_id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_DEPOSITED) + self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) # when update_uri = reverse(EM_IRI, args=[self.collection.name, deposit_id]) response = self.client.delete(update_uri) # then self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) deposit = Deposit.objects.get(pk=deposit_id) self.assertIsNotNone(deposit) - @istest - def delete_partial_deposit_works(self): + def test_delete_partial_deposit_works(self): """Delete deposit should return a 204 response """ # given deposit_id = self.create_simple_deposit_partial() deposit = Deposit.objects.get(pk=deposit_id) assert deposit.id == deposit_id # when url = reverse(EDIT_SE_IRI, args=[self.collection.name, deposit_id]) response = self.client.delete(url) # then self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) deposit_requests = list(DepositRequest.objects.filter(deposit=deposit)) - self.assertEquals(deposit_requests, []) + self.assertEqual(deposit_requests, []) deposits = list(Deposit.objects.filter(pk=deposit_id)) - self.assertEquals(deposits, []) + self.assertEqual(deposits, []) - @istest - def delete_on_edit_se_iri_cannot_delete_non_partial_deposit(self): + def test_delete_on_edit_se_iri_cannot_delete_non_partial_deposit(self): """Delete !partial deposit should return a 400 response """ # given deposit_id = self.create_deposit_ready() deposit = Deposit.objects.get(pk=deposit_id) assert deposit.id == deposit_id # when url = reverse(EDIT_SE_IRI, args=[self.collection.name, deposit_id]) response = self.client.delete(url) # then self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) deposit = Deposit.objects.get(pk=deposit_id) self.assertIsNotNone(deposit) diff --git a/swh/deposit/tests/api/test_deposit_list.py b/swh/deposit/tests/api/test_deposit_list.py index fe05ff46..6fb84349 100644 --- a/swh/deposit/tests/api/test_deposit_list.py +++ b/swh/deposit/tests/api/test_deposit_list.py @@ -1,96 +1,94 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.urlresolvers import reverse -from nose.tools import istest -from nose.plugins.attrib import attr +import pytest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.api.converters import convert_status_detail from ...config import DEPOSIT_STATUS_PARTIAL, PRIVATE_LIST_DEPOSITS from ..common import BasicTestCase, WithAuthTestCase, CommonCreationRoutine from ...models import Deposit -@attr('fs') +@pytest.mark.fs class CheckDepositListTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine): """Check deposit list endpoints. """ def setUp(self): super().setUp() - @istest - def deposit_list(self): + def test_deposit_list(self): """Deposit list api should return the deposits """ deposit_id = self.create_deposit_partial() # amend the deposit with a status_detail deposit = Deposit.objects.get(pk=deposit_id) status_detail = { 'url': { 'summary': 'At least one compatible url field. Failed', 'fields': ['testurl'], }, 'metadata': [ { 'summary': 'Mandatory fields missing', 'fields': ['9', 10, 1.212], }, ], 'archive': [ { 'summary': 'Invalid archive', 'fields': ['3'], }, { 'summary': 'Unsupported archive', 'fields': [2], } ], } deposit.status_detail = status_detail deposit.save() deposit_id2 = self.create_deposit_partial() # NOTE: does not work as documented # https://docs.djangoproject.com/en/1.11/ref/urlresolvers/#django.core.urlresolvers.reverse # noqa # url = reverse(PRIVATE_LIST_DEPOSITS, kwargs={'page_size': 1}) main_url = reverse(PRIVATE_LIST_DEPOSITS) url = '%s?page_size=1' % main_url response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json() self.assertEqual(data['count'], 2) # 2 deposits expected_next = '%s?page=2&page_size=1' % main_url self.assertTrue(data['next'].endswith(expected_next)) self.assertIsNone(data['previous']) self.assertEqual(len(data['results']), 1) # page of size 1 deposit = data['results'][0] - self.assertEquals(deposit['id'], deposit_id) - self.assertEquals(deposit['status'], DEPOSIT_STATUS_PARTIAL) + self.assertEqual(deposit['id'], deposit_id) + self.assertEqual(deposit['status'], DEPOSIT_STATUS_PARTIAL) expected_status_detail = convert_status_detail(status_detail) - self.assertEquals(deposit['status_detail'], expected_status_detail) + self.assertEqual(deposit['status_detail'], expected_status_detail) # then 2nd page response2 = self.client.get(expected_next) self.assertEqual(response2.status_code, status.HTTP_200_OK) data2 = response2.json() self.assertEqual(data2['count'], 2) # still 2 deposits self.assertIsNone(data2['next']) expected_previous = '%s?page_size=1' % main_url self.assertTrue(data2['previous'].endswith(expected_previous)) self.assertEqual(len(data2['results']), 1) # page of size 1 deposit2 = data2['results'][0] - self.assertEquals(deposit2['id'], deposit_id2) - self.assertEquals(deposit2['status'], DEPOSIT_STATUS_PARTIAL) + self.assertEqual(deposit2['id'], deposit_id2) + self.assertEqual(deposit2['status'], DEPOSIT_STATUS_PARTIAL) diff --git a/swh/deposit/tests/api/test_deposit_multipart.py b/swh/deposit/tests/api/test_deposit_multipart.py index 8388d2ec..4bd37b6a 100644 --- a/swh/deposit/tests/api/test_deposit_multipart.py +++ b/swh/deposit/tests/api/test_deposit_multipart.py @@ -1,408 +1,402 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.files.uploadedfile import InMemoryUploadedFile from django.core.urlresolvers import reverse from io import BytesIO -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.config import COL_IRI from swh.deposit.config import DEPOSIT_STATUS_DEPOSITED from swh.deposit.models import Deposit, DepositRequest from swh.deposit.parsers import parse_xml from ..common import BasicTestCase, WithAuthTestCase from ..common import FileSystemCreationRoutine class DepositMultipartTestCase(APITestCase, WithAuthTestCase, BasicTestCase, FileSystemCreationRoutine): """Post multipart deposit scenario """ def setUp(self): super().setUp() self.data_atom_entry_ok = b""" Title urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2005-10-07T17:17:08Z Contributor The abstract The abstract Access Rights Alternative Title Date Available Bibliographic Citation # noqa Contributor Description Has Part Has Version Identifier Is Part Of Publisher References Rights Holder Source Title Type """ self.data_atom_entry_update_in_place = """ urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa7b Title Type """ - @istest - def post_deposit_multipart_without_slug_header_is_bad_request(self): + def test_post_deposit_multipart_without_slug_header_is_bad_request(self): # given url = reverse(COL_IRI, args=[self.collection.name]) data_atom_entry = self.data_atom_entry_ok archive_content = b'some content representing archive' archive = InMemoryUploadedFile( BytesIO(archive_content), field_name='archive0', name='archive0', content_type='application/zip', size=len(archive_content), charset=None) atom_entry = InMemoryUploadedFile( BytesIO(data_atom_entry), field_name='atom0', name='atom0', content_type='application/atom+xml; charset="utf-8"', size=len(data_atom_entry), charset='utf-8') # when response = self.client.post( url, format='multipart', data={ 'archive': archive, 'atom_entry': atom_entry, }, # + headers HTTP_IN_PROGRESS='false') self.assertIn(b'Missing SLUG header', response.content) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) - @istest - def post_deposit_multipart_zip(self): + def test_post_deposit_multipart_zip(self): """one multipart deposit (zip+xml) should be accepted """ # given url = reverse(COL_IRI, args=[self.collection.name]) # from django.core.files import uploadedfile data_atom_entry = self.data_atom_entry_ok archive = InMemoryUploadedFile( BytesIO(self.archive['data']), field_name=self.archive['name'], name=self.archive['name'], content_type='application/zip', size=self.archive['length'], charset=None) atom_entry = InMemoryUploadedFile( BytesIO(data_atom_entry), field_name='atom0', name='atom0', content_type='application/atom+xml; charset="utf-8"', size=len(data_atom_entry), charset='utf-8') external_id = 'external-id' # when response = self.client.post( url, format='multipart', data={ 'archive': archive, 'atom_entry': atom_entry, }, # + headers HTTP_IN_PROGRESS='false', HTTP_SLUG=external_id) # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.client, self.user) self.assertIsNone(deposit.swh_id) deposit_requests = DepositRequest.objects.filter(deposit=deposit) - self.assertEquals(len(deposit_requests), 2) + self.assertEqual(len(deposit_requests), 2) for deposit_request in deposit_requests: - self.assertEquals(deposit_request.deposit, deposit) + self.assertEqual(deposit_request.deposit, deposit) if deposit_request.type.name == 'archive': self.assertRegex(deposit_request.archive.name, self.archive['name']) self.assertIsNone(deposit_request.metadata) self.assertIsNone(deposit_request.raw_metadata) else: - self.assertEquals( + self.assertEqual( deposit_request.metadata['id'], 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') - self.assertEquals(deposit_request.raw_metadata, - data_atom_entry.decode('utf-8')) + self.assertEqual(deposit_request.raw_metadata, + data_atom_entry.decode('utf-8')) - @istest - def post_deposit_multipart_tar(self): + def test_post_deposit_multipart_tar(self): """one multipart deposit (tar+xml) should be accepted """ # given url = reverse(COL_IRI, args=[self.collection.name]) # from django.core.files import uploadedfile data_atom_entry = self.data_atom_entry_ok archive = InMemoryUploadedFile( BytesIO(self.archive['data']), field_name=self.archive['name'], name=self.archive['name'], content_type='application/x-tar', size=self.archive['length'], charset=None) atom_entry = InMemoryUploadedFile( BytesIO(data_atom_entry), field_name='atom0', name='atom0', content_type='application/atom+xml; charset="utf-8"', size=len(data_atom_entry), charset='utf-8') external_id = 'external-id' # when response = self.client.post( url, format='multipart', data={ 'archive': archive, 'atom_entry': atom_entry, }, # + headers HTTP_IN_PROGRESS='false', HTTP_SLUG=external_id) # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.client, self.user) self.assertIsNone(deposit.swh_id) deposit_requests = DepositRequest.objects.filter(deposit=deposit) - self.assertEquals(len(deposit_requests), 2) + self.assertEqual(len(deposit_requests), 2) for deposit_request in deposit_requests: - self.assertEquals(deposit_request.deposit, deposit) + self.assertEqual(deposit_request.deposit, deposit) if deposit_request.type.name == 'archive': self.assertRegex(deposit_request.archive.name, self.archive['name']) self.assertIsNone(deposit_request.metadata) self.assertIsNone(deposit_request.raw_metadata) else: - self.assertEquals( + self.assertEqual( deposit_request.metadata['id'], 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') - self.assertEquals(deposit_request.raw_metadata, - data_atom_entry.decode('utf-8')) + self.assertEqual(deposit_request.raw_metadata, + data_atom_entry.decode('utf-8')) - @istest - def post_deposit_multipart_put_to_replace_metadata(self): + def test_post_deposit_multipart_put_to_replace_metadata(self): """One multipart deposit followed by a metadata update should be accepted """ # given url = reverse(COL_IRI, args=[self.collection.name]) data_atom_entry = self.data_atom_entry_ok archive = InMemoryUploadedFile( BytesIO(self.archive['data']), field_name=self.archive['name'], name=self.archive['name'], content_type='application/zip', size=self.archive['length'], charset=None) atom_entry = InMemoryUploadedFile( BytesIO(data_atom_entry), field_name='atom0', name='atom0', content_type='application/atom+xml; charset="utf-8"', size=len(data_atom_entry), charset='utf-8') external_id = 'external-id' # when response = self.client.post( url, format='multipart', data={ 'archive': archive, 'atom_entry': atom_entry, }, # + headers HTTP_IN_PROGRESS='true', HTTP_SLUG=external_id) # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) deposit_id = response_content['deposit_id'] deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.status, 'partial') self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.client, self.user) self.assertIsNone(deposit.swh_id) deposit_requests = DepositRequest.objects.filter(deposit=deposit) - self.assertEquals(len(deposit_requests), 2) + self.assertEqual(len(deposit_requests), 2) for deposit_request in deposit_requests: - self.assertEquals(deposit_request.deposit, deposit) + self.assertEqual(deposit_request.deposit, deposit) if deposit_request.type.name == 'archive': self.assertRegex(deposit_request.archive.name, self.archive['name']) else: - self.assertEquals( + self.assertEqual( deposit_request.metadata['id'], 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') - self.assertEquals(deposit_request.raw_metadata, - data_atom_entry.decode('utf-8')) + self.assertEqual(deposit_request.raw_metadata, + data_atom_entry.decode('utf-8')) replace_metadata_uri = response._headers['location'][1] response = self.client.put( replace_metadata_uri, content_type='application/atom+xml;type=entry', data=self.data_atom_entry_update_in_place, HTTP_IN_PROGRESS='false') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # deposit_id did not change deposit = Deposit.objects.get(pk=deposit_id) self.assertEqual(deposit.status, DEPOSIT_STATUS_DEPOSITED) self.assertEqual(deposit.external_id, external_id) self.assertEqual(deposit.collection, self.collection) self.assertEqual(deposit.client, self.user) self.assertIsNone(deposit.swh_id) deposit_requests = DepositRequest.objects.filter(deposit=deposit) - self.assertEquals(len(deposit_requests), 2) + self.assertEqual(len(deposit_requests), 2) for deposit_request in deposit_requests: - self.assertEquals(deposit_request.deposit, deposit) + self.assertEqual(deposit_request.deposit, deposit) if deposit_request.type.name == 'archive': self.assertRegex(deposit_request.archive.name, self.archive['name']) else: - self.assertEquals( + self.assertEqual( deposit_request.metadata['id'], 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa7b') - self.assertEquals( + self.assertEqual( deposit_request.raw_metadata, self.data_atom_entry_update_in_place) # FAILURE scenarios - @istest - def post_deposit_multipart_only_archive_and_atom_entry(self): + def test_post_deposit_multipart_only_archive_and_atom_entry(self): """Multipart deposit only accepts one archive and one atom+xml""" # given url = reverse(COL_IRI, args=[self.collection.name]) archive_content = b'some content representing archive' archive = InMemoryUploadedFile(BytesIO(archive_content), field_name='archive0', name='archive0', content_type='application/x-tar', size=len(archive_content), charset=None) other_archive_content = b"some-other-content" other_archive = InMemoryUploadedFile(BytesIO(other_archive_content), field_name='atom0', name='atom0', content_type='application/x-tar', size=len(other_archive_content), charset='utf-8') # when response = self.client.post( url, format='multipart', data={ 'archive': archive, 'atom_entry': other_archive, }, # + headers HTTP_IN_PROGRESS='false', HTTP_SLUG='external-id') # then self.assertEqual(response.status_code, status.HTTP_415_UNSUPPORTED_MEDIA_TYPE) self.assertTrue( 'Only 1 application/zip (or application/x-tar) archive' in response.content.decode('utf-8')) # when archive.seek(0) response = self.client.post( url, format='multipart', data={ 'archive': archive, }, # + headers HTTP_IN_PROGRESS='false', HTTP_SLUG='external-id') # then self.assertEqual(response.status_code, status.HTTP_415_UNSUPPORTED_MEDIA_TYPE) self.assertTrue( 'You must provide both 1 application/zip (or ' 'application/x-tar) and 1 atom+xml entry for ' 'multipart deposit' in response.content.decode('utf-8') ) diff --git a/swh/deposit/tests/api/test_deposit_read_archive.py b/swh/deposit/tests/api/test_deposit_read_archive.py index 21c4bf90..4c82ad2b 100644 --- a/swh/deposit/tests/api/test_deposit_read_archive.py +++ b/swh/deposit/tests/api/test_deposit_read_archive.py @@ -1,130 +1,125 @@ # Copyright (C) 2017 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import hashlib import os from django.core.urlresolvers import reverse -from nose.tools import istest -from nose.plugins.attrib import attr +import pytest from rest_framework import status from rest_framework.test import APITestCase from swh.core import tarball from swh.deposit.config import PRIVATE_GET_RAW_CONTENT from swh.deposit.tests import TEST_CONFIG from ..common import BasicTestCase, WithAuthTestCase, CommonCreationRoutine from ..common import FileSystemCreationRoutine, create_arborescence_archive -@attr('fs') +@pytest.mark.fs class DepositReadArchivesTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine, FileSystemCreationRoutine): def setUp(self): super().setUp() self.archive2 = create_arborescence_archive( self.root_path, 'archive2', 'file2', b'some other content in file') self.workdir = os.path.join(self.root_path, 'workdir') - @istest - def access_to_existing_deposit_with_one_archive(self): + def test_access_to_existing_deposit_with_one_archive(self): """Access to deposit should stream a 200 response with its raw content """ deposit_id = self.create_simple_binary_deposit() url = reverse(PRIVATE_GET_RAW_CONTENT, args=[self.collection.name, deposit_id]) r = self.client.get(url) - self.assertEquals(r.status_code, status.HTTP_200_OK) - self.assertEquals(r._headers['content-type'][1], - 'application/octet-stream') + self.assertEqual(r.status_code, status.HTTP_200_OK) + self.assertEqual(r._headers['content-type'][1], + 'application/octet-stream') # read the stream data = b''.join(r.streaming_content) actual_sha1 = hashlib.sha1(data).hexdigest() - self.assertEquals(actual_sha1, self.archive['sha1sum']) + self.assertEqual(actual_sha1, self.archive['sha1sum']) # this does not touch the extraction dir so this should stay empty - self.assertEquals(os.listdir(TEST_CONFIG['extraction_dir']), []) + self.assertEqual(os.listdir(TEST_CONFIG['extraction_dir']), []) def _check_tarball_consistency(self, actual_sha1): tarball.uncompress(self.archive['path'], self.workdir) - self.assertEquals(os.listdir(self.workdir), ['file1']) + self.assertEqual(os.listdir(self.workdir), ['file1']) tarball.uncompress(self.archive2['path'], self.workdir) lst = set(os.listdir(self.workdir)) - self.assertEquals(lst, {'file1', 'file2'}) + self.assertEqual(lst, {'file1', 'file2'}) new_path = self.workdir + '.zip' tarball.compress(new_path, 'zip', self.workdir) with open(new_path, 'rb') as f: h = hashlib.sha1(f.read()).hexdigest() self.assertEqual(actual_sha1, h) self.assertNotEqual(actual_sha1, self.archive['sha1sum']) self.assertNotEqual(actual_sha1, self.archive2['sha1sum']) - @istest - def access_to_existing_deposit_with_multiple_archives(self): + def test_access_to_existing_deposit_with_multiple_archives(self): """Access to deposit should stream a 200 response with its raw contents """ deposit_id = self.create_complex_binary_deposit() url = reverse(PRIVATE_GET_RAW_CONTENT, args=[self.collection.name, deposit_id]) r = self.client.get(url) - self.assertEquals(r.status_code, status.HTTP_200_OK) - self.assertEquals(r._headers['content-type'][1], - 'application/octet-stream') + self.assertEqual(r.status_code, status.HTTP_200_OK) + self.assertEqual(r._headers['content-type'][1], + 'application/octet-stream') # read the stream data = b''.join(r.streaming_content) actual_sha1 = hashlib.sha1(data).hexdigest() self._check_tarball_consistency(actual_sha1) # this touches the extraction directory but should clean up # after itself - self.assertEquals(os.listdir(TEST_CONFIG['extraction_dir']), []) + self.assertEqual(os.listdir(TEST_CONFIG['extraction_dir']), []) class DepositReadArchivesFailureTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine): - @istest - def access_to_nonexisting_deposit_returns_404_response(self): + def test_access_to_nonexisting_deposit_returns_404_response(self): """Read unknown collection should return a 404 response """ unknown_id = '999' url = reverse(PRIVATE_GET_RAW_CONTENT, args=[self.collection.name, unknown_id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertIn('Deposit with id %s does not exist' % unknown_id, response.content.decode('utf-8')) - @istest - def access_to_nonexisting_collection_returns_404_response(self): + def test_access_to_nonexisting_collection_returns_404_response(self): """Read unknown deposit should return a 404 response """ collection_name = 'non-existing' deposit_id = self.create_deposit_partial() url = reverse(PRIVATE_GET_RAW_CONTENT, args=[collection_name, deposit_id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertIn('Unknown collection name %s' % collection_name, response.content.decode('utf-8')) diff --git a/swh/deposit/tests/api/test_deposit_read_metadata.py b/swh/deposit/tests/api/test_deposit_read_metadata.py index 15653fd7..9f40e701 100644 --- a/swh/deposit/tests/api/test_deposit_read_metadata.py +++ b/swh/deposit/tests/api/test_deposit_read_metadata.py @@ -1,210 +1,205 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.urlresolvers import reverse -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.models import Deposit from swh.deposit.config import PRIVATE_GET_DEPOSIT_METADATA from swh.deposit.config import DEPOSIT_STATUS_LOAD_SUCCESS from swh.deposit.config import DEPOSIT_STATUS_PARTIAL from ...config import SWH_PERSON from ..common import BasicTestCase, WithAuthTestCase, CommonCreationRoutine class DepositReadMetadataTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine): """Deposit access to read metadata information on deposit. """ - @istest - def read_metadata(self): + def test_read_metadata(self): """Private metadata read api to existing deposit should return metadata """ deposit_id = self.create_deposit_partial() url = reverse(PRIVATE_GET_DEPOSIT_METADATA, args=[self.collection.name, deposit_id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEquals(response._headers['content-type'][1], - 'application/json') + self.assertEqual(response._headers['content-type'][1], + 'application/json') data = response.json() expected_meta = { 'origin': { 'url': 'https://hal-test.archives-ouvertes.fr/' + 'some-external-id', 'type': 'deposit' }, 'origin_metadata': { 'metadata': { '@xmlns': ['http://www.w3.org/2005/Atom'], 'author': ['some awesome author', 'another one', 'no one'], 'external_identifier': 'some-external-id', 'url': 'https://hal-test.archives-ouvertes.fr/' + 'some-external-id' }, 'provider': { 'provider_name': 'hal', 'provider_type': 'deposit_client', 'provider_url': 'https://hal-test.archives-ouvertes.fr/', 'metadata': {} }, 'tool': { - 'tool_name': 'swh-deposit', - 'tool_version': '0.0.1', - 'tool_configuration': { + 'name': 'swh-deposit', + 'version': '0.0.1', + 'configuration': { 'sword_version': '2' } } }, 'revision': { 'synthetic': True, 'committer_date': None, 'message': 'hal: Deposit %s in collection hal' % deposit_id, 'author': SWH_PERSON, 'committer': SWH_PERSON, 'date': None, 'metadata': { '@xmlns': ['http://www.w3.org/2005/Atom'], 'author': ['some awesome author', 'another one', 'no one'], 'external_identifier': 'some-external-id', 'url': 'https://hal-test.archives-ouvertes.fr/' + 'some-external-id' }, 'type': 'tar' }, 'branch_name': 'master', } - self.assertEquals(data, expected_meta) + self.assertEqual(data, expected_meta) - @istest - def read_metadata_revision_with_parent(self): + def test_read_metadata_revision_with_parent(self): """Private read metadata to a deposit (with parent) returns metadata """ swh_id = 'da78a9d4cf1d5d29873693fd496142e3a18c20fa' swh_persistent_id = 'swh:1:rev:%s' % swh_id deposit_id1 = self.create_deposit_with_status( status=DEPOSIT_STATUS_LOAD_SUCCESS, external_id='some-external-id', swh_id=swh_persistent_id) deposit_parent = Deposit.objects.get(pk=deposit_id1) - self.assertEquals(deposit_parent.swh_id, swh_persistent_id) - self.assertEquals(deposit_parent.external_id, 'some-external-id') - self.assertEquals(deposit_parent.status, DEPOSIT_STATUS_LOAD_SUCCESS) + self.assertEqual(deposit_parent.swh_id, swh_persistent_id) + self.assertEqual(deposit_parent.external_id, 'some-external-id') + self.assertEqual(deposit_parent.status, DEPOSIT_STATUS_LOAD_SUCCESS) deposit_id = self.create_deposit_partial( external_id='some-external-id') deposit = Deposit.objects.get(pk=deposit_id) - self.assertEquals(deposit.external_id, 'some-external-id') - self.assertEquals(deposit.swh_id, None) - self.assertEquals(deposit.parent, deposit_parent) - self.assertEquals(deposit.status, DEPOSIT_STATUS_PARTIAL) + self.assertEqual(deposit.external_id, 'some-external-id') + self.assertEqual(deposit.swh_id, None) + self.assertEqual(deposit.parent, deposit_parent) + self.assertEqual(deposit.status, DEPOSIT_STATUS_PARTIAL) url = reverse(PRIVATE_GET_DEPOSIT_METADATA, args=[self.collection.name, deposit_id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEquals(response._headers['content-type'][1], - 'application/json') + self.assertEqual(response._headers['content-type'][1], + 'application/json') data = response.json() expected_meta = { 'origin': { 'url': 'https://hal-test.archives-ouvertes.fr/' + 'some-external-id', 'type': 'deposit' }, 'origin_metadata': { 'metadata': { '@xmlns': ['http://www.w3.org/2005/Atom'], 'author': ['some awesome author', 'another one', 'no one'], 'external_identifier': 'some-external-id', 'url': 'https://hal-test.archives-ouvertes.fr/' + 'some-external-id' }, 'provider': { 'provider_name': 'hal', 'provider_type': 'deposit_client', 'provider_url': 'https://hal-test.archives-ouvertes.fr/', 'metadata': {} }, 'tool': { - 'tool_name': 'swh-deposit', - 'tool_version': '0.0.1', - 'tool_configuration': { + 'name': 'swh-deposit', + 'version': '0.0.1', + 'configuration': { 'sword_version': '2' } } }, 'revision': { 'synthetic': True, 'date': None, 'committer_date': None, 'author': SWH_PERSON, 'committer': SWH_PERSON, 'type': 'tar', 'message': 'hal: Deposit %s in collection hal' % deposit_id, 'metadata': { '@xmlns': ['http://www.w3.org/2005/Atom'], 'author': ['some awesome author', 'another one', 'no one'], 'external_identifier': 'some-external-id', 'url': 'https://hal-test.archives-ouvertes.fr/' + 'some-external-id' }, 'parents': [swh_id] }, 'branch_name': 'master', } self.assertEqual(data, expected_meta) - @istest - def access_to_nonexisting_deposit_returns_404_response(self): + def test_access_to_nonexisting_deposit_returns_404_response(self): """Read unknown collection should return a 404 response """ unknown_id = '999' url = reverse(PRIVATE_GET_DEPOSIT_METADATA, args=[self.collection.name, unknown_id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertIn('Deposit with id %s does not exist' % unknown_id, response.content.decode('utf-8')) - @istest - def access_to_nonexisting_collection_returns_404_response(self): + def test_access_to_nonexisting_collection_returns_404_response(self): """Read unknown deposit should return a 404 response """ collection_name = 'non-existing' deposit_id = self.create_deposit_partial() url = reverse(PRIVATE_GET_DEPOSIT_METADATA, args=[collection_name, deposit_id]) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertIn('Unknown collection name %s' % collection_name, response.content.decode('utf-8'),) diff --git a/swh/deposit/tests/api/test_deposit_status.py b/swh/deposit/tests/api/test_deposit_status.py index d2362449..256f2cf6 100644 --- a/swh/deposit/tests/api/test_deposit_status.py +++ b/swh/deposit/tests/api/test_deposit_status.py @@ -1,151 +1,144 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.urlresolvers import reverse from io import BytesIO -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase -from swh.deposit.api.deposit_status import convert_status_detail from swh.deposit.config import (COL_IRI, STATE_IRI, DEPOSIT_STATUS_DEPOSITED, DEPOSIT_STATUS_REJECTED) from swh.deposit.models import Deposit, DEPOSIT_STATUS_DETAIL from swh.deposit.models import DEPOSIT_STATUS_LOAD_SUCCESS from swh.deposit.parsers import parse_xml from ..common import BasicTestCase, WithAuthTestCase, FileSystemCreationRoutine from ..common import CommonCreationRoutine class DepositStatusTestCase(APITestCase, WithAuthTestCase, BasicTestCase, FileSystemCreationRoutine, CommonCreationRoutine): """Status on deposit """ - @istest - def post_deposit_with_status_check(self): + def test_post_deposit_with_status_check(self): """Binary upload should be accepted """ # given url = reverse(COL_IRI, args=[self.collection.name]) external_id = 'some-external-id-1' # when response = self.client.post( url, content_type='application/zip', # as zip data=self.archive['data'], # + headers CONTENT_LENGTH=self.archive['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) deposit = Deposit.objects.get(external_id=external_id) status_url = reverse(STATE_IRI, args=[self.collection.name, deposit.id]) # check status status_response = self.client.get(status_url) self.assertEqual(status_response.status_code, status.HTTP_200_OK) r = parse_xml(BytesIO(status_response.content)) self.assertEqual(int(r['deposit_id']), deposit.id) self.assertEqual(r['deposit_status'], DEPOSIT_STATUS_DEPOSITED) self.assertEqual(r['deposit_status_detail'], DEPOSIT_STATUS_DETAIL[DEPOSIT_STATUS_DEPOSITED]) - @istest - def status_with_swh_information(self): + def test_status_with_swh_information(self): _status = DEPOSIT_STATUS_LOAD_SUCCESS _context = 'https://hal.archives-ouvertes.fr/hal-01727745' _swh_id = 'swh:1:dir:42a13fc721c8716ff695d0d62fc851d641f3a12b' _swh_id_context = '%s;%s' % (_swh_id, _context) _swh_anchor_id = 'swh:rev:1:548b3c0a2bb43e1fca191e24b5803ff6b3bc7c10' _swh_anchor_id_context = '%s;%s' % (_swh_anchor_id, _context) # given deposit_id = self.create_deposit_with_status( status=_status, swh_id=_swh_id, swh_id_context=_swh_id_context, swh_anchor_id=_swh_anchor_id, swh_anchor_id_context=_swh_anchor_id_context ) url = reverse(STATE_IRI, args=[self.collection.name, deposit_id]) # when status_response = self.client.get(url) # then self.assertEqual(status_response.status_code, status.HTTP_200_OK) r = parse_xml(BytesIO(status_response.content)) self.assertEqual(int(r['deposit_id']), deposit_id) self.assertEqual(r['deposit_status'], _status) self.assertEqual(r['deposit_status_detail'], DEPOSIT_STATUS_DETAIL[DEPOSIT_STATUS_LOAD_SUCCESS]) self.assertEqual(r['deposit_swh_id'], _swh_id) self.assertEqual(r['deposit_swh_id_context'], _swh_id_context) self.assertEqual(r['deposit_swh_anchor_id'], _swh_anchor_id) self.assertEqual(r['deposit_swh_anchor_id_context'], _swh_anchor_id_context) - @istest - def status_on_unknown_deposit(self): + def test_status_on_unknown_deposit(self): """Asking for the status of unknown deposit returns 404 response""" status_url = reverse(STATE_IRI, args=[self.collection.name, 999]) status_response = self.client.get(status_url) self.assertEqual(status_response.status_code, status.HTTP_404_NOT_FOUND) - @istest - def status_with_http_accept_header_should_not_break(self): + def test_status_with_http_accept_header_should_not_break(self): """Asking deposit status with Accept header should return 200 """ deposit_id = self.create_deposit_partial() status_url = reverse(STATE_IRI, args=[ self.collection.name, deposit_id]) response = self.client.get( status_url, HTTP_ACCEPT='text/html,application/xml;q=9,*/*,q=8') self.assertEqual(response.status_code, status.HTTP_200_OK) - @istest - def status_on_deposit_rejected(self): + def test_status_on_deposit_rejected(self): _status = DEPOSIT_STATUS_REJECTED _swh_id = '548b3c0a2bb43e1fca191e24b5803ff6b3bc7c10' _status_detail = {'url': {'summary': 'Wrong url'}} # given deposit_id = self.create_deposit_with_status( status=_status, swh_id=_swh_id, status_detail=_status_detail) url = reverse(STATE_IRI, args=[self.collection.name, deposit_id]) # when status_response = self.client.get(url) # then self.assertEqual(status_response.status_code, status.HTTP_200_OK) r = parse_xml(BytesIO(status_response.content)) self.assertEqual(int(r['deposit_id']), deposit_id) self.assertEqual(r['deposit_status'], _status) self.assertEqual(r['deposit_status_detail'], '- Wrong url') self.assertEqual(r['deposit_swh_id'], _swh_id) diff --git a/swh/deposit/tests/api/test_deposit_update.py b/swh/deposit/tests/api/test_deposit_update.py index 22478011..45935564 100644 --- a/swh/deposit/tests/api/test_deposit_update.py +++ b/swh/deposit/tests/api/test_deposit_update.py @@ -1,345 +1,333 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.urlresolvers import reverse -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.models import Deposit, DepositRequest from swh.deposit.config import EDIT_SE_IRI, EM_IRI from ..common import BasicTestCase, WithAuthTestCase, CommonCreationRoutine from ..common import FileSystemCreationRoutine, create_arborescence_archive class DepositUpdateOrReplaceExistingDataTest( APITestCase, WithAuthTestCase, BasicTestCase, FileSystemCreationRoutine, CommonCreationRoutine): """Try put/post (update/replace) query on EM_IRI """ def setUp(self): super().setUp() self.atom_entry_data1 = b""" bar """ self.atom_entry_data1 = b""" bar """ self.archive2 = create_arborescence_archive( self.root_path, 'archive2', 'file2', b'some other content in file') - @istest - def replace_archive_to_deposit_is_possible(self): + def test_replace_archive_to_deposit_is_possible(self): """Replace all archive with another one should return a 204 response """ # given deposit_id = self.create_simple_binary_deposit(status_partial=True) deposit = Deposit.objects.get(pk=deposit_id) requests = DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['archive']) assert len(list(requests)) == 1 assert self.archive['name'] in requests[0].archive.name # we have no metadata for that deposit requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['metadata'])) assert len(requests) == 0 deposit_id = self._update_deposit_with_status(deposit_id, status_partial=True) requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['metadata'])) assert len(requests) == 1 update_uri = reverse(EM_IRI, args=[self.collection.name, deposit_id]) external_id = 'some-external-id-1' response = self.client.put( update_uri, content_type='application/zip', # as zip data=self.archive2['data'], # + headers CONTENT_LENGTH=self.archive2['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive2['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=%s' % ( self.archive2['name'], )) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) requests = DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['archive']) - self.assertEquals(len(list(requests)), 1) + self.assertEqual(len(list(requests)), 1) self.assertRegex(requests[0].archive.name, self.archive2['name']) # check we did not touch the other parts requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['metadata'])) - self.assertEquals(len(requests), 1) + self.assertEqual(len(requests), 1) - @istest - def replace_metadata_to_deposit_is_possible(self): + def test_replace_metadata_to_deposit_is_possible(self): """Replace all metadata with another one should return a 204 response """ # given deposit_id = self.create_simple_binary_deposit(status_partial=True) deposit = Deposit.objects.get(pk=deposit_id) requests = DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['metadata']) assert len(list(requests)) == 0 requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['archive'])) assert len(requests) == 1 update_uri = reverse(EDIT_SE_IRI, args=[self.collection.name, deposit_id]) response = self.client.put( update_uri, content_type='application/atom+xml;type=entry', data=self.atom_entry_data1) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) requests = DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['metadata']) - self.assertEquals(len(list(requests)), 1) + self.assertEqual(len(list(requests)), 1) metadata = requests[0].metadata - self.assertEquals(metadata['foobar'], 'bar') + self.assertEqual(metadata['foobar'], 'bar') # check we did not touch the other parts requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['archive'])) - self.assertEquals(len(requests), 1) + self.assertEqual(len(requests), 1) - @istest - def add_archive_to_deposit_is_possible(self): + def test_add_archive_to_deposit_is_possible(self): """Add another archive to a deposit return a 201 response """ # given deposit_id = self.create_simple_binary_deposit(status_partial=True) deposit = Deposit.objects.get(pk=deposit_id) requests = DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['archive']) assert len(list(requests)) == 1 assert self.archive['name'] in requests[0].archive.name requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['metadata'])) assert len(requests) == 0 update_uri = reverse(EM_IRI, args=[self.collection.name, deposit_id]) external_id = 'some-external-id-1' response = self.client.post( update_uri, content_type='application/zip', # as zip data=self.archive2['data'], # + headers CONTENT_LENGTH=self.archive2['length'], HTTP_SLUG=external_id, HTTP_CONTENT_MD5=self.archive2['md5sum'], HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_IN_PROGRESS='false', HTTP_CONTENT_DISPOSITION='attachment; filename=%s' % ( self.archive2['name'],)) self.assertEqual(response.status_code, status.HTTP_201_CREATED) requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['archive']).order_by('id')) - self.assertEquals(len(requests), 2) + self.assertEqual(len(requests), 2) # first archive still exists self.assertRegex(requests[0].archive.name, self.archive['name']) # a new one was added self.assertRegex(requests[1].archive.name, self.archive2['name']) # check we did not touch the other parts requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['metadata'])) - self.assertEquals(len(requests), 0) + self.assertEqual(len(requests), 0) - @istest - def add_metadata_to_deposit_is_possible(self): + def test_add_metadata_to_deposit_is_possible(self): """Add metadata with another one should return a 204 response """ # given deposit_id = self.create_deposit_partial() deposit = Deposit.objects.get(pk=deposit_id) requests = DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['metadata']) assert len(list(requests)) == 2 requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['archive'])) assert len(requests) == 0 update_uri = reverse(EDIT_SE_IRI, args=[self.collection.name, deposit_id]) response = self.client.post( update_uri, content_type='application/atom+xml;type=entry', data=self.atom_entry_data1) self.assertEqual(response.status_code, status.HTTP_201_CREATED) requests = DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['metadata']).order_by('id') - self.assertEquals(len(list(requests)), 3) + self.assertEqual(len(list(requests)), 3) # a new one was added - self.assertEquals(requests[1].metadata['foobar'], 'bar') + self.assertEqual(requests[1].metadata['foobar'], 'bar') # check we did not touch the other parts requests = list(DepositRequest.objects.filter( deposit=deposit, type=self.deposit_request_types['archive'])) - self.assertEquals(len(requests), 0) + self.assertEqual(len(requests), 0) class DepositUpdateFailuresTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine): """Failure scenario about add/replace (post/put) query on deposit. """ - @istest - def add_metadata_to_unknown_collection(self): + def test_add_metadata_to_unknown_collection(self): """Replacing metadata to unknown deposit should return a 404 response """ url = reverse(EDIT_SE_IRI, args=['test', 1000]) response = self.client.post( url, content_type='application/atom+xml;type=entry', data=self.atom_entry_data0) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertRegex(response.content.decode('utf-8'), 'Unknown collection name test') - @istest - def add_metadata_to_unknown_deposit(self): + def test_add_metadata_to_unknown_deposit(self): """Replacing metadata to unknown deposit should return a 404 response """ url = reverse(EDIT_SE_IRI, args=[self.collection.name, 999]) response = self.client.post( url, content_type='application/atom+xml;type=entry', data=self.atom_entry_data0) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertRegex(response.content.decode('utf-8'), 'Deposit with id 999 does not exist') - @istest - def replace_metadata_to_unknown_deposit(self): + def test_replace_metadata_to_unknown_deposit(self): """Adding metadata to unknown deposit should return a 404 response """ url = reverse(EDIT_SE_IRI, args=[self.collection.name, 998]) response = self.client.put( url, content_type='application/atom+xml;type=entry', data=self.atom_entry_data0) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertRegex(response.content.decode('utf-8'), 'Deposit with id 998 does not exist') - @istest - def add_archive_to_unknown_deposit(self): + def test_add_archive_to_unknown_deposit(self): """Adding metadata to unknown deposit should return a 404 response """ url = reverse(EM_IRI, args=[self.collection.name, 997]) response = self.client.post( url, content_type='application/zip', data=self.atom_entry_data0) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertRegex(response.content.decode('utf-8'), 'Deposit with id 997 does not exist') - @istest - def replace_archive_to_unknown_deposit(self): + def test_replace_archive_to_unknown_deposit(self): """Replacing archive to unknown deposit should return a 404 response """ url = reverse(EM_IRI, args=[self.collection.name, 996]) response = self.client.put( url, content_type='application/zip', data=self.atom_entry_data0) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertRegex(response.content.decode('utf-8'), 'Deposit with id 996 does not exist') - @istest - def post_metadata_to_em_iri_failure(self): + def test_post_metadata_to_em_iri_failure(self): """Update (POST) archive with wrong content type should return 400 """ deposit_id = self.create_deposit_partial() # only update on partial update_uri = reverse(EM_IRI, args=[self.collection.name, deposit_id]) response = self.client.post( update_uri, content_type='application/x-gtar-compressed', data=self.atom_entry_data0) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertRegex(response.content.decode('utf-8'), 'Packaging format supported is restricted to ' 'application/zip, application/x-tar') - @istest - def put_metadata_to_em_iri_failure(self): + def test_put_metadata_to_em_iri_failure(self): """Update (PUT) archive with wrong content type should return 400 """ # given deposit_id = self.create_deposit_partial() # only update on partial # when update_uri = reverse(EM_IRI, args=[self.collection.name, deposit_id]) response = self.client.put( update_uri, content_type='application/atom+xml;type=entry', data=self.atom_entry_data0) # then self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertRegex(response.content.decode('utf-8'), 'Packaging format supported is restricted to ' 'application/zip, application/x-tar') diff --git a/swh/deposit/tests/api/test_deposit_update_status.py b/swh/deposit/tests/api/test_deposit_update_status.py index 23f35052..1ec4dbdb 100644 --- a/swh/deposit/tests/api/test_deposit_update_status.py +++ b/swh/deposit/tests/api/test_deposit_update_status.py @@ -1,136 +1,130 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import json from django.core.urlresolvers import reverse -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.models import Deposit, DEPOSIT_STATUS_DETAIL from swh.deposit.config import PRIVATE_PUT_DEPOSIT, DEPOSIT_STATUS_VERIFIED from swh.deposit.config import DEPOSIT_STATUS_LOAD_SUCCESS from ..common import BasicTestCase class UpdateDepositStatusTest(APITestCase, BasicTestCase): """Update the deposit's status scenario """ def setUp(self): super().setUp() deposit = Deposit(status=DEPOSIT_STATUS_VERIFIED, collection=self.collection, client=self.user) deposit.save() self.deposit = Deposit.objects.get(pk=deposit.id) assert self.deposit.status == DEPOSIT_STATUS_VERIFIED - @istest - def update_deposit_status(self): + def test_update_deposit_status(self): """Existing status for update should return a 204 response """ url = reverse(PRIVATE_PUT_DEPOSIT, args=[self.collection.name, self.deposit.id]) possible_status = set(DEPOSIT_STATUS_DETAIL.keys()) - set( [DEPOSIT_STATUS_LOAD_SUCCESS]) for _status in possible_status: response = self.client.put( url, content_type='application/json', data=json.dumps({'status': _status})) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) deposit = Deposit.objects.get(pk=self.deposit.id) - self.assertEquals(deposit.status, _status) + self.assertEqual(deposit.status, _status) - @istest - def update_deposit_status_with_info(self): + def test_update_deposit_status_with_info(self): """Existing status for update with info should return a 204 response """ url = reverse(PRIVATE_PUT_DEPOSIT, args=[self.collection.name, self.deposit.id]) expected_status = DEPOSIT_STATUS_LOAD_SUCCESS origin_url = 'something' directory_id = '42a13fc721c8716ff695d0d62fc851d641f3a12b' revision_id = '47dc6b4636c7f6cba0df83e3d5490bf4334d987e' expected_swh_id = 'swh:1:dir:%s' % directory_id expected_swh_id_context = 'swh:1:dir:%s;origin=%s' % ( directory_id, origin_url) expected_swh_anchor_id = 'swh:1:rev:%s' % revision_id expected_swh_anchor_id_context = 'swh:1:rev:%s;origin=%s' % ( revision_id, origin_url) response = self.client.put( url, content_type='application/json', data=json.dumps({ 'status': expected_status, 'revision_id': revision_id, 'directory_id': directory_id, 'origin_url': origin_url, })) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) deposit = Deposit.objects.get(pk=self.deposit.id) - self.assertEquals(deposit.status, expected_status) - self.assertEquals(deposit.swh_id, expected_swh_id) - self.assertEquals(deposit.swh_id_context, expected_swh_id_context) - self.assertEquals(deposit.swh_anchor_id, expected_swh_anchor_id) - self.assertEquals(deposit.swh_anchor_id_context, - expected_swh_anchor_id_context) - - @istest - def update_deposit_status_will_fail_with_unknown_status(self): + self.assertEqual(deposit.status, expected_status) + self.assertEqual(deposit.swh_id, expected_swh_id) + self.assertEqual(deposit.swh_id_context, expected_swh_id_context) + self.assertEqual(deposit.swh_anchor_id, expected_swh_anchor_id) + self.assertEqual(deposit.swh_anchor_id_context, + expected_swh_anchor_id_context) + + def test_update_deposit_status_will_fail_with_unknown_status(self): """Unknown status for update should return a 400 response """ url = reverse(PRIVATE_PUT_DEPOSIT, args=[self.collection.name, self.deposit.id]) response = self.client.put( url, content_type='application/json', data=json.dumps({'status': 'unknown'})) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) - @istest - def update_deposit_status_will_fail_with_no_status_key(self): + def test_update_deposit_status_will_fail_with_no_status_key(self): """No status provided for update should return a 400 response """ url = reverse(PRIVATE_PUT_DEPOSIT, args=[self.collection.name, self.deposit.id]) response = self.client.put( url, content_type='application/json', data=json.dumps({'something': 'something'})) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) - @istest - def update_deposit_status_success_without_swh_id_fail(self): + def test_update_deposit_status_success_without_swh_id_fail(self): """Providing successful status without swh_id should return a 400 """ url = reverse(PRIVATE_PUT_DEPOSIT, args=[self.collection.name, self.deposit.id]) response = self.client.put( url, content_type='application/json', data=json.dumps({'status': DEPOSIT_STATUS_LOAD_SUCCESS})) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) diff --git a/swh/deposit/tests/api/test_parser.py b/swh/deposit/tests/api/test_parser.py index d874867f..8e9cc917 100644 --- a/swh/deposit/tests/api/test_parser.py +++ b/swh/deposit/tests/api/test_parser.py @@ -1,104 +1,101 @@ # Copyright (C) 2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import io from collections import OrderedDict -from nose.tools import istest from rest_framework.test import APITestCase from swh.deposit.parsers import SWHXMLParser class ParsingTest(APITestCase): """Access to main entry point is ok without authentication """ - @istest - def parsing_without_duplicates(self): + def test_parsing_without_duplicates(self): xml_no_duplicate = io.BytesIO(b''' Awesome Compiler GPL3.0 https://opensource.org/licenses/GPL-3.0 Python3 author1 Inria ocaml http://issuetracker.com ''') actual_result = SWHXMLParser().parse(xml_no_duplicate) expected_dict = OrderedDict( [('@xmlns', 'http://www.w3.org/2005/Atom'), ('@xmlns:codemeta', 'https://doi.org/10.5063/SCHEMA/CODEMETA-2.0'), ('title', 'Awesome Compiler'), ('codemeta:license', OrderedDict([('codemeta:name', 'GPL3.0'), ('codemeta:url', 'https://opensource.org/licenses/GPL-3.0')])), ('codemeta:runtimePlatform', 'Python3'), ('codemeta:author', OrderedDict([('codemeta:name', 'author1'), ('codemeta:affiliation', 'Inria')])), ('codemeta:programmingLanguage', 'ocaml'), ('codemeta:issueTracker', 'http://issuetracker.com')]) self.assertEqual(expected_dict, actual_result) - @istest - def parsing_with_duplicates(self): + def test_parsing_with_duplicates(self): xml_with_duplicates = io.BytesIO(b''' Another Compiler GNU/Linux GPL3.0 https://opensource.org/licenses/GPL-3.0 Un*x author1 Inria author2 Inria ocaml haskell spdx http://spdx.org python3 ''') actual_result = SWHXMLParser().parse(xml_with_duplicates) expected_dict = OrderedDict([ ('@xmlns', 'http://www.w3.org/2005/Atom'), ('@xmlns:codemeta', 'https://doi.org/10.5063/SCHEMA/CODEMETA-2.0'), ('title', 'Another Compiler'), ('codemeta:runtimePlatform', ['GNU/Linux', 'Un*x']), ('codemeta:license', [OrderedDict([('codemeta:name', 'GPL3.0'), ('codemeta:url', 'https://opensource.org/licenses/GPL-3.0')]), OrderedDict([('codemeta:name', 'spdx'), ('codemeta:url', 'http://spdx.org')])]), ('codemeta:author', [OrderedDict([('codemeta:name', 'author1'), ('codemeta:affiliation', 'Inria')]), OrderedDict([('codemeta:name', 'author2'), ('codemeta:affiliation', 'Inria')])]), ('codemeta:programmingLanguage', ['ocaml', 'haskell', 'python3'])]) self.assertEqual(expected_dict, actual_result) diff --git a/swh/deposit/tests/api/test_service_document.py b/swh/deposit/tests/api/test_service_document.py index f61f86dd..3afa1ca5 100644 --- a/swh/deposit/tests/api/test_service_document.py +++ b/swh/deposit/tests/api/test_service_document.py @@ -1,107 +1,102 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.core.urlresolvers import reverse -from nose.tools import istest from rest_framework import status from rest_framework.test import APITestCase from swh.deposit.tests import TEST_CONFIG from swh.deposit.config import SD_IRI from ..common import BasicTestCase, WithAuthTestCase class ServiceDocumentNoAuthCase(APITestCase, BasicTestCase): """Service document endpoints are protected with basic authentication. """ - @istest - def service_document_no_authentication_fails(self): + def test_service_document_no_authentication_fails(self): """Without authentication, service document endpoint should return 401 """ url = reverse(SD_IRI) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) - @istest - def service_document_with_http_accept_should_not_break(self): + def test_service_document_with_http_accept_should_not_break(self): """Without auth, sd endpoint through browser should return 401 """ url = reverse(SD_IRI) # when response = self.client.get( url, HTTP_ACCEPT='text/html,application/xml;q=9,*/*,q=8') self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) class ServiceDocumentCase(APITestCase, WithAuthTestCase, BasicTestCase): def assertResponseOk(self, response): # noqa: N802 self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEquals(response.content.decode('utf-8'), + self.assertEqual(response.content.decode('utf-8'), ''' 2.0 %s The Software Heritage (SWH) Archive %s Software Collection application/zip application/x-tar Collection Policy Software Heritage Archive Collect, Preserve, Share false false http://purl.org/net/sword/package/SimpleZip http://testserver/1/%s/ %s ''' % (TEST_CONFIG['max_upload_size'], self.username, self.username, self.username, self.username)) # noqa - @istest - def service_document(self): + def test_service_document(self): """With authentication, service document list user's collection """ url = reverse(SD_IRI) # when response = self.client.get(url) # then self.assertResponseOk(response) - @istest - def service_document_with_http_accept_header(self): + def test_service_document_with_http_accept_header(self): """With authentication, with browser, sd list user's collection """ url = reverse(SD_IRI) # when response = self.client.get( url, HTTP_ACCEPT='text/html,application/xml;q=9,*/*,q=8') self.assertResponseOk(response) diff --git a/swh/deposit/tests/common.py b/swh/deposit/tests/common.py index c2799717..d7d9de20 100644 --- a/swh/deposit/tests/common.py +++ b/swh/deposit/tests/common.py @@ -1,573 +1,573 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import base64 import hashlib import os import shutil import tarfile import tempfile from django.core.urlresolvers import reverse from django.test import TestCase from io import BytesIO -from nose.plugins.attrib import attr +import pytest from rest_framework import status from swh.deposit.config import (COL_IRI, EM_IRI, EDIT_SE_IRI, DEPOSIT_STATUS_PARTIAL, DEPOSIT_STATUS_VERIFIED, DEPOSIT_STATUS_REJECTED, DEPOSIT_STATUS_DEPOSITED) from swh.deposit.models import DepositClient, DepositCollection, Deposit from swh.deposit.models import DepositRequest from swh.deposit.models import DepositRequestType from swh.deposit.parsers import parse_xml from swh.deposit.settings.testing import MEDIA_ROOT from swh.core import tarball def compute_info(archive_path): """Given a path, compute information on path. """ with open(archive_path, 'rb') as f: length = 0 sha1sum = hashlib.sha1() md5sum = hashlib.md5() data = b'' for chunk in f: sha1sum.update(chunk) md5sum.update(chunk) length += len(chunk) data += chunk return { 'dir': os.path.dirname(archive_path), 'name': os.path.basename(archive_path), 'path': archive_path, 'length': length, 'sha1sum': sha1sum.hexdigest(), 'md5sum': md5sum.hexdigest(), 'data': data } def _compress(path, extension, dir_path): """Compress path according to extension """ if extension == 'zip' or extension == 'tar': return tarball.compress(path, extension, dir_path) elif '.' in extension: split_ext = extension.split('.') if split_ext[0] != 'tar': raise ValueError( 'Development error, only zip or tar archive supported, ' '%s not supported' % extension) # deal with specific tar mode = split_ext[1] supported_mode = ['xz', 'gz', 'bz2'] if mode not in supported_mode: raise ValueError( 'Development error, only %s supported, %s not supported' % ( supported_mode, mode)) files = tarball._ls(dir_path) with tarfile.open(path, 'w:%s' % mode) as t: for fpath, fname in files: t.add(fpath, arcname=fname, recursive=False) return path def create_arborescence_archive(root_path, archive_name, filename, content, up_to_size=None, extension='zip'): """Build an archive named archive_name in the root_path. This archive contains one file named filename with the content content. Args: root_path (str): Location path of the archive to create archive_name (str): Archive's name (without extension) filename (str): Archive's content is only one filename content (bytes): Content of the filename up_to_size (int | None): Fill in the blanks size to oversize or complete an archive's size extension (str): Extension of the archive to write (default is zip) Returns: dict with the keys: - dir: the directory of that archive - path: full path to the archive - sha1sum: archive's sha1sum - length: archive's length """ os.makedirs(root_path, exist_ok=True) archive_path_dir = tempfile.mkdtemp(dir=root_path) dir_path = os.path.join(archive_path_dir, archive_name) os.mkdir(dir_path) filepath = os.path.join(dir_path, filename) _length = len(content) count = 0 batch_size = 128 with open(filepath, 'wb') as f: f.write(content) if up_to_size: # fill with blank content up to a given size count += _length while count < up_to_size: f.write(b'0'*batch_size) count += batch_size _path = '%s.%s' % (dir_path, extension) _path = _compress(_path, extension, dir_path) return compute_info(_path) def create_archive_with_archive(root_path, name, archive): """Create an archive holding another. """ invalid_archive_path = os.path.join(root_path, name) with tarfile.open(invalid_archive_path, 'w:gz') as _archive: _archive.add(archive['path'], arcname=archive['name']) return compute_info(invalid_archive_path) -@attr('fs') +@pytest.mark.fs class FileSystemCreationRoutine(TestCase): """Mixin intended for tests needed to tamper with archives. """ def setUp(self): """Define the test client and other test variables.""" super().setUp() self.root_path = '/tmp/swh-deposit/test/build-zip/' os.makedirs(self.root_path, exist_ok=True) self.archive = create_arborescence_archive( self.root_path, 'archive1', 'file1', b'some content in file') self.atom_entry = b""" Awesome Compiler urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 1785io25c695 2017-10-07T15:17:08Z some awesome author https://hal-test.archives-ouvertes.fr """ def tearDown(self): super().tearDown() shutil.rmtree(self.root_path) def create_simple_binary_deposit(self, status_partial=True): response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/zip', data=self.archive['data'], CONTENT_LENGTH=self.archive['length'], HTTP_MD5SUM=self.archive['md5sum'], HTTP_SLUG='external-id', HTTP_IN_PROGRESS=status_partial, HTTP_CONTENT_DISPOSITION='attachment; filename=%s' % ( self.archive['name'], )) # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) _status = response_content['deposit_status'] if status_partial: expected_status = DEPOSIT_STATUS_PARTIAL else: expected_status = DEPOSIT_STATUS_VERIFIED self.assertEqual(_status, expected_status) deposit_id = int(response_content['deposit_id']) return deposit_id def create_complex_binary_deposit(self, status_partial=False): deposit_id = self.create_simple_binary_deposit( status_partial=True) # Add a second archive to the deposit # update its status to DEPOSIT_STATUS_VERIFIED response = self.client.post( reverse(EM_IRI, args=[self.collection.name, deposit_id]), content_type='application/zip', data=self.archive2['data'], CONTENT_LENGTH=self.archive2['length'], HTTP_MD5SUM=self.archive2['md5sum'], HTTP_SLUG='external-id', HTTP_IN_PROGRESS=status_partial, HTTP_CONTENT_DISPOSITION='attachment; filename=filename1.zip') # then assert response.status_code == status.HTTP_201_CREATED response_content = parse_xml(BytesIO(response.content)) deposit_id = int(response_content['deposit_id']) return deposit_id def create_deposit_archive_with_archive(self, archive_extension): # we create the holding archive to a given extension archive = create_arborescence_archive( self.root_path, 'archive1', 'file1', b'some content in file', extension=archive_extension) # now we create an archive holding the first created archive invalid_archive = create_archive_with_archive( self.root_path, 'invalid.tar.gz', archive) # we deposit it response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/x-tar', data=invalid_archive['data'], CONTENT_LENGTH=invalid_archive['length'], HTTP_MD5SUM=invalid_archive['md5sum'], HTTP_SLUG='external-id', HTTP_IN_PROGRESS=False, HTTP_CONTENT_DISPOSITION='attachment; filename=%s' % ( invalid_archive['name'], )) # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) _status = response_content['deposit_status'] self.assertEqual(_status, DEPOSIT_STATUS_DEPOSITED) deposit_id = int(response_content['deposit_id']) return deposit_id def update_binary_deposit(self, deposit_id, status_partial=False): # update existing deposit with atom entry metadata response = self.client.post( reverse(EDIT_SE_IRI, args=[self.collection.name, deposit_id]), content_type='application/atom+xml;type=entry', data=self.codemeta_entry_data1, HTTP_SLUG='external-id', HTTP_IN_PROGRESS=status_partial) # then self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_content = parse_xml(BytesIO(response.content)) _status = response_content['deposit_status'] if status_partial: expected_status = DEPOSIT_STATUS_PARTIAL else: expected_status = DEPOSIT_STATUS_DEPOSITED self.assertEqual(_status, expected_status) deposit_id = int(response_content['deposit_id']) return deposit_id -@attr('fs') +@pytest.mark.fs class BasicTestCase(TestCase): """Mixin intended for data setup purposes (user, collection, etc...) """ def setUp(self): """Define the test client and other test variables.""" super().setUp() # expanding diffs in tests self.maxDiff = None # basic minimum test data deposit_request_types = {} # Add deposit request types for deposit_request_type in ['archive', 'metadata']: drt = DepositRequestType(name=deposit_request_type) drt.save() deposit_request_types[deposit_request_type] = drt _name = 'hal' _provider_url = 'https://hal-test.archives-ouvertes.fr/' _domain = 'archives-ouvertes.fr/' # set collection up _collection = DepositCollection(name=_name) _collection.save() # set user/client up _client = DepositClient.objects.create_user(username=_name, password=_name, provider_url=_provider_url, domain=_domain) _client.collections = [_collection.id] _client.last_name = _name _client.save() self.collection = _collection self.user = _client self.username = _name self.userpass = _name self.deposit_request_types = deposit_request_types def tearDown(self): super().tearDown() # Clean up uploaded files in temporary directory (tests have # their own media root folder) if os.path.exists(MEDIA_ROOT): for d in os.listdir(MEDIA_ROOT): shutil.rmtree(os.path.join(MEDIA_ROOT, d)) class WithAuthTestCase(TestCase): """Mixin intended for testing the api with basic authentication. """ def setUp(self): super().setUp() _token = '%s:%s' % (self.username, self.userpass) token = base64.b64encode(_token.encode('utf-8')) authorization = 'Basic %s' % token.decode('utf-8') self.client.credentials(HTTP_AUTHORIZATION=authorization) def tearDown(self): super().tearDown() self.client.credentials() class CommonCreationRoutine(TestCase): """Mixin class to share initialization routine. cf: `class`:test_deposit_update.DepositReplaceExistingDataTest `class`:test_deposit_update.DepositUpdateDepositWithNewDataTest `class`:test_deposit_update.DepositUpdateFailuresTest `class`:test_deposit_delete.DepositDeleteTest """ def setUp(self): super().setUp() self.atom_entry_data0 = b""" some-external-id https://hal-test.archives-ouvertes.fr/some-external-id some awesome author """ self.atom_entry_data1 = b""" another one no one """ self.atom_entry_data2 = b""" Awesome Compiler urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 1785io25c695 2017-10-07T15:17:08Z some awesome author https://hal-test.archives-ouvertes.fr/id """ self.codemeta_entry_data0 = b""" Awesome Compiler https://hal-test.archives-ouvertes.fr/1785io25c695 urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 1785io25c695 2017-10-07T15:17:08Z some awesome author description key-word 1 """ self.codemeta_entry_data1 = b""" Composing a Web of Audio Applications hal hal-01243065 hal-01243065 https://hal-test.archives-ouvertes.fr/hal-01243065 test DSP programming,Web 2017-05-03T16:08:47+02:00 this is the description 1 phpstorm stable php python C GNU General Public License v3.0 only CeCILL Free Software License Agreement v1.1 HAL hal@ccsd.cnrs.fr Morane Gruenpeter """ def create_deposit_with_invalid_archive(self, external_id='some-external-id-1'): url = reverse(COL_IRI, args=[self.collection.name]) data = b'some data which is clearly not a zip file' md5sum = hashlib.md5(data).hexdigest() # when response = self.client.post( url, content_type='application/zip', # as zip data=data, # + headers CONTENT_LENGTH=len(data), # other headers needs HTTP_ prefix to be taken into account HTTP_SLUG=external_id, HTTP_CONTENT_MD5=md5sum, HTTP_PACKAGING='http://purl.org/net/sword/package/SimpleZip', HTTP_CONTENT_DISPOSITION='attachment; filename=filename0') response_content = parse_xml(BytesIO(response.content)) deposit_id = int(response_content['deposit_id']) return deposit_id def create_deposit_with_status( self, status, external_id='some-external-id-1', swh_id=None, swh_id_context=None, swh_anchor_id=None, swh_anchor_id_context=None, status_detail=None): # create an invalid deposit which we will update further down the line deposit_id = self.create_deposit_with_invalid_archive(external_id) # We cannot create some form of deposit with a given status in # test context ('rejected' for example). Update in place the # deposit with such status to permit some further tests. deposit = Deposit.objects.get(pk=deposit_id) if status == DEPOSIT_STATUS_REJECTED: deposit.status_detail = status_detail deposit.status = status if swh_id: deposit.swh_id = swh_id if swh_id_context: deposit.swh_id_context = swh_id_context if swh_anchor_id: deposit.swh_anchor_id = swh_anchor_id if swh_anchor_id_context: deposit.swh_anchor_id_context = swh_anchor_id_context deposit.save() return deposit_id def create_simple_deposit_partial(self, external_id='some-external-id'): """Create a simple deposit (1 request) in `partial` state and returns its new identifier. Returns: deposit id """ response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/atom+xml;type=entry', data=self.atom_entry_data0, HTTP_SLUG=external_id, HTTP_IN_PROGRESS='true') assert response.status_code == status.HTTP_201_CREATED response_content = parse_xml(BytesIO(response.content)) deposit_id = int(response_content['deposit_id']) return deposit_id def create_deposit_partial_with_data_in_args(self, data): """Create a simple deposit (1 request) in `partial` state with the data or metadata as an argument and returns its new identifier. Args: data: atom entry Returns: deposit id """ response = self.client.post( reverse(COL_IRI, args=[self.collection.name]), content_type='application/atom+xml;type=entry', data=data, HTTP_SLUG='external-id', HTTP_IN_PROGRESS='true') assert response.status_code == status.HTTP_201_CREATED response_content = parse_xml(BytesIO(response.content)) deposit_id = int(response_content['deposit_id']) return deposit_id def _update_deposit_with_status(self, deposit_id, status_partial=False): """Add to a given deposit another archive and update its current status to `deposited` (by default). Returns: deposit id """ # when response = self.client.post( reverse(EDIT_SE_IRI, args=[self.collection.name, deposit_id]), content_type='application/atom+xml;type=entry', data=self.atom_entry_data1, HTTP_SLUG='external-id', HTTP_IN_PROGRESS=status_partial) # then assert response.status_code == status.HTTP_201_CREATED return deposit_id def create_deposit_ready(self, external_id='some-external-id'): """Create a complex deposit (2 requests) in status `deposited`. """ deposit_id = self.create_simple_deposit_partial( external_id=external_id) deposit_id = self._update_deposit_with_status(deposit_id) return deposit_id def create_deposit_partial(self, external_id='some-external-id'): """Create a complex deposit (2 requests) in status `partial`. """ deposit_id = self.create_simple_deposit_partial( external_id=external_id) deposit_id = self._update_deposit_with_status( deposit_id, status_partial=True) return deposit_id def add_metadata_to_deposit(self, deposit_id, status_partial=False): """Add metadata to deposit. """ # when response = self.client.post( reverse(EDIT_SE_IRI, args=[self.collection.name, deposit_id]), content_type='application/atom+xml;type=entry', data=self.codemeta_entry_data1, HTTP_SLUG='external-id', HTTP_IN_PROGRESS=status_partial) assert response.status_code == status.HTTP_201_CREATED # then deposit = Deposit.objects.get(pk=deposit_id) assert deposit is not None deposit_requests = DepositRequest.objects.filter(deposit=deposit) assert deposit_requests is not [] for dr in deposit_requests: if dr.type.name == 'metadata': assert deposit_requests[0].metadata is not {} return deposit_id diff --git a/swh/deposit/tests/loader/conftest.py b/swh/deposit/tests/loader/conftest.py new file mode 100644 index 00000000..cf035755 --- /dev/null +++ b/swh/deposit/tests/loader/conftest.py @@ -0,0 +1,9 @@ +import pytest +from swh.scheduler.tests.conftest import * # noqa + + +@pytest.fixture(scope='session') +def celery_includes(): + return [ + 'swh.deposit.loader.tasks', + ] diff --git a/swh/deposit/tests/loader/test_checker.py b/swh/deposit/tests/loader/test_checker.py index b48afc92..d1721d64 100644 --- a/swh/deposit/tests/loader/test_checker.py +++ b/swh/deposit/tests/loader/test_checker.py @@ -1,71 +1,68 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information -from nose.tools import istest from rest_framework.test import APITestCase from swh.deposit.models import Deposit from swh.deposit.config import PRIVATE_CHECK_DEPOSIT, DEPOSIT_STATUS_VERIFIED from swh.deposit.config import DEPOSIT_STATUS_REJECTED from swh.deposit.loader.checker import DepositChecker from django.core.urlresolvers import reverse from .common import SWHDepositTestClient, CLIENT_TEST_CONFIG from ..common import BasicTestCase, WithAuthTestCase, CommonCreationRoutine from ..common import FileSystemCreationRoutine class DepositCheckerScenarioTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine, FileSystemCreationRoutine): def setUp(self): super().setUp() # 2. Sets a basic client which accesses the test data checker_client = SWHDepositTestClient(client=self.client, config=CLIENT_TEST_CONFIG) # 3. setup loader with no persistence and that client self.checker = DepositChecker(client=checker_client) - @istest - def check_deposit_ready(self): + def test_check_deposit_ready(self): """Check on a valid 'deposited' deposit should result in 'verified' """ # 1. create a deposit with archive and metadata deposit_id = self.create_simple_binary_deposit() deposit_id = self.update_binary_deposit(deposit_id, status_partial=False) args = [self.collection.name, deposit_id] deposit_check_url = reverse(PRIVATE_CHECK_DEPOSIT, args=args) # when actual_result = self.checker.check(deposit_check_url=deposit_check_url) # then deposit = Deposit.objects.get(pk=deposit_id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_VERIFIED) - self.assertEquals(actual_result, {'status': 'eventful'}) + self.assertEqual(deposit.status, DEPOSIT_STATUS_VERIFIED) + self.assertEqual(actual_result, {'status': 'eventful'}) - @istest - def check_deposit_rejected(self): + def test_check_deposit_rejected(self): """Check on invalid 'deposited' deposit should result in 'rejected' """ # 1. create a deposit with archive and metadata deposit_id = self.create_deposit_with_invalid_archive() args = [self.collection.name, deposit_id] deposit_check_url = reverse(PRIVATE_CHECK_DEPOSIT, args=args) # when actual_result = self.checker.check(deposit_check_url=deposit_check_url) # then deposit = Deposit.objects.get(pk=deposit_id) - self.assertEquals(deposit.status, DEPOSIT_STATUS_REJECTED) - self.assertEquals(actual_result, {'status': 'eventful'}) + self.assertEqual(deposit.status, DEPOSIT_STATUS_REJECTED) + self.assertEqual(actual_result, {'status': 'eventful'}) diff --git a/swh/deposit/tests/loader/test_client.py b/swh/deposit/tests/loader/test_client.py index 55b857d9..8d19497e 100644 --- a/swh/deposit/tests/loader/test_client.py +++ b/swh/deposit/tests/loader/test_client.py @@ -1,268 +1,258 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import os import shutil import tempfile import unittest -from nose.plugins.attrib import attr -from nose.tools import istest +import pytest from swh.deposit.client import PrivateApiDepositClient from swh.deposit.config import DEPOSIT_STATUS_LOAD_SUCCESS from swh.deposit.config import DEPOSIT_STATUS_LOAD_FAILURE from .common import CLIENT_TEST_CONFIG class StreamedResponse: """Streamed response facsimile """ def __init__(self, ok, stream): self.ok = ok self.stream = stream def iter_content(self): yield from self.stream class FakeRequestClientGet: """Fake request client dedicated to get method calls. """ def __init__(self, response): self.response = response def get(self, *args, **kwargs): self.args = args self.kwargs = kwargs return self.response -@attr('fs') +@pytest.mark.fs class PrivateApiDepositClientReadArchiveTest(unittest.TestCase): def setUp(self): super().setUp() self.temporary_directory = tempfile.mkdtemp(dir='/tmp') def tearDown(self): super().setUp() shutil.rmtree(self.temporary_directory) - @istest - def archive_get(self): + def test_archive_get(self): """Reading archive should write data in temporary directory """ stream_content = [b"some", b"streamed", b"response"] response = StreamedResponse( ok=True, stream=(s for s in stream_content)) _client = FakeRequestClientGet(response) deposit_client = PrivateApiDepositClient(config=CLIENT_TEST_CONFIG, _client=_client) archive_path = os.path.join(self.temporary_directory, 'test.archive') archive_path = deposit_client.archive_get('/some/url', archive_path) self.assertTrue(os.path.exists(archive_path)) with open(archive_path, 'rb') as f: actual_content = f.read() - self.assertEquals(actual_content, b''.join(stream_content)) - self.assertEquals(_client.args, ('http://nowhere:9000/some/url', )) - self.assertEquals(_client.kwargs, { + self.assertEqual(actual_content, b''.join(stream_content)) + self.assertEqual(_client.args, ('http://nowhere:9000/some/url', )) + self.assertEqual(_client.kwargs, { 'stream': True }) - @istest - def archive_get_with_authentication(self): + def test_archive_get_with_authentication(self): """Reading archive should write data in temporary directory """ stream_content = [b"some", b"streamed", b"response", b"for", b"auth"] response = StreamedResponse( ok=True, stream=(s for s in stream_content)) _client = FakeRequestClientGet(response) _config = CLIENT_TEST_CONFIG.copy() _config['auth'] = { # add authentication setup 'username': 'user', 'password': 'pass' } deposit_client = PrivateApiDepositClient(_config, _client=_client) archive_path = os.path.join(self.temporary_directory, 'test.archive') archive_path = deposit_client.archive_get('/some/url', archive_path) self.assertTrue(os.path.exists(archive_path)) with open(archive_path, 'rb') as f: actual_content = f.read() - self.assertEquals(actual_content, b''.join(stream_content)) - self.assertEquals(_client.args, ('http://nowhere:9000/some/url', )) - self.assertEquals(_client.kwargs, { + self.assertEqual(actual_content, b''.join(stream_content)) + self.assertEqual(_client.args, ('http://nowhere:9000/some/url', )) + self.assertEqual(_client.kwargs, { 'stream': True, 'auth': ('user', 'pass') }) - @istest - def archive_get_can_fail(self): + def test_archive_get_can_fail(self): """Reading archive can fail for some reasons """ response = StreamedResponse(ok=False, stream=None) _client = FakeRequestClientGet(response) deposit_client = PrivateApiDepositClient(config=CLIENT_TEST_CONFIG, _client=_client) with self.assertRaisesRegex( ValueError, 'Problem when retrieving deposit archive'): deposit_client.archive_get('/some/url', 'some/path') class JsonResponse: """Json response facsimile """ def __init__(self, ok, response): self.ok = ok self.response = response def json(self): return self.response class PrivateApiDepositClientReadMetadataTest(unittest.TestCase): - @istest - def metadata_get(self): + def test_metadata_get(self): """Reading archive should write data in temporary directory """ expected_response = {"some": "dict"} response = JsonResponse( ok=True, response=expected_response) _client = FakeRequestClientGet(response) deposit_client = PrivateApiDepositClient(config=CLIENT_TEST_CONFIG, _client=_client) actual_metadata = deposit_client.metadata_get('/metadata') - self.assertEquals(actual_metadata, expected_response) + self.assertEqual(actual_metadata, expected_response) - @istest - def metadata_get_can_fail(self): + def test_metadata_get_can_fail(self): """Reading metadata can fail for some reasons """ _client = FakeRequestClientGet(JsonResponse(ok=False, response=None)) deposit_client = PrivateApiDepositClient(config=CLIENT_TEST_CONFIG, _client=_client) with self.assertRaisesRegex( ValueError, 'Problem when retrieving metadata at'): deposit_client.metadata_get('/some/metadata/url') class FakeRequestClientPut: """Fake Request client dedicated to put request method calls. """ args = None kwargs = None def put(self, *args, **kwargs): self.args = args self.kwargs = kwargs class PrivateApiDepositClientStatusUpdateTest(unittest.TestCase): - @istest - def status_update(self): + def test_status_update(self): """Update status """ _client = FakeRequestClientPut() deposit_client = PrivateApiDepositClient(config=CLIENT_TEST_CONFIG, _client=_client) deposit_client.status_update('/update/status', DEPOSIT_STATUS_LOAD_SUCCESS, revision_id='some-revision-id') - self.assertEquals(_client.args, - ('http://nowhere:9000/update/status', )) - self.assertEquals(_client.kwargs, { + self.assertEqual(_client.args, + ('http://nowhere:9000/update/status', )) + self.assertEqual(_client.kwargs, { 'json': { 'status': DEPOSIT_STATUS_LOAD_SUCCESS, 'revision_id': 'some-revision-id', } }) - @istest - def status_update_with_no_revision_id(self): + def test_status_update_with_no_revision_id(self): """Reading metadata can fail for some reasons """ _client = FakeRequestClientPut() deposit_client = PrivateApiDepositClient(config=CLIENT_TEST_CONFIG, _client=_client) deposit_client.status_update('/update/status/fail', DEPOSIT_STATUS_LOAD_FAILURE) - self.assertEquals(_client.args, - ('http://nowhere:9000/update/status/fail', )) - self.assertEquals(_client.kwargs, { + self.assertEqual(_client.args, + ('http://nowhere:9000/update/status/fail', )) + self.assertEqual(_client.kwargs, { 'json': { 'status': DEPOSIT_STATUS_LOAD_FAILURE, } }) class PrivateApiDepositClientCheckTest(unittest.TestCase): - @istest - def check(self): + def test_check(self): """When check ok, this should return the deposit's status """ _client = FakeRequestClientGet( JsonResponse(ok=True, response={'status': 'something'})) deposit_client = PrivateApiDepositClient(config=CLIENT_TEST_CONFIG, _client=_client) r = deposit_client.check('/check') - self.assertEquals(_client.args, - ('http://nowhere:9000/check', )) - self.assertEquals(_client.kwargs, {}) - self.assertEquals(r, 'something') + self.assertEqual(_client.args, + ('http://nowhere:9000/check', )) + self.assertEqual(_client.kwargs, {}) + self.assertEqual(r, 'something') - @istest - def check_fails(self): + def test_check_fails(self): """Checking deposit can fail for some reason """ _client = FakeRequestClientGet( JsonResponse(ok=False, response=None)) deposit_client = PrivateApiDepositClient(config=CLIENT_TEST_CONFIG, _client=_client) with self.assertRaisesRegex( ValueError, 'Problem when checking deposit'): deposit_client.check('/check/fails') - self.assertEquals(_client.args, - ('http://nowhere:9000/check/fails', )) - self.assertEquals(_client.kwargs, {}) + self.assertEqual(_client.args, + ('http://nowhere:9000/check/fails', )) + self.assertEqual(_client.kwargs, {}) diff --git a/swh/deposit/tests/loader/test_loader.py b/swh/deposit/tests/loader/test_loader.py index 8b7e646c..e8cea274 100644 --- a/swh/deposit/tests/loader/test_loader.py +++ b/swh/deposit/tests/loader/test_loader.py @@ -1,308 +1,169 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import os import unittest import shutil -from nose.tools import istest -from nose.plugins.attrib import attr +import pytest from rest_framework.test import APITestCase from swh.model import hashutil from swh.deposit.models import Deposit from swh.deposit.loader import loader from swh.deposit.config import ( PRIVATE_GET_RAW_CONTENT, PRIVATE_GET_DEPOSIT_METADATA, PRIVATE_PUT_DEPOSIT ) from django.core.urlresolvers import reverse +from swh.loader.core.tests import BaseLoaderStorageTest from .common import SWHDepositTestClient, CLIENT_TEST_CONFIG from .. import TEST_LOADER_CONFIG from ..common import (BasicTestCase, WithAuthTestCase, CommonCreationRoutine, FileSystemCreationRoutine) -TOOL_ID = 99 -PROVIDER_ID = 12 - - -class DepositLoaderInhibitsStorage: - """Mixin class to inhibit the persistence and keep in memory the data - sent for storage. - - cf. SWHDepositLoaderNoStorage - - """ - def __init__(self, client=None): - # client is not used here, transit it nonetheless to other mixins - super().__init__(client=client) - # typed data - self.state = { - 'origin': [], - 'origin_visit': [], - 'origin_metadata': [], - 'content': [], - 'directory': [], - 'revision': [], - 'release': [], - 'snapshot': [], - 'tool': [], - 'provider': [] - } - - def _add(self, type, l): - """Add without duplicates and keeping the insertion order. - - Args: - type (str): Type of objects concerned by the action - l ([object]): List of 'type' object - - """ - col = self.state[type] - for o in l: - if o in col: - continue - col.extend([o]) - - def send_origin(self, origin): - origin.update({'id': 1}) - self._add('origin', [origin]) - return origin['id'] - - def send_origin_visit(self, origin_id, visit_date): - origin_visit = { - 'origin': origin_id, - 'visit_date': visit_date, - 'visit': 1, - } - self._add('origin_visit', [origin_visit]) - return origin_visit - - def send_origin_metadata(self, origin_id, visit_date, provider_id, tool_id, - metadata): - origin_metadata = { - 'origin_id': origin_id, - 'visit_date': visit_date, - 'provider_id': provider_id, - 'tool_id': tool_id, - 'metadata': metadata - } - self._add('origin_metadata', [origin_metadata]) - return origin_metadata - - def send_tool(self, tool): - tool = { - 'tool_name': tool['tool_name'], - 'tool_version': tool['tool_version'], - 'tool_configuration': tool['tool_configuration'] - } - self._add('tool', [tool]) - tool_id = TOOL_ID - return tool_id - - def send_provider(self, provider): - provider = { - 'provider_name': provider['provider_name'], - 'provider_type': provider['provider_type'], - 'provider_url': provider['provider_url'], - 'metadata': provider['metadata'] - } - self._add('provider', [provider]) - provider_id = PROVIDER_ID - return provider_id - - def maybe_load_contents(self, contents): - self._add('content', contents) - - def maybe_load_directories(self, directories): - self._add('directory', directories) - - def maybe_load_revisions(self, revisions): - self._add('revision', revisions) - - def maybe_load_releases(self, releases): - self._add('release', releases) - - def maybe_load_snapshot(self, snapshot): - self._add('snapshot', [snapshot]) - - def open_fetch_history(self): - pass - - def close_fetch_history_failure(self, fetch_history_id): - pass - - def close_fetch_history_success(self, fetch_history_id): - pass - - def update_origin_visit(self, origin_id, visit, status): - self.status = status - - # Override to do nothing at the end - def close_failure(self): - pass - - def close_success(self): - pass - - class TestLoaderUtils(unittest.TestCase): def assertRevisionsOk(self, expected_revisions): # noqa: N802 """Check the loader's revisions match the expected revisions. Expects self.loader to be instantiated and ready to be inspected (meaning the loading took place). Args: expected_revisions (dict): Dict with key revision id, value the targeted directory id. """ # The last revision being the one used later to start back from for rev in self.loader.state['revision']: rev_id = hashutil.hash_to_hex(rev['id']) directory_id = hashutil.hash_to_hex(rev['directory']) - self.assertEquals(expected_revisions[rev_id], directory_id) - - -class SWHDepositLoaderNoStorage(DepositLoaderInhibitsStorage, - loader.DepositLoader): - """Loader to test. - - It inherits from the actual deposit loader to actually test its - correct behavior. It also inherits from - DepositLoaderInhibitsStorage so that no persistence takes place. - - """ - pass + self.assertEqual(expected_revisions[rev_id], directory_id) -@attr('fs') +@pytest.mark.fs class DepositLoaderScenarioTest(APITestCase, WithAuthTestCase, BasicTestCase, CommonCreationRoutine, - FileSystemCreationRoutine, TestLoaderUtils): + FileSystemCreationRoutine, TestLoaderUtils, + BaseLoaderStorageTest): def setUp(self): super().setUp() # create the extraction dir used by the loader os.makedirs(TEST_LOADER_CONFIG['extraction_dir'], exist_ok=True) # 1. create a deposit with archive and metadata self.deposit_id = self.create_simple_binary_deposit() # 2. Sets a basic client which accesses the test data loader_client = SWHDepositTestClient(self.client, config=CLIENT_TEST_CONFIG) - # 3. setup loader with no persistence and that client - self.loader = SWHDepositLoaderNoStorage(client=loader_client) + # 3. setup loader with that client + self.loader = loader.DepositLoader(client=loader_client) + + self.storage = self.loader.storage def tearDown(self): super().tearDown() shutil.rmtree(TEST_LOADER_CONFIG['extraction_dir']) - @istest - def inject_deposit_ready(self): + def test_inject_deposit_ready(self): """Load a deposit which is ready """ args = [self.collection.name, self.deposit_id] archive_url = reverse(PRIVATE_GET_RAW_CONTENT, args=args) deposit_meta_url = reverse(PRIVATE_GET_DEPOSIT_METADATA, args=args) deposit_update_url = reverse(PRIVATE_PUT_DEPOSIT, args=args) # when - self.loader.load(archive_url=archive_url, - deposit_meta_url=deposit_meta_url, - deposit_update_url=deposit_update_url) + res = self.loader.load(archive_url=archive_url, + deposit_meta_url=deposit_meta_url, + deposit_update_url=deposit_update_url) # then - self.assertEquals(len(self.loader.state['content']), 1) - self.assertEquals(len(self.loader.state['directory']), 1) - self.assertEquals(len(self.loader.state['revision']), 1) - self.assertEquals(len(self.loader.state['release']), 0) - self.assertEquals(len(self.loader.state['snapshot']), 1) - - @istest - def inject_deposit_verify_metadata(self): + self.assertEqual(res['status'], 'eventful', res) + self.assertCountContents(1) + self.assertCountDirectories(1) + self.assertCountRevisions(1) + self.assertCountReleases(0) + self.assertCountSnapshots(1) + + def test_inject_deposit_verify_metadata(self): """Load a deposit with metadata, test metadata integrity """ self.deposit_metadata_id = self.add_metadata_to_deposit( self.deposit_id) args = [self.collection.name, self.deposit_metadata_id] archive_url = reverse(PRIVATE_GET_RAW_CONTENT, args=args) deposit_meta_url = reverse(PRIVATE_GET_DEPOSIT_METADATA, args=args) deposit_update_url = reverse(PRIVATE_PUT_DEPOSIT, args=args) # when self.loader.load(archive_url=archive_url, deposit_meta_url=deposit_meta_url, deposit_update_url=deposit_update_url) # then - self.assertEquals(len(self.loader.state['content']), 1) - self.assertEquals(len(self.loader.state['directory']), 1) - self.assertEquals(len(self.loader.state['revision']), 1) - self.assertEquals(len(self.loader.state['release']), 0) - self.assertEquals(len(self.loader.state['snapshot']), 1) - self.assertEquals(len(self.loader.state['origin_metadata']), 1) - self.assertEquals(len(self.loader.state['tool']), 1) - self.assertEquals(len(self.loader.state['provider']), 1) + self.assertCountContents(1) + self.assertCountDirectories(1) + self.assertCountRevisions(1) + self.assertCountReleases(0) + self.assertCountSnapshots(1) codemeta = 'codemeta:' origin_url = 'https://hal-test.archives-ouvertes.fr/hal-01243065' expected_origin_metadata = { '@xmlns': 'http://www.w3.org/2005/Atom', '@xmlns:codemeta': 'https://doi.org/10.5063/SCHEMA/CODEMETA-2.0', 'author': { 'email': 'hal@ccsd.cnrs.fr', 'name': 'HAL' }, codemeta + 'url': origin_url, codemeta + 'runtimePlatform': 'phpstorm', codemeta + 'license': [ { codemeta + 'name': 'GNU General Public License v3.0 only' }, { codemeta + 'name': 'CeCILL Free Software License Agreement v1.1' # noqa } ], codemeta + 'author': { codemeta + 'name': 'Morane Gruenpeter' }, codemeta + 'programmingLanguage': ['php', 'python', 'C'], codemeta + 'applicationCategory': 'test', codemeta + 'dateCreated': '2017-05-03T16:08:47+02:00', codemeta + 'version': '1', 'external_identifier': 'hal-01243065', 'title': 'Composing a Web of Audio Applications', codemeta + 'description': 'this is the description', 'id': 'hal-01243065', 'client': 'hal', codemeta + 'keywords': 'DSP programming,Web', codemeta + 'developmentStatus': 'stable' } - result = self.loader.state['origin_metadata'][0] - self.assertEquals(result['metadata'], expected_origin_metadata) - self.assertEquals(result['tool_id'], TOOL_ID) - self.assertEquals(result['provider_id'], PROVIDER_ID) + self.assertOriginMetadataContains('deposit', origin_url, + expected_origin_metadata) deposit = Deposit.objects.get(pk=self.deposit_id) self.assertRegex(deposit.swh_id, r'^swh:1:dir:.*') - self.assertEquals(deposit.swh_id_context, '%s;origin=%s' % ( + self.assertEqual(deposit.swh_id_context, '%s;origin=%s' % ( deposit.swh_id, origin_url )) self.assertRegex(deposit.swh_anchor_id, r'^swh:1:rev:.*') - self.assertEquals(deposit.swh_anchor_id_context, '%s;origin=%s' % ( + self.assertEqual(deposit.swh_anchor_id_context, '%s;origin=%s' % ( deposit.swh_anchor_id, origin_url )) diff --git a/swh/deposit/tests/loader/test_tasks.py b/swh/deposit/tests/loader/test_tasks.py new file mode 100644 index 00000000..9d69d43a --- /dev/null +++ b/swh/deposit/tests/loader/test_tasks.py @@ -0,0 +1,41 @@ +# Copyright (C) 2018 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +from unittest.mock import patch + + +@patch('swh.deposit.loader.loader.DepositLoader.load') +def test_deposit_load(mock_loader, swh_app, celery_session_worker): + mock_loader.return_value = {'status': 'eventful'} + + res = swh_app.send_task( + 'swh.deposit.loader.tasks.LoadDepositArchiveTsk', + kwargs=dict(archive_url='archive_url', + deposit_meta_url='deposit_meta_url', + deposit_update_url='deposit_update_url')) + assert res + res.wait() + assert res.successful() + + assert res.result == {'status': 'eventful'} + mock_loader.assert_called_once_with( + archive_url='archive_url', + deposit_meta_url='deposit_meta_url', + deposit_update_url='deposit_update_url') + + +@patch('swh.deposit.loader.checker.DepositChecker.check') +def test_check_deposit(mock_checker, swh_app, celery_session_worker): + mock_checker.return_value = {'status': 'uneventful'} + + res = swh_app.send_task( + 'swh.deposit.loader.tasks.ChecksDepositTsk', + args=('check_deposit_url',)) + assert res + res.wait() + assert res.successful() + + assert res.result == {'status': 'uneventful'} + mock_checker.assert_called_once_with('check_deposit_url') diff --git a/swh/deposit/tests/test_utils.py b/swh/deposit/tests/test_utils.py index 1dfe46e6..aa3ecfa7 100644 --- a/swh/deposit/tests/test_utils.py +++ b/swh/deposit/tests/test_utils.py @@ -1,138 +1,132 @@ # Copyright (C) 2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import unittest -from nose.tools import istest from swh.deposit import utils class UtilsTestCase(unittest.TestCase): """Utils library """ - @istest - def merge(self): + def test_merge(self): """Calling utils.merge on dicts should merge without losing information """ d0 = { 'author': 'someone', 'license': [['gpl2']], 'a': 1 } d1 = { 'author': ['author0', {'name': 'author1'}], 'license': [['gpl3']], 'b': { '1': '2' } } d2 = { 'author': map(lambda x: x, ['else']), 'license': 'mit', 'b': { '2': '3', } } d3 = { 'author': (v for v in ['no one']), } actual_merge = utils.merge(d0, d1, d2, d3) expected_merge = { 'a': 1, 'license': [['gpl2'], ['gpl3'], 'mit'], 'author': [ 'someone', 'author0', {'name': 'author1'}, 'else', 'no one'], 'b': { '1': '2', '2': '3', } } - self.assertEquals(actual_merge, expected_merge) + self.assertEqual(actual_merge, expected_merge) - @istest - def merge_2(self): + def test_merge_2(self): d0 = { 'license': 'gpl2', 'runtime': { 'os': 'unix derivative' } } d1 = { 'license': 'gpl3', 'runtime': 'GNU/Linux' } expected = { 'license': ['gpl2', 'gpl3'], 'runtime': [ { 'os': 'unix derivative' }, 'GNU/Linux' ], } actual = utils.merge(d0, d1) self.assertEqual(actual, expected) - @istest - def merge_edge_cases(self): + def test_merge_edge_cases(self): input_dict = { 'license': ['gpl2', 'gpl3'], 'runtime': [ { 'os': 'unix derivative' }, 'GNU/Linux' ], } # against empty dict actual = utils.merge(input_dict, {}) self.assertEqual(actual, input_dict) # against oneself actual = utils.merge(input_dict, input_dict, input_dict) self.assertEqual(input_dict, input_dict) - @istest - def merge_one_dict(self): + def test_merge_one_dict(self): """Merge one dict should result in the same dict value """ input_and_expected = {'anything': 'really'} actual = utils.merge(input_and_expected) self.assertEqual(actual, input_and_expected) - @istest - def merge_raise(self): + def test_merge_raise(self): """Calling utils.merge with any no dict argument should raise """ d0 = { 'author': 'someone', 'a': 1 } d1 = ['not a dict'] with self.assertRaises(ValueError): utils.merge(d0, d1) with self.assertRaises(ValueError): utils.merge(d1, d0) with self.assertRaises(ValueError): utils.merge(d1) - self.assertEquals(utils.merge(d0), d0) + self.assertEqual(utils.merge(d0), d0) diff --git a/swh/deposit/urls.py b/swh/deposit/urls.py index e889fabe..355029b5 100644 --- a/swh/deposit/urls.py +++ b/swh/deposit/urls.py @@ -1,50 +1,30 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information """swhdeposit URL Configuration -The :data:`urlpatterns` list routes URLs to views. For more information please - see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ - -Examples: - -- Function views: - - 1. Add an import: ``from my_app import views`` - 2. Add a URL to urlpatterns: ``url(r'^$', views.home, name='home')`` - -- Class-based views: - - 1. Add an import: ``from other_app.views import Home`` - 2. Add a URL to urlpatterns: ``url(r'^$', Home.as_view(), name='home')`` - -- Including another URLconf: - - 1. Import the include function: ``from django.conf.urls import url, include`` - 2. Add a URL to urlpatterns: ``url(r'^blog/', include('blog.urls'))`` - """ from django.conf.urls import url, include from django.shortcuts import render from django.views.generic.base import RedirectView from rest_framework.urlpatterns import format_suffix_patterns favicon_view = RedirectView.as_view(url='/static/img/icons/swh-logo-32x32.png', permanent=True) def default_view(req): return render(req, "homepage.html") urlpatterns = [ url(r'^favicon\.ico$', favicon_view), url(r'^1/', include('swh.deposit.api.urls')), url(r'^1/private/', include('swh.deposit.api.private.urls')), url(r'^$', default_view, name='home'), ] urlpatterns = format_suffix_patterns(urlpatterns) diff --git a/swh/manage.py b/swh/manage.py index dff61735..5d758e80 100755 --- a/swh/manage.py +++ b/swh/manage.py @@ -1,54 +1,53 @@ #!/usr/bin/env python3 # Copyright (C) 2017 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import os import sys from swh.core import config DEFAULT_CONFIG = { 'port': ('int', 5006), 'host': ('str', '127.0.0.1'), } if __name__ == "__main__": settings_file = 'development' - if sys.argv[1] == 'runserver': # override the default host:port - # for the 'runserver' task - + if sys.argv[1] == 'runserver': + # override the default host:port for the 'runserver' task conf = config.load_named_config('deposit/server', default_conf=DEFAULT_CONFIG) extra_cmd = ['%s:%s' % (conf['host'], conf['port'])] cmd = sys.argv + extra_cmd - elif sys.argv[1] == 'test': # override the default settings file - # to read in testing mode + elif sys.argv[1] == 'test': + # override the default settings file to read in testing mode settings_file = 'testing' cmd = sys.argv else: # otherwise, do nothing cmd = sys.argv os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'swh.deposit.settings.%s' % settings_file) try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django # noqa except ImportError: 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?" ) raise execute_from_command_line(cmd) diff --git a/version.txt b/version.txt index 671d190e..44cef4a7 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -v0.0.63-0-gda91e04 \ No newline at end of file +v0.0.65-0-g3e26744 \ No newline at end of file