atheist-0.20110402/0000755000175000017500000000000011547306062012546 5ustar cletocletoatheist-0.20110402/BUGS0000644000175000017500000000615411523712777013247 0ustar cletocleto- The stdout files should not be created until the begin of test execution -- david@fry:~/repos/public/prj/atheist$ ./athcmd.py -i5 -vveo test/notify_runner.test [DD] Log level is DEBUG [DD] Registered plugins: ['CompositeCondition', 'DebPkgBuild', 'DebPkgInstall', 'DebPkgInstalled', 'DocTest', 'DroidDeviceReady', 'DroidTest', 'Dummy', 'JabberReporter', 'NotifyRunner', 'OpenPort', 'Or', 'SMTP_Reporter', 'TaskFinished', 'TaskRunning', 'TaskTerminator', 'TimeLessThan', 'UnitTask', 'UnitTestCase', 'UntilFailRunner', 'WebTest'] [DD] ./test/notify_runner.test loading [II] Test case ./test/notify_runner.test ------------------------------------------------------ [II] T1: [II] T1: Pre: <[ OK ]Not (FileExists '/tmp/hello.test'> [II] T1: starts (pid: 10134) [DD] T1: finish with 0 [II] T1: Post: <[ OK ]FileExists '/tmp/hello.test'> [II] T2: [DD] T2: detaching [II] T3: > /tmp/hello.test; sync')> [II] T2: Pre: <[ OK ]Not (FileExists '/tmp/atheist/T2_10131.err'> [II] T2: starts (pid: 10136) T2:err| [ OK ] TaskCase: /tmp/hello.test Traceback (most recent call last): File "./athcmd.py", line 85, in sys.exit(main(sys.argv)) File "./athcmd.py", line 67, in main runner.run() File "/home/david/repos/public/prj/atheist/atheist/__init__.py", line 1526, in run self.mng.run(self.pb.inc) File "/home/david/repos/public/prj/atheist/atheist/manager.py", line 297, in run cases[0].run(ob) File "/home/david/repos/public/prj/atheist/atheist/__init__.py", line 1398, in run end_callback=ob) File "/home/david/repos/public/prj/atheist/atheist/__init__.py", line 1266, in run_task task.setup() File "/home/david/repos/public/prj/atheist/atheist/__init__.py", line 856, in setup c.before(self, self.pre, i) File "/home/david/repos/public/prj/atheist/atheist/__init__.py", line 461, in before condlist[pos:pos] = [FileExists(self.fname)] MemoryError -- $ ./athcmd.py -w0 test Traceback (most recent call last):-------------------- ] 62/216 ( 28%) 13s File "/home/david/repos/public/prj/atheist/test/unit/FileContains.test", line 32, in test_insert_FileExists c.before(task, task.post, 0) File "/home/david/repos/public/prj/atheist/atheist/__init__.py", line 554, in before if exists in condlist or exists in newconds: TypeError: argument of type 'int' is not iterable Traceback (most recent call last):-------------------- ] 70/216 ( 32%) 13s File "/home/david/repos/public/prj/atheist/test/unit/keywords.test", line 55, in test_stderr_implies_save_stderr test = atheist.Test(self.mng, 'echo', stderr='hola') File "/home/david/repos/public/prj/atheist/atheist/pyarco/Type.py", line 221, in __call__ return self.func(*args, **kwargs) File "/home/david/repos/public/prj/atheist/atheist/__init__.py", line 1162, in __init__ Task.__init__(self, mng, **kargs) File "/home/david/repos/public/prj/atheist/atheist/__init__.py", line 889, in __init__ current_ids = [x.tid for x in self.mng.ts] # Only this testcase AttributeError: 'CxxCompiler' object has no attribute 'tid' atheist-0.20110402/bugs/0000755000175000017500000000000011546632050013504 5ustar cletocletoatheist-0.20110402/bugs/istreams_fd.test0000644000175000017500000001240411546632050016706 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- import sys import unittest sys.path.insert(1, "$testdir") # import isa_for_tests as isa # import vm_for_tests as vm import streams_for_tests as streams # from mock_vm import MockVM from mock_streams import MockIstreamFD from test_base import assure_stream_calls# get_sum16, get_sum8 class TestIStreamFD(unittest.TestCase): # #define ISFD_RAM_SIZE 512 # #define ISFD_BUFFER_SIZE ISFD_RAM_SIZE / 8 # def setUp(self): # self.src = MockIstreamFD() # pipe2(_fds, O_NONBLOCK) # byte retval = istream_fd_init(&self.src, _fds[0], _ram, ISFD_BUFFER_SIZE) # assert(retval == 0) # _check_istream_fd_ready() def test_ostream_fd_init_correct(self): s = streams.istream_fd(0) self.assertTrue(isinstance(s, streams.istream_fd)) def test_ostream_fd_init_incorrect(self): self.assertRaises(Exception, streams.istream_fd, -1) def test_read_returns_data_when_present(self): data = "some text to read" src = MockIstreamFD(data) read_data = src.read() self.assertEqual(data, read_data) # update, clean, read, size, write, remain assure_stream_calls(self, src, 0, 0, 1, 0, 0, 0) def test_size_is_correct(self): data = "more text to read" src = MockIstreamFD(data) # _make_data_ready_for_read(data) # # size_t size = istream_fd_size(&self.src) # self.assertEqual(size, data.size()) # # def test_size_is_zero_when_no_data(self): # size_t size = istream_fd_size(&self.src) # self.assertEqual((int)size, 0) # # def test_update_when_buffer_empty(self): # char* read_data # # std::string data1 = "all bytes of " # write(_fds[1], data1.c_str(), data1.size()) # istream_fd_update(&self.src) # # read_data = istream_fd_read(&self.src) # self.assertEqual(std::string(read_data, data1.size()), data1) # # std::string data2 = "a large string" # write(_fds[1], data2.c_str(), data2.size()) # istream_fd_update(&self.src) # # std::string data = data1 + data2 # read_data = istream_fd_read(&self.src) # self.assertEqual(std::string(read_data, data.size()), data) # # def test_update_when_buffer_full(self): # char data[ISFD_BUFFER_SIZE] # memset(data, '!', ISFD_BUFFER_SIZE) # _make_data_ready_for_read(std::string(data, ISFD_BUFFER_SIZE)) # # char* overload = (char*)"more data" # write(_fds[1], overload, strlen(overload)) # istream_fd_update(&self.src) # # char* read_data = istream_fd_read(&self.src) # self.assertEqual(std::string(read_data, ISFD_BUFFER_SIZE), std::string(data, ISFD_BUFFER_SIZE)) # # def test_update_when_buffer_full_at_end(self): # char cdata1[ISFD_BUFFER_SIZE/2] # memset(cdata1, 'a', ISFD_BUFFER_SIZE/2) # char cdata2[ISFD_BUFFER_SIZE/2] # memset(cdata2, 'b', ISFD_BUFFER_SIZE/2) # # std::string data1(cdata1, ISFD_BUFFER_SIZE/2) # std::string data2(cdata2, ISFD_BUFFER_SIZE/2) # _make_data_ready_for_read(data1 + data2) # istream_fd_clean(&self.src, data1.size()) # # char* overload = (char*)"cccccccccccc" # write(_fds[1], overload, strlen(overload)) # istream_fd_update(&self.src) # # std::string data = data2 + std::string(overload) # char* read_data = istream_fd_read(&self.src) # self.assertEqual(std::string(read_data, data.size()), data) # # def test_update_when_buffer_at_end(self): # char cdata[ISFD_BUFFER_SIZE] # memset(cdata, '!', ISFD_BUFFER_SIZE) # std::string data(cdata, ISFD_BUFFER_SIZE) # # _make_data_ready_for_read(data) # istream_fd_clean(&self.src, data.size()) # # std::string new_data = "some more words" # write(_fds[1], new_data.c_str(), new_data.size()) # istream_fd_update(&self.src) # # char* read_data = istream_fd_read(&self.src) # self.assertEqual(std::string(read_data, new_data.size()), new_data) # # def test_update_does_not_change_when_no_data(self): # std::string data = "some text to read" # _make_data_ready_for_read(data) # istream_fd_update(&self.src) # # char* read1 = istream_fd_read(&self.src) # istream_fd_update(&self.src) # char* read2 = istream_fd_read(&self.src) # # self.assertEqual(read1, read2) # self.assertEqual(std::string(read1, data.size()), std::string(read2, data.size())) # self.assertEqual(std::string(read1, data.size()), data) # self.assertEqual(self.src.base->size(&self.src), data.size()) # # def test_clean_is_correct(self): # std::string data1 = "some " # std::string data2 = "text to read" # _make_data_ready_for_read(data1 + data2) # # istream_fd_clean(&self.src, data1.size()) # char* data_read = istream_fd_read(&self.src) # # self.assertEqual(std::string(data_read, data2.size()), data2) # # def _make_data_ready_for_read(self, data): # assert self.src.write(data) == len(data) # self.src.update() # assert(data.size() > 5) # assert(write(_fds[1], data.c_str(), data.size()) == (int)data.size()) # istream_fd_update(&self.src) # # def _checkself.src_fd_ready(self): # self.assertTrue(self.src.min >= 0) # self.assertTrue(self.src.max >= 0) # self.assertTrue(self.src.max > self.src.min) # self.assertTrue(self.src.start >= self.src.min && self.src.end <= self.src.max) UnitTestCase(TestIStreamFD) atheist-0.20110402/bugs/istreams_fd.test.out0000644000175000017500000000241511546632050017515 0ustar cletocleto[II] Test case ./istreams_fd.test ------------------------------------------------------------- [II] U5: [II] U1: [II] U2: [II] U3: U3:err| Traceback (most recent call last): U3:err| File "/home/oscar/Repos/hg/them/test/unit/python/istreams_fd.test", line 41, in test_read_returns_data_when_present U3:err| self.assertEqual(data, read_data) U3:err| AssertionError: 'some text to read' != 'some text to readTrue(self.src.min >= 0)\n# self.assertTrue(self.src.max >= 0)\n# self.assertTrue(self.src.max > self.src.min)\n# self.assertTrue(self.src.start >= self.src.min && self.src.end <= self.src.max)\n\n\nUnitTestCase(TestIStreamFD)\n' [II] U4: [II] U5: FAIL, skipping remaining tasks ('keep-going mode' disabled) [FAIL] TaskCase: ./istreams_fd.test [FAIL] └─ UCas-5 -(na: 0) TestIStreamFD [ OK ] ├─ Unit-1 -(na: 0) _ostream_fd_init_correct [ OK ] ├─ Unit-2 -(na: 0) _ostream_fd_init_incorrect [FAIL] ├─ Unit-3 -(na: 0) _read_returns_data_when_present [ OK ] └─ Unit-4 -(na: 0) _size_is_correct [ FAIL ] - 0.01s - 0/1 test atheist-0.20110402/athcmd.py0000755000175000017500000000176511527474305014400 0ustar cletocleto#!/usr/bin/python2.6 # -*- mode: python; coding: utf-8 -*- # atheist # # Copyright (C) 2009,2010,2011 David Villa Alises # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import sys from atheist.manager import DefaultManager def main(argv): mng = DefaultManager(argv[1:]) return mng.run() if __name__ == '__main__': sys.exit(main(sys.argv)) atheist-0.20110402/gui.xml0000644000175000017500000003400011457026443014053 0ustar cletocleto 500 Atheist 600 True vertical True True _Archivo True True gtk-new True True True gtk-open True True True gtk-save True True True gtk-save-as True True True True gtk-quit True True True True _Editar True True gtk-cut True True True gtk-copy True True True gtk-paste True True True gtk-delete True True True True _Ver True True Ay_uda True True gtk-about True True True False 0 True True automatic automatic True True tasks True 1 vertical True 3 True autosize 1 True 0 autosize True 0 center 600 5 4 autosize kind True 1 2 autosize # 1 True 2 right 0 True Name True True True 3 1 autosize Run True checkbutton_run 6 autosize Active True True 1 gtk-execute True True False True half True True atheist-0.20110402/DESIGN0000644000175000017500000000016211546632050013437 0ustar cletocleto- Prefer language features to DSL support. - Avoid support for multiple tasks or conditions at same invocation. atheist-0.20110402/COPYING0000644000175000017500000010451311457026443013607 0ustar cletocleto 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 . atheist-0.20110402/atheist-gui.py0000755000175000017500000000370611546632050015352 0ustar cletocleto#!/usr/bin/python -u # -*- mode: python; coding: utf-8 -*- import sys import gtk import atheist from atheist.const import * from atheist.manager import Manager from atheist.utils import relpath import pyarco.UI pyarco.UI.get_ostream().color = False def pretty(value): RESULT_STR = {\ FAIL: ('#f77', 'FAIL'), OK: ('green', 'OK'), NOEXEC: ('#fff', '--'), ERROR: ('#f00', '!!'), UNKNOWN: ('#ccc' , '??'), TODO: ('#fbf', 'ToDo'), mild_FAIL: ('#fcc', 'fail')} return RESULT_STR[value] class AtheistGui: def __init__(self): gui = gtk.Builder() gui.add_from_file('gui.xml') window = gui.get_object('window') window.connect('delete-event', gtk.main_quit) window.show_all() mng = Manager(sys.argv[1:]) mng.reload() i = 0 self.store = gui.get_object('tasks') for case in mng.itercases(): bgcolor, result = pretty(case.result) iter_ = self.store.append(None) self.store.set(iter_, 1, relpath(case.fname), 2, "Case", 4, result, 5, bgcolor, 6, False) for task in case.tasks: cmd_desc = task.cmd if hasattr(task, 'cmd') else task.desc bgcolor, result = pretty(i) if i < 6: i += 1 child_iter = self.store.append(iter_) self.store.set(child_iter, 0, task.indx, 1, pyarco.UI.ellipsis(cmd_desc), 2, task.acro, 3, cmd_desc.replace('\n', '\n\t') + '\n---\n' + task.desc, 4, result, 5, bgcolor, 6, False) AtheistGui() gtk.main() atheist-0.20110402/changelog.atheist0000644000175000017500000000106411457026443016063 0ustar cletocleto# date +%Y.%m.%d 2009.11.03 * Minimal bug in the ConsoleSummaryRender * IniParser does not requires ".atheist". * -f: show output only for failed tasks. 2009.11.02 * notifiers for console, jabber and mail (SMTP) * Test -> Task * argument 'check' to difference tests and non-tests 2009.10.06 * variable substitution in the "include" statement 2009.09.18 * "id" attributed renamed to "tid" * 'tests/cmd_not_found.test' fixed * condition stores its value whenever is executed 2009.09.14 * "id" duplicity is checked only in the testcase instead of all the tests. atheist-0.20110402/doc/0000755000175000017500000000000011547304161013311 5ustar cletocletoatheist-0.20110402/doc/plugins.rst0000644000175000017500000000517611457344714015545 0ustar cletocletoPlugins ------- It is possible to create plugin for Task and Conditions. This section includes information about off-the-shelf plugins distributed with atheist. Tasks ^^^^^ .. function:: DebPkgBuild .. function:: DebPkgInstall .. function:: DocTest Wrapper to add standard `doctest `_ to atheist testcases. .. function:: TaskTerminator(task, [task,...], key-vals) It's a special test to kill and **ensure** the termination of other tasks. The next example runs a netcat server for 10 seconds and then kills it:: nc = Daemon("nc -l -p 2000") TaskTerminator(nc, delay=10) .. _unittestcase: .. function:: UnitTestCase Wrapper for standard ``unitest.TestCase``. A sample:: class TestSample(unittest.TestCase): def test_trivial(): self.assertEqual(1, 1) UnitTestCase(TestSample) .. function:: WebTest It is a test to check webpages are correct and accessible. **Authentication with cookie:** If you want to get a page from a restricted site you may need a cookie file:: WebTest('example.org', cookie='cookie.txt') To get the cookie you may use a ``curl`` command similar to this:: curl -c cookie.txt -d "name=John.Doe&pass=secret&form_id=user_login" http://example.orrg/login Conditions ^^^^^^^^^^ .. function:: CompositeCondition(oper, condition, [condition,...]) Apply an arbitrary operator to compose results for given condition. It is the same idea of `compositetask`_ but applied to conditions. Sample:: CompositeCondition(all, cond1, cond2) .. function:: DebPkgInstalled(package) Checks that Debian package *package* is installed. .. function:: Or(condition, [condition,...]) Checks that at least one of the given conditions is satisfied. .. function:: TaskFinished(task, [task,...]) Checks that all the given tasks are finished. Usually used with a ``Poll`` decorator. .. function:: TaskRunning(task, [task,...]) Check that all the given tasks are running. Extending atheist ----------------- Customizable Task methods: .. function:: terminate() Ask task to finish as soon as possible and free its resources. Returns nothing. .. function:: is_running() Returns a boolean about task is already running. Customizable Conditions methods: .. function:: __eq__() By default, conditions of same class are the same condition. You need to overwrite the __eq__() method to diferenciate instances of your Condidition subclass, depending on their attributes .. Local Variables: .. coding: utf-8 .. mode: flyspell .. ispell-local-dictionary: "american" .. End: atheist-0.20110402/doc/examples.rst0000644000175000017500000000005211457026445015664 0ustar cletocletoExamples description ==================== atheist-0.20110402/doc/classes.dia0000644000175000017500000000314711457026445015440 0ustar cletocleto]Ks6Wp H"gt%9k PCKBvC~{$-"EvW3Xr?ߚd#IRʣ#MUHF;Op>7ORgDin.ߎFOOOS,x]~`HEwbcQ,DB+A/XaUUipfQfTswdpص&_uLeS*M:ngSZ(߿zS <@%N4jܰ" Ðɰ}\799nz]8v]p4< 9"Y8ibŌ OY&vr /܊/O4Ux_tseׯN޻{ΆC+4(F^kPfC0&I3B*-Fw{ӿH 8r|b8M]!+/Z5I',|7; qtZhH`"Aw\ݾՑ0UBI sK2ϫ #g)w]1g%O :>^ j4PR,m;G"hB=?~)̡4Gk{d!Fle+zՉwW< nHS*1]9:9we-j3,P5Zo⽛{yinZ*zbDwcޭ3Z]o [3 D>>(|PA >(|P;j3OȞKo2M]fxC}|oeX-TB*ZꔾZȲ|dzv\w" n c~3ǘJNg[+OEp:7ŮMHrCF͍l>Q8 "]%eiVN| A}o_@K _۹7P&}I{J b"KPAكe=({PAكeO9>tNg1$SґfS6iQG.ljyma %U䜳Kʬ_pI"v_rIĆ) e ia   [?\,mү}{+YIw-3Ied#_ [=XeTͿrSrmatheist-0.20110402/doc/faq.rst0000644000175000017500000000254611457026445014627 0ustar cletocletoFrequently asked questions (FAQ) ================================ .. _faq_shell: Why do I get strange behavior when the Task command line has quotation? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You need to use a shell to execute your command. Use ``shell=True`` when you define the **Task**. Why don't the environment variables expand? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Environment variable expansion must made by a shell. Use ``shell=True`` when you define the **Task**. Why not shell=True is the default value? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Shell is expensive if you want to run many tests. Use only when is needed. Why I get "<[FAIL]FileExists ''>"? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Probably you are checking existence of the stdout or stderr of a Task. You must put ``save_stdout=true`` o ``save_stdout`` in the Task if you need those files. Why I have Python errors in my correct test files? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ atheist executes the .test files with the same Python version that it runs. It you use new Python features in your .test files but you run atheist with a old version the problem appears. To solve that always execute atheist with the newer Python version that you have. .. Local variables: .. ispell-local-dictionary: "american" .. TeX-master: "main.tex" .. End: atheist-0.20110402/doc/conf.py0000644000175000017500000001452711457026445014627 0ustar cletocleto# -*- coding: utf-8 -*- # Atheist documentation build configuration file, created by # sphinx-quickstart on Tue Aug 4 15:55:15 2009. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Atheist' copyright = u'2009,2010, David Villa' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. sys.path.insert(0, '..') from atheist.const import VERSION version = VERSION # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Atheistdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Atheist.tex', u'Atheist Documentation', u'David Villa', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True atheist-0.20110402/doc/other.rst0000644000175000017500000000032411457026445015171 0ustar cletocletoRelated tools ============= * `Twisted trial`_ * `Testing Framework`_ .. _`Twisted trial`: http://twistedmatrix.com/trac/wiki/TwistedTrial .. _`Testing Framework`: http://www.c2.com/cgi/wiki?TestingFramework atheist-0.20110402/doc/task_creation0000644000175000017500000000143311524504451016062 0ustar cletocletoManager ------- -- Manager -- Manager.reload -- .process_files -- create "cases" -- Manager.run -- RunnerClass -- RunnerClass.run -- run "cases" -- Manager.summary -- run "reporters" Case creation ------------- -- TastCase -- TaskCase.process_file -- Task -- Task.enable_outs + task.post <- FileExists for stdout y stderr + task.gen <- stdout y stderr -- TaskCase.run -- run_task -- task.do_pre_run + before para task.pre y task.post + FileContains y FileEquals pueden crear FileExists incluso para stdout y stderr + task.pre <- Not(FileExists) para task.gen + task.post <- FileExists para task.gen -- Manager -- reload -- Manager.start -- RunnerClass -- RunnerClass.run -- run "cases" -- run reporter atheist-0.20110402/doc/classes_new.dia0000644000175000017500000000502011457026445016301 0ustar cletocleto]Ks6ϯPi >ةS{V `;=!}̗Dc*Odn>4?}YQx;HXE ?\ގ~tDžO˘G0nǫ40<==`4QoQ& h20`AS*˿imF!]zߖq U΋(=va3L {Cl3kn7,.wDϛMIC?mV o.>l~̆qnB5~XmdБ:7qWMlraÊ&ӘiU<FLjoYw9G>N%Ńљ? i@jt.cqzZ4/"se'<`uôwt_;{}\r6d5>#\xXnKLbVy9۵5LUa?G"{;R9z~ﯣO&{_܎ӊF*{bM/ˈ 4\(Gt!S&l=8F w)U,"Uzw~:jR |.,fMbEfa:Yp"VB&fI2{CrRRITirLR;j|)SL7K|uμˣԺ[iC`6 XcbHrY{!{x{ a%cu3~Pd.Zˆ`Uݾn@~0J6UDţh,&H2) ӿ`<캘7Q[Gf{FT`<JB{ Y{to;y8Npl{ R(^c3I.,'YyJ ”VVG%A4}@>?]ύigJ[1g:4䇝Hhz8P;Ea$UBD~:{/9.SZ&Su0Xċ'Fgq)2;o8ӥb\҉ʄN.gJLdu7A6ęLK'דÒ69 3`΀9 3`΀9 3` Efxo"CI!g)2 _(|8p>|翓 K£,Ȑ ȐF,J_{E^h8'Li^C3kg;5ȡ;S>_tloN;XnOdjHwtG2W|c4E㼭2 Չ8łFӋ{+9e"i?G;:OꜫJ# >Ґ&*kUf/$3ldB*745ka#&J]?<ՠTm րm րm րm րm րO,=VZF}j|:R kn#K{yrvG9۷j SZE.a` -1M9FLM 8K+W{\^WV>r ___Ry }@ EOĚ~~FDZf/0}M'[r+9e- 5(Ӄ|ExS>]WsUf\dL.ij9|KhA̍[8[wswvy矓$rMϼ\[qTX#YEOZTvV7#=mӝB)Ǵ [LXh`܄7a&U,\~0rrExxhO- oD+.,ToMvŬZn?Ԋ6aauPU}T1%V)1I^.t' 2Q4dϔAvr*vnP2 J]k4[]ɴټZDfd8b4#@Hm 38Z_KRԐT/QΒ{/׫])K8MVyF|GKV!H·|H·|H·|H·|H·|H·75Ѯ2n8}S{/Fs4 ŬkNssLm3nٻ@Vܜ?v}%~0'?VÖ"7s#o)L|w?f\Qvf"^Y۷؊ -`wffc݇]t}`gFatheist-0.20110402/doc/fdl.rst0000644000175000017500000005464311457026445014632 0ustar cletocletoGNU Free Documentation License ============================== Version 1.3, 3 November 2008 Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque". Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. The "publisher" means any person or entity that distributes copies of the Document to the public. A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified Version. N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements". 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. 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, receipt of a copy of some or all of the same material does not give you any rights to use it. 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation 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. See http://www.gnu.org/copyleft/. Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document. 11. RELICENSING "Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site. "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. "Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. ADDENDUM: How to use this License for your documents To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (c) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this: with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software. atheist-0.20110402/doc/index.rst0000644000175000017500000000156711457026445015171 0ustar cletocleto.. Atheist documentation master file, created by sphinx-quickstart on Tue Aug 4 15:55:15 2009. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Atheist's documentation ======================= Copyright (C) 2009,2010 David Villa Alises Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". .. toctree:: :maxdepth: 2 intro.rst plugins.rst examples.rst faq.rst other.rst fdl.rst Indices and tables ================== * :ref:`genindex` * :ref:`search` .. * :ref:`modindex atheist-0.20110402/doc/Makefile0000644000175000017500000000626511457026445014770 0ustar cletocleto# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = python /usr/bin/sphinx-build PAPER = # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest all: latex $(MAKE) -C _build/latex all cp _build/latex/Atheist.pdf . install: all html scp -r _build/html develsite:web/atheist/ scp _build/latex/Atheist.pdf develsite:web/atheist/ help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: $(RM) -r _build/ $(RM) Atheist.pdf html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html @echo @echo "Build finished. The HTML pages are in _build/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) _build/dirhtml @echo @echo "Build finished. The HTML pages are in _build/dirhtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in _build/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) _build/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in _build/qthelp, like this:" @echo "# qcollectiongenerator _build/qthelp/Atheist.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile _build/qthelp/Atheist.qhc" latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex @echo @echo "Build finished; the LaTeX files are in _build/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes @echo @echo "The overview file is in _build/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in _build/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) _build/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in _build/doctest/output.txt." vclean: clean $(RM) Atheist.pdf atheist-0.20110402/doc/intro.rst0000644000175000017500000004202111547304161015175 0ustar cletocletoIntroduction ============ Atheist is a simple framework for running test cases. You write small files in Python language using a set of predefined functions and classes. In many senses, the concept is quite similar to *make* or the SCons framework although Atheist is not a building system at all. Features: * `Black-box testing `_: system and acceptance tests. It may execute any kind of external shell program. * `White-box testing `_ by means of `unitest `_ and standard Python functions. * `Python doctests `_. * `Python unittest `_. * New kinds of "tests" by means of plugins. * Plugable pre- and post- condition system. ToDo: * Per-project plugins. * Limit/perf testing. * Remote testing. * Test deployment. * Remote management. * Distributed testing. Test objects ------------ The Test object is the minimal testing unit. Each Test instance defines an individual execution (a shell command) that may be checked for success upon termination. The Test constructor accepts many parameters that may change the test's exception behavior in several ways. The only mandatory parameter is ``cmd`` which is the command to execute. The Test object is responsible for executing the command and checking its termination value. A very basic example:: Test('true') Test files (TestCases) ---------------------- Test instances need to be defined in text source files (with ``.test`` extension). Although these files are written in a subset of the Python language, they may be seen as declarative programs. You tell Atheist what you want to test and even the order, but the decision about when to run the corresponding action is taken by Atheist; some of them may be never done. The file **does not define sequential** imperative sentences. For example, if you write this in a ``.test`` file:: Test('ls /') print "hello" the ``print`` statement will be executed when the test is **LOADED** and the ``ls`` command will run later, when the test is **EXECUTED**. You must take in mind that the atheist .test file defines a set of tests. It is not a conventional python program. Key-args ^^^^^^^^ Any Test constructor accepts the next key-val parameters. All of them are optional. Beside the parameter's name appear its type and default value. **check** -- type: ``bool``, default: ``True`` If 'check' is ``False`` there is no consequences when the Task fails and it is not considered in the final stats. **cwd** -- type: ``str`` Directory for the task execution. **delay** -- type: ``int``, default: ``0`` Waits for 'delay' seconds before launching the task actions. **desc** -- type: ``str`` One-liner textual task description. **detach** -- type: ``bool``, default: ``False`` When ``detach`` is ``False`` the next task does not start until the current one ends. When ``detach`` is ``True`` the next task is executed even if the current one is still running. **env** -- type: ``str``:``str`` map A dictionary with shell environment variables. **expected** -- type: int Expected return code for the command. It may be negative if the process is killed by a signal. **tid** -- type: ``str`` It is a unique string Task IDentifier. You can get a reference to the task later by giving this value to the :func:`get_task` function. **must_fail** -- type: ``bool``, default: ``False`` When you expect the program to end with an error but the return code is not known (i.e: is different from zero). You should check other conditions (stdout, stderr, generated files, etc) to differentiate alternative fails. .. _compositetask: **parent** -- type: CompositeTask Use this to aggregate the current test to an already defined CompositeTask. **template** -- type: Template list A list of templates. See :ref:`templates`. **timeout** -- type: int, default: ``5`` The maximum task execution time (in seconds). When the timeout finishes, Atheist sends the programmed signal to the process. To avoid timed termination (daemonic task) give ``timeout=0``. **save_stderr** -- type: ``bool``, default: ``False`` Store the process' stderr in a text file. If the ``stderr`` parameter is not set, Atheist will create an unique name for the file. **save_stdout** -- type: ``bool``, default: ``False`` Store the process' stdout in a text file. If the ``stdout`` parameter is not set, Atheist will create an unique name for the file. **shell** -- type: ``bool``, default: ``False`` Execute the command within a shell session. ``bash`` is the used shell. **signal** -- type: int, default: SIGKILL It is the signal that Atheist sends to the process when the ``timeout`` finishes. **stdout** -- type: ``str`` It is the name of the file where to save the process' stdout. Setting this parameters implies save_stdout = True. **todo** -- type: ``bool``, default: ``False`` It indicates that the task is not fully verified and it is possible that it fail unduly. This has no effect when the task ends successfully. Not all of these key-args are available for all Task classes. See :ref:`task_types`. Task results ------------ The execution of any task returns a value, which can be: * **FAIL**: The task ran normally but user requirements or conditions were not met. The test **failed**. * **OK**: The task ran successfully and all required conditions and/or return values were correct. * **NOEXEC**: The task was skipped or it was not executed. * **ERROR**: The implementation of the task is wrong and the task execution failed itself. * **UNKNOWN**: The task was executed but its result is not known. * **TODO**: The task implementation is unstable and it may produce false failures. .. _templates: Templates --------- The template is a set of predefined values for Test key-values. You may use the same configuration for many tests avoiding to repeat them. This is an example:: t1 = Template(timeout=6, expected=-9) Test('foo', templates=[t1]) Test('bar', templates=[t1]) Both tests will be automatically killed after 6 seconds and the expected return value is -9. This means that these processes receive the SIGKILL(9) signal. You may specify several templates as a list. Conditions ---------- *Conditions* are predicates (actually, functors) that check for specific conditions. Conditions may be specified to be checked before (pre-conditions) or after (post-conditions) the task execution. If any of the conditions fail, then the task fails. This is an example:: t = Test('foo') t.pre += FileExists('/path/to/foofile') t.post += FileContains('path/to/barfile', 'some text') Available builtin conditions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. function:: AtheistVersion(version) Checks that the installed version of **atheist** is equal or newer than the given number. This is useful to assure recent or experimental features. .. function:: Callback(*args) Call the specified function with the given arguments. You must avoid the use of this condition as much as possible. .. function:: DirExists(path) Checks that directory *path* exists. .. function:: EnvVarDefined(name[, value]) Checks that the environment variable *name* exists, and optionally has the value *value*. .. function:: FileExists(filename) Checks that file *filename* exists. .. function:: FileContains(val[, filename=task.stdout, strip='', whole=False, times=1]) Checks that file *filename* exists and contains *val*, which may be a string or a string list. If *whole* is ``False`` (default) val must be a strip and the whole content of file must be equal to *val*. Otherwise, the file must contain **at least** *times* occurrences of *val*. The default value for *filename* is the stdout of the corresponding task, and it implies ``save_stdout=True``. This implies also the automatic creation of a FileExists condition for that file. The file content may be stripped by means of *strip* argument. No stripping by default. .. function:: FileEquals(filename1[, filename2=task.stdout]) Checks that the contents of *filename1* and *filename2* are identical. The default value for *filename2* is the stdout of the current task, and it implies ``save_stdout=True``. .. function:: OpenPort(port[, host='localhost'[, proto='tcp']]) Checks that port number *port* is open, i.e., a process is listening to it. .. function:: ProcessRunning(pid) Checks that the given PID belongs to a running process. There are other available conditions as plugins. Condition decorators ^^^^^^^^^^^^^^^^^^^^ .. function:: Not(condition) It is True when *condition* is evaluated as False. Example:: t = Test('rm foo_file') t.pre += Not(FileExists(foo_file)) .. function:: Poll(condition[, interval=1[, timeout=5]]) Checks *condition* every *interval* seconds, stopping after *timeout* seconds or when its value becomes True. In the next example, the task waits (a maximum of 5 seconds) for the ``nc`` server to become ready before continuing:: t = Test('nc -l -p 2000') t.post += Poll(OpenPort(2000)) Condition decorators may be combined. The following example shows a task that waits for an environment variable to be removed before executing the command:: t = Test('command') t.pre += Poll(Not(EnvVarDefined('WAIT_FLAG')), timeout=10) Note that the effect of Poll(Not(condition)) is not the same that Not(Poll(condition)). .. _task_types: Task's, Test's, Commands, Daemons... ------------------------------------ ``Task`` is the base class for all executable items. ``Test`` is-a ``Task`` that runs a shell command but other kind of ``Task`` are possible: **Command** It is a non-checked ``Test``. Command is exactly the same that a Test with a ``check=False`` parameter. The Commands (or other non-checked Tasks) are not considered in results counting. **Daemon** Command shortcut for detached commands. Predefined parameters are: * ``detach = True`` * ``expected = -9`` (sigkilled) * ``timeout = None`` (runs "forerver") * ``check = False`` **TestFunc** Check the return value of arbitrary Python functions or methods. A return value of 0 means success, otherwise is a error code. For unit testing, prefer `unittestcase`_ instead of TestFunc. There are other available Task subclasses as plugins. Function utilities ------------------ .. function:: get_task(name) Returns the task whose ``tid`` attribute is *name*. ToDo: [include a sample here] .. function:: load(filename) Makes possible to reuse atheist or python code in other files. ``load()`` returns a module-like object that may be used to access to functions, classes and variables defined in the "loaded" module. All atheist classes are available within the loaded modules:: common = load("files/common.py") Test("./server %s" % common.server_params()) .. warning:: Previous ``include()`` function is not supported any more. Variable substitutions ---------------------- Test files may include some substitutable variable. This is useful to locate test-relevant related files. You must write the symbol '$' preceding each one of the next words: **basedir** is the name of the directory where atheist was executed. Usually this is a ``tests`` directory into your project. **dirname** is the name of the directory where the testfile is. **fname** is the path to the testfile without its extension (.test). **testname** is just the name of the testfile, without extension nor directory path. For example, for the following ``vars.test`` file:: Test("echo $basedir $dirname $fname $testname") When you run atheist, you get:: ~/sample$ atheist -i2 tests/vars.test [ OK ] Test case: ./tests/substitutions.test [ OK ] +- T-1 ( 0: 0) echo . ./tests ./tests/vars vars Total: ALL OK!! - 0.24s - 1 test hooks: setup and teardown ------------------------- You may write tasks to execute before and after **each** test file. To do so, just put this tasks in files called ``_setup.test`` and ``_teardown.test``. Clean-up -------- When your task creates files you may track them for automatic cleaning. Just add their filenames to the task ``gen`` attribute. Here's an example:: t = Test('touch foo') t.gen += 'foo' You may specify one o more filenames (as a string list). If you want the generated files not to be automatically removed for manual inspection of the results, you must specify the ``--dirty`` option (see below). To clean-up these files later, specify the ``-C`` option. Invoking Atheist ================ .. program:: atheist .. cmdoption:: -h, --help Show basic help information. .. cmdoption:: -a ARGS, --task-args=ARGS Colon-separated options for the tests. .. cmdoption:: -b PATH, --base-dir=PATH Change working directory. .. cmdoption:: -C, --clean-only Don't execute anything, only remove generated files. .. cmdoption:: -d, --describe Describe tasks but don't execute anything. .. cmdoption:: -e, --stderr Print the test process' stderr. .. cmdoption:: -f, --out-on-fail Print task output, but only if it fails. .. cmdoption:: -g, --gen-template Generate a test file template with default values. .. cmdoption:: -i LEVEL, --report-detail=LEVEL Verbosity level (0:nothing, [1:case], 2:task, 3:composite, 4:condition) .. cmdoption:: -j, --skip-hooks Skip _setup and _teardown files. .. cmdoption:: -k, --keep-going Continue despite failed tests. .. cmdoption:: -l, --list List tests but do not execute them. .. cmdoption:: -o, --stdout Print the test process' stdout. .. cmdoption:: -p PATH, --plugin-dir=PATH Load plugins from that directory (may be given several times). Print the test process' stdout. .. cmdoption:: -q, --quiet Do not show result summary nor warnings, only totals. .. cmdoption:: -r RANDOM, --random=RANDOM Run testcases in random order using the specified seed. .. cmdoption:: -s INLINE, --script=INLINE Specifies command line script. .. cmdoption:: -t, --time-tag Include time info in the logs. .. cmdoption:: -u, --until-failure Repeat tests until something fails. .. cmdoption:: -v, --verbose Increase verbosity. .. cmdoption:: -w WORKERS, --workers=WORKERS Number of simultaneous tasks. '0' allows atheist to choose the number. Default is 1. .. cmdoption:: -x COMMAND, --exec=COMMAND Exec COMMAND like in "Test(COMMAND, shell=True)" .. cmdoption:: --case-time Print case execution time in reports .. cmdoption:: --cols=WIDTH Set terminal width (in chars). .. cmdoption:: --config=FILE Alternate config file. .. cmdoption:: --dirty Don't remove generated files after test execution. .. cmdoption:: --disable-bar Don't show progress bar. .. cmdoption:: --ignore=PATTERN Files to ignore (glob patterns) separated with semicolon. .. cmdoption:: --log=LOG List tasks but do not execute them. .. cmdoption:: --plain Avoid color codes in console output. .. cmdoption:: --save-stdout Save stdout of all tasks .. cmdoption:: --save-stderr Save stderr of all tasks .. cmdoption:: --version Atheist version .. cmdoption:: --notify-jabber=JABBER Notify failed tests to the given jabber account (may be given several times). .. cmdoption:: --notify-smtp=MAIL Notify failed tests to the given email address (may be given several times). Logging control --------------- **[ToDo]** Result report ------------- **[ToDo]** Config files ============ **[ToDo]** Notifications (other reporters) =============================== You may use Atheist to monitor the proper working of any application. It may send you notifications when something is wrong. The easiest way is to run a testcase with ``cron`` specifying one ``--notify-*`` command-line argument. Currently, two notificators are implemented: **Email** The destination is a email account using the SMTP protocol. Atheist does not require an SMTP server or smarthost. You only need to configure an email account that will be used by Atheist to send mail to any destination. That information must be written in the ``~/.atheist/config`` configuration file. This is an example:: [smtp] host = smtp.server.org port = 587 user = atheist.notify@server.org pasw = somesecret **Jabber** You must indicate a jabber account that will be used by Atheist to send notification messages to any other jabber account. The destination account must accept this contact previously. The following is an example for the configuration in the ``~/.atheist/config`` file:: [jabber] user = atheist.notify@server.org pasw = anothersecret To ask for a notification you just need to specify a test file and one or more destinations. For example:: $ atheist --notify-jabber John.Doe@jabber.info test/some_test.test It is possible to give several --notify-* arguments in the same command-line to send notifications to different destinations. .. Local variables: .. coding: utf-8 .. ispell-local-dictionary: "american" .. End: atheist-0.20110402/remote-tests/0000755000175000017500000000000011457026445015205 5ustar cletocletoatheist-0.20110402/remote-tests/server.test0000644000175000017500000000024511457026445017415 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- server = Daemon('./server.py tests') t = Task('./client.py', timeout=5, expected=-9) t.pre += Poll(TaskRunning(server), 0.5) atheist-0.20110402/hard-tests/0000755000175000017500000000000011457026445014630 5ustar cletocletoatheist-0.20110402/hard-tests/debian.test0000644000175000017500000000062611457026445016757 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test('sudo pbuilder update', desc="Conditions: AtheistVersion, DebPkgInstalled") t.pre += AtheistVersion('0.200908') t.pre += DebPkgInstalled('atheist') t.pre += DebPkgInstalled('python', '2.5.0') b = DebPkgBuild(".") i = DebPkgInstall(b.packages, mirrors = ["http://babel.esi.uclm.es/debian"], warn_broken_symlinks = True) atheist-0.20110402/pyarco/0000755000175000017500000000000011547306061014042 5ustar cletocletoatheist-0.20110402/pyarco/__init__.py0000644000175000017500000000021411457026445016155 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- """pyarco is an useful general purpose python library. .. moduleauthor:: Arco Research Group """ atheist-0.20110402/pyarco/Type.py0000644000175000017500000002670311523712751015346 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- """types module provides more powerful structures and functions than built-in .. moduleauthor:: Arco Research Group """ import string, csv import inspect import warnings import collections class Record(object): "kargs are automatic attributes" def __init__(self, **kargs): self._attrs = kargs.keys() for k,v in kargs.items(): setattr(self, k, v) def __str__(self): retval = "" for k in self._attrs: retval += "%s:'%s' " % (k, getattr(self, k)) return "" % retval # FIXME: probaly may be replaced with collections.OrderedDict in python2.7 # iniparse has a simpler SortedDict class SortedDict(dict): """A fixed-position dictionary. The keys will be stored on a list in the same order as are inserted.""" def __init__(self, other={}, default=None, **kargs): self.__keylist = [] self.default = default if isinstance(other, dict): self.update(other) if isinstance(other, list): for key,val in other: self[key] = val for k,v in kargs.items(): self[k] = v def __getitem__(self, key): if not key in dict.keys(self): if self.default is None: raise KeyError(key) self[key] = self.default return dict.__getitem__(self, key) def __setitem__(self, key, value): dict.__setitem__(self, key, value) if key in self.__keylist: self.__keylist.remove(key) self.__keylist.append(key) def update(self, other): for k,v in other.items(): self[k] = v def keys(self): return self.__keylist def values(self): return [self[k] for k in self.__keylist] def items(self): return [(k, self[k]) for k in self.__keylist] def __iter__(self): return self.__keylist.__iter__() def clear(self): self.__keylist = [] dict.clear(self) # # DEPRECATED: Use 'default' param in SortedDict # #class ListDict(SortedDict): # """A special case of a SortedDict. Here, if a key is unknown, it is created # en empty list for it.""" # # def __getitem__(self, key): # if not key in dict.keys(self): # self[key] = [] # return SortedDict.__getitem__(self, key) class DictTemplate: '''Read a template from file and generate a dict allowing substitutions template_file: full_name = Mr. $firstname %surname The $title = $value dt = DictTemplate('template_file', delimiter='=') result = t.substitute(dict(firstname='John', surname='Doe', title='job', value='fireman')) DictTemplate.render(result, 'out_file') out_file: full_name = Mr. John Doe The job = fireman ''' def __init__(self, file_, delimiter=','): if isinstance(file_, str): self.fd = open(file_) else: self.fd = file_ self.delimiter = delimiter def substitute(self, values): self.fd.seek(0) result = string.Template(self.fd.read()).safe_substitute(values) csv_file = csv.reader(result.split('\n'), delimiter=self.delimiter) retval = SortedDict() for row in csv_file: if not row or len(row) < 2: continue if any(['$' in x for x in row]): continue retval[row[0].strip()] = self.delimiter.join((row[1:])).strip() return retval @classmethod def render(cls, data, fname, delimiter=','): """Render dict 'data' for file 'fname' using 'delimiter' """ assert isinstance(data, dict) with file(fname, 'w') as fd: for x in data.items(): fd.write("%s = %s\n" % x) def striplit(val, sep=' ', require_len=None): ''' >>> striplit(' this - is a - sample ', sep='-') ['this', 'is a', 'sample'] ''' val = val.strip(sep) retval = [x.strip() for x in val.split(sep)] if require_len is not None and len(retval) != require_len: raise ValueError("Incorrect size != %s" % require_len) return retval def uniq(alist): ''' >>> list(uniq([1, 2, 2, 3, 2, 3, 5])) [1, 2, 3, 5] ''' s = set() for i in alist: if i in s: continue s.add(i) yield i def merge(*input): """ >>> merge([1,2], [2,4], [5, 6]) [1, 2, 2, 4, 5, 6] >>> merge([[1,2], [2,4]]) [[1, 2], [2, 4]] >>> merge(*[[1,2], [2,4]]) [1, 2, 2, 4] """ return reduce(list.__add__, input, list()) def merge_uniq(*input): """ >>> merge_uniq([1,2], [2,4], [5, 6]) [1, 2, 4, 5, 6] >>> merge_uniq([1,2]) [1, 2] >>> merge_uniq(*[[1,2], [2,4]]) [1, 2, 4] >>> merge_uniq([1, 2, 2, 3, 2, 3, 5]) [1, 2, 3, 5] """ return list(set(merge(*input))) def get_supercls(cls): "Returns all ancestor superclasses as a list" return [cls] + merge(*[get_supercls(x) for x in cls.__bases__]) class FullWrapper(object): ''' Simple modification over: module: method_decorator author: denis@ryzhkov.org license: free url: http://denis.ryzhkov.org/soft/python_lib/method_decorator.py Usage: class my_dec(method_decorator): def pre(self, function, *args, **kwargs): print 'calling', function @my_dec def func_or_method(...) ''' def __init__(self, func, obj=None, cls=None, method_type='function'): self.func = func self.obj = obj self.cls = cls self.method_type = method_type def __get__(self, obj=None, cls=None): if self.obj == obj and self.cls == cls: return self if isinstance(self.func, staticmethod): method_type = 'staticmethod' elif isinstance(self.func, classmethod): method_type = 'classmethod' else: method_type = 'instancemethod' return object.__getattribute__(self, '__class__')( self.func.__get__(obj, cls), obj, cls, method_type) def __call__(self, *args, **kwargs): self.decoration(self.func, *args, **kwargs) return self.func(*args, **kwargs) def decoration(self, func, *args, **kargs): pass def __getattribute__(self, attr_name): if attr_name in ('__init__', '__get__', '__call__', '__getattribute__', 'func', 'obj', 'cls', 'decoration', 'method_type'): return object.__getattribute__(self, attr_name) return getattr(self.func, attr_name) def __repr__(self): return self.func.__repr__() class accept: level = 'error' # None, 'error', 'warn' def __init__(self, *types_as_values, **types_as_dict): self.types_as_values = types_as_values self.types_as_dict = types_as_dict if self.level is None: return class decorator(FullWrapper): def decoration(deco, function, *args, **kargs): self.check_types(deco, function, *args, **kargs) self.__call__ = decorator def __call__(self, function): 'no decoration by default' return function def check_types(self, deco, function, *args, **kargs): def typerepr(typespec): if isinstance(typespec, type): return typespec.__name__ if isinstance(typespec, tuple): return str.join('/', [typerepr(x) for x in typespec]) raise TypeError, "'{0}' is not a type or tuple of types".format(typespec) def get_argspec(): args, varargs, keywords, defaults = inspect.getargspec(function) if deco.method_type in ['instancemethod', 'classmethod']: args = args[1:] #skip self/cls return inspect.ArgSpec(args, varargs, keywords, defaults) def get_type_map(): if self.types_as_dict: if self.types_as_values: self.error("mix key and non-key args is forbidden") return self.types_as_dict if len(spec.args) != len(self.types_as_values): self.error("{0}() takes {1} arguments ({2} types given)".format( function.__name__, len(spec.args), len(self.types_as_values))) return dict(zip(spec.args, self.types_as_values)) def check_type_map(): for arg_name in types_map.keys(): if not arg_name in spec.args and arg_name != spec.varargs: self.error("{0}() has not an argument '{1}'".format( function.__name__, arg_name)) def check_args(): # print 'args 1:%s %s' % (len(args), args[1:]) for i,arg_name in enumerate(spec.args): try: value = kargs[arg_name] except KeyError: try: value = args[i] except IndexError: continue try: expected_type = types_map[arg_name] except KeyError: continue # print "%s %s '%s' %s" % (i, arg_name, value, expected_type) if not isinstance(value, expected_type): self.error("Argument '{0}' should be '{1}' ('{2}' given)".format(\ arg_name, typerepr(expected_type), type(value).__name__)) def check_varargs(): if not spec.varargs: return # print types_map expected_type = types_map[spec.varargs] for value in args[len(spec.args):]: if not isinstance(value, expected_type): self.error("Argument '{0}' should be '{1}' ('{2}' given)".format(\ value, expected_type.__name__, type(value).__name__)) spec = get_argspec() # print spec types_map = get_type_map() # print types_map check_type_map() check_args() check_varargs() @classmethod def error(cls, msg): if cls.level == 'error': raise TypeError, msg if cls.level == 'warn': warnings.warn(msg, RuntimeWarning) return raise TypeError, "accept.level must be one of ['error', 'warn', None]" def attributes(*arg_names): class decorator(FullWrapper): def decoration(self, function, *args, **kargs): # print inspect.getargspec(function) formal_args = inspect.getargspec(function).args[1:] # skip self defaults = inspect.getargspec(function).defaults or [] n_positionals = len(formal_args) - len(defaults) for name in arg_names: if not name in formal_args: raise TypeError, "'{0}()' method has no argument '{1}'".format( function.__name__, name) pos = formal_args.index(name) # print "--\n%s %s %s" % (name, pos, n_positionals) # print args # print kargs try: value = args[pos] except IndexError: try: value = kargs[name] except KeyError: value = defaults[pos-n_positionals] setattr(self.obj, name, value) return decorator def check_type(val, cls): if not isinstance(val, cls): raise TypeError(("A %s is required, not %s." % \ (cls.__name__, val.__class__.__name__))) return val atheist-0.20110402/pyarco/Conio.py0000644000175000017500000000041111527474305015464 0ustar cletocletoESC = chr(27) GREY = ESC+'[38m' RED = ESC+'[31m' PURPLE = ESC+'[95m' GREEN = ESC+'[32m' LIGHT_RED = ESC+'[1;91m' LIGHT_RED_BG = ESC+'[7;91m' LIGHT_GREEN_BG = ESC+'[7;32m' BOLD = ESC+'[1m' HIGH = ESC+'[1m' NORM = ESC+'[m' CLS = ESC+'[2J' + ESC+'[0;0f' atheist-0.20110402/pyarco/UI.py0000644000175000017500000000743011546632050014734 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- """ Command line User Interface utilities .. moduleauthor:: Arco Research Group """ import sys, os, string import time import logging import locale from pyarco.Conio import * from pyarco.Pattern import Singleton Log = logging.getLogger('pyarco.UI') class ProgressBar: def __init__(self, max_val=100, width=80, label='', disable=False): self.max = max_val # total item amount self.label = label # prefix for the bar self.width = min(100, width - 37) # bar width disable = disable or max_val<4 if disable: self.__disable() self.alfa = 0.2 self.logger = None self.clean_len = 0 self.reset() def reset(self): self.val = 0 self.blk = 0 self.pct = 0 self.tinit = time.time() self.tlast = self.tinit self.eta = '~' self.lasteta = 0 # self.inc() def __disable(self): self._render = lambda x:None self.clean = lambda:None self.inc = lambda:None self.abort = lambda:None def inc(self, val=1, cad=''): self.val += val if self.val > self.max: self.reset() self.blk = self.val * self.width / self.max self.pct = self.val * 100 / self.max current = time.time() if self.val > 3 and (current - self.lasteta > 1): per_item = (1-self.alfa) * ((current - self.tinit) / self.val) \ + self.alfa * (current-self.tlast) remain = self.max - self.val self.eta = 1 + int(1.1 * remain * per_item) self.lasteta = current self._render(cad) self.tlast = current def _render(self, ustr): cad = ':%4s [ %s' % (self.label[:4], self.blk * '#') cad += (self.width - self.blk) * '-' cad += " ] {0:{1}}/{2} ({3:0>3}%) {4:>3}s:{5:>3}s {6}\r".format( self.val, len(str(self.max)), self.max, self.pct, int(time.time() - self.tinit), self.eta, ellipsis(unicode(ustr))) self.clean_len = max(self.clean_len, len(cad)) sys.__stdout__.write(cad) sys.__stdout__.flush() def clean(self): "clean the whole bar from screen" # clean_line = "%s%s\r" % (' ' * self.clean_len, '&') clean_line = "%s\r" % (' ' * self.clean_len) sys.__stdout__.write(clean_line) sys.__stdout__.flush() def listen_logger(self, logger, level): ''' Register a monitor handler in the given logger. If it is invoqued, progress bar is aborted. ''' class DummyHandler(logging.Handler): def __init__(self, pb, level): self._pb = pb self.level = level def handle(self, *args): self._pb.abort() if self.logger is None: self.logger = logger logger.addHandler(DummyHandler(self, level)) def abort(self): print "progress-bar canceled by logging events." self.__disable() def ellipsis(text, width=None, just=False, char=u'…'): """ >>> ellipsis("this is a sentence", width=10, char='_') u'this is a_' >>> ellipsis("this is a ", width=12, just=True, char='_') u'this is a ' """ if not text: text = u'' if not isinstance(text, unicode): text = unicode(text, encoding='utf-8', errors='replace') cad = text.strip() retval = cad.split('\n')[0] if width is not None: width = int(width) retval = retval[:width-1] if retval != cad: retval += char if just and width is not None: retval = retval.ljust(width) return retval def cls(): sys.stdout.write(CLS) sys.stdout.flush() atheist-0.20110402/pyarco/Pattern.py0000644000175000017500000002437111523712751016041 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- """patterns module includes classes and structures of design patterns. .. moduleauthor:: Arco Research Group """ from __future__ import with_statement import logging from thread import allocate_lock import threading class Singleton(type): """A metaclass for make any other class a Singleton_ (the design pattern). Example of use:: class MySingletonClass: __metaclass__ = Singleton # your code goes here :) .. _Singleton: http://en.wikipedia.org/wiki/Singleton_pattern """ def __init__(cls, name, bases, dct): cls.__lock = threading.Lock() cls.__instance = None type.__init__(cls, name, bases, dct) def __call__(cls, *args, **kw): with cls.__lock: if cls.__instance is None: cls.__instance = type.__call__(cls, *args, **kw) return cls.__instance def loaded(cls): return cls.__instance != None class Flyweight(type): '''Flyweight dessign pattern (for identical objects) class Sample(object): __metaclass__ = Flyweight def __init__(self, key, [...]): [...] ''' def __init__(cls, name, bases, dct): cls.__instances = {} type.__init__(cls, name, bases, dct) def __call__(cls, key, *args, **kw): instance = cls.__instances.get(key) if instance is None: instance = type.__call__(cls, key, *args, **kw) cls.__instances[key] = instance return instance # Observer Pattern class Observable: '''Observer design pattern implementation. Observable class: * Constructor can optionally receive two params. topics : A list of topic names (as strings) logger : A logger from logging module * Store a manage a dictionary with key:IdTopic, value:list of subscribers ''' # Exceptions class ObserverException(Exception): def __str__(self): return "%s: %s" % (self.__class__.__name__, Exception.__str__(self)) class TopicAlreadyExists(ObserverException): pass class NotSuchTopic(ObserverException): pass class InvalidTopicName(ObserverException): pass class InvalidSubscriber(ObserverException): pass class NotASubscriber(ObserverException): pass def __init__(self, topics=['default'], logger=logging.getLogger('Observable')): self._logger = logger self._logger.propagate = 0 self.__topics = {} for topic in topics: if not isinstance(topic, str): raise self.InvalidTopicName() self.__topics[topic] = [] def getTopicNames(self): return self.__topics.keys() def addTopic(self, topicName): if topicName in self.__topics.keys(): raise self.TopicAlreadyExists() if not isinstance(topicName, str): raise self.InvalidTopicName() self.__topics[topicName] = [] self._logger.info('New topic created for %s instance: %s' % (str(self.__class__.__name__), topicName)) def removeTopic(self, topicName): try: del self.__topics[topicName] except KeyError: raise self.NotSuchTopic() def attach(self, subscriber, topicName='default'): if not callable(subscriber): raise self.InvalidSubscriber() try: if subscriber in self.__topics[topicName]: return self.__topics[topicName].append(subscriber) except KeyError: raise self.NotSuchTopic() def detach(self, subscriber, topicName='default'): try: self.__topics[topicName].remove(subscriber) except ValueError: raise self.NotASubscriber() except KeyError: raise self.NotSuchTopic() def _notify(self, sub, value): sub(value) def notify(self, topicName, value): try: for sub in self.__topics[topicName]: try: self._notify(sub, value) except Exception, e: self._logger.warning('The subscriber %s raises an exception' % sub) self._logger.debug('Subscriber exception: %s' % e) except KeyError: raise self.NotSuchTopic() def status(self): '''Return the topic configurations compound by dictionary with key:IdTopic and value:List of subscribers''' return self.__topics.copy() class ObjectObservable(Observable): '''Observer design pattern implementation based in interfaces. Observable class: * Constructor can optionally receive two params. topics : A dictionary k:id_topic v:callback_name (as string) logger : A logger from logging module * Store a manage a dictionary with key:IdTopic, value:list of subscribers''' class InvalidObserverInterface(Observable.ObserverException): pass class InvalidCallbackName(Observable.ObserverException): pass def __init__(self, topics={'default':'update'}, logger=logging.getLogger('Observable')): Observable.__init__(self, topics.keys(), logger) #Topics: # key: id_topic # val:(str_callback, [subscribers_callbacks]) self.__interface = {} for topicName, topicCb in topics.items(): if not isinstance(topicName, str): raise self.InvalidTopic(topicName) if not isinstance(topicCb, str): raise self.InvalidObserverInterface(topicCb) self.__interface[topicName] = topicCb def addTopic(self, topic, callbackName): '''Register a new topic. If the topic exists raise the TopicAlreadyExists exception''' if not isinstance(callbackName, str): raise self.InvalidCallbackName() if topic in self.__interface.keys(): raise Observable.TopicAlreadyExists(topic) Observable.addTopic(self, topic) self.__interface[topic] = callbackName self._logger.debug('Added topic [%s] with callback [%s]' % (str(topic), callbackName)) def removeTopic(self, topicName): '''Unregister a topic. If the topic not exists raise the NotSuchTopic exception''' try: del self.__interface[topic] Observable.removeTopic(self, topicName) self._logger.debug('Removed topic [%s]' % str(topic)) except KeyError: raise self.NotSuchTopic() def attach(self, subscriber, topicName='default'): '''Subscribe a class into topic. If topic not is specified, the subscriber is registered into default topic. If the topic not exits raise NotSuchTopic exception''' try: meth = getattr(subscriber, self.__interface[topicName]) Observable.attach(self, meth, topicName) self._logger.debug('Subscribed [%s]' % str(subscriber)) except KeyError: raise self.NotSuchTopic(topicName) except AttributeError: raise self.InvalidObserverInterface() def detach(self, subscriber, topic='default'): '''Unsubscribe a subscriber class from a topic. If topic not exist raise the NotSuchTopic exception. If the subscriber not is subcribed into topic raise the NotSuchObserver exception''' try: meth = getattr(subscriber, self.__interface[topic]) Observable.detach(self, meth, topic) self._logger.debug('Unsubscribe [%s] from [%s]' % \ (str(subscriber), str(topic))) except AttributeError: raise self.InvalidObserverInterface() except KeyError: raise Observable.NotSuchTopic() class ObjectObservableAsync(ObjectObservable): '''Observer design pattern implementation. Observable Asynchronous class (one thread by notification). * Constructor can optionally receive four params: topics : A dictionary k:id_topic v:callback_name (as string) pollSize: Size of thread poll for asyncronous notifications (15 by default) logger : A logger from logging module * Store a manage a dictionary with key:IdTopic, value:list of subscribers * Store and manage the thread poll of asyncronous notifications * Wait to end all the notifications * If the thread poll is full the notifications will be ignore''' class CallbackThread(threading.Thread): def __init__(self, callback, value, onExit): threading.Thread.__init__(self) self._cb = callback self._val = value self._onExit = onExit def run(self): try: self._cb(self._val) finally: self._onExit(self.getName()) def __init__(self, topics={'default':'update'}, pollSize=15, logger=logging.getLogger('Observable')): ObjectObservable.__init__(self, topics, logger) self._poll = pollSize self._lockAT = allocate_lock() self._activeThreads = 0 self._threads = {} # Private Method def _onExit(self, ident): '''Unregister the thread of the active threads''' self._lockAT.acquire() self._activeThreads = self._activeThreads - 1 try: del self._threads[ident] except KeyError, e: self._log.debug('Thread [%s] already removed' % ident) finally: self._lockAT.release() # Private overwrite method def _notify(self, subs_cb, value): '''Overwrite the _nofify method to use asyncronous notification. Start the method into Thread and register it''' if self._poll >= self._activeThreads: t = self.CallbackThread(subs_cb, value, self._onExit) self._lockAT.acquire() self._threads[t.getName()] = t self._activeThreads = self._activeThreads + 1 self._lockAT.release() t.start() else: self._log.error('Unable notify, full poll') # Public overwrite method def status(self): '''Overwrite the status method to return the tuple status compound by: Topics - Dictionary k:IdTopic, v:List of subscribers Number Threads - Number of active threads ''' return (self._topics.copy(), self._activeThreads) atheist-0.20110402/pyarco/model.py0000755000175000017500000001021711546632050015517 0ustar cletocleto#!/usr/bin/python # -*- coding:utf-8; tab-width:4; mode:python -*- __all__ = ['IntField', 'TextField', 'Foreign', 'Model', 'Schema', 'IniModel', 'MissingMandatoryAttr', 'UnknownAttr', 'CastingError', 'MissingSchema'] import sys import inspect try: from collections import OrderedDict except ImportError: from pyarco.Type import SortedDict as OrderedDict import pyarco.iniparser import pyarco.fs class MissingMandatoryAttr(Exception): pass class UnknownAttr(Exception): pass class CastingError(Exception): pass class MissingSchema(Exception): pass def getattributes(instance): return [item for item in inspect.getmembers(instance, lambda x:not callable(x)) if not item[0].startswith('__')] def attr_names(attrs): return [x[0] for x in attrs] class Schema(OrderedDict): def __init__(self, *args, **kargs): OrderedDict.__init__(self, *args, **kargs) # self.__setattr__ = self.proto__setattr__ def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError # def proto__setattr__(self, key, value): # self[key] = value def copy(self): return Schema(self) class Register(dict): def __init__(self): dict.__init__(self, dict(getattributes(self))) def __setattr__(self, key, value): self[key] = value class Field(object): cast=None def __init__(self, opt=False, auto=False): self.opt = opt self.auto = auto if self.auto: self.opt = True def to_python(self, value): assert self.cast is not None, "You must subclass the Field" return self.cast(value) class TextField(Field): cast = str class IntField(Field): cast = int class Foreign(Field): def __init__(self, model, **kargs): self.cast = model Field.__init__(self, **kargs) class Model(object): def __init__(self, register): if not hasattr(self, 'schema') or not isinstance(self.schema, Schema): raise MissingSchema() schema_mandatory_attr_names = set(self.get_mandatory_attrs().keys()) schema_all_attr_names = set(self.schema.keys()) register_attr_names = set(register.keys()) # print 'schema all ', self.schema.keys() # print 'schema mandatory', self.get_mandatory_attrs().keys() # print 'register ', register.keys() # print missing_attrs = schema_mandatory_attr_names - register_attr_names if missing_attrs: raise MissingMandatoryAttr(list(missing_attrs)) unknown_attrs = register_attr_names - schema_all_attr_names if unknown_attrs: raise UnknownAttr(register, list(unknown_attrs)) self.load_register(register) def load_register(self, register): # print register for key,field in self.schema.items(): # print key, field try: raw_value = register[key] except KeyError: if field.opt: continue try: value = field.to_python(raw_value) setattr(self, key, value) except (ValueError), e: raise CastingError("Can not cast value '{0}' to type '{1}'".format( repr(raw_value), field.cast.__name__)) @classmethod def get_mandatory_attrs(cls): return dict(x for x in cls.schema.items() if not x[1].opt) @classmethod def get_optional_attrs(cls): return dict(x for x in cls.schema.items() if x[1].opt) @classmethod def get_auto_attrs(cls): return dict(x for x in cls.schema.items() if x[1].auto) def text_render(self): retval = '' for k,v in self.schema.items(): retval += "{0}: {1}\n".format(k, getattr(self, k)) return retval class IniParser(pyarco.iniparser.IniParser): default_section = 'MAIN' class IniModel(Model): FS = pyarco.fs.ActualFileSystem() def __init__(self, fname): assert isinstance(fname, str) ini = IniParser() ini.readfp(self.FS.open(fname)) Model.__init__(self, ini) atheist-0.20110402/pyarco/Thread.py0000644000175000017500000002627211547300376015637 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- """threads module provides useful structures for concurrent and threading programming tools. .. moduleauthor:: Arco Research Group """ from __future__ import with_statement import threading import logging import time import Queue class ThreadFunc(threading.Thread): """If it is needed to execute the function on another thread and stop is requiered. Otherwise, use thread.start_new_thread """ def __init__(self, function, args=(), kargs={}, start=True): threading.Thread.__init__(self, name=function.__name__) self.function = function self.args = args self.kargs = kargs self.active = threading.Event() self.active.set() if start: self.start() def cancel(self): self.active.clear() def run(self): self.function(*self.args, **self.kargs) class ThreadTimeout(threading.Thread): """ Run a function each interval seconds. Function must return 'True' to continue executing. Based on threding.Timer class """ def __init__(self, interval, function, args=[], at_init=False): threading.Thread.__init__(self, name=function.__name__) self.interval = interval # secs self.function = function self.args = args self.at_init = at_init self.finished = threading.Event() self.play = threading.Event() self.start() def __del__(self): self.cancel() def cancel(self): "terminates the thread" self.play.set() self.finished.set() def pause(self): self.play.clear() def play(self): self.play.set() def run(self): if self.at_init: if not self.function(*self.args): return while 1: self.finished.wait(self.interval) if self.finished.isSet(): break if not self.function(*self.args): break class EventPool(threading.Thread): '''Event pool based exclusively upon threads.''' class Task: def __init__(self, ctx, interval, func, args=[]): self.ctx = ctx self.interval = interval self.function = func self.args = args self.diff = interval def __repr__(self): return "%s.%s i:%s, d:%s" % (self.ctx.name, self.function.__name__, self.interval, self.diff) class Context: def __init__(self, poll, persistent, name=''): self.pool = poll self.persistent = persistent self.name = name self.tasks = [] self.reset = self.add def add_func(self, interval, func, *args): retval = EventPool.Task(self, interval, func, args) self.add(retval) return retval def new_task(self, interval, function, *args): return EventPool.Task(self, interval, function, args) def add(self, task): if task not in self.tasks: self.tasks.append(task) self.pool.add_task(task) return task def cancel(self, task=None): if isinstance(task, EventPool.Task): try: self.tasks.remove(task) except ValueError: return self.pool.cancel_task_now(task) return if task == None: task = self.tasks[:] if isinstance(task, list): for t in task: self.cancel(t) def __repr__(self): return repr(self.tasks) def __init__(self, persistent=True, name=None): threading.Thread.__init__(self, name=name) self.persistent = persistent self.name = name self.lock = threading.RLock() self.finished = threading.Event() self.__contexts = [] self.__tasks = [] self.__added = [] def new_context(self, persistent=True, name=''): # deny if thread is running ctx = EventPool.Context(self, persistent, name) self.__contexts.append(ctx) return ctx def add_task(self, task): self.__added.append(task) def cancel_task_now(self, task): self.lock.acquire() if task in self.__added: self.__added.remove(task) else: self.__cancel_task(task) self.lock.release() def close(self): self.finished.set() def __add_task(self, new_task): total = 0 for i,t in enumerate(self.__tasks): if total + t.diff > new_task.interval: new_task.diff = new_task.interval - total t.diff -= new_task.diff self.__tasks.insert(i, new_task) return total += t.diff new_task.diff = new_task.interval - total self.__tasks.append(new_task) def __cancel_task(self, task): if task not in self.__tasks: return i = self.__tasks.index(task) if len(self.__tasks) > i+1: self.__tasks[i+1].diff += task.diff self.__tasks.remove(task) def __pending(self): for t in self.__added: if t in self.__tasks: self.__cancel_task(t) self.__add_task(t) self.__added = [] # clear empty __contexts for c in self.__contexts: if not c.persistent and not c.tasks: self.__contexts.remove(c) if not self.persistent and not self.__contexts: self.finished.set() def run(self): while not self.finished.isSet(): self.lock.acquire() self.__pending() while self.__tasks and self.__tasks[0].diff <= 0: task = self.__tasks[0] self.__tasks.remove(task) result = task.function(*task.args) if result: self.__add_task(task) else: try: task.ctx.tasks.remove(task) except ValueError: pass if self.__tasks: self.__tasks[0].diff -= 1 self.lock.release() time.sleep(1) # from http://code.activestate.com/recipes/203871/ class ThreadPool: class JoiningEx: pass """ Flexible thread pool class. Creates a pool of threads, then accepts tasks that will be dispatched to the next available thread """ def __init__(self, numThreads): """Initialize the thread pool with numThreads workers """ self.__threads = [] self.__resizeLock = threading.Lock() self.__taskLock = threading.Condition(threading.Lock()) self.__tasks = [] self.__isJoining = False self.resize(numThreads) def resize(self, newsize): """ public method to set the current pool size """ if self.__isJoining: raise ThreadPool.JoiningEx() with self.__resizeLock: self.__resize(newsize) return True def __resize(self, newsize): """Set the current pool size, spawning or terminating threads if necessary. Internal use only; assumes the resizing lock is held.""" diff = newsize - len(self.__threads) # If we need to grow the pool, do so for i in range(diff): self.__threads.append(ThreadPool.Worker(self)) # If we need to shrink the pool, do so for i in range(-diff): thread = self.__threads.pop() thread.stop = True def __len__(self): """Return the number of threads in the pool.""" with self.__resizeLock: return len(self.__threads) def add(self, task, args=None, callback=None): """Insert a task into the queue. task must be callable; args and taskCallback can be None.""" assert callable(task) if self.__isJoining: raise ThreadPool.JoiningEx() with self.__taskLock: self.__tasks.append((task, args, callback)) self.__taskLock.notify() return True def nextTask(self): """ Retrieve the next task from the task queue. For use only by ThreadPoolWorker objects contained in the pool """ with self.__taskLock: while not self.__tasks: if self.__isJoining: raise ThreadPool.JoiningEx() self.__taskLock.wait() assert self.__tasks return self.__tasks.pop(0) def join(self, waitForTasks=True, waitForThreads=True): """ Clear the task queue and terminate all pooled threads, optionally allowing the tasks and threads to finish """ self.__isJoining = True # prevent more task queueing if waitForTasks: while self.__tasks: time.sleep(0.1) with self.__resizeLock: if waitForThreads: with self.__taskLock: self.__taskLock.notifyAll() for t in self.__threads: t.join() # ready to reuse del self.__threads[:] self.__isJoining = False class Worker(threading.Thread): """ Pooled thread class """ def __init__(self, pool): """ Initialize the thread and remember the pool. """ threading.Thread.__init__(self) self.__pool = pool self.stop = False self.start() def run(self): """ Until told to quit, retrieve the next task and execute it, calling the callback if any. """ while not self.stop: try: cmd, args, callback = self.__pool.nextTask() except ThreadPool.JoiningEx: break logging.debug("thread %s taken %s" % (self, cmd)) result = cmd(*args) if callback: callback(result) class SimpleThreadPool: def __init__(self, numThreads): self.tasks = Queue.Queue() self.threads = [SimpleThreadPool.Worker(self.tasks) for x in range(numThreads)] def add(self, func, args=None, callback=None): assert callable(func) self.tasks.put((func, args, callback)) def map(self, func, values): holders = [SimpleThreadPool.Holder() for x in range(len(values))] for value, callback in zip(values, holders): self.add(func, (value,), callback) self.join() return [x.value for x in holders] def join(self): self.tasks.join() class Worker(threading.Thread): def __init__(self, tasks): threading.Thread.__init__(self) self.tasks = tasks self.daemon = True self.start() def run(self): while 1: func, args, callback = self.tasks.get() logging.debug("thread %s taken %s", self, func) result = func(*args) self.tasks.task_done() if callback: callback(result) class Holder: def __init__(self): self.value = None def __call__(self, arg): self.value = arg atheist-0.20110402/pyarco/iniparser.py0000755000175000017500000000330211546632050016410 0ustar cletocleto#!/usr/bin/python # -*- coding:utf-8; tab-width:4; mode:python -*- import ConfigParser class IniParser(ConfigParser.SafeConfigParser): default_section = 'DEFAULT' class Section: def __init__(self, parser, section_name): self.parser = parser self.section_name = section_name def keys(self): return [k for k,v in self.items()] def items(self): return self.parser.items(self.section_name) def __getattr__(self, key): try: return self.parser.get(self.section_name, key) except ConfigParser.NoOptionError: raise AttributeError(key) def __str__(self): return "
" % (self.parser.fname, self.section_name) def __init__(self, fname=None): self.fname = fname ConfigParser.SafeConfigParser.__init__(self) if fname: self.read(fname) def keys(self): return self.Section(self, self.default_section).keys() def __getitem__(self, path): if '.' in path: section, key = path.split('.') else: section, key = self.default_section, path return getattr(self.Section(self, section), key) def __getattr__(self, section): if section.startswith('__'): raise AttributeError(section) if not self.has_section(section): raise ConfigParser.NoSectionError(section) return self.Section(self, section) def safe_get(self, path, default=None): try: return self[path] except AttributeError,e: if default is not None: return default raise atheist-0.20110402/pyarco/Net.py0000644000175000017500000000063411457026445015152 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- """net module provides functions for network programming .. moduleauthor:: Arco Research Group """ import socket def getFreePort(host=""): """Get a free port. :param host: The hostname. :type host: str. :returns: int -- the free port. """ s = socket.socket() s.bind((host, 0)) port = s.getsockname()[1] s.close() return port atheist-0.20110402/pyarco/test.py0000755000175000017500000000376511547300376015414 0ustar cletocleto#!/usr/bin/python # -*- coding:utf-8; tab-width:4; mode:python -*- # test utilities import os import io def path_to_items(path): if path == os.sep: return [] return path.strip(os.sep).split(os.sep) class FakeFileSystem: class FakeFile(io.BytesIO): def close(self): self.seek(0) def __init__(self, init=None): self.dirs = {'/': []} self.files = dict() if init is not None: self.files.update(init) def mkdir(self, path): if not path: raise OSError assert path.startswith(os.sep) if self.dirs.has_key(path): raise OSError path = path.strip(os.sep) items = path.split('/') for i in range(1, len(items)+1): key = os.sep + str.join(os.sep, items[:i]) if not self.dirs.has_key(key): self.dirs[key] = [] def listdir(self, path): try: # files retval = self.dirs[path][:] # directories path_items = path_to_items(path) lon = len(path_items) for dname in self.dirs: if path == dname: continue items = path_to_items(dname) if path_items != items[:lon]: continue if not items[lon] in retval: retval.append(items[lon]) return retval except KeyError: e = OSError() e.strerror = 'No such file or directory' e.filename = path raise e def open(self, fname, mode='r', relative=True): if 'r' in mode: try: return self.files[fname] except KeyError: e = IOError() e.strerror="No such file or directory" e.filename=fname raise e if 'w' in mode: self.files[fname] = FakeFileSystem.FakeFile() return self.files[fname] atheist-0.20110402/pyarco/fs.py0000755000175000017500000000034111546632050015024 0ustar cletocleto#!/usr/bin/python # -*- coding:utf-8; tab-width:4; mode:python -*- import os class ActualFileSystem: def open(self, fname, mode='r'): return open(fname, mode) def mkdir(self, path): os.mkdir(path) atheist-0.20110402/pyarco/Path.py0000644000175000017500000000072211457026445015316 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os def resolve_path(fname, paths, find_all=False): '''Busca fname en las rutas indicadas y devuelve la primera ruta completa dónde lo encuentre. Todas si se indica find_all''' retval = [] for p in paths: path = os.path.join(p, fname) if os.path.exists(path): if find_all: retval.append(path) else: return [path] return retval atheist-0.20110402/atheist.ice0000644000175000017500000000312011457026443014667 0ustar cletocleto// -*- mode: c++; coding: utf-8 -*- #include module Atheist { enum Status {FAIL, OK, NOEXEC, ERR, UNKNOWN, RUNNING, TODO}; dictionary StatusDict; struct TaskStatus { Status value; StatusDict conditions; }; dictionary TaskStatusDict; struct TaskConfig { int indx; string tid; bool ckeck; string cwd; int delay; string desc; bool detach; // dict env; int expected; bool mustFail; string path; int timeout; // bool saveStdout; // bool shell; int signal; string stdout; Status value; long age; }; dictionary TaskConfigDict; interface TaskCase { void run(); TaskConfigDict getConfig(); StatusDict getStatus(); }; sequence TaskCaseSeq; interface StatusObserver { void updateTasks(StatusDict val); void updateTaskCases(StatusDict val); void updateManager(Status val); }; interface OutObserver { void append(string taskID, string val); }; enum LogLevel {CRITICAL, ERROR, WARNING, INFO, DEBUG}; struct LogEntry { LogLevel level; int time; string msg; }; sequence LogEntrySeq; interface LogObserver { void append(string taskID, LogEntrySeq val); }; interface Manager { TaskCaseSeq getTaskCases(); void runAll(); void attachStatusOb(StatusObserver* ob); void attachOutOb(OutObserver* ob, Ice::StringSeq taskIds); void attachLogOb(LogObserver* ob, Ice::StringSeq taskIds); }; }; atheist-0.20110402/ChangeLog0000644000175000017500000001203511457026703014322 0ustar cletocleto# date +%Y.%m.%d 2010.10.18 * exec_file: ignore not existant test files (like emacs .#...#) * TypedList.__init__: optional initial values argument * Condition inherites from 'object' * FileContains.before: if file is stdout does not requires create * exists condition in its own * NEW ConditionDecorator.__eq__: Same class and same children * Task: NEW 'loglevel' key per logging by task * Task: NEW 'wrap_outs' attribute to ask out wrapping from subclasses * NEW Task.is_running() method * NEW Task.terminate() method * CompositeTask.__init__: children is now a TypedList(Task) * TaskCase.create_gen_list -> TaskCase.save_dirty_filelist * Reporter.build_task: 'na' for 'retcode' in not proccess tasks * atheist.clean_generated -> atheist.remove_generated * ConfigFacade.get_item -> ConfigFacade.get * NEW Manager._check_option_conflicts_and_ilegals() * utils.IniParser is replaced by iniparse.INIConfig * NEW cmdline and config option 'ignore' to exclude files by pattern * NEW cmdline option 'disable-bar' to disable progress-bar * atheist/utils.py: remove old code, now in pyarco * plugins/doctest: redirect output using Task.wrap_outs * NEW plugins/manual_repeat_runner: --again cmdline option * plugins/task_management/TaskRunning: use Task.is_running() instead * of 'ps' attribute. * plugins/unittest: now uses Task.wrap_outs * plugins/until_fail_runner: it is incompatible with --keep-going 2010.08.22 * atheist: ConfigFacade for optparse and iniparse. * pyarco.Logging: lazy connect for JabberHandler. 2010.08.21 * atheist: New base class 'Reporter' to implement pluggable reporters. * atheist: ConsoleReporter is the built-in reporter. * atheist: New class 'FailReporter' for reporters that are executed only when some task fails. * atheist: JabberReporter and SMPT_Reporter are now pluggins (inherit from FailReporter) * atheist: tree_draw() is now in atheist/utils.py * atheist: * pyarco.Logging: bugfix: needs to import 'string' and 'types' 2010.08.15 * atheist: New --version option. * atheist: Execution control in athcmd goes to the Runner class. * atheist: mgr.abort is now a method, with observers. * atheist: New method Plugin.config(). * atheist: argparser definition from athcmd.py to atheist/manager.py * atheist: new function create_logger in log.py * atheist: @public decorator for function callable form .test files. * atheist: Avoid extra attributes in Manager.config. * atheist: Random seed with --random=0 * atheist: New NotifyRunner (as plugin) * atheist: New UntilFailRunner (as plugin) * atheist: help.test does not able to plugin options. * pyarco.UI: New method ProgressBar.reset() 2010.07.17 * pyarco.Type: SortedDict may be init from a list o tuples * pyarco.Type: SortedDict accepts a 'default' argument in constructor * pyarco.Pattern: Flyweight 2010.07.11 * atheist: .gen accepts now a tuple of strings. * atheist: OpenPort condition goes to the new "net" plugin * atheist: OpenPort does not use nmap, use Python sockets instead. * atheist: New key "dirty" for tasks. * atheist: New API function "temp_name()" to get temporary filenames inside the .test file 2010.07.09 * pyarco: Removing all ostream staff from pyarco/UI. Now only cout() and cout_config() * pyarco: UI.ProgressBar may be interrupted by a logger with listen_logger() * atheist: compath() is now a function with attributes instead of a singleton class. * atheist: Log is in gvar (global variables) module. * atheist: dirty-mode warnings about not removed files. 2010.07.08 * atheist: fullbasedir and fulltestdir added 2010.07.05 * Fixes in compath() for curdir. * atheist: Directories are now sorted at test loading. 2010.06.30 * atheist: process_directory sorts subdirectories 2010.06.20 * atheist: $dirname -> $testdir 2010.06.13 * atheist: plugins/webtesting.py: WebTest using curl. * atheist: now works with python2.5 2010.05.23 * pyarco: ostream class to make transparent the use of terminal color scaping * atheist logger is now on atheist/log.py * skip-setup is now "setup-hooks" (documentation and manpage changed) * pyarco: making Singleton thread-safe * pyarco: ProgressBar ETA estimation modified, now updates only one time per second 2010.05.22 * Multiple tasks may be checked with TaskFinished and TaskRunning. * FileContains allow specify 'whole' content and 'strip' of file. * New Task hierarchy. 2010.01.20 * Multiple task may be killed in TaskTerminator. 2009.11.03 * Minimal bug in the ConsoleSummaryRender. * IniParser does not requires ".atheist". * -f: show output only for failed tasks. 2009.11.02 * notifiers for console, jabber and mail (SMTP). * Test -> Task * argument 'check' to difference tests and non-tests 2009.10.06 * variable substitution in the "include" statement 2009.09.18 * "id" attributed renamed to "tid" * 'tests/cmd_not_found.test' fixed * condition stores its value whenever is executed 2009.09.14 * "id" duplicity is checked only within the TestCase instead of all the tests. %%% Local Variables: %%% mode: flyspell %%% ispell-local-dictionary: "american" %%% End: atheist-0.20110402/client.py0000755000175000017500000000473211457026443014411 0ustar cletocleto#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time import gobject import logging import Ice Ice.loadSlice('-I%s atheist.ice' % Ice.getSliceDir()) import Atheist import atheist.log log = logging.getLogger() log.setLevel(logging.DEBUG) log.addHandler(atheist.log.create_basic_handler()) class StatusObserverI(Atheist.StatusObserver): def updateTasks(self, tasks, current=None): log.info("statusOb Task: %s" % tasks) def updateTaskCases(self, cases, current=None): log.info("statusOb TaskCase: %s" % cases) def updateManager(self, value, current=None): log.info("statusOb Manager: %s" % value) class OutObserverI(Atheist.OutObserver): def update(self, taskID, val, current=None): print taskID, val class LogObserverI(Atheist.LogObserver): def update(self, taskID, entry, current=None): print taskID, entry class client(Ice.Application): def run(self, argv): self.shutdownOnInterrupt() ic = self.communicator() adapter = ic.createObjectAdapterWithEndpoints("Client", "default") base = ic.stringToProxy(ic.getProperties().getProperty("Manager.Proxy")) print base self.mng = Atheist.ManagerPrx.checkedCast(base) if not self.mng: raise RuntimeError("Invalid proxy") self.mng.attachStatusOb( Atheist.StatusObserverPrx.uncheckedCast( adapter.addWithUUID(StatusObserverI()))) self.mng.attachOutOb( Atheist.OutObserverPrx.uncheckedCast( adapter.addWithUUID(OutObserverI())).ice_batchOneway(), []) self.mng.attachLogOb( Atheist.LogObserverPrx.uncheckedCast( adapter.addWithUUID(LogObserverI())).ice_batchOneway(), []) adapter.activate() self.callbackOnInterrupt() gobject.threads_init() gobject.timeout_add(3, self.event) self.loop = gobject.MainLoop() self.loop.run() self.communicator().shutdown() return 0 def interruptCallback(self, args): gobject.idle_add(self.loop.quit) def event(self): print 'Event!' cases = self.mng.getTaskCases() if cases: print len(cases), "task cases" print cases[0].getConfig() self.mng.ice_oneway().runAll() print "FIN ------------" gobject.timeout_add(20000, self.event) return False if __name__ == "__main__": sys.exit(client().main(sys.argv)) atheist-0.20110402/.pc/0000755000175000017500000000000011412462700013217 5ustar cletocletoatheist-0.20110402/.pc/.version0000644000175000017500000000000211406126245014701 0ustar cletocleto2 atheist-0.20110402/.pc/.quilt_series0000644000175000017500000000000711406126245015731 0ustar cletocletoseries atheist-0.20110402/.pc/.quilt_patches0000644000175000017500000000001711406126245016067 0ustar cletocletodebian/patches atheist-0.20110402/test/0000755000175000017500000000000011546304257013530 5ustar cletocletoatheist-0.20110402/test/load.test0000644000175000017500000000035311457026445015352 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- import sys, os sample = load("$testdir/files/sample.pt") def f(): val = sample.included_func() print val return not (sys.platform, os.getpid()) == val TestFunc(f) sample.factory() atheist-0.20110402/test/load-fail-by-missing-func.mtest0000644000175000017500000000015711523712750021445 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- sample = load("$testdir/files/sample.pt") TestFunc(sample.missing_func) atheist-0.20110402/test/remove_gen.mtest0000644000175000017500000000050611457026445016736 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- f = "/tmp/generated" g = Test('touch %s' % f) g.post += FileExists(f) g.gen += f # Don't remove file until all other tasks finished d = Daemon('while true; do if [ ! -f %s ]; then exit 1; fi; done' % f, shell=True, delay=2) d.pre += FileExists(f) d.post += FileExists(f) atheist-0.20110402/test/wrong_keyword.mtest0000644000175000017500000000003511457026445017505 0ustar cletocleto Test('ls', not_exists=True) atheist-0.20110402/test/list-only.test0000644000175000017500000000053411527474305016366 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os def test_files(): return [x for x in os.listdir('$testdir') if x.endswith('.test')] t = Test('$atheist -l $testdir', timeout=10) for f in sorted(test_files()): if os.path.exists(os.path.join('$testdir', f)): t.post += FileContains(f) else: t.post += Not(FileContains(f)) atheist-0.20110402/test/DebPkgInstalled.mtest0000644000175000017500000000027111457026445017603 0ustar cletocleto# -*- mode: python; coding:utf-8 -*- Test(None, desc="Is bash installed?").pre += DebPkgInstalled('bfash') Test(None, desc="Is bash version >= 4").pre += DebPkgInstalled('bash', '4') atheist-0.20110402/test/fileEquals.test0000644000175000017500000000067511457377464016546 0ustar cletocleto# -*- mode: python -*- import logging this_file = '$testdir/$testname.test' t1 = Test('cat %s | cat' % this_file, shell=True, desc="FileEquals") t1.post += FileEquals(this_file) t2 = Test('ncat --send-only -l 3010 < %s' % this_file, shell=True, detach=True, timeout=0) t2.pre += Not(OpenPort(3010)) t3 = Test('ncat localhost 3010') t3.pre += Poll(TaskRunning(t2)) t3.pre += Poll(OpenPort(3010)) t3.post += FileEquals(this_file) atheist-0.20110402/test/clean.test0000644000175000017500000000236411546304257015520 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- import os from atheist.const import ATHEIST_TMP_BASE fname = os.path.join(ATHEIST_TMP_BASE, '$testname') Command('rm -f %s*' % fname) def filename(n): return '{0}-{1}'.format(fname, n) def touch(n): return "Test('echo hola > {0}', shell=True).gen += '{0}'".format(filename(n)) def exists(n): return FileExists(filename(n)) t2 = Test('$atheist -vvo --dirty -s "%s"' % touch(1), shell=True, desc="Check file creation (--dirty mode)") t2.post += exists(1) t3 = Test('rm %s-1' % fname) t3.pre += exists(1) t3.post += Not(exists(1)) t4 = Test('$atheist -s "%s"' % touch(2), shell=True, desc="Clean after test (default)") t4.pre += Not(exists(2)) t4.post += Not(exists(2)) t5 = Test('$atheist -vvo --dirty -s "%s"' % touch(3), shell=True, desc="Check file creation (--dirty mode)") t5.post += exists(3) t6 = Test('$atheist -C -s "%s"' % touch(3), shell=True, desc="-C: Clean only") t6.pre += exists(3) t6.post += Not(exists(3)) # clean also when test fails touch_fail = "Test('touch {0}; exit 1', shell=True).gen += '{0}'".format(filename(4)) t7 = Test('$atheist -s "%s"' % touch_fail, expected=1, shell=True, desc="clean even when fails (default)") t7.post += Not(exists(4)) atheist-0.20110402/test/files/0000755000175000017500000000000011547304457014635 5ustar cletocletoatheist-0.20110402/test/files/package.py0000644000175000017500000000010311457026444016571 0ustar cletocleto def sample(): """ >>> sample() 1 """ return 1 atheist-0.20110402/test/files/sample.pt0000644000175000017500000000031611457026444016460 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- import sys, os def included_func(): return sys.platform, os.getpid() def error_func(): print time.time() return 0 def factory(): return Test('ls') atheist-0.20110402/test/files/module.py0000644000175000017500000000007511457026444016473 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- TEXT="sample package" atheist-0.20110402/test/test_func.mtest0000644000175000017500000000277711457026445016616 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- # Copyright (C) 2009 David Villa Alises # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA def ok(): return 0 TestFunc(ok, (), desc="Test a python function") #-- def return3(): return 3 TestFunc(return3, (), expected=3, desc="Expect an specific value") #-- # import os # def changeCWD(d): # if os.getcwd() != d: return 1 # return 0 # # TestFunc(changeCWD, (os.path.abspath("$testdir/files"),), cwd="$testdir/files", # desc="TestFunc accepts 'cwd' param") # -- # Task(None) #.pre += FileExists('/etc/hosts') # Task("true") ## Test if stdout can be saved on TestFunc #def printSomething(msg): # print msg # return True # #msg = "Test message" #t = TestFunc(printSomething, [msg], save_stdout=True, # desc="stdout control for Task1Funcs") #t.post += FileContains(t.stdout, msg) atheist-0.20110402/test/touch_tmp_kk.mtest0000644000175000017500000000021211457026445017271 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- t = Test('touch /tmp/$testname') t.post += FileExists('/tmp/$testname') t.gen += '/tmp/$testname' atheist-0.20110402/test/doctest.test0000644000175000017500000000015411457026445016077 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- DocTest('atheist.utils') DocTest('package', cwd='$testdir/files') atheist-0.20110402/test/dir_gen.test0000644000175000017500000000053511546304257016043 0ustar cletocleto# -*- mode: python -*- import os dname = temp_name() mkdir = """t = Test('mkdir -p %(dname)s') t.gen += '%(dname)s' """ % locals() t = Test("$atheist -s \"%s\"" % mkdir, shell=True, desc="Create a directory [inline]") Command('rmdir %s' % dname, shell=True) Test('ls %s' % dname, must_fail=True, desc="Check directory deletion") atheist-0.20110402/test/auto-exists.test0000644000175000017500000000113411546304257016715 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- t = Test("$atheist $testdir/auto-exists.mtest", save_stderr=True, expected=1) t.post += FileContainsRE(r"pre: Not \(FileExists '/tmp/atheist-.+/([0-9]+)/T1.out'", t.stderr) t.post += FileContainsRE("post: FileExists '/tmp/atheist-.+/([0-9]+)/T1.out", t.stderr) contents = [ "post: FileExists '/other/file'", "post: FileContains '/some/file'", "post: FileExists '/some/file'", "post: Not (FileContains '/other/file'" ] for c in contents: t.post += FileContains(c, t.stderr) t.post += Not(FileContains(c, t.stderr, times=2)) atheist-0.20110402/test/_SETUP.test0000644000175000017500000000021411523712750015461 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- t = Test(None) t.post += DebPkgInstalled('cdbs') t.post += DebPkgInstalled('python-mock') atheist-0.20110402/test/hello-utf8.test0000644000175000017500000000013711523712750016415 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test('echo "hello world! ñú"', desc="trivial test") atheist-0.20110402/test/conditions-net.test0000644000175000017500000000133411457026445017370 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import logging this_file = '$testdir/$testname.test' t1 = Test('cat %s | cat' % this_file, shell=True, desc="FileEquals") t1.post += FileEquals(this_file) t2 = Test('ncat --send-only -l 2000 < %s' % this_file, shell=True, detach=True, timeout=0) t2.pre += Not(OpenPort(2000)) t3 = Test('ncat localhost 2000') t3.pre += Poll(TaskRunning(t2)) t3.pre += Poll(OpenPort(2000)) t3.post += FileEquals(this_file) # TaskFinished tests t4 = Test("true", desc="TaskFinished using a finished task") t4.pre += Poll(TaskFinished(t1), interval=0.5) d1 = Daemon('ncat -l localhost') t6 = Test("true", desc="TaskFinished using a running task") t6.pre += Poll(Not(TaskFinished(d1)), interval=0.5) atheist-0.20110402/test/logging-issues.test0000644000175000017500000000040611526204745017367 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- msg = 'atheist logger do not show this message' t = Test('$atheist $basedir/test/log-from-tests.test', save_stdout=True, save_stderr=True) t.post += Not(FileContains(msg, t.stdout)) t.post += Not(FileContains(msg, t.stderr)) atheist-0.20110402/test/env.test0000644000175000017500000000116611527474305015226 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- opts = "" # undefined -> define Test("$atheist -v %s $testdir/env.mtest" % opts, timeout=10, env={"VAR_UA":"var defined", "VAR_DA":"former value", "VAR_DOI":"former", "VAR_SUFFIX":"suffix"}) # defined -> replace Test("$atheist -v %s $testdir/env.mtest" % opts, timeout=10, env={"VAR_DA":"former value", "VAR_DOI":"former", "VAR_SUFFIX":"suffix"}) t = Test(""" export SAMPLE_VAR="hola" $atheist -o -s 'Test("echo $SAMPLE_VAR", shell=True)' """, timeout=10, shell=True) t.post += FileContains("hola") atheist-0.20110402/test/detach.test0000644000175000017500000000027211527474305015663 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- test = "for i in range(10): Test('sleep 2', detach=True)" t = Test('$atheist -v -s "%s"' % test, shell=True, timeout=12) t.post += TimeLessThan(10) atheist-0.20110402/test/signal_capture.py0000644000175000017500000000215411457026445017105 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- # Copyright (C) 2009 David Villa Alises # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import signal, time import sys import atexit abort = False def abort_handler(signal, frame): global abort print "C-c pulsado" sys.stdout.flush() abort = True signal.signal(signal.SIGINT, abort_handler) #atexit.register(abort_handler, 0,0) while 1: time.sleep(1) if abort: print 'quit' break sys.exit(3) atheist-0.20110402/test/log-from-tests.test0000644000175000017500000000045611524504450017311 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import logging logging.error('atheist logger do not show this message') log = logging.getLogger("1") log.addHandler(logging.StreamHandler()) def use_logging(arg): log.error("hi %s" % arg) return 0 TestFunc(use_logging, [1]) TestFunc(use_logging, [2]) atheist-0.20110402/test/basedir.test0000644000175000017500000000020511546304257016037 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- fname = '$basedir/kk' t = Test('echo hi > %s' % fname, shell=True) t.gen += fname atheist-0.20110402/test/plugin/0000755000175000017500000000000011547304457015031 5ustar cletocletoatheist-0.20110402/test/plugin/cxxtest-todo.mtest0000644000175000017500000000026711523712750020552 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- import os fname = os.path.join('$tmp', "sample.c") t = Test("touch " + fname, shell=True) t.gen += fname CxxTest(fname, todo=True) atheist-0.20110402/test/plugin/cxxtest-keywords.test0000644000175000017500000000032711546304257021300 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- t = Test('$atheist $testdir/cxxtest-todo.mtest', save_stderr=True, timeout=10) t.post += FileContains('[ToDo] TaskCase: ./test/plugin/cxxtest-todo.mtest', t.stderr) atheist-0.20110402/test/plugin/path.test0000644000175000017500000000034311475251202016653 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- t = Test("$atheist -p missing-path test/hello.test", expected=2, save_stderr=True) t.post += FileContains("error: plugin directory 'missing-path' not exist", t.stderr) atheist-0.20110402/test/plugin/imap.test0000644000175000017500000000046411474750346016665 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- # NOTE: you need to add a valid IMAP account to pass this test account = IMAP('imap', misconfig=True) todayMails = account.filter("(ON 14-Nov-2010)") for match in ["subject test1", "subject test 2"]: todayMails.post += todayMails.findOnSubjects(match) atheist-0.20110402/test/plugin/cxxtest.test0000644000175000017500000000112711523712750017426 0ustar cletocleto#!/usr/bin/python # -*- mode:python; coding:utf-8; tab-width:4 -*- single = CxxTest('$testdir/cxxtest/single_ok.cc') multiple = CxxTest('$testdir/cxxtest/multi_ok.cc') header = CxxTest('$testdir/cxxtest/with_header.cc', compiling_flags='-I$testdir/cxxtest') make = Command('rm $testdir/cxxtest/*.o; CC=g++ make -C $testdir/cxxtest add.o', shell=True) make.gen += '$testdir/cxxtest/add.o' extern_obj = CxxTest('$testdir/cxxtest/with_extern_obj.cc', compiling_flags='-I$testdir', objs={'$testdir/cxxtest/': ['add.o']}) atheist-0.20110402/test/plugin/until-fail-runner.test0000644000175000017500000000147111527474305021306 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os import signal tmptest = os.path.join('$tmp','$testname-hello.test') cp = Test('cp $basedir/test/hello.test %s' % tmptest, shell=True) cp.gen += tmptest repeater = Test('$atheist --until-fail %s' % tmptest, save_stdout=True, save_stderr=True, detach=True, timeout=0, signal=signal.SIGINT, expected=1) repeater.post += FileContains('[FAIL] `- Test-2 -( 1: 0) false', repeater.stderr) fail = Test("echo -e \"\nTest('false')\" >> %s; sync" % tmptest, shell=True) fail.pre += Poll(TaskRunning(repeater)) fail.pre += FileExists(repeater.stdout) fail.pre += Poll(FileContains("ALL OK, repeat until failure:", repeater.stdout, times=2)) TaskTerminator(repeater, delay=2) atheist-0.20110402/test/plugin/xunit.test0000644000175000017500000001175511546304257017107 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- import unittest import StringIO from mock import Mock from atheist import Suite from atheist.const import * from atheist.plugins.xunit_reporter import XUnit_Reporter XML_HEAD = '' class StrIO(StringIO.StringIO): def __enter__(self): pass def __exit__(self, *args): pass class Test_XUnit(unittest.TestCase): def setUp(self): self.config = Mock() self.sut = XUnit_Reporter(self.config) self.sut.with_hostname = False self.sut.with_time = False def tearDown(self): pass def create_test(self, name): retval = Mock() retval.name = name retval.result = OK retval.stdout = retval.stderr = '/dev/null' retval.persistent_log = StrIO() return retval def create_case(self, casename, testprefix, num): case = Mock() case.name = casename case.tasks = [] result = '' for i in range(num): testname = '%s_%s' % (testprefix, i) test = self.create_test(testname) case.tasks.append(test) return case def create_suite(self, cases=0, tests_per_case=0): retval = Suite() for i in range(cases): retval.append(self.create_case('TestCase%s' % i, 'test', tests_per_case)) return retval def sut_render_to_str(self, suite): fd = StrIO() for case in suite: self.sut.add_case(case) self.sut.render(suite, fd) return fd.getvalue() def test_case_1_OK(self): case = self.create_case('TestCase0', 'test', 1) result = '''\ \ \ \ \ \ ''' print self.sut._render_case(case) self.assertEquals(result, self.sut._render_case(case)) def test_case_2_OK(self): case = self.create_case('Foo', 'test_number', 2) result = '''\ \ \ \ \ \ \ \ \ \ \ \ ''' print self.sut._render_case(case) self.assertEquals(result, self.sut._render_case(case)) def test_empty_suite(self): result = XML_HEAD + '''\ \ \ ''' self.assertEquals(result, self.sut_render_to_str(Suite())) def test_suite_1_OK(self): suite = self.create_suite(1, 1) result = XML_HEAD + '''\ \ \ \ \ \ \ \ \ ''' rendered = self.sut_render_to_str(suite) print rendered self.assertEquals(result, rendered) def test_suite_2_cases_2_tests_OK(self): suite = self.create_suite(cases=2, tests_per_case=2) result = XML_HEAD + '''\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ''' rendered = self.sut_render_to_str(suite) print rendered self.assertEquals(result, rendered) def test_suite_1_FAIL(self): suite = self.create_suite(cases=1, tests_per_case=1) suite[0].tasks[0].result = FAIL result = XML_HEAD + '''\ \ \ \ \ \ \ \ \ \ ''' rendered = self.sut_render_to_str(suite) print rendered self.assertEquals(result, rendered) def test_suite_1_FAIL_1_OK(self): suite = self.create_suite(cases=1, tests_per_case=2) suite[0].tasks[0].result = FAIL result = XML_HEAD + '''\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ''' rendered = self.sut_render_to_str(suite) print rendered self.assertEquals(result, rendered) UnitTestCase(Test_XUnit) atheist-0.20110402/test/plugin/smtp.test0000644000175000017500000000051611523712750016710 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- import time uniq = str(time.time()) smtp = SMTP('smtp', misconfig=True) smtp.send('arco.logging@gmail.com', subject=uniq, data='hello mail again') imap = IMAP('imap', delay=10, misconfig=True) mailset = imap.filter('UNSEEN', todo=True) mailset.post += mailset.findOnSubjects(uniq) atheist-0.20110402/test/plugin/FileContainsRE.test0000644000175000017500000000156011546304257020536 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- import re import unittest from atheist.plugins.FileContainsRE import FileContainsRE class Test_FileContainsRE_check(unittest.TestCase): def setUp(self): self.sut = FileContainsRE.check def test_2_ocurrences(self): self.assertEquals(2, self.sut("hello", "rehellopojahellofai asd")) def test_unbalanced_parenthesis(self): try: self.sut("(he", "hello") except re.error: return self.fail() def test_escaped_parenthesis(self): self.assertEquals(1, self.sut("\( \w+", "( hello")) def test_real_life_example(self): self.assertEquals(1, self.sut( "pre: Not \(FileExists '/tmp/\w+-\w+/([0-9]+)/T1.out'", "pre: Not (FileExists '/tmp/atheist-david/10243/T1.out'")) UnitTestCase(Test_FileContainsRE_check) atheist-0.20110402/test/plugin/inotify-runner-watch-tests.test0000644000175000017500000000157311527474305023172 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os import signal tmptest = os.path.join('$tmp','$testname-hello.test') cp = Test('cp $basedir/test/hello.test %s' % tmptest, shell=True) cp.gen += tmptest watch = Test('$atheist --watch-tests %s' % tmptest, save_stderr=True, detach=True, timeout=0, signal=signal.SIGINT) for i in range(1,3): mod = Test('echo -e " " >> %s; sync' % tmptest, delay=1, shell=True) if i == 1: mod.pre += Poll(TaskRunning(watch)) mod.post += Poll(FileContains("[ OK ] TaskCase: %s" % tmptest, watch.stderr, times=i), timeout=10) error = Test("echo -e \"\nTest('false')\" >> %s; sync" % tmptest, shell=True) error.post += Poll(FileContains("[FAIL]", watch.stderr), timeout=10) killer = TaskTerminator(watch, delay=2) killer.pre += Poll(TaskRunning(watch)) atheist-0.20110402/test/plugin/webtest.test0000644000175000017500000000010711523712750017376 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- WebTest('https://www.google.com') atheist-0.20110402/test/plugin/inotify-runner-watch-dir.test0000644000175000017500000000124411527474305022601 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os import signal token = os.path.join('$tmp','token') test = './test/hello.test' watch = Test('$atheist --watch-file $tmp %s' % test, save_stderr=True, detach=True, timeout=0, signal=signal.SIGINT) for i in range(1,3): mod = Test('echo -e " " >> %s; sync' % token, delay=0.5, shell=True) if i == 1: mod.gen += token mod.pre += Poll(TaskRunning(watch)) mod.post += Poll(FileContains("[ OK ] TaskCase: %s" % test, watch.stderr, times=i), timeout=10) killer = TaskTerminator(watch) killer.pre += Poll(TaskRunning(watch)) atheist-0.20110402/test/plugin/cxxtest/0000755000175000017500000000000011547304457016533 5ustar cletocletoatheist-0.20110402/test/plugin/cxxtest/with_header.cc0000644000175000017500000000035011523712750021314 0ustar cletocleto// MyTestSuite.h #include #include "add.h" int add(int a, int b) { return a+b; } class MyTestSuite : public CxxTest::TestSuite { public: void testAddition(void) { TS_ASSERT(add(1,1) == 2); } }; atheist-0.20110402/test/plugin/cxxtest/add.h0000644000175000017500000000003011523712750017416 0ustar cletocleto int add(int a, int b); atheist-0.20110402/test/plugin/cxxtest/single_ok.cc0000644000175000017500000000032411523712750021004 0ustar cletocleto// MyTestSuite.h #include class MyTestSuite : public CxxTest::TestSuite { public: void testAddition( void ) { TS_ASSERT( 1 + 1 > 1 ); TS_ASSERT_EQUALS( 1 + 1, 2 ); } }; atheist-0.20110402/test/plugin/cxxtest/with_extern_obj.cc0000644000175000017500000000031011523712750022217 0ustar cletocleto// MyTestSuite.h #include #include class MyTestSuite : public CxxTest::TestSuite { public: void testAddition(void) { TS_ASSERT(add(1,1) == 2); } }; atheist-0.20110402/test/plugin/cxxtest/multi_ok.cc0000644000175000017500000000055611523712750020664 0ustar cletocleto// MyTestSuite.h #include class MyTestSuite : public CxxTest::TestSuite { public: void testAddition( void ) { TS_ASSERT( 1 + 1 > 1 ); } void testDiff( void ) { TS_ASSERT( 1 - 1 == 0 ); } void testMult(void) { TS_ASSERT((10*2) == 20); } void testDiv(void) { TS_ASSERT((10/2) == 5); } }; atheist-0.20110402/test/plugin/cxxtest/add.c0000644000175000017500000000007311523712750017420 0ustar cletocleto#include "add.h" int add(int a, int b) { return a+b; } atheist-0.20110402/test/hooks.test0000644000175000017500000000107011546304257015552 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os from atheist.const import ATHEIST_TMP_BASE fname = os.path.join(ATHEIST_TMP_BASE, 'hook-log') t1 = Test('touch ' + fname) t1.gen += fname t2 = Test('$atheist -vv -i2 $testdir/hooks/hello.mtest', save_stderr=True) t2.post += FileContains(['_setup ran', 'test ran', '_teardown ran'], fname) t2.post += FileContains(['Test-1 s( 0: 0) echo "_setup ran"', 'Test-2 -( 0: 0) echo "test ran"', 'Test-3 t( 0: 0) echo "_teardown ran"'], t2.stderr) atheist-0.20110402/test/send-signal.test0000644000175000017500000000176211546304257016643 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- # Copyright (C) 2009 David Villa Alises # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import signal a = Test('python $testdir/signal_capture.py', detach=True, timeout=10, signal=signal.SIGINT, expected=3, save_stdout=True) a.post += FileContains("quit") TaskTerminator(a, delay=2) atheist-0.20110402/test/dirty.test0000644000175000017500000000105311546304257015563 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os from atheist.const import ATHEIST_TMP_BASE fname_a = os.path.join(ATHEIST_TMP_BASE, 'dirty-touch-a') fname_b = os.path.join(ATHEIST_TMP_BASE, 'dirty-touch-b') t = Test('$atheist $testdir/dirty-touch.mtest', save_stderr=True, desc="'dirty' key for individual tests") t.gen += fname_a, fname_b t.post += FileContains( ["[WW] T1: 'dirty' without 'gen' has no sense.", "[WW] T1: dirty-task, not removing gen: []", "[WW] T2: dirty-task, not removing gen: ['%s']" % fname_b], t.stderr) atheist-0.20110402/test/TESTS0000644000175000017500000000032711457026445014360 0ustar cletocleto * Atheist informa de que Daemon no puede usar los atributos fijos si se intenta. * El .test, unitests y TaskFunc pueden usar stdout, stderr y loggin para sus mensajes. * Make test for syntax errors in .test files atheist-0.20110402/test/description-latin-1.test0000644000175000017500000000015311523712750020212 0ustar cletocleto# -*- mode:python; coding:latin-1; tab-width:4 -*- Test('true', desc="descripcin con tildes en latin-1") atheist-0.20110402/test/classes.test0000644000175000017500000000021411457026445016064 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- Test('true') Command('true') Daemon('true') TestFunc(lambda:0) t = Test('true') CompositeTask(all, t) atheist-0.20110402/test/clean-outs.test0000644000175000017500000000167111546304257016510 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- ls_out = "Test('ls', shell=True, save_stdout=True)" rm_out = "\[DD\] - removing file '/tmp/atheist-.+/[0-9]+/T1." t1 = Test('$atheist -vv -s "%s"' % ls_out, shell=True, save_stderr=True, desc="Remove saved stdout") t1.post += FileContainsRE(rm_out+'out', t1.stderr) t2 = Test('$atheist -vv --dirty -s "%s"' % ls_out, shell=True, save_stderr=True, desc="NOT remove saved stdout") t2.post += Not(FileContainsRE(rm_out+'out', t2.stderr)) ls_err = "Test('ls 1>&2', shell=True, save_stderr=True)" t3 = Test('$atheist -vv -s "%s"' % ls_err, shell=True, save_stderr=True, desc="Remove saved stderr") t3.post += FileContainsRE(rm_out+'err', t3.stderr) t4 = Test('$atheist -vv --dirty -s "%s"' % ls_err, shell=True, save_stderr=True, desc="NOT remove saved stderr") t4.post += Not(FileContainsRE(rm_out+'err', t4.stderr)) # assure the stdout files are clean # FIXME atheist-0.20110402/test/params.test0000644000175000017500000000047611457026445015724 0ustar cletocleto# -*- mode: python; coding:utf-8 -*- task = "Test('ls', not_exists=True)" t = Test('$atheist -s "%s"' % task, save_stderr=True, shell=True, desc="Checking invalid Test keys", must_fail=True) t.post += FileContains("AssertionError: 'not_exists' is not a valid keyword", t.stderr) atheist-0.20110402/test/hello-with-conditions.test0000644000175000017500000000021111457026445020647 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test('echo "hello world!"') t.pre += AtheistVersion('0.2010') t.post += DebPkgInstalled('bash') atheist-0.20110402/test/load-fail-by-missing-module.mtest0000644000175000017500000000013611523712750021774 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- sample = load("$testdir/missing_path/missing_file.py") atheist-0.20110402/test/duplicate-id.test0000644000175000017500000000047111527474305017000 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- test = """ Test(None, tid='foo') Test(None, tid='bar') Test(None, tid='foo') """ t = Test('$atheist -s "%s"' % test, shell=True, must_fail=True, save_stderr=True, desc="Check duplicate task ids") t.post += FileContains("Duplicate task id: 'foo'", t.stderr) atheist-0.20110402/test/sample_config0000644000175000017500000000051211475251202016247 0ustar cletocleto# -*- mode: conf -*- [ui] ignore = #*,*~,*.impossible [jabber] user = jabber.user@gmail.com pasw = 23456 [imap] host = example.org port = 220 user = user pasw = 12345 [smtp:smtp.user] host = smtp.gmail.com port = 587 user = smtp.user@gmail.com pasw = 12345 [smtp:google] host = google.com port = 25 [vars] myname = John Doe atheist-0.20110402/test/cmd-not-found.test0000644000175000017500000000054411524504450017077 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- for s in ['True', 'False']: test = "Test('lss /tmp', shell=%s)" % s t = Test('$atheist -s "%s"' % test, shell=True, must_fail=True, save_stderr=True, desc="Invoking a not existing cmd with shell=%s" % s) t.post += FileContains("No such file or directory: 'lss /tmp'", t.stderr) atheist-0.20110402/test/wrong-condition.mtest0000644000175000017500000000003611546304257017725 0ustar cletocleto a = Test('true') a.pre += 2 atheist-0.20110402/test/testfunc.test0000644000175000017500000000125211523712750016260 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- hello = FileContains("F1:out| hello!!") bye = FileContains("F1:err| bye??") t1 = Test("$atheist test/testfunc_out.mtest", desc="TestFunc stdout not stderr are not shown") t1.post += Not(hello) t1.post += Not(bye) t2 = Test("$atheist -o test/testfunc_out.mtest", desc="unless explicitly solicited (-o for stdout)") t2.post += hello t2.post += Not(bye) t3 = Test("$atheist -e test/testfunc_out.mtest", desc="unless explicitly solicited (-e for stderr)") t3.post += bye t3.post += Not(hello) t4 = Test("$atheist -o -e test/testfunc_out.mtest", desc="both of them (-o -e)") t4.post += hello t4.post += bye atheist-0.20110402/test/alternate-config-file.test0000755000175000017500000000065011524504450020565 0ustar cletocleto#!/usr/bin/python # -*- mode:python; coding:utf-8; tab-width:4 -*- t1 = Test('$atheist -vv --config $testdir/sample_config $testdir/hello.test', save_stderr=True) t1.post += FileContains('*.impossible', t1.stderr) t2 = Test('$atheist --config $testdir/missing_config $testdir/hello.test', save_stderr=True) t2.post += FileContains("[WW] Config file './test/missing_config' does not exists", t2.stderr) atheist-0.20110402/test/none.test0000644000175000017500000000024311457026445015370 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- Command(None, desc='Task(None)') t = Test(None, desc='Task(None) with valid pre-condition') t.pre += FileExists('/etc/motd') atheist-0.20110402/test/or.test0000644000175000017500000000040211546304257015045 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- a = temp_name('a') b = temp_name('b') t1 = Test('rm -f {0} {1}'.format(a,b)) t1.post += Not(Or(FileExists(a), FileExists(b))) t1 = Test('touch ' + a) t1.post += Or(FileExists(a), FileExists(b)) t1.gen += a atheist-0.20110402/test/pyarco/0000755000175000017500000000000011547300376015024 5ustar cletocletoatheist-0.20110402/test/pyarco/DictTemplate.test0000644000175000017500000000551011526204745020305 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- import sys, os import unittest import StringIO import imp values = imp.find_module('Type', [os.path.abspath('$basedir/pyarco/')]) pyarco_type = imp.load_module('Type', *values) DictTemplate = pyarco_type.DictTemplate # values = dict( # locator_instancename = "ALP.Locator", # locator_host = "127.0.0.1", # locator_port = "8000", # locator_proto = "tcp", # lookup_endpoints = "udp:udp -h 224.2.2.4 -p 8000", # request_proxy = "ALP.Lookup -d:udp -h 224.2.2.4 -p 8000", # config_file = "/tmp/config.cfg" # ) # # # template = '$testdir/files/templateSample.template' # target_file = tempfile.mktemp('.out', 'atheist') # # # def test_DictTemplate(): # t = DictTemplate(template, delimiter='=') # result = t.substitute(values) # # result['Other key'] = 'other value' # print result # # DictTemplate.render(result, target_file) # return 0 # # # t = TestFunc(test_DictTemplate) # t.gen += target_file # t.pre += FileExists(template) # t.post += FileEquals(target_file, '$testdir/files/templateSample.out') class DictTemplateTest(unittest.TestCase): def create_cut(self, template): template = StringIO.StringIO(template) return DictTemplate(template, delimiter='=') def test_fixed_key_and_value(self): cut = self.create_cut('foo = bar') result = cut.substitute(dict()) self.assert_(result['foo'] == 'bar') def test_fixed_key_variable_value(self): cut = self.create_cut('foo.bar = $var_name') result = cut.substitute(dict(var_name='hello')) self.assert_(result['foo.bar'] == 'hello') def test_variable_key_and_value(self): cut = self.create_cut('foo.$key_name = $var_name') result = cut.substitute(dict(key_name='bye', var_name='hello')) self.assert_(result.has_key('foo.bye')) self.assert_(result['foo.bye'] == 'hello') def test_non_existent_key_is_removed(self): cut = self.create_cut('foo.bar = $var_name') result = cut.substitute({}) self.assert_(result == {}) def test_non_existent_value_is_removed(self): cut = self.create_cut('foo.$key_name = bar') result = cut.substitute({}) self.assert_(result == {}) def test_line_without_delimiter_is_removed(self): cut = self.create_cut('key.only') result = cut.substitute({}) self.assert_(result == {}) def test_line_without_value_is_empty(self): cut = self.create_cut('key.only =') result = cut.substitute({}) self.assert_(result['key.only'] == '') def test_mind_only_the_first_delimiter(self): cut = self.create_cut('foo = bar = other') result = cut.substitute({}) self.assert_(result['foo'] == 'bar = other') UnitTestCase(DictTemplateTest) atheist-0.20110402/test/pyarco/files/0000755000175000017500000000000011457026444016127 5ustar cletocletoatheist-0.20110402/test/pyarco/files/templateSample.template0000644000175000017500000000241011457026444022636 0ustar cletocletoALPService.Locator.InstanceName = $locator_instancename ALPService.LocatorAdapter.Endpoints = $locator_endpoints ALPService.LocatorAdapter.Endpoints = $locator_proto -h $locator_host -p $locator_port ALPService.Lookup.InstanceName = $lookup_instancename ALPService.LookupAdapter.Endpoints = $lookup_endpoints ALPService.LookupAdapter.Endpoints = $lookup_proto -h $lookup_request -p $lookup_port ALPService.Request.Proxy = $request_id -d:$request_proto -h $request_host -p $request_port ALP.Request.Proxy = $request_proxy ALP.Request.Proxy = $request_id -t:$request_proto -h $request_host -p $request_port ALP.Locator.Proxy = $locator_proxy ALP.Locator.Proxy = $locator_instancename -t:$locator_proto -h $locator_host -p $locator_port ALPService.LookupAdapter.Endpoints = $lookup_proto -h $lookup_host -p $lookup_port IDM.LocalRouter.Identity = $router_identity $router_identity.Endpoints = $router_endpoints IDM.LocalRouter.Proxy = $router_identity -t:$router_endpoints IDM.LocalRouter.Proxy = $router_proxy Ice.ThreadPool.Client.SizeMax = $threads_client Ice.ThreadPool.Server.SizeMax = $threads_server IceBox.Service.Router = IDMRouter:createRouter --Ice.Config=$config_file Esto tiene salir = Esto tiene salir atheist-0.20110402/test/pyarco/files/templateSample.out0000644000175000017500000000061311457026444021635 0ustar cletocletoALPService.LookupAdapter.Endpoints = udp:udp -h 224.2.2.4 -p 8000 ALPService.Locator.InstanceName = ALP.Locator ALPService.LocatorAdapter.Endpoints = tcp -h 127.0.0.1 -p 8000 ALP.Request.Proxy = ALP.Lookup -d:udp -h 224.2.2.4 -p 8000 Other key = other value IceBox.Service.Router = IDMRouter:createRouter --Ice.Config=/tmp/config.cfg ALP.Locator.Proxy = ALP.Locator -t:tcp -h 127.0.0.1 -p 8000 atheist-0.20110402/test/pyarco/observer-async-multiple-topic.test0000644000175000017500000000542411524504450023633 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import sys import unittest from pyarco.Pattern import ObjectObservableAsync class Observer: def __init__(self): self.val0 = False self.val1 = False def callback_t0(self, value=None): self.val0 = value def callback_t1(self, value=None): self.val1 = value class TestObserverAsyncMultipleTopic(unittest.TestCase): def setUp(self): self.observable = ObjectObservableAsync({'topic0':'callback_t0', 'topic1':'callback_t1', 'topicN':'callback_n'}) self.observers = [Observer(), Observer(), Observer()] def test_subscribe_pos(self): try: for obs in self.observers: self.observable.attach(obs, 'topic0') self.observable.attach(obs, 'topic1') self.assertTrue(True) except ObjectObservableAsync.NotSuchTopic: self.assertTrue(False) def test_subscribe_neg_topic(self): try: self.observable.attach(self.observers[0], 'unexistTopic') self.assertTrue(False) except ObjectObservableAsync.NotSuchTopic: self.assertTrue(True) def test_subscribe_neg_callback(self): try: self.observable.attach(self.observers[0], 'topicN') self.assertTrue(False) except ObjectObservableAsync.InvalidObserverInterface: self.assertTrue(True) except Exception, e: print e self.assertTrue(False) def test_unsubscribe(self): try: for obs in self.observers: self.observable.attach(obs, 'topic0') self.observable.attach(obs, 'topic1') self.observable.detach(obs, 'topic0') self.observable.detach(obs, 'topic1') self.assertTrue(True) except ObjectObservableAsync.NotSuchTopic: self.assertTrue(False) def test_unsubscribe_neg(self): try: self.observable.detach(self.observers[0], 'unexistTopic') self.assertTrue(False) except ObjectObservableAsync.NotSuchTopic: self.assertTrue(True) def test_notify(self): for obs in self.observers: self.observable.attach(obs, 'topic0') self.observable.attach(obs, 'topic1') self.observable.notify('topic0', True) self.observable.notify('topic1', True) from time import sleep sleep(0.5) for obs in self.observers: if not obs.val0 or not obs.val1: self.assertTrue(False) self.assertTrue(True) UnitTestCase(TestObserverAsyncMultipleTopic) atheist-0.20110402/test/pyarco/doctest.test0000644000175000017500000000011111523712750017360 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- DocTest('pyarco.Type') atheist-0.20110402/test/pyarco/accept-decorator.test0000644000175000017500000001360011523712750021141 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- import sys, os import unittest import logging import imp import warnings import types Type = imp.load_module(\ 'Type', *imp.find_module('Type', [os.path.abspath('$basedir/pyarco/')])) accept = Type.accept class TestAccepts(unittest.TestCase): def setUp(self): accept.level = 'error' def test_ok_all_types_with_keys(self): accept.level = 'error' @accept(i1=int, i2=int, s1=str) def func_int_int_str(i1, i2, s1): pass func_int_int_str(1, 2, 'hi') def test_fail_all_types_wrong_with_keys(self): accept.level = 'error' @accept(i1=int, i2=int, s1=str) def func_int_int_str(i1, i2, s1): pass try: func_int_int_str('by', 1, 'hi') except TypeError, e: self.assert_(e.args[0] == "Argument 'i1' should be 'int' ('str' given)") return self.fail() def test_ok_some_types_with_keys(self): accept.level = 'error' @accept(i1=int, s1=str) def func_int_int_str(i1, i2, s1): pass func_int_int_str(1, 2, 'hi') def test_ok_all_positional(self): accept.level = 'error' @accept(int, int, str) def func_int_int_str(i1, i2, s1): pass func_int_int_str(1, 2, 'hi') def test_fail_wrong_positional(self): accept.level = 'error' @accept(int, int, str) def func_int_int_str(i1, i2, s1): pass try: func_int_int_str('bye', 1, 'hi') except TypeError,e: self.assert_(e.args[0] == "Argument 'i1' should be 'int' ('str' given)") return self.fail() def test_fail_not_enough_types_positional(self): accept.level = 'error' @accept(int, int) def func_int_int_str(i1, i2, s1): pass try: func_int_int_str(1, 2, 'hi') except TypeError: return self.fail() #--- Testing keyword functions --- def test_ok_keyword_func_all_args_with_keys(self): accept.level = 'error' @accept(i1=int, i2=int, s1=str) def func_int_int_str(i1, i2, s1): pass func_int_int_str(1, i2=2, s1='hi') def test_ok_keyword_func_some_args_with_keys(self): accept.level = 'error' @accept(i1=int, i2=int, s1=str) def func_int_int_str(i1, i2=0, s1=''): pass func_int_int_str(i1=1, s1='hi') def test_fail_keyword_func_some_args_with_keys(self): accept.level = 'error' @accept(i1=int, i2=int, s1=str) def func_int_int_str(i1, i2=0, s1=''): pass try: func_int_int_str(i1=1, s1=7) except TypeError,e: self.assert_(e.args[0] == "Argument 's1' should be 'str' ('int' given)") return self.fail() #--- secuences --- def test_ok_varargs(self): @accept(a=int) def f(*a): pass f(1, 2, 3, 4) def test_fail_varargs(self): @accept(a=int) def f(*a): pass try: f(1, 2, 'hi', 4) except TypeError,e: self.assert_(e.args[0] == "Argument 'hi' should be 'int' ('str' given)") return self.fail() def test_ok_mixed_args_and_varargs(self): @accept(a=int, b=str) def f(b, *a): pass f('hi', 2, 3, 4) def test_ok_func_and_tuple(self): @accept(func=types.FunctionType, args=tuple) def f(func, args=()): pass def g(): pass f(g, (1,2)) f(g) def test_ok_method(self): class A: @accept(b=int) def f(self, a, b): pass a1 = A() a1.f('a', 2) def test_ok_ctor(self): class A: @accept(b=int) def __init__(self, a, b, **kargs): pass a1 = A('a', 3) def test_fail_subclass_ctor(self): class A: @accept(b=int) def __init__(self, a, b): pass class B(A): def __init__(self, b): A.__init__(self, 'A', b) try: B(1) except TypeError,e: self.assert_(e.args[0] == "Argument 'b' should be 'int' ('str' given)") return self.fail() def test_ok_subclass_ctor(self): class A: @accept(b=int) def __init__(self, a, b): pass class B(A): def __init__(self, b): A.__init__(self, 'A', b=b) B(1) def test_ok_method_func_and_tuple(self): class A: @accept(func=types.FunctionType, args=tuple) def f(self, func, args=()): pass def g(): pass a1 = A() a1.f(g, (1,2)) a1.f(g) #--- tuples of types --- def test_several_posible_types_positional(self): @accept((int, str)) def f(a): pass f(1) f('hi') def test_several_posible_types_with_keys(self): @accept(a=(int, str)) def f(a): pass f(1) f('hi') #--- Testing error levels --- def test_level_None(self): accept.level = None @accept(int) def f(s): return len(s) with warnings.catch_warnings(record=True) as catcher: retval = f('hi') self.assert_(retval == 2) self.assert_(len(catcher) == 0) def test_level_warn(self): accept.level = 'warn' @accept(int) def f(a): pass with warnings.catch_warnings(record=True) as catcher: f('hi') self.assert_(len(catcher) == 1) self.assert_(issubclass(catcher[-1].category, RuntimeWarning)) def test_wrong_level(self): accept.level = 'wrong' @accept(int) def f(a): pass try: f('hi') except TypeError,e: self.assert_(e.args[0] == "accept.level must be one of ['error', 'warn', None]") return self.fail() UnitTestCase(TestAccepts) atheist-0.20110402/test/pyarco/iniparser.test0000644000175000017500000000450211546304257017723 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- import sys import io import unittest import ConfigParser from mock import Mock sys.path.append('$basedir/pyarco') from iniparser import IniParser class TestIniParser(unittest.TestCase): def setUp(self): self.cut = IniParser() self.cut.add_section('sect1') self.cut.set('sect1', 'value', '5') def test_readfp(self): sample = ''' [section] value = 0 ''' cut = IniParser() cut.readfp(io.BytesIO(sample)) self.assertEquals(cut.get('section', 'value'), '0') def test_as_attr_section(self): self.assert_(isinstance(self.cut.sect1, IniParser.Section)) def test_as_attr_key(self): self.assert_(self.cut.sect1.value == '5') def test_as_attr_missing_section(self): try: self.cut.missing except ConfigParser.NoSectionError: return self.fail() def test_as_attr_missing_key(self): try: self.cut.sect1.missing except AttributeError: return self.fail() def test_as_attr_missing_key_in_missing_section(self): try: self.cut.missing1.missing2 except ConfigParser.NoSectionError: return self.fail() def test_as_dict_key(self): self.assertEquals(self.cut['sect1.value'], '5') def test_as_dict_missing_key(self): try: self.cut['sect1.missing2'] except AttributeError: return self.fail() def test_safe_key(self): self.assert_(self.cut.safe_get('sect1.value', 10) == '5') def test_safe_existing_section(self): try: self.cut.safe_get('missing1.missing2', '10') except ConfigParser.NoSectionError: return self.fail() def test_safe_missing_key(self): self.assert_(self.cut.safe_get('sect1.missing', '10') == '10') def test_safe_missing_key_without_default(self): try: self.cut.safe_get('sect1.missing') except AttributeError: return self.fail() def test_safe_missing_section_key_without_default(self): try: self.cut.safe_get('missing1.missing2') except ConfigParser.NoSectionError: return self.fail() UnitTestCase(TestIniParser) atheist-0.20110402/test/pyarco/SortedDict.test0000644000175000017500000000150611457026444017774 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import sys, os import unittest #sys.path.insert(0, os.path.abspath('$basedir')) from pyarco.Type import SortedDict keys = ['5', 0 , 'c', None, 'a'] dikt = {'b':1, 'a': 2, 'd': 3} tuples = [(2,'a'), (3,'e'), (1,'h')] class TestSortedDict(unittest.TestCase): def test_order(self): sd = SortedDict() for k in keys: sd[k] = 1 self.assert_(sd.keys() == keys) def test_fromdict(self): sd = SortedDict(dikt) self.assert_(sd == dikt) def test_fromtuplelist(self): sd = SortedDict(tuples) print sd.keys() print [x[0] for x in tuples] self.assert_(sd.keys() == [x[0] for x in tuples]) def test_default(self): sd = SortedDict(default=[]) sd[0].append(1) UnitTestCase(TestSortedDict) atheist-0.20110402/test/pyarco/singleton.test0000644000175000017500000000103611523712750017724 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import sys import unittest from pyarco.Pattern import Singleton class A: __metaclass__ = Singleton def __init__(self): pass class AnotherA: __metaclass__ = Singleton def __init__(self): a = A() class TestSingleton(unittest.TestCase): def test_equals(self): a = A() b = A() self.assertEqual(a,b) def test_two_singletons(self): a = A() another = AnotherA() self.assertTrue(True) UnitTestCase(TestSingleton) atheist-0.20110402/test/pyarco/obj-observer-sync.test0000644000175000017500000000606511524504450021277 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import sys import unittest from pyarco.Pattern import Observable, ObjectObservable class Observer: def __init__(self): self.val = False def callback(self, value=None): self.val = value class TestObserverSingleTopic(unittest.TestCase): def setUp(self): self.observable = ObjectObservable({'topicTest': 'callback'}) self.observers = [Observer(), Observer(), Observer()] def test_subscribe_pos(self): try: for obs in self.observers: self.observable.attach(obs, 'topicTest') self.assertTrue(True) except: self.assertTrue(False) def test_subscribe_neg(self): try: self.observable.attach(self.observers[0].callback, 'unexistTopic') self.assertTrue(False) except Observable.NotSuchTopic: self.assertTrue(True) except: self.assertTrue(False) def test_subscribe_doble_neg(self): self.observable.attach(self.observers[0], 'topicTest') self.observable.attach(self.observers[0], 'topicTest') self.assertTrue(len(self.observable.status()['topicTest']) == 1) def test_unsubscribe(self): try: for obs in self.observers: self.observable.attach(obs, 'topicTest') self.observable.detach(obs, 'topicTest') self.assertTrue(True) except Observable.NotSuchTopic: self.assertTrue(False) def test_unsubscribe_neg(self): try: self.observable.detach(self.observers[0], 'unexistTopic') self.assertTrue(False) except Observable.NotSuchTopic: self.assertTrue(True) except Exception, e: print e.__class__ self.assertTrue(False) def test_notify(self): for obs in self.observers: self.observable.attach(obs, 'topicTest') self.observable.notify('topicTest', True) for obs in self.observers: if not obs.val: self.assertTrue(False) self.assertTrue(True) def test_create_topic_pos(self): try: self.observable.addTopic('test', 'callback') self.assertTrue(True) except: self.assertTrue(False) def test_create_topic_neg(self): try: self.observable.addTopic(1, '') self.assertTrue(False) except Observable.InvalidTopicName: self.assertTrue(True) except: self.assertTrue(False) def test_create_topic_dup_neg(self): try: self.observable.addTopic('test', 'callback') self.observable.addTopic('test', 'callback') self.assertTrue(False) except Observable.TopicAlreadyExists: self.assertTrue(True) except: self.assertTrue(False) UnitTestCase(TestObserverSingleTopic) atheist-0.20110402/test/pyarco/observer-sync-single-topic.test0000644000175000017500000000666111524504450023124 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import sys import unittest from pyarco.Pattern import Observable class Observer: def __init__(self): self.val = False def callback(self, value=None): self.val = value class TestObserverSingleTopic(unittest.TestCase): def setUp(self): self.observable = Observable(['topicTest']) self.observers = [Observer(), Observer(), Observer()] def test_subscribe_pos(self): try: for obs in self.observers: self.observable.attach(obs.callback, 'topicTest') self.assertTrue(True) except: self.assertTrue(False) def test_subscribe_neg(self): try: self.observable.attach(self.observers[0].callback, 'unexistTopic') self.assertTrue(False) except Observable.NotSuchTopic: self.assertTrue(True) except: self.assertTrue(False) def test_subscribe_doble_neg(self): #try: self.observable.attach(self.observers[0].callback, 'topicTest') self.observable.attach(self.observers[0].callback, 'topicTest') self.assertTrue(len(self.observable.status()['topicTest']) == 1) # except Exception: # self.assertTrue(False) def test_subscribe_bad_subscriber(self): try: self.observable.attach(self.observers[0], # not a callable object 'topicTest') self.assertTrue(False) except Observable.InvalidSubscriber: self.assertTrue(True) except: self.assertTrue(False) def test_unsubscribe(self): try: for obs in self.observers: self.observable.attach(obs.callback, 'topicTest') self.observable.detach(obs.callback, 'topicTest') self.assertTrue(True) except Observable.NotSuchTopic: self.assertTrue(False) def test_unsubscribe_neg(self): try: self.observable.detach(self.observers[0].callback, 'unexistTopic') self.assertTrue(False) except Observable.NotSuchTopic: self.assertTrue(True) except: self.assertTrue(False) def test_notify(self): for obs in self.observers: self.observable.attach(obs.callback, 'topicTest') self.observable.notify('topicTest', True) for obs in self.observers: if not obs.val: self.assertTrue(False) self.assertTrue(True) def test_create_topic_pos(self): try: self.observable.addTopic('test') self.assertTrue(True) except: self.assertTrue(False) def test_create_topic_neg(self): try: self.observable.addTopic(1) self.assertTrue(False) except Observable.InvalidTopicName: self.assertTrue(True) except: self.assertTrue(False) def test_create_topic_dup_neg(self): try: self.observable.addTopic('test') self.observable.addTopic('test') self.assertTrue(False) except Observable.TopicAlreadyExists: self.assertTrue(True) except: self.assertTrue(False) UnitTestCase(TestObserverSingleTopic) atheist-0.20110402/test/pyarco/threadpool.test0000644000175000017500000000246511547300376020075 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import sys import time import unittest from pyarco.Thread import ThreadPool, SimpleThreadPool class TestPool(unittest.TestCase): def setUp(self): self.pool = ThreadPool(3) self.add_job() def add_job(self): for i in range(10): self.pool.add(time.sleep, [i/3]) time.sleep(1) def test_increase(self): assert len(self.pool) == 3 self.pool.resize(5) assert len(self.pool) == 5 def test_decrease(self): assert len(self.pool) == 3 self.pool.resize(2) assert len(self.pool) == 2 def tearDown(self): self.pool.join() class TestSimplePool(unittest.TestCase): def setUp(self): self.pool = SimpleThreadPool(3) def square(self, x): time.sleep(float(x)/4) return x*x def test_work(self): values = [] for i in range(10): self.pool.add(self.square, (i,), values.append) self.pool.join() self.assertEquals( sorted(values), [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) def test_map(self): self.assertEquals( self.pool.map(self.square, range(9,-1,-1)), [81, 64, 49, 36, 25, 16, 9, 4, 1, 0]) #UnitTestCase(TestPool) UnitTestCase(TestSimplePool) atheist-0.20110402/test/pyarco/model.test0000644000175000017500000001037011546304257017027 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- import sys import io import unittest import ConfigParser from mock import Mock sys.path.append('$basedir/pyarco') from model import * from pyarco.test import FakeFileSystem simple_register = dict(a='str_a', b='str_b') class Simple(Model): schema = Schema( a = TextField(), b = TextField(), ) class Simple_2fixed_1opt(Model): schema = Schema( a = TextField(), b = TextField(), optional = TextField(opt=True), automatic = TextField(auto=True), ) class M_int(Model): schema = Schema( a = IntField() ) class M_A(Model): schema = Schema( a = Foreign(M_int) ) class TestField(unittest.TestCase): def test_auto_implies_optional(self): a = TextField(auto=True) self.assert_(a.opt) def test_IntField(self): cut = IntField() class TestModel(unittest.TestCase): def test_has_schema(self): class A(Model): schema = Schema() A(dict()) def test_has_not_schema(self): class A(Model): pass self.assertRaises(MissingSchema, A, [simple_register]) def test_all_schema(self): self.assertEquals(set(Simple.schema.keys()), set(['a', 'b'])) def test_requires_argument(self): self.assertRaises(TypeError, Simple) def test_get_mandatory_attributes(self): self.assertEquals( Simple_2fixed_1opt.get_mandatory_attrs().keys(), ['a','b']) def test_get_optional_attributes(self): self.assertEquals( set(Simple_2fixed_1opt.get_optional_attrs().keys()), set(['optional', 'automatic'])) def test_get_auto_attributes(self): self.assertEquals( Simple_2fixed_1opt.get_auto_attrs().keys(), ['automatic']) def test_validate_valid_register(self): Simple(simple_register) def test_validate_register_with_missing_mandatory_attributes(self): self.assertRaises(MissingMandatoryAttr, Simple, dict()) def test_validate_register_with_unknown_attributes(self): register = simple_register.copy() register['unknown'] = True self.assertRaises(UnknownAttr, Simple, register) def test_validate_register_with_correct_types(self): class Cut(Model): schema = Simple.schema.copy() schema['c'] = IntField() register = simple_register.copy() register['c'] = 1 Cut(register) def test_validate_register_with_optional_field(self): class Cut(Model): schema = Simple.schema.copy() schema['c'] = IntField(opt=True) Cut(simple_register.copy()) def test_validate_register_with_wrong_types(self): self.assertRaises(CastingError, M_int, {'a': 'text'}) class TestIniModel(unittest.TestCase): def setUp(self): class A(IniModel): schema = Simple.schema.copy() self.fs = FakeFileSystem() self.A = A self.A.FS = self.fs def create_file(self, fname, content): with self.fs.open(fname, 'w') as fd: fd.write(content) def test_create(self): fname = 'sample.ini' self.create_file(fname,''' [MAIN] a: John b: Doe ''') a1 = self.A(fname) print a1.text_render() self.assertEquals(a1.a, 'John') def test_validate_register_with_mssing_file(self): fname = 'missing.ini' self.assertRaises(IOError, self.A, fname) def test_validate_register_with_empty_file(self): fname = 'empty.ini' self.create_file(fname, '') self.assertRaises(ConfigParser.NoSectionError, self.A, fname) def test_validate_register_with_missing_mandatory_attributes(self): fname = 'sample.ini' self.create_file(fname,''' [MAIN] a: John ''') self.assertRaises(MissingMandatoryAttr, self.A, fname) class TestModelAssociations(unittest.TestCase): def test_simple_association_ok(self): M_A( {'a': {'a': '1'}} ) def test_simple_association_wrong_register(self): self.assertRaises(CastingError, M_A, {'a': {'a': 'wrong'}}) UnitTestCase(TestField) UnitTestCase(TestModel) UnitTestCase(TestModelAssociations) UnitTestCase(TestIniModel) atheist-0.20110402/test/pyarco/test.test0000644000175000017500000000237511547300376016713 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- import os, sys import unittest sys.path.insert(0, '$basedir') from pyarco.test import FakeFileSystem class Test_mkdir(unittest.TestCase): def setUp(self): self.sut = FakeFileSystem() def assert_dirs(self, contents): for dname, dirs in contents: self.assertEquals(self.sut.listdir(dname), dirs) def test_empty_path(self): self.assertRaises(OSError, self.sut.mkdir ,"") def test_already_exists(self): self.sut.mkdir("/foo") self.assertRaises(OSError, self.sut.mkdir, "/foo") def test_usr(self): dname = "/usr" self.sut.mkdir(dname) self.assertEquals(self.sut.listdir("/"), ['usr']) self.assertEquals(self.sut.listdir(dname), []) def test_usr_local(self): self.sut.mkdir("/usr/local") self.assert_dirs([ ("/", ['usr']), ("/usr", ['local']), ("/usr/local", []), ]) def test_usr_local_stow(self): self.sut.mkdir("/usr/local/stow") self.assert_dirs([ ("/", ['usr']), ("/usr", ['local']), ("/usr/local", ['stow']), ("/usr/local/stow", []), ]) UnitTestCase(Test_mkdir) atheist-0.20110402/test/pyarco/observer-async-single-topic.test0000644000175000017500000000371211524504450023257 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import sys import unittest from pyarco.Pattern import ObjectObservableAsync class Observer: def __init__(self): self.val = False def callback(self, value=None): self.val = value class TestObserverAsyncSingleTopic(unittest.TestCase): def setUp(self): self.observable = ObjectObservableAsync({'topicTest':'callback'}) self.observers = [Observer(), Observer(), Observer()] def test_subscribe_pos(self): try: for obs in self.observers: self.observable.attach(obs, 'topicTest') self.assertTrue(True) except ObjectObservableAsync.NotSuchTopic: self.assertTrue(False) def test_subscribe_neg(self): try: self.observable.attach(self.observers[0], 'unexistTopic') self.assertTrue(False) except ObjectObservableAsync.NotSuchTopic: self.assertTrue(True) def test_unsubscribe(self): try: for obs in self.observers: self.observable.attach(obs, 'topicTest') self.observable.detach(obs, 'topicTest') self.assertTrue(True) except ObjectObservableAsync.NotSuchTopic: self.assertTrue(False) def test_unsubscribe_neg(self): try: self.observable.detach(self.observers[0], 'unexistTopic') self.assertTrue(False) except ObjectObservableAsync.NotSuchTopic: self.assertTrue(True) def test_notify(self): for obs in self.observers: self.observable.attach(obs, 'topicTest') self.observable.notify('topicTest', True) from time import sleep sleep(0.5) for obs in self.observers: if not obs.val: self.assertTrue(False) self.assertTrue(True) UnitTestCase(TestObserverAsyncSingleTopic) atheist-0.20110402/test/pyarco/ellipsis.test0000644000175000017500000000063311546304257017554 0ustar cletocleto# -*- coding:utf-8; tab-width:4; mode:python -*- import sys import unittest from pyarco.UI import ellipsis class Test_ellipsis(unittest.TestCase): def test_empty(self): self.assert_(ellipsis('') == '') def test_ascii(self): self.assert_(ellipsis('hello') == 'hello') def test_utf8(self): self.assert_(ellipsis(u'ñandú') == u'ñandú') UnitTestCase(Test_ellipsis) atheist-0.20110402/test/pyarco/attributes-decorator.test0000644000175000017500000000404111523712750022067 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- import sys, os import unittest import logging import imp Type = imp.load_module(\ 'Type', *imp.find_module('Type', [os.path.abspath('$basedir/pyarco/')])) attributes = Type.attributes class TestAttributes(unittest.TestCase): def test_set_an_attribute(self): class A: @attributes('v') def m(self, v): pass a1 = A() a1.m(1) self.assert_(a1.v == 1) def test_init(self): class A: @attributes('i1') def __init__(self, i1): pass a1 = A(1) a1.i1 def test_set_all_from_defaults(self): class A: @attributes('i1', 'i2') def m(self, i1, i2=2): pass a1 = A() a1.m(11) self.assert_(a1.i1 == 11) self.assert_(a1.i2 == 2) def test_set_from_call_pos_with_defaults(self): class A: @attributes('i1', 'i2') def m(self, i1, i2=2): pass a1 = A() a1.m(11, 8) self.assert_(a1.i1 == 11) self.assert_(a1.i2 == 8) def test_set_from_call_key_with_defaults(self): class A: @attributes('i1', 'i2') def m(self, i1, i2=2): pass a1 = A() a1.m(11, i2=8) self.assert_(a1.i1 == 11) self.assert_(a1.i2 == 8) def test_set_some_from_defaults(self): class A: @attributes('i1', 'i3') def m(self, i1, i2=2, i3=3): pass a1 = A() a1.m(11, 22) self.assert_(a1.i1 == 11) self.assert_(not hasattr(a1, 'i2')) self.assert_(a1.i3 == 3) def test_missing_arg(self): class A: @attributes('i1', 'wrong') def m(self, i1, i2=2, i3=3): pass a1 = A() try: a1.m(1) except TypeError, e: self.assert_(e.args[0] == "'m()' method has no argument 'wrong'") return self.fail() # def test_with_non_method(self): # self.fail() UnitTestCase(TestAttributes) atheist-0.20110402/test/dir-hooks/0000755000175000017500000000000011523712750015423 5ustar cletocletoatheist-0.20110402/test/dir-hooks/test-a.test0000644000175000017500000000007611523712750017524 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test('echo "A ran"') atheist-0.20110402/test/dir-hooks/_teardown.test0000644000175000017500000000010211523712750020277 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- Test('echo "_teardown ran"') atheist-0.20110402/test/dir-hooks/_setup.test0000644000175000017500000000007711523712750017627 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- Test('echo "_setup ran"') atheist-0.20110402/test/dir-hooks/_SETUP.test0000644000175000017500000000007711523712750017367 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- Test('echo "_SETUP ran"') atheist-0.20110402/test/dir-hooks/test-z.test0000644000175000017500000000007611523712750017555 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test('echo "Z ran"') atheist-0.20110402/test/dir-hooks/_TEARDOWN.test0000644000175000017500000000010211523712750017677 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- Test('echo "_TEARDOWN ran"') atheist-0.20110402/test/loop.mtest0000644000175000017500000000013711457026445015561 0ustar cletocleto# -*- mode: python; coding:utf-8 -*- Test('sleep 5', timeout=10) Test('sleep 5', timeout=10) atheist-0.20110402/test/conditions/0000755000175000017500000000000011546304257015701 5ustar cletocletoatheist-0.20110402/test/conditions/process-running.test0000644000175000017500000000070711546304257021742 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- Command('killall -9 tailf') d = Daemon("tailf /var/log/Xorg.0.log") test_pid = """ import commands; t=Test(None); t.pre += ProcessRunning(int(commands.getoutput('pidof tailf'))) """ t = Test('$atheist -i5 -s "%s"' % test_pid, shell=True) t.pre += Poll(TaskRunning(d)) test_program = """ import commands; t=Test(None); t.pre += ProcessRunning('tailf') """ Test('$atheist -i5 -s "%s"' % test_program, shell=True) atheist-0.20110402/test/conditions/conditions.test0000644000175000017500000000235711546304257020762 0ustar cletocleto# -*- mode: python -*- errmsg = "A Condition is required, not int." t = Test(None) t.pre += FileExists('/usr/bin/ncat') t1 = Test("$atheist -s 'Test(None).pre += 2'", desc="Pre Condition type checking", shell=True, save_stderr=True, must_fail=True) t1.post += FileContains(errmsg, t1.stderr) t2 = Test("$atheist -s 'Test(None).post += 2'", desc="Post Condition type checking", shell=True, save_stderr=True, must_fail=True) t2.post += FileContains(errmsg, t1.stderr) fname = temp_name() Command('rm %s' % fname) t4 = Test("echo 1hello2world3adios4hello5world6otro > %s" % fname, shell=True, desc="Test FileContains 'times' parameter") t4.post += FileContains(["hello", "world", "adios"], fname) t4.post += FileContains(["hello", "world"], fname, times=2) t4.post += Not(FileContains(["hello", "world"], fname, times=3)) t4.gen += fname #fail = "Test(None).post += FileContains('/tmp/$testname', ['hello', 'world'], 3)" #Test("$atheist -s \"%s\"" % fail, must_fail=True, shell=True) fileA = temp_name() fileB = temp_name() t5 = Test('touch %s; sleep 1; touch %s' % (fileA, fileB), shell=True) t5.gen += [fileA, fileB] t5.post += Poll(FileIsNewerThan(fileB, fileA)) atheist-0.20110402/test/missing-file.test0000644000175000017500000000041311524504450017006 0ustar cletocleto# -*- mode: python; coding:utf-8 -*- t = Test('$atheist -v /tmp/not_exists_file.nothing', must_fail=True, save_stderr=True, desc="Run atheist on a non existing test file.") t.post += FileContains("[WW] Ignored file: /tmp/not_exists_file.nothing", t.stderr) atheist-0.20110402/test/composite/0000755000175000017500000000000011546304257015532 5ustar cletocletoatheist-0.20110402/test/composite/composite.test0000644000175000017500000000026311546304257020436 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t1 = Test('ls') t2 = Test('date') t3 = Test('ls') t4 = Test('ls') t5 = Test('ls') CompositeTask(all, t1, t2) CompositeTask(all, t3, t4, t5) atheist-0.20110402/test/composite/composite-command.test0000644000175000017500000000023011546304257022044 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t1 = Command('ls') c = CompositeTask(all, t1, desc='Composites must run command also') c.post += TaskFinished(t1) atheist-0.20110402/test/composite/composite-termination.test0000644000175000017500000000030311546304257022760 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t1 = Test('cat', timeout=10, expected=-9) c2 = CompositeTask(all, t1, detach=True) t3 = Test('echo end') t3.pre += Poll(TaskRunning(t1)) TaskTerminator(c2) atheist-0.20110402/test/dummy.test0000644000175000017500000000012611523712750015557 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = SampleTask() t.post += SampleCondition('hi') atheist-0.20110402/test/options/0000755000175000017500000000000011526204745015222 5ustar cletocletoatheist-0.20110402/test/options/optparser.test0000644000175000017500000000346511526204745020152 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import optparse import mock def get_opts(): import atheist.manager parser = atheist.manager.OptParser() # FIXME: find other way to test plugin options # mng = mock.Mock() # mng.config.pluginpath = [] # api = atheist.manager.Manager.AInternal(mng) # for plugin in api.plugins: # plugin.config(mock.Mock(), parser) return parser.option_list def parser_opts(): retval = [] for opt in get_opts(): _short = str.join('', opt._short_opts) _long = opt._long_opts[0] if opt.metavar: dest = opt.metavar elif opt.dest: dest = opt.dest.upper() else: dest = '' val = '' if opt.takes_value(): if _short: val = "%s %s, " % (_short, dest) val += "%s=%s" % (_long, dest) else: if _short: val = "%s, " % _short val += _long # print opt._short_opts, val retval.append(val) return retval def doc_opts(): return ['cmdoption:: %s' % x for x in parser_opts()] # --help t = Test('$atheist', expected=1) t.post += FileContains('ABSOLUTELY NO WARRANTY') for opt in parser_opts(): t.post += FileContains(opt) # sphinx documentation atheist_doc = '$basedir/doc/intro.rst' t = Test('cat %s' % atheist_doc) t.pre += FileExists(atheist_doc) for opt in doc_opts(): t.post += FileContains(opt) # manpage man_src = '$basedir/debian/atheist.xml' man_dst = '$basedir/debian/atheist.1' t = Test('./debian/rules %s' % man_dst, shell=True, timeout=10) t.pre += DebPkgInstalled('cdbs') t.pre += DebPkgInstalled('docbook-xsl') t.pre += FileExists(man_src) t.gen += man_dst t = Test('man %s | cat' % man_dst, shell=True) for opt in parser_opts(): t.post += FileContains(opt) atheist-0.20110402/test/options/inline.test0000644000175000017500000000031711526204745017402 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- one = "Test('echo one')" two = "Test('echo two')" t = Test('$atheist -o -s "%s" -s "%s"' % (one, two), shell=True) t.post += FileContains(['T1:out| one', 'T2:out| two']) atheist-0.20110402/test/options/exec.test0000644000175000017500000000051111526204745017044 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os base = os.path.join('$tmp', 'token') cmd = '$atheist -o' fnames = ["%s.%s" % (base, i) for i in range(2)] for fname in fnames: touch = Test('touch %s' % fname) touch.gen += fname cmd += ' -x "ls %s"' % fname t = Test(cmd, shell=True) t.post += FileContains(fnames) atheist-0.20110402/test/dirty-touch.mtest0000644000175000017500000000050111546304257017055 0ustar cletocleto#!/usr/bin/python # -*- mode:python; coding:utf-8 -*- import os from atheist.const import ATHEIST_TMP_BASE fname_a = os.path.join(ATHEIST_TMP_BASE, '$testname-a') fname_b = os.path.join(ATHEIST_TMP_BASE, '$testname-b') t = Test('touch ' + fname_a, dirty=True) t = Test('touch ' + fname_b, dirty=True) t.gen += fname_b atheist-0.20110402/test/hooks/0000755000175000017500000000000011546304257014653 5ustar cletocletoatheist-0.20110402/test/hooks/_teardown.test0000644000175000017500000000034311546304257017536 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os from atheist.const import ATHEIST_TMP_BASE fname = os.path.join(ATHEIST_TMP_BASE, 'hook-log') t = Test('echo "_teardown ran" >> %s' % fname, shell=True) t.pre += FileExists(fname) atheist-0.20110402/test/hooks/_setup.test0000644000175000017500000000034111546304257017051 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os from atheist.const import ATHEIST_TMP_BASE fname = os.path.join(ATHEIST_TMP_BASE, 'hook-log') t = Test('echo "_setup ran" >> %s' % fname, shell=True) t.pre += FileExists(fname) atheist-0.20110402/test/hooks/hello.mtest0000644000175000017500000000033711546304257017037 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import os from atheist.const import ATHEIST_TMP_BASE fname = os.path.join(ATHEIST_TMP_BASE, 'hook-log') t = Test('echo "test ran" >> %s' % fname, shell=True) t.pre += FileExists(fname) atheist-0.20110402/test/daemon.test0000644000175000017500000000041311457026445015673 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- Daemon('cat', shell=True) # With daemon, save_stdout must work msg = "some string" d = Daemon("while true; do echo '%s'; sleep 1; done" % msg, save_stdout=True, shell=True) d.post += FileContains(msg) Test('sleep 3') atheist-0.20110402/test/description-utf8.test0000644000175000017500000000015011523712750017630 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- Test('true', desc="descripción con tildes en UTF-8") atheist-0.20110402/test/newclean.test0000644000175000017500000000014411546304257016224 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- fname = temp_name() t = Test('touch ' + fname) t.gen += fname atheist-0.20110402/test/testfunc_out.mtest0000644000175000017500000000024511457026445017332 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import sys def a(): sys.stdout.write("hello!!") sys.stderr.write("bye??") return 0 TestFunc(a, ()) TestFunc(a, ()) atheist-0.20110402/test/include.mtest0000644000175000017500000000021011457026445016223 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- sample = load("$testdir/files/sample.pt") sample.included_func() print sample sample.factory() atheist-0.20110402/test/user_vars.test0000644000175000017500000000024611475251202016434 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- t = Test("$atheist --config test/sample_config -o test/user_vars.mtest") t.post += FileContains('T1:out| John Doe') atheist-0.20110402/test/time-tag.test0000644000175000017500000000026611457026445016145 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import time date = time.strftime('%d/%m/%y') t = Test('$atheist -vt test/hello.test', save_stderr=True) t.post += FileContains(date, t.stderr) atheist-0.20110402/test/run_mtests.test0000644000175000017500000000204211457026445016633 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- # Copyright (C) 2009 David Villa Alises # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ok_tests = ['include.mtest', 'test_func.mtest', 'remove_gen.mtest'] for f in ok_tests: Test("$atheist $testdir/%s" % f, desc=f) fail_tests = [('test_func_fail.mtest', 3)] for f,res in fail_tests: Test("$atheist $testdir/%s" % f, expected=res, desc=f) atheist-0.20110402/test/stdnames.test0000644000175000017500000000035411523712750016245 0ustar cletocleto#!/usr/bin/python # -*- mode:python; coding:utf-8 -*- from atheist import ATHEIST_TMP date = Test('date', save_stdout=True) t = Test('echo %s' % date.stdout) t.post += FileContains(['{0}/{1}'.format(ATHEIST_TMP, date.name), '.out']) atheist-0.20110402/test/env.mtest0000644000175000017500000000252411457026445015402 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- module = '/tmp/testmodule.py' c = Command("echo 'print \"testmodule loaded\"' > %s" % module, shell=True) c.gen += module # PYTHONPATH env = Test("python -c 'import testmodule'", shell=True, env={"PYTHONPATH":"/tmp"}, save_stdout=True) env.post += FileContains("testmodule loaded") # any other: undefined -> defined ud = Test("echo $VAR_UD", env={"VAR_UD":"var defined"}, save_stdout=True, shell=True) ud.pre += Not(EnvVarDefined("VAR_UD")) ud.post += FileContains("var defined") # any other: undefined -> append, defined -> replaced ua = Test('if [ "$VAR_UA" == "var defined" ]; then echo ok; fi', env={"VAR_UA":"var defined"}, save_stdout=True, shell=True) ua.post += FileContains("ok") # any other: defined -> append da = Test('if [ "$VAR_DA" == "former value new value" ]; then echo ok; fi', env={"VAR_DA":"$VAR_DA new value"}, save_stdout=True, shell=True) da.pre += EnvVarDefined("VAR_DA", "former value") da.post += FileContains("ok") # any other: defined + other -> insert doi = Test('if [ "$VAR_DOI" == "prefix former suffix" ]; then echo ok; fi', save_stdout=True, shell=True, env={"VAR_DOI":"prefix $VAR_DOI $VAR_SUFFIX"}) doi.pre += EnvVarDefined("VAR_DOI", "former") doi.pre += EnvVarDefined("VAR_SUFFIX", "suffix") doi.post += FileContains("ok") atheist-0.20110402/test/template.test0000644000175000017500000000022211457026445016241 0ustar cletocleto# -*- mode: python -*- tmpl1 = """\ t = Template(must_fail=True) Test('false', template=[t]) """ Test("$atheist -s \"%s\"" % tmpl1, shell=True) atheist-0.20110402/test/test_func_fail.mtest0000644000175000017500000000060211457026445017572 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- # Test if a function which return nothing is handled as False def returnNothing(): pass TestFunc(returnNothing, ()) TestFunc(returnNothing, (), must_fail=True) #-- def raiseException(): raise AssertionError, "This an expected 'unexpected exceptiion'" TestFunc(raiseException, (), desc="An uncatched exception implies ERROR") atheist-0.20110402/test/load-fail.test0000644000175000017500000000077611523712750016267 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- msg1 = "[EE] | AttributeError: 'module' object has no attribute 'missing_func'" t1 = Test('$atheist $testdir/load-fail-by-missing-func.mtest', expected=1, save_stderr=True) t1.post += FileContains(msg1, t1.stderr) msg2 = "[EE] | IOError: [Errno 2] No such file or directory: './test/missing_path/missing_file.py'" t2 = Test('$atheist $testdir/load-fail-by-missing-module.mtest', expected=1, save_stderr=True) t2.post += FileContains(msg2, t2.stderr) atheist-0.20110402/test/dir-hooks.test0000644000175000017500000000121111527474305016324 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test('$atheist -i2 $testdir/dir-hooks', save_stderr=True, timeout=10) t.post += FileContains(['Test-1 S( 0: 0) echo "_SETUP ran"', 'Test-2 s( 0: 0) echo "_setup ran"', 'Test-3 -( 0: 0) echo "A ran"', 'Test-4 t( 0: 0) echo "_teardown ran"', 'Test-5 s( 0: 0) echo "_setup ran"', 'Test-6 -( 0: 0) echo "Z ran"', 'Test-7 t( 0: 0) echo "_teardown ran"', 'Test-8 T( 0: 0) echo "_TEARDOWN ran"'], t.stderr) atheist-0.20110402/test/child.test0000644000175000017500000000054511457026445015521 0ustar cletocleto# -*- mode: python; coding:utf-8 -*- python_loop =''' import time while 1: time.sleep(1) ''' a = Test('python -c "%s" > /dev/null' % python_loop, shell=True, detach=True, timeout=3, expected=-9) b = Test('true', delay=5) b.pre += Poll(Not(TaskRunning(a))) c = Test('pgrep -f "python -c %s"' % python_loop, shell=True, must_fail=True) atheist-0.20110402/test/get-task.test0000644000175000017500000000035411523712750016146 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- d0 = Daemon("cat", tid='cat') def same_task(a, b): return 0 if a is b else 1 t = TestFunc(same_task, (d0, get_task('cat')), desc="Task equality") t.pre += Poll(TaskRunning(d0)) atheist-0.20110402/test/substitutions.test0000644000175000017500000000023711457026445017373 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test("echo $basedir $testdir $fname $testname") t.post += FileContains(". ./test ./test/substitutions substitutions") atheist-0.20110402/test/unit/0000755000175000017500000000000011547304457014512 5ustar cletocletoatheist-0.20110402/test/unit/atheist_mock.py0000644000175000017500000000072611546304257017540 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- import atheist from mock import Mock class Task(Mock): def __init__(self): Mock.__init__(self) self.pre = atheist.ConditionList() self.post = atheist.ConditionList() class MockManager(atheist.manager.Manager): ts = [] cfg = Mock() cfg.timetag = '' cfg.screen_width = 80 cfg.save_stdout = False cfg.save_stderr = False suite = Mock() suite.next = lambda :0 atheist-0.20110402/test/unit/condition_list.test0000644000175000017500000000113211523712750020422 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- import sys import unittest import atheist sys.path.append('$testdir') from atheist_mock import Task class TestConditionList(unittest.TestCase): def test_ignore_condition_duplicates(self): task = Task() task.post += atheist.FileExists('/some/file') task.post += atheist.FileExists('/some/file') self.assert_(len(task.post) == 1) def test_Not_equality(self): e1 = atheist.FileExists('some/file') not_e1 = atheist.Not(e1) self.assert_(e1 != not_e1) UnitTestCase(TestConditionList) atheist-0.20110402/test/unit/alias.test0000644000175000017500000000411711523712750016500 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import logging import unittest from optparse import Option, OptionParser from mock import Mock import atheist logging.info("using %s", atheist.__file__) from atheist.plugins.alias import Alias class TestAlias(unittest.TestCase): def parser_with_options(self): parser = OptionParser() parser.add_option("--plain", action='store_true', default=False) parser.add_option("--disable-bar", action='store_true', default=False) parser.add_option("--cols", type=int) return parser def config_with_alias(self): config = Mock() config.alias.items._return_value = [('hudson', '--plain --cols 120 --disable-bar')] config.plain = False config.disable_bar = False config.cols = 80 return config def test_add_options_includes_alias_in_group(self): config = self.config_with_alias() parser = self.parser_with_options() group = Alias.get_options(config, parser) self.assert_(len(group) == 1) opt = group[0] self.assert_(opt.get_opt_string() == '--hudson') self.assert_(opt.action == 'store_true') def test_add_options_with_no_alias_section_does_nothing(self): class Empty: pass config = Empty() parser = Mock() group = Alias.get_options(config, parser) self.assert_(len(group) == 0) def test_config_apply_alias_on_cmdline(self): config = self.config_with_alias() config.hudson = True parser = self.parser_with_options() Alias.config(config, parser) self.assert_(config.plain) self.assert_(config.disable_bar) self.assert_(config.cols == 120) def test_config_do_NOT_apply_when_no_alias_on_cmdline(self): config = self.config_with_alias() config.hudson = False parser = self.parser_with_options() Alias.config(config, parser) self.assert_(config.plain == False) self.assert_(config.disable_bar == False) self.assert_(config.cols == 80) UnitTestCase(TestAlias) atheist-0.20110402/test/unit/keywords.test0000644000175000017500000000244511523712750017260 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import logging import unittest import atheist import atheist_mock logging.info("using %s" % atheist.__file__) class TestOuts(unittest.TestCase): def setUp(self): self.mng = atheist_mock.MockManager() def test_stdout_wrong_type_None(self): try: atheist.Test(self.mng, 'echo', stdout=None) except TypeError: return raise Exception def test_stdout_wrong_type_int(self): try: atheist.Test(self.mng, 'echo', stdout=0) except TypeError: return raise Exception def test_stderr_wrong_type_None(self): try: atheist.Test(self.mng, 'echo', stderr=None) except TypeError: return raise Exception def test_stderr_wrong_type_int(self): try: atheist.Test(self.mng, 'echo', stderr=0) except TypeError: return raise Exception def test_stdout_implies_save_stdout(self): test = atheist.Test(self.mng, 'echo', stdout='hola') self.assert_(test.save_stdout == True) def test_stderr_implies_save_stderr(self): test = atheist.Test(self.mng, 'echo', stderr='hola') self.assert_(test.save_stderr == True) UnitTestCase(TestOuts) atheist-0.20110402/test/unit/cxxtest.test0000644000175000017500000000776611546304257017132 0ustar cletocleto#!/usr/bin/python # -*- mode:python; coding:utf-8; tab-width:4 -*- import sys import os import unittest from mock import Mock sys.path.extend(['.', '$basedir/atheist']) from plugins.cxxtest import CxxTest import atheist import atheist_mock from atheist.plugins.debianpkg import DebPkgInstalled class TestCxxTest(unittest.TestCase): def setUp(self): self.mng = atheist_mock.MockManager() def test_creation_with_valid_single_file(self): cut = CxxTest(self.mng, 'test/cxxtest/single_ok.cc') self.assertEquals(cut.acro, 'Cxx') self.assertEquals(cut.testfile, 'test/cxxtest/single_ok.cc') def test_creation_with_invalid_single_file(self): fname = 'test/cxxtest/NOEXIST.cpp' t = CxxTest(self.mng, fname) self.assert_(atheist.FileExists(fname) in t.children[0].pre) def test_creation_without_compilation_flags(self): cut = CxxTest(self.mng, 'test/cxxtest/single_ok.cc') self.assertEquals(cut.compiling_flags, '-lcxxtest') def test_creation_with_others_compilation_flags(self): cut = CxxTest(self.mng, 'test/cxxtest/single_ok.cc', compiling_flags='-I/tmp') self.assertEquals(cut.compiling_flags, '-I/tmp -lcxxtest') def test_creation_with_objs(self): cut = CxxTest(self.mng, 'test/cxxtest/single_ok.cc', objs={'$testdir':['add.o','diff.o']}) self.assertEquals(cut.objs, {'$testdir':['add.o','diff.o']}) def test_get_information_of_params(self): cut = CxxTest(self.mng, 'test/cxxtest/single_ok.cc') self.assertEquals(cut.str_param(), 'test/cxxtest/single_ok.cc') def test_cxxtest_children(self): cut = CxxTest(self.mng, 'test/cxxtest/single_ok.cc') children = [CxxTest.Generator, CxxTest.CxxCompiler, atheist.Subprocess] for i,klass in enumerate(children): self.assertTrue(isinstance(cut.children[i], klass)) def test_generator_child(self): full_filename = os.path.abspath('test/cxxtest/single_ok.cc') runner = os.path.join(atheist.ATHEIST_TMP, 'single_ok_runner.cc') cxx = CxxTest(self.mng, full_filename) cut = cxx.children[0] self.assert_(runner in cut.gen) self.assertEquals(cut.cmd, 'cxxtestgen --error-printer -o {0} {1}'.format( runner, full_filename)) self.assertEquals(full_filename, cut.str_param()) def test_cxxcompiler_child(self): cxx = CxxTest(self.mng, 'test/cxxtest/single_ok.cc') runner = os.path.join(atheist.ATHEIST_TMP, 'single_ok_runner') cut = cxx.children[1] self.assert_(runner in cut.gen) self.assertEquals(runner+'.cc', cut.str_param()) def test_cxxcompiler_child_with_flags(self): cxx = CxxTest(self.mng, 'test/cxxtest/single_ok.cc', compiling_flags='-I/tmp') cut = cxx.children[1] flags = '-I/tmp -lcxxtest' input_file = os.path.join(atheist.ATHEIST_TMP, 'single_ok_runner.cc') output_file = input_file[:-3] self.assertEquals(cut.flags, flags) self.assertEquals(cut.objs,[]) self.assertEquals(cut.outputfile, output_file) self.assertEquals(cut.cmd, 'g++ %s %s -o %s' % (input_file, flags, output_file)) def test_cxxcompiler_child_with_objs(self): cxx = CxxTest(self.mng, 'test/cxxtest/single_ok.cc',objs={'.':['add.o','diff.o']}) cut = cxx.children[1] flags = '-lcxxtest' objs = ['./'+x for x in ['add.o','diff.o']] input_file = os.path.join(atheist.ATHEIST_TMP, 'single_ok_runner.cc') output_file = input_file[:-3] self.assertEquals(cut.flags, flags) self.assertEquals(cut.objs,objs) self.assertEquals(cut.outputfile,output_file) self.assertEquals(cut.cmd, 'g++ %s %s %s -o %s' % (input_file, flags, str.join(' ', objs), output_file)) UnitTestCase(TestCxxTest) atheist-0.20110402/test/unit/FileContains.test0000644000175000017500000000301711527474305017770 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- import sys import logging import unittest import atheist logging.info("using %s" % atheist.__file__) sys.path.append('$testdir') from atheist_mock import Task class TestFileContains(unittest.TestCase): def create_condition(self): return atheist.FileContains('hello', '/tmp/a') def test_equality(self): c1 = self.create_condition() c2 = self.create_condition() self.assert_(c1 == c2) def test_insert_FileExists(self): c = self.create_condition() task = Task() task.post += c newconds = c.pre_task_run(task, task.post) e = atheist.FileExists('/tmp/a') # print "-- %s --" % task.post self.assert_(len(task.pre) == 0) self.assert_(e in newconds) self.assert_(newconds.count(e) == 1) def test_insert_FileExists_in_correct_list(self): c_pre = atheist.FileContains('foo', '/some/file') c_post = atheist.FileContains('bar', '/some/file') task = Task() task.pre += c_pre task.post += c_post pre_newconds = c_pre.pre_task_run(task, task.pre) post_newconds = c_post.pre_task_run(task, task.post) e = FileExists('/some/file') self.assert_(e in pre_newconds) self.assert_(pre_newconds.count(e) == 1) self.assert_(e in post_newconds) self.assert_(post_newconds.count(e) == 1) def test_insert_FileExists_when_decorated(self): pass UnitTestCase(TestFileContains) atheist-0.20110402/test/unit/conditions.test0000644000175000017500000000664711546304257017576 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- from unittest import TestCase from mock import Mock import atheist import atheist.plugins.debianpkg as debianpkg import atheist.plugins.net as net import atheist.plugins.perf as perf import atheist.plugins.task_management as taskmng from atheist_mock import MockManager class TestConditionList(TestCase): def check_clist(self, n, *items): clist = atheist.ConditionList() for i in items: clist += i clist.remove_dups() self.assert_(len(clist)==n) def test_duplicate_Callback(self): def f(*args): pass def g(*args): pass self.check_clist(\ 3, atheist.Callback(f, (1,1,1)), atheist.Callback(f, (1,2,3)), atheist.Callback(f, (1,2,3)), atheist.Callback(g, (1,2,3))) def test_duplicate_EnvVarDefined(self): self.check_clist(\ 3, atheist.EnvVarDefined('var1'), atheist.EnvVarDefined('var2'), atheist.EnvVarDefined('var2'), atheist.EnvVarDefined('var2', 1)) def test_duplicate_FileEContains(self): self.check_clist(\ 3, atheist.FileContains('data1', 'file1'), atheist.FileContains('data1', 'file2'), atheist.FileContains('data1', 'file2'), atheist.FileContains('data2', 'file2')) def test_duplicate_FileExists(self): self.check_clist(\ 2, atheist.FileExists('file1'), atheist.FileExists('file2'), atheist.FileExists('file2')) def test_duplicate_FileEquals(self): self.check_clist(\ 3, atheist.FileEquals('file1', 'file2'), atheist.FileEquals('file2', 'file3'), atheist.FileEquals('file1', 'file3'), atheist.FileEquals('file1', 'file3')) def test_duplicate_FileIsNewerThan(self): self.check_clist(\ 3, atheist.FileIsNewerThan('file1', 'file2'), atheist.FileIsNewerThan('file2', 'file3'), atheist.FileIsNewerThan('file1', 'file3'), atheist.FileIsNewerThan('file1', 'file3')) def test_duplicate_ProcessRunning(self): self.check_clist(\ 2, atheist.ProcessRunning(1), atheist.ProcessRunning(2), atheist.ProcessRunning(2)) def test_duplicate_DebPkgInstalled(self): self.check_clist(\ 2, debianpkg.DebPkgInstalled('pkg1'), debianpkg.DebPkgInstalled('pkg2'), debianpkg.DebPkgInstalled('pkg2')) def test_duplicate_OpenPort(self): self.check_clist(\ 5, net.OpenPort(200), net.OpenPort(300), net.OpenPort(200, host='localhost'), net.OpenPort(200, host='localhost', proto='udp'), net.OpenPort(200, host='host1'), net.OpenPort(200, host='host2')) def test_duplicate_TimeLessThan(self): self.check_clist(\ 2, perf.TimeLessThan(1), perf.TimeLessThan(2), perf.TimeLessThan(2)) def test_duplicate_TaskFinished(self): mng = MockManager() t1 = atheist.Task(mng) t2 = atheist.Task(mng) self.check_clist(\ 2, taskmng.TaskFinished(t1), taskmng.TaskFinished(t2), taskmng.TaskFinished(t2)) UnitTestCase(TestConditionList) atheist-0.20110402/test/unit/ConfigFacade.test0000644000175000017500000000206011546304257017677 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- import sys import unittest sys.path.append('$basedir/atheist') from pyarco.iniparser import IniParser import atheist.manager class TestConfigFacade(unittest.TestCase): def test_key_holder(self): config = dict(sample=2) cut = atheist.manager.ConfigFacade() cut.add_holder(config) self.assert_(cut['sample'] == 2) try: cut['missing'] except KeyError: return self.fail() def test_getattr_from_IniParser(self): cut = atheist.manager.ConfigFacade() ini = IniParser() ini.add_section('sect1') ini.set('sect1', 'value', '5') cut.add_holder(ini) self.assert_(cut.sect1.value == '5') def test_getitem_from_IniParser(self): cut = atheist.manager.ConfigFacade() ini = IniParser() ini.add_section('sect1') ini.set('sect1', 'value', '5') cut.add_holder(ini) self.assert_(cut['sect1.value'] == '5') UnitTestCase(TestConfigFacade) atheist-0.20110402/test/unit/tasks.test0000644000175000017500000000052011523712750016526 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import sys, os from unittest import TestCase import logging import atheist import atheist_mock logging.info("using %s" % atheist.__file__) class TestTasks(TestCase): def test_command(self): mng = atheist_mock.MockManager() atheist.Test(mng, 'true') UnitTestCase(TestTasks) atheist-0.20110402/test/unit/unittest.test0000644000175000017500000000160311526204745017266 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- import random import unittest # Example taken from http://docs.python.org/library/unittest.html class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def test_shuffle(self): """ Make sure the shuffled sequence does not lose any elements """ random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) def test_choice(self): "Make sure choice select items from sequence" element = random.choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): """ Test if sample choices unique numbers """ self.assertRaises(ValueError, random.sample, self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) UnitTestCase(TestSequenceFunctions) atheist-0.20110402/test/user_vars.mtest0000644000175000017500000000011011475251202016577 0ustar cletocleto# -*- mode:python; coding:utf-8; tab-width:4 -*- Test("echo $myname") atheist-0.20110402/test/env-polution.test0000644000175000017500000000041311527474305017067 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test('$atheist -s "a=1" -s "print a"', shell=True, expected=1, save_stderr=True, desc="Assure the taskcases have isolated environments") t.post += FileContains("NameError: name 'a' is not defined", t.stderr) atheist-0.20110402/test/describe.test0000644000175000017500000000031511526204745016207 0ustar cletocleto# -*- mode: python; coding:utf-8 -*- import glob #Test('$atheist -d $testdir/list-only.test') for test in sorted(glob.glob('$testdir/*.test')): Test('$atheist -d %s' % test, detach=True, timeout=6) atheist-0.20110402/test/hello.test0000644000175000017500000000013211546304257015530 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test('echo "hello world!"', desc="trivial test") atheist-0.20110402/test/command.test0000644000175000017500000000006011457026445016044 0ustar cletocleto#-*-python-*- Command('ls') Command('ls /tmp') atheist-0.20110402/test/auto-exists.mtest0000644000175000017500000000050211524504450017061 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- t = Test('ls', desc="atheist automatically adds a FileExists condition for FileContains") # stdout t.post += FileContains('something') # other file t.post += FileContains('something', '/some/file') # even decorated t.post += Not(FileContains('something', '/other/file')) atheist-0.20110402/test/ctrl-c.test0000644000175000017500000000031611457026445015616 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import signal a = Test('$atheist -t -vv $testdir/loop.mtest', detach=True, timeout=30, signal=signal.SIGINT, expected=2) TaskTerminator(a, delay=3) atheist-0.20110402/server.py0000755000175000017500000000766711457026443014453 0ustar cletocleto#!/usr/bin/python -u # -*- mode: python; coding: utf-8 -*- from __future__ import with_statement import sys import threading import os import logging import Ice cwd = os.path.dirname(__file__) Ice.loadSlice('-I%s --all %s/atheist.ice' % (Ice.getSliceDir(), cwd)) import Atheist as rath import atheist from atheist.manager import Manager log = logging.getLogger('atheist.server') log.setLevel(logging.DEBUG) log.debug('log init') def get_proxies(adapter, cast, servants): proxies = [adapter.addWithUUID(x) for x in servants] return [cast.uncheckedCast(x) for x in proxies] class TaskCaseI(rath.TaskCase): def __init__(self, mng, tc): self.mng = mng self.tc = tc self.lock = threading.Lock() # from TaskCase interface def run(self, current=None): self.mng.statusOb.updateTaskCases({self.tc.fname: rath.Status.RUNNING}) if self.lock.locked(): return with self.lock: self.tc.run() self.mng.statusOb.updateTasks( dict([("%s:%s" % (t.fname, t.name), rath.Status(t.result)) for t in self.tc.tasks])) self.mng.statusOb.updateTaskCases( {self.tc.fname: rath.Status(self.tc.result)}) # from TaskCase interface def getConfig(self, current=None): retval = {} for task in self.tc.tasks: config = rath.TaskConfig(indx=task.indx) for name in [x for x in dir(config) if x in atheist.task_attrs.keys()]: setattr(config, name, getattr(task, name)) retval[str(task.indx)] = config return retval # from TaskCase interface def getStatus(self, current=None): raise NotImplementedError class ManagerI(rath.Manager): def __init__(self, argv, adap): self.mng = Manager(argv) self.adap = adap self.statusOb = None self.outOb = None self.logOb = None self.cases = [] self.proxies = [] self.lock = threading.Lock() def refresh(self): # FIXME: Se deben eliminar los proxies de los cases que ya no # existen y añadir solo los nuevos for prx in self.proxies: self.adap.remove(prx.ice_getIdentity()) self.mng.reload() self.cases = [TaskCaseI(self,x) for x in self.mng.itercases()] self.proxies = get_proxies(self.adap, rath.TaskCasePrx, self.cases) for c in self.mng.itercases(): print c log.info("cases: %s" % len(self.cases)) # from Manager interface def getTaskCases(self, current=None): return self.proxies # from Manager interface def runAll(self, current=None): if self.lock.locked(): log.warning('runAll: Manager is already running .............') return with self.lock: self.refresh() self.statusOb.updateManager(rath.Status.RUNNING) for tc in self.cases: tc.run() self.statusOb.updateManager(rath.Status.UNKNOWN) # from Manager interface def attachStatusOb(self, ob, current=None): self.statusOb = ob # from Manager interface def attachOutOb(self, ob, taskIds, current=None): self.outOb = ob # from Manager interface def attachLogOb(self, ob, taskIds, current=None): self.logOb = ob class server(Ice.Application): def run(self, argv): self.shutdownOnInterrupt() ic = self.communicator() adapter = self.communicator().createObjectAdapter("Manager.Adapter") oid = ic.getProperties().getProperty("Manager.InstanceName") oid = ic.stringToIdentity(oid) proxy = adapter.add(ManagerI(argv, adapter), oid) adapter.activate() log.debug("Manager at '%s'" % proxy) self.communicator().waitForShutdown() return 0 if __name__ == "__main__": sys.exit(server().main(sys.argv[1:])) atheist-0.20110402/setup.py0000644000175000017500000000244211457026443014264 0ustar cletocleto#!/usr/bin/env python # Copyright (C) 2009 David Villa Alises # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA from distutils.core import setup from atheist import VERSION setup(name = 'atheist', version = VERSION, description = 'Atheist is a general purpose test framework written in Python.', author = 'David Villa Alises', author_email = '', url = 'https://savannah.nongnu.org/projects/atheist/', license = 'GPL v2 or later', data_files = [('share/man/man1',['debian/atheist.1'])], packages = ['atheist', 'atheist.plugins', 'pyarco'] ) atheist-0.20110402/samples/0000755000175000017500000000000011547300376014214 5ustar cletocletoatheist-0.20110402/samples/_teardown.test0000644000175000017500000000002011457026445017071 0ustar cletocletoCommand('true') atheist-0.20110402/samples/netcat.test0000644000175000017500000000200711457026445016374 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- # Copyright (C) 2009 David Villa Alises # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA cond = OpenPort(2000, proto='udp') server = Test('nc -l -u -p 2000', detach=True, timeout=4, expected=-9) server.pre += Not(cond) client = Test('nc -u localhost 2000 -c "echo hola"', shell=True) client.pre += Poll(cond) TaskTerminator(server) atheist-0.20110402/samples/ping_group.test0000644000175000017500000000016011457026445017265 0ustar cletocleto# -*- mode: python; coding: utf-8 -*- for i in range(1,20): Test('ping -c 1 161.67.106.%s' % i, timeout=1) atheist-0.20110402/samples/_setup.test0000644000175000017500000000003711457026445016416 0ustar cletocleto Daemon('cat') Command('true') atheist-0.20110402/samples/package.pt0000644000175000017500000000004611457026445016156 0ustar cletocleto def defineTest(): Test('ls ') atheist-0.20110402/samples/is_google_reachable.test0000644000175000017500000000265211547300376021057 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- # Copyright (C) 2009 David Villa Alises # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA link = Test('ip link | grep eth0 | grep "state UP"', desc="interface link up", shell=True) gw = Test("ping -c2 $(/sbin/route -n | grep ^0.0.0.0 | awk '{print $2}')", desc="local router reachable", shell=True) for line in file('/etc/resolv.conf'): if not line.startswith('nameserver'): continue Test('ping -c 2 %s' % line.split(' ')[1], desc="DNS server reachable") dns = Test('host www.google.com', desc="Resolve google website") Test('ping -c 1 www.google.com', desc="google reachable") http = WebTest('http://www.google.es') http.post += FileContains('value="Voy a tener suerte"') atheist-0.20110402/samples/hello-fail.test0000644000175000017500000000013311457026445017130 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- t = Test('true') t.post += FileExists('non-existent') atheist-0.20110402/samples/poll.test0000644000175000017500000000016311457026445016065 0ustar cletocleto Test('touch /tmp/hola', delay=3, detach=True) t1 = Test(None) t1.pre += Poll(Not(FileExists('/tmp/hola')), 1, 4) atheist-0.20110402/samples/ping.test0000644000175000017500000000500311457026445016052 0ustar cletocleto# -*- mode:python; coding:utf-8 -*- import signal, re, math, numpy, sys #ping_obj = re.compile("(\d+) bytes from (.+) \(([\d\.]+)\): icmp_seq=(\d+) ttl=(\d+) time=(?P