├── .gitignore ├── AESCryptFileLib.php ├── LICENSE.md ├── README.md ├── aes256 ├── AES256Implementation.php └── MCryptAES256Implementation.php ├── docs └── AES - File Format.htm ├── example_usage.php └── tests ├── AESCryptFileLibTest.php ├── CorruptionTest.php ├── ExtensionBlockTest.php ├── files ├── altered.jpg.aes ├── dench.jpg ├── file_with_null_ending.bin └── sample_text.txt ├── index.php └── simpletest ├── HELP_MY_TESTS_DONT_WORK_ANYMORE ├── LICENSE ├── README ├── VERSION ├── arguments.php ├── authentication.php ├── autorun.php ├── browser.php ├── collector.php ├── compatibility.php ├── cookies.php ├── default_reporter.php ├── detached.php ├── docs ├── en │ ├── authentication_documentation.html │ ├── browser_documentation.html │ ├── docs.css │ ├── expectation_documentation.html │ ├── form_testing_documentation.html │ ├── group_test_documentation.html │ ├── index.html │ ├── mock_objects_documentation.html │ ├── overview.html │ ├── partial_mocks_documentation.html │ ├── reporter_documentation.html │ ├── unit_test_documentation.html │ └── web_tester_documentation.html └── fr │ ├── authentication_documentation.html │ ├── browser_documentation.html │ ├── docs.css │ ├── expectation_documentation.html │ ├── form_testing_documentation.html │ ├── group_test_documentation.html │ ├── index.html │ ├── mock_objects_documentation.html │ ├── overview.html │ ├── partial_mocks_documentation.html │ ├── reporter_documentation.html │ ├── unit_test_documentation.html │ └── web_tester_documentation.html ├── dumper.php ├── eclipse.php ├── encoding.php ├── errors.php ├── exceptions.php ├── expectation.php ├── extensions ├── pear_test_case.php ├── testdox.php └── testdox │ └── test.php ├── form.php ├── frames.php ├── http.php ├── invoker.php ├── mock_objects.php ├── page.php ├── php_parser.php ├── recorder.php ├── reflection_php4.php ├── reflection_php5.php ├── remote.php ├── reporter.php ├── scorer.php ├── selector.php ├── shell_tester.php ├── simpletest.php ├── socket.php ├── tag.php ├── test ├── acceptance_test.php ├── adapter_test.php ├── all_tests.php ├── arguments_test.php ├── authentication_test.php ├── autorun_test.php ├── bad_test_suite.php ├── browser_test.php ├── collector_test.php ├── command_line_test.php ├── compatibility_test.php ├── cookies_test.php ├── detached_test.php ├── dumper_test.php ├── eclipse_test.php ├── encoding_test.php ├── errors_test.php ├── exceptions_test.php ├── expectation_test.php ├── form_test.php ├── frames_test.php ├── http_test.php ├── interfaces_test.php ├── interfaces_test_php5_1.php ├── live_test.php ├── mock_objects_test.php ├── page_test.php ├── parse_error_test.php ├── parsing_test.php ├── php_parser_test.php ├── recorder_test.php ├── reflection_php5_test.php ├── remote_test.php ├── shell_test.php ├── shell_tester_test.php ├── simpletest_test.php ├── site │ └── file.html ├── socket_test.php ├── support │ ├── collector │ │ ├── collectable.1 │ │ └── collectable.2 │ ├── empty_test_file.php │ ├── failing_test.php │ ├── latin1_sample │ ├── passing_test.php │ ├── recorder_sample.php │ ├── spl_examples.php │ ├── supplementary_upload_sample.txt │ ├── test1.php │ └── upload_sample.txt ├── tag_test.php ├── test_with_parse_error.php ├── unit_tester_test.php ├── unit_tests.php ├── url_test.php ├── user_agent_test.php ├── visual_test.php ├── web_tester_test.php └── xml_test.php ├── test_case.php ├── tidy_parser.php ├── unit_tester.php ├── url.php ├── user_agent.php ├── web_tester.php └── xml.php /.gitignore: -------------------------------------------------------------------------------- 1 | /nbproject/private/ 2 | /nbproject/project.properties 3 | /nbproject/project.xml -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Philip Nicholls 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PHP AES File Encryption 2 | ============= 3 | 4 | PHP implementation of the open source aes crypt file format 5 | 6 | File specification is described here 7 | https://www.aescrypt.com/aes_file_format.html 8 | 9 | ##Introduction 10 | There are many PHP AES implementations available online which offer AES encryption for data streams. It is possible to utilise these low level libraries to encrypt files, but unless you do everything correctly you can end up with an insecure (or broken) library. This library works at a higher level, depending on a low level AES encryption engine (which you can configure), and implementing the open source aes crypt file format. 11 | 12 | ##Problems 13 | There are many problems to solve when implementing file encryption using a low level library such as mycrpt. Many people incorrectly think you can just encrypt data and shove it in a file. Alas, it is not that simple. 14 | 15 | The open source file format handles many issues such as null bytes trimming, file integrity and fast password checking. It even comes with file extension identifiers which allows arbitrary data to be tagged within the AES file (unencrypted). 16 | 17 | This library makes it easier for users who are only interested in encrypting and decrypting .aes files with passwords. Other technicalities such as file structure, versions & encryption keys are transparent to the user. 18 | 19 | ##Requirements 20 | 1. PHP 5 21 | 2. An AES 256 bit Encryption Implementation (you can use the included mcrypt implementation or some other) 22 | If you don't have mcrypt available, you only need to implement the AES256Implementation interface using whatever library you want. 23 | 24 | ##Usage (see example_usage.php) 25 | 1. Include the AESCryptFileLib.php class 26 | 2. Construct an instance of the library using an AES256 implementation 27 | 3. Call the public functions 28 | 29 | ##Compatibility 30 | This library writes version 2 of the file specification defined at https://www.aescrypt.com/aes_file_format.html 31 | Backwards compatibility with the older two versions (reading old .aes files) is untested. 32 | Output .aes files are fully compatible with any software using the AES Crypt standard file format. 33 | 34 | ##To do 35 | 1. Test reading files stored in version 0 and 1 formats. 36 | 37 | ##License 38 | I believe that open source software should be free for everyone and non restrictive. My code is based on a completely free to use open source file format which I did not invent. I will choose MIT since it seems to be the least restrictive license out there. -------------------------------------------------------------------------------- /aes256/AES256Implementation.php: -------------------------------------------------------------------------------- 1 | encryptFile($file_to_encrypt, "1234", $encrypted_file); 24 | 25 | //Ensure file does not exist 26 | @unlink($decrypted_file); 27 | //Decrypt using same password 28 | $lib->decryptFile($encrypted_file, "1234", $decrypted_file); 29 | 30 | echo "Done"; -------------------------------------------------------------------------------- /tests/AESCryptFileLibTest.php: -------------------------------------------------------------------------------- 1 | file_orig = $file_to_test; 14 | $this->file_enc = $file_to_test . ".aes"; 15 | $this->file_dec = $file_to_test . ".dec"; 16 | } 17 | 18 | function setUp() { 19 | @unlink($this->file_enc); 20 | @unlink($this->file_dec); 21 | } 22 | 23 | function tearDown() { 24 | @unlink($this->file_enc); 25 | @unlink($this->file_dec); 26 | } 27 | 28 | function testVariables() { 29 | $this->assertNotEqual($this->passphrase, $this->badpassphrase); 30 | $this->assertTrue(file_exists($this->file_orig)); 31 | $this->assertTrue(filesize($this->file_orig) > 0); 32 | $this->assertFalse(file_exists($this->file_enc)); 33 | $this->assertFalse(file_exists($this->file_dec)); 34 | } 35 | 36 | function encryptFileAndReturnLib() { 37 | $mcrypt = new MCryptAES256Implementation(); 38 | $lib = new AESCryptFileLib($mcrypt); 39 | 40 | //Encrypt file 41 | $encrypted_file = $lib->encryptFile($this->file_orig, $this->passphrase, $this->file_enc); 42 | $this->assertTrue(file_exists($encrypted_file)); 43 | $this->assertTrue(filesize($encrypted_file) > 0); 44 | 45 | return $lib; 46 | } 47 | 48 | function testCorrectPassword() { 49 | $lib = $this->encryptFileAndReturnLib(); 50 | 51 | //Attempt to decrypt with good passphrase 52 | $decrypted_file = $lib->decryptFile($this->file_enc, $this->passphrase, $this->file_dec); 53 | $this->assertTrue(file_exists($decrypted_file)); 54 | $this->assertEqual(hash_file("sha256", $this->file_orig), hash_file("sha256", $decrypted_file)); 55 | } 56 | 57 | function testBadPassword() { 58 | $lib = $this->encryptFileAndReturnLib(); 59 | 60 | //Attempt decryption with bad passphrase 61 | $decrypted_file = NULL; 62 | try { 63 | $decrypted_file = $lib->decryptFile($this->file_enc, $this->badpassphrase, $this->file_dec); 64 | } catch (AESCryptInvalidPassphraseException $e) { 65 | //OK 66 | $this->pass("Yes, incorrect password"); 67 | } catch (Exception $e) { 68 | $this->fail("Not an AESCryptInvalidPassphraseException: " . get_class($e)); 69 | } 70 | $this->assertNull($decrypted_file); 71 | } 72 | } 73 | 74 | class DenchTest extends AESCryptFileLibTest { 75 | public function __construct() { 76 | parent::__construct("files/dench.jpg"); 77 | } 78 | } 79 | 80 | class NullEndingFileTest extends AESCryptFileLibTest { 81 | public function __construct() { 82 | parent::__construct("files/file_with_null_ending.bin"); 83 | } 84 | } 85 | 86 | class SampleTextFileTest extends AESCryptFileLibTest { 87 | public function __construct() { 88 | parent::__construct("files/sample_text.txt"); 89 | } 90 | } -------------------------------------------------------------------------------- /tests/CorruptionTest.php: -------------------------------------------------------------------------------- 1 | file_enc = $file_to_decode; 13 | $this->file_dec = $file_to_decode . ".dec"; 14 | } 15 | 16 | function setUp() { 17 | @unlink($this->file_dec); 18 | } 19 | 20 | function tearDown() { 21 | @unlink($this->file_dec); 22 | } 23 | 24 | function testVariables() { 25 | $this->assertNotEqual($this->passphrase, $this->badpassphrase); 26 | $this->assertTrue(file_exists($this->file_enc)); 27 | $this->assertTrue(filesize($this->file_enc) > 0); 28 | $this->assertFalse(file_exists($this->file_dec)); 29 | } 30 | 31 | function testCorrectPassword() { 32 | //Attempt to decrypt corrupted file with good passphrase 33 | $decrypted_file = NULL; 34 | try { 35 | $mcrypt = new MCryptAES256Implementation(); 36 | $lib = new AESCryptFileLib($mcrypt); 37 | $decrypted_file = $lib->decryptFile($this->file_enc, $this->passphrase, $this->file_dec); 38 | } catch (AESCryptCorruptedFileException $e) { 39 | //OK 40 | $this->pass("Yes, file correctly detected as corrupted"); 41 | } catch (Exception $e) { 42 | $this->fail("Not an AESCryptCorruptedFileException: " . get_class($e)); 43 | } 44 | $this->assertNull($decrypted_file); 45 | } 46 | } 47 | 48 | class DenchCorruptedTest extends CorruptionTest { 49 | public function __construct() { 50 | parent::__construct("files/altered.jpg.aes"); 51 | } 52 | } -------------------------------------------------------------------------------- /tests/ExtensionBlockTest.php: -------------------------------------------------------------------------------- 1 | file_orig = $file_to_test; 10 | $this->file_enc = $file_to_test . ".aes"; 11 | $this->file_dec = $file_to_test . ".dec"; 12 | } 13 | 14 | function setUp() { 15 | @unlink($this->file_enc); 16 | @unlink($this->file_dec); 17 | } 18 | 19 | function tearDown() { 20 | @unlink($this->file_enc); 21 | @unlink($this->file_dec); 22 | } 23 | 24 | function assertBadExtensionBlock($lib, $ext_data) 25 | { 26 | $success = NULL; 27 | try { 28 | $success = $lib->encryptFile($this->file_orig, '1234', $this->file_enc, $ext_data); 29 | } catch (AESCryptInvalidExtensionException $aiee) { 30 | $this->pass("Bad extension block correctly identified"); 31 | } catch (Exception $e) { 32 | $this->fail("Not an AESCryptInvalidExtensionException: " . get_class($e)); 33 | } 34 | $this->assertNull($success); 35 | } 36 | 37 | function testInvalidExtensionBlocks() { 38 | $mcrypt = new MCryptAES256Implementation(); 39 | $lib = new AESCryptFileLib($mcrypt); 40 | 41 | $this->assertBadExtensionBlock($lib, "Just a string"); 42 | $this->assertBadExtensionBlock($lib, array("Array of single string")); 43 | $this->assertBadExtensionBlock($lib, array("Array of lots", "of strings")); 44 | $this->assertBadExtensionBlock($lib, array(array('bad' => 'xxx', 'keys' => 'xxx'))); 45 | $this->assertBadExtensionBlock($lib, array(array('identifie' => 'misspelling', 'contents' => 'good'))); 46 | $this->assertBadExtensionBlock($lib, array(array('identifier' => 'good', 'content' => 'misspelling'))); 47 | $this->assertBadExtensionBlock($lib, array(array('identifier' => 'good', 'contents' => 'good'), 'bad item')); 48 | $this->assertBadExtensionBlock($lib, array(array('identifier' => 'good', 'contents' => 'good'), array('identifie' => 'misspelling', 'contents' => 'good'))); 49 | $this->assertBadExtensionBlock($lib, array(array('identifier' => 'good', 'contents' => 'good'), NULL, NULL)); 50 | $this->assertBadExtensionBlock($lib, array(array('identifier' => 'repeated', 'contents' => 'good'), array('identifier' => 'repeated', 'contents' => 'something else'))); 51 | } 52 | 53 | function assertGoodExtensionBlock($lib, $ext_data) 54 | { 55 | //First encrypt the file 56 | $lib->encryptFile($this->file_orig, '1234', $this->file_enc, $ext_data); 57 | 58 | //Then read the blocks back out 59 | $read_blocks = $lib->readExtensionBlocks($this->file_enc); 60 | 61 | //These should match 62 | $this->assertIdentical($read_blocks, $ext_data); 63 | } 64 | 65 | function testValidExtensionBlocks() { 66 | $mcrypt = new MCryptAES256Implementation(); 67 | $lib = new AESCryptFileLib($mcrypt); 68 | 69 | $this->assertGoodExtensionBlock($lib, array(array('identifier' => 'first', 'contents' => 'one'), array('identifier' => 'second', 'contents' => 'two'), array('identifier' => 'third', 'contents' => 'three'))); 70 | } 71 | 72 | } 73 | 74 | class DenchExtensionBlockTest extends ExtensionBlockTest { 75 | public function __construct() { 76 | parent::__construct("files/dench.jpg"); 77 | } 78 | } -------------------------------------------------------------------------------- /tests/files/altered.jpg.aes: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philios33/PHP-AES-File-Encryption/e8f5901afcd51bfc19aa4a40bd50ef7f5ab6f627/tests/files/altered.jpg.aes -------------------------------------------------------------------------------- /tests/files/dench.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philios33/PHP-AES-File-Encryption/e8f5901afcd51bfc19aa4a40bd50ef7f5ab6f627/tests/files/dench.jpg -------------------------------------------------------------------------------- /tests/files/file_with_null_ending.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philios33/PHP-AES-File-Encryption/e8f5901afcd51bfc19aa4a40bd50ef7f5ab6f627/tests/files/file_with_null_ending.bin -------------------------------------------------------------------------------- /tests/files/sample_text.txt: -------------------------------------------------------------------------------- 1 | Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. 2 | 3 | Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. 4 | 5 | Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. -------------------------------------------------------------------------------- /tests/index.php: -------------------------------------------------------------------------------- 1 | collect(dirname(__FILE__) . '/', new SimplePatternCollector('/Test.php/')); 10 | } 11 | } -------------------------------------------------------------------------------- /tests/simpletest/README: -------------------------------------------------------------------------------- 1 | SimpleTest 2 | ========== 3 | 4 | You probably got this package from: 5 | 6 | http://simpletest.org/en/download.html 7 | 8 | If there is no licence agreement with this package please download 9 | a version from the location above. You must read and accept that 10 | licence to use this software. The file is titled simply LICENSE. 11 | 12 | What is it? It's a framework for unit testing, web site testing and 13 | mock objects for PHP 5.0.5+. 14 | 15 | If you have used JUnit, you will find this PHP unit testing version very 16 | similar. Also included is a mock objects and server stubs generator. 17 | The stubs can have return values set for different arguments, can have 18 | sequences set also by arguments and can return items by reference. 19 | The mocks inherit all of this functionality and can also have 20 | expectations set, again in sequences and for different arguments. 21 | 22 | A web tester similar in concept to JWebUnit is also included. There is no 23 | JavaScript or tables support, but forms, authentication, cookies and 24 | frames are handled. 25 | 26 | You can see a release schedule at http://simpletest.org/en/overview.html 27 | which is also copied to the documentation folder with this release. 28 | A full PHPDocumenter API documentation exists at 29 | http://simpletest.org/api/. 30 | 31 | The user interface is minimal in the extreme, but a lot of information 32 | flows from the test suite. After version 1.0 we will release a better 33 | web UI, but we are leaving XUL and GTK versions to volunteers as 34 | everybody has their own opinion on a good GUI, and we don't want to 35 | discourage development by shipping one with the toolkit. You can 36 | download an Eclipse plug-in separately. 37 | 38 | The unit tests for SimpleTest itself can be run here: 39 | 40 | test/unit_tests.php 41 | 42 | And tests involving live network connections as well are here: 43 | 44 | test/all_tests.php 45 | 46 | The full tests will typically overrun the 8Mb limit often allowed 47 | to a PHP process. A workaround is to run the tests on the command 48 | with a custom php.ini file or with the switch -dmemory_limit=-1 49 | if you do not have access to your server version. 50 | 51 | The full tests read some test data from simpletest.org. If the site 52 | is down or has been modified for a later version then you will get 53 | spurious errors. A unit_tests.php failure on the other hand would be 54 | very serious. Please notify us if you find one. 55 | 56 | Even if all of the tests run please verify that your existing test suites 57 | also function as expected. The file: 58 | 59 | HELP_MY_TESTS_DONT_WORK_ANYMORE 60 | 61 | ...contains information on interface changes. It also points out 62 | deprecated interfaces, so you should read this even if all of 63 | your current tests appear to run. 64 | 65 | There is a documentation folder which contains the core reference information 66 | in English and French, although this information is fairly basic. 67 | You can find a tutorial on... 68 | 69 | http://simpletest.org/en/first_test_tutorial.html 70 | 71 | ...to get you started and this material will eventually become included 72 | with the project documentation. A French translation exists at: 73 | 74 | http://simpletest.org/fr/first_test_tutorial.html 75 | 76 | If you download and use, and possibly even extend this tool, please let us 77 | know. Any feedback, even bad, is always welcome and we will work to get 78 | your suggestions into the next release. Ideally please send your 79 | comments to: 80 | 81 | simpletest-support@lists.sourceforge.net 82 | 83 | ...so that others can read them too. We usually try to respond within 48 84 | hours. 85 | 86 | There is no change log except at Sourceforge. You can visit the 87 | release notes to see the completed TODO list after each cycle and also the 88 | status of any bugs, but if the bug is recent then it will be fixed in SVN only. 89 | The SVN check-ins always have all the tests passing and so SVN snapshots should 90 | be pretty usable, although the code may not look so good internally. 91 | 92 | Oh, and one last thing: SimpleTest is called "Simple" because it should 93 | be simple to use. We intend to add a complete set of tools for a test 94 | first and "test as you code" type of development. "Simple" does not mean 95 | "Lite" in this context. 96 | 97 | Thanks to everyone who has sent comments and offered suggestions. They 98 | really are invaluable, but sadly you are too many to mention in full. 99 | Thanks to all on the advanced PHP forum on SitePoint, especially Harry 100 | Fuecks. Early adopters are always an inspiration. 101 | 102 | -- Marcus Baker, Jason Sweat, Travis Swicegood, Perrick Penet and Edward Z. Yang. 103 | -------------------------------------------------------------------------------- /tests/simpletest/VERSION: -------------------------------------------------------------------------------- 1 | 1.1.0 2 | -------------------------------------------------------------------------------- /tests/simpletest/arguments.php: -------------------------------------------------------------------------------- 1 | 0) { 31 | list($key, $value) = $this->parseArgument($arguments); 32 | $this->assign($key, $value); 33 | } 34 | } 35 | 36 | /** 37 | * Sets the value in the argments object. If multiple 38 | * values are added under the same key, the key will 39 | * give an array value in the order they were added. 40 | * @param string $key The variable to assign to. 41 | * @param string value The value that would norally 42 | * be colected on the command line. 43 | */ 44 | function assign($key, $value) { 45 | if ($this->$key === false) { 46 | $this->all[$key] = $value; 47 | } elseif (! is_array($this->$key)) { 48 | $this->all[$key] = array($this->$key, $value); 49 | } else { 50 | $this->all[$key][] = $value; 51 | } 52 | } 53 | 54 | /** 55 | * Extracts the next key and value from the argument list. 56 | * @param array $arguments The remaining arguments to be parsed. 57 | * The argument list will be reduced. 58 | * @return array Two item array of key and value. 59 | * If no value can be found it will 60 | * have the value true assigned instead. 61 | */ 62 | private function parseArgument(&$arguments) { 63 | $argument = array_shift($arguments); 64 | if (preg_match('/^-(\w)=(.+)$/', $argument, $matches)) { 65 | return array($matches[1], $matches[2]); 66 | } elseif (preg_match('/^-(\w)$/', $argument, $matches)) { 67 | return array($matches[1], $this->nextNonFlagElseTrue($arguments)); 68 | } elseif (preg_match('/^--(\w+)=(.+)$/', $argument, $matches)) { 69 | return array($matches[1], $matches[2]); 70 | } elseif (preg_match('/^--(\w+)$/', $argument, $matches)) { 71 | return array($matches[1], $this->nextNonFlagElseTrue($arguments)); 72 | } 73 | } 74 | 75 | /** 76 | * Attempts to use the next argument as a value. It 77 | * won't use what it thinks is a flag. 78 | * @param array $arguments Remaining arguments to be parsed. 79 | * This variable is modified if there 80 | * is a value to be extracted. 81 | * @return string/boolean The next value unless it's a flag. 82 | */ 83 | private function nextNonFlagElseTrue(&$arguments) { 84 | return $this->valueIsNext($arguments) ? array_shift($arguments) : true; 85 | } 86 | 87 | /** 88 | * Test to see if the next available argument is a valid value. 89 | * If it starts with "-" or "--" it's a flag and doesn't count. 90 | * @param array $arguments Remaining arguments to be parsed. 91 | * Not affected by this call. 92 | * boolean True if valid value. 93 | */ 94 | function valueIsNext($arguments) { 95 | return isset($arguments[0]) && ! $this->isFlag($arguments[0]); 96 | } 97 | 98 | /** 99 | * It's a flag if it starts with "-" or "--". 100 | * @param string $argument Value to be tested. 101 | * @return boolean True if it's a flag. 102 | */ 103 | function isFlag($argument) { 104 | return strncmp($argument, '-', 1) == 0; 105 | } 106 | 107 | /** 108 | * The arguments are available as individual member 109 | * variables on the object. 110 | * @param string $key Argument name. 111 | * @return string/array/boolean Either false for no value, 112 | * the value as a string or 113 | * a list of multiple values if 114 | * the flag had been specified more 115 | * than once. 116 | */ 117 | function __get($key) { 118 | if (isset($this->all[$key])) { 119 | return $this->all[$key]; 120 | } 121 | return false; 122 | } 123 | 124 | /** 125 | * The entire argument set as a hash. 126 | * @return hash Each argument and it's value(s). 127 | */ 128 | function all() { 129 | return $this->all; 130 | } 131 | } 132 | 133 | /** 134 | * Renders the help for the command line arguments. 135 | * @package SimpleTest 136 | * @subpackage UnitTester 137 | */ 138 | class SimpleHelp { 139 | private $overview; 140 | private $flag_sets = array(); 141 | private $explanations = array(); 142 | 143 | /** 144 | * Sets up the top level explanation for the program. 145 | * @param string $overview Summary of program. 146 | */ 147 | function __construct($overview = '') { 148 | $this->overview = $overview; 149 | } 150 | 151 | /** 152 | * Adds the explanation for a group of flags that all 153 | * have the same function. 154 | * @param string/array $flags Flag and alternates. Don't 155 | * worry about leading dashes 156 | * as these are inserted automatically. 157 | * @param string $explanation What that flag group does. 158 | */ 159 | function explainFlag($flags, $explanation) { 160 | $flags = is_array($flags) ? $flags : array($flags); 161 | $this->flag_sets[] = $flags; 162 | $this->explanations[] = $explanation; 163 | } 164 | 165 | /** 166 | * Generates the help text. 167 | * @returns string The complete formatted text. 168 | */ 169 | function render() { 170 | $tab_stop = $this->longestFlag($this->flag_sets) + 4; 171 | $text = $this->overview . "\n"; 172 | for ($i = 0; $i < count($this->flag_sets); $i++) { 173 | $text .= $this->renderFlagSet($this->flag_sets[$i], $this->explanations[$i], $tab_stop); 174 | } 175 | return $this->noDuplicateNewLines($text); 176 | } 177 | 178 | /** 179 | * Works out the longest flag for formatting purposes. 180 | * @param array $flag_sets The internal flag set list. 181 | */ 182 | private function longestFlag($flag_sets) { 183 | $longest = 0; 184 | foreach ($flag_sets as $flags) { 185 | foreach ($flags as $flag) { 186 | $longest = max($longest, strlen($this->renderFlag($flag))); 187 | } 188 | } 189 | return $longest; 190 | } 191 | 192 | /** 193 | * Generates the text for a single flag and it's alternate flags. 194 | * @returns string Help text for that flag group. 195 | */ 196 | private function renderFlagSet($flags, $explanation, $tab_stop) { 197 | $flag = array_shift($flags); 198 | $text = str_pad($this->renderFlag($flag), $tab_stop, ' ') . $explanation . "\n"; 199 | foreach ($flags as $flag) { 200 | $text .= ' ' . $this->renderFlag($flag) . "\n"; 201 | } 202 | return $text; 203 | } 204 | 205 | /** 206 | * Generates the flag name including leading dashes. 207 | * @param string $flag Just the name. 208 | * @returns Fag with apropriate dashes. 209 | */ 210 | private function renderFlag($flag) { 211 | return (strlen($flag) == 1 ? '-' : '--') . $flag; 212 | } 213 | 214 | /** 215 | * Converts multiple new lines into a single new line. 216 | * Just there to trap accidental duplicate new lines. 217 | * @param string $text Text to clean up. 218 | * @returns string Text with no blank lines. 219 | */ 220 | private function noDuplicateNewLines($text) { 221 | return preg_replace('/(\n+)/', "\n", $text); 222 | } 223 | } 224 | ?> -------------------------------------------------------------------------------- /tests/simpletest/authentication.php: -------------------------------------------------------------------------------- 1 | type = $type; 34 | $this->root = $url->getBasePath(); 35 | $this->username = false; 36 | $this->password = false; 37 | } 38 | 39 | /** 40 | * Adds another location to the realm. 41 | * @param SimpleUrl $url Somewhere in realm. 42 | * @access public 43 | */ 44 | function stretch($url) { 45 | $this->root = $this->getCommonPath($this->root, $url->getPath()); 46 | } 47 | 48 | /** 49 | * Finds the common starting path. 50 | * @param string $first Path to compare. 51 | * @param string $second Path to compare. 52 | * @return string Common directories. 53 | * @access private 54 | */ 55 | protected function getCommonPath($first, $second) { 56 | $first = explode('/', $first); 57 | $second = explode('/', $second); 58 | for ($i = 0; $i < min(count($first), count($second)); $i++) { 59 | if ($first[$i] != $second[$i]) { 60 | return implode('/', array_slice($first, 0, $i)) . '/'; 61 | } 62 | } 63 | return implode('/', $first) . '/'; 64 | } 65 | 66 | /** 67 | * Sets the identity to try within this realm. 68 | * @param string $username Username in authentication dialog. 69 | * @param string $username Password in authentication dialog. 70 | * @access public 71 | */ 72 | function setIdentity($username, $password) { 73 | $this->username = $username; 74 | $this->password = $password; 75 | } 76 | 77 | /** 78 | * Accessor for current identity. 79 | * @return string Last succesful username. 80 | * @access public 81 | */ 82 | function getUsername() { 83 | return $this->username; 84 | } 85 | 86 | /** 87 | * Accessor for current identity. 88 | * @return string Last succesful password. 89 | * @access public 90 | */ 91 | function getPassword() { 92 | return $this->password; 93 | } 94 | 95 | /** 96 | * Test to see if the URL is within the directory 97 | * tree of the realm. 98 | * @param SimpleUrl $url URL to test. 99 | * @return boolean True if subpath. 100 | * @access public 101 | */ 102 | function isWithin($url) { 103 | if ($this->isIn($this->root, $url->getBasePath())) { 104 | return true; 105 | } 106 | if ($this->isIn($this->root, $url->getBasePath() . $url->getPage() . '/')) { 107 | return true; 108 | } 109 | return false; 110 | } 111 | 112 | /** 113 | * Tests to see if one string is a substring of 114 | * another. 115 | * @param string $part Small bit. 116 | * @param string $whole Big bit. 117 | * @return boolean True if the small bit is 118 | * in the big bit. 119 | * @access private 120 | */ 121 | protected function isIn($part, $whole) { 122 | return strpos($whole, $part) === 0; 123 | } 124 | } 125 | 126 | /** 127 | * Manages security realms. 128 | * @package SimpleTest 129 | * @subpackage WebTester 130 | */ 131 | class SimpleAuthenticator { 132 | private $realms; 133 | 134 | /** 135 | * Clears the realms. 136 | * @access public 137 | */ 138 | function SimpleAuthenticator() { 139 | $this->restartSession(); 140 | } 141 | 142 | /** 143 | * Starts with no realms set up. 144 | * @access public 145 | */ 146 | function restartSession() { 147 | $this->realms = array(); 148 | } 149 | 150 | /** 151 | * Adds a new realm centered the current URL. 152 | * Browsers privatey wildly on their behaviour in this 153 | * regard. Mozilla ignores the realm and presents 154 | * only when challenged, wasting bandwidth. IE 155 | * just carries on presenting until a new challenge 156 | * occours. SimpleTest tries to follow the spirit of 157 | * the original standards committee and treats the 158 | * base URL as the root of a file tree shaped realm. 159 | * @param SimpleUrl $url Base of realm. 160 | * @param string $type Authentication type for this 161 | * realm. Only Basic authentication 162 | * is currently supported. 163 | * @param string $realm Name of realm. 164 | * @access public 165 | */ 166 | function addRealm($url, $type, $realm) { 167 | $this->realms[$url->getHost()][$realm] = new SimpleRealm($type, $url); 168 | } 169 | 170 | /** 171 | * Sets the current identity to be presented 172 | * against that realm. 173 | * @param string $host Server hosting realm. 174 | * @param string $realm Name of realm. 175 | * @param string $username Username for realm. 176 | * @param string $password Password for realm. 177 | * @access public 178 | */ 179 | function setIdentityForRealm($host, $realm, $username, $password) { 180 | if (isset($this->realms[$host][$realm])) { 181 | $this->realms[$host][$realm]->setIdentity($username, $password); 182 | } 183 | } 184 | 185 | /** 186 | * Finds the name of the realm by comparing URLs. 187 | * @param SimpleUrl $url URL to test. 188 | * @return SimpleRealm Name of realm. 189 | * @access private 190 | */ 191 | protected function findRealmFromUrl($url) { 192 | if (! isset($this->realms[$url->getHost()])) { 193 | return false; 194 | } 195 | foreach ($this->realms[$url->getHost()] as $name => $realm) { 196 | if ($realm->isWithin($url)) { 197 | return $realm; 198 | } 199 | } 200 | return false; 201 | } 202 | 203 | /** 204 | * Presents the appropriate headers for this location. 205 | * @param SimpleHttpRequest $request Request to modify. 206 | * @param SimpleUrl $url Base of realm. 207 | * @access public 208 | */ 209 | function addHeaders(&$request, $url) { 210 | if ($url->getUsername() && $url->getPassword()) { 211 | $username = $url->getUsername(); 212 | $password = $url->getPassword(); 213 | } elseif ($realm = $this->findRealmFromUrl($url)) { 214 | $username = $realm->getUsername(); 215 | $password = $realm->getPassword(); 216 | } else { 217 | return; 218 | } 219 | $this->addBasicHeaders($request, $username, $password); 220 | } 221 | 222 | /** 223 | * Presents the appropriate headers for this 224 | * location for basic authentication. 225 | * @param SimpleHttpRequest $request Request to modify. 226 | * @param string $username Username for realm. 227 | * @param string $password Password for realm. 228 | * @access public 229 | */ 230 | static function addBasicHeaders(&$request, $username, $password) { 231 | if ($username && $password) { 232 | $request->addHeaderLine( 233 | 'Authorization: Basic ' . base64_encode("$username:$password")); 234 | } 235 | } 236 | } 237 | ?> -------------------------------------------------------------------------------- /tests/simpletest/autorun.php: -------------------------------------------------------------------------------- 1 | createSuiteFromClasses( 52 | basename(initial_file()), 53 | $loader->selectRunnableTests($candidates)); 54 | return $suite->run(new DefaultReporter()); 55 | } catch (Exception $stack_frame_fix) { 56 | print $stack_frame_fix->getMessage(); 57 | return false; 58 | } 59 | } 60 | 61 | /** 62 | * Checks the current test context to see if a test has 63 | * ever been run. 64 | * @return boolean True if tests have run. 65 | */ 66 | function tests_have_run() { 67 | if ($context = SimpleTest::getContext()) { 68 | return (boolean)$context->getTest(); 69 | } 70 | return false; 71 | } 72 | 73 | /** 74 | * The first autorun file. 75 | * @return string Filename of first autorun script. 76 | */ 77 | function initial_file() { 78 | static $file = false; 79 | if (! $file) { 80 | if (isset($_SERVER, $_SERVER['SCRIPT_FILENAME'])) { 81 | $file = $_SERVER['SCRIPT_FILENAME']; 82 | } else { 83 | $included_files = get_included_files(); 84 | $file = reset($included_files); 85 | } 86 | } 87 | return $file; 88 | } 89 | 90 | /** 91 | * Every class since the first autorun include. This 92 | * is safe enough if require_once() is always used. 93 | * @return array Class names. 94 | */ 95 | function capture_new_classes() { 96 | global $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES; 97 | return array_map('strtolower', array_diff(get_declared_classes(), 98 | $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES ? 99 | $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES : array())); 100 | } 101 | ?> -------------------------------------------------------------------------------- /tests/simpletest/collector.php: -------------------------------------------------------------------------------- 1 | 7 | * @package SimpleTest 8 | * @subpackage UnitTester 9 | * @version $Id: collector.php 2011 2011-04-29 08:22:48Z pp11 $ 10 | */ 11 | 12 | /** 13 | * The basic collector for {@link GroupTest} 14 | * 15 | * @see collect(), GroupTest::collect() 16 | * @package SimpleTest 17 | * @subpackage UnitTester 18 | */ 19 | class SimpleCollector { 20 | 21 | /** 22 | * Strips off any kind of slash at the end so as to normalise the path. 23 | * @param string $path Path to normalise. 24 | * @return string Path without trailing slash. 25 | */ 26 | protected function removeTrailingSlash($path) { 27 | if (substr($path, -1) == DIRECTORY_SEPARATOR) { 28 | return substr($path, 0, -1); 29 | } elseif (substr($path, -1) == '/') { 30 | return substr($path, 0, -1); 31 | } else { 32 | return $path; 33 | } 34 | } 35 | 36 | /** 37 | * Scans the directory and adds what it can. 38 | * @param object $test Group test with {@link GroupTest::addTestFile()} method. 39 | * @param string $path Directory to scan. 40 | * @see _attemptToAdd() 41 | */ 42 | function collect(&$test, $path) { 43 | $path = $this->removeTrailingSlash($path); 44 | if ($handle = opendir($path)) { 45 | while (($entry = readdir($handle)) !== false) { 46 | if ($this->isHidden($entry)) { 47 | continue; 48 | } 49 | $this->handle($test, $path . DIRECTORY_SEPARATOR . $entry); 50 | } 51 | closedir($handle); 52 | } 53 | } 54 | 55 | /** 56 | * This method determines what should be done with a given file and adds 57 | * it via {@link GroupTest::addTestFile()} if necessary. 58 | * 59 | * This method should be overriden to provide custom matching criteria, 60 | * such as pattern matching, recursive matching, etc. For an example, see 61 | * {@link SimplePatternCollector::_handle()}. 62 | * 63 | * @param object $test Group test with {@link GroupTest::addTestFile()} method. 64 | * @param string $filename A filename as generated by {@link collect()} 65 | * @see collect() 66 | * @access protected 67 | */ 68 | protected function handle(&$test, $file) { 69 | if (is_dir($file)) { 70 | return; 71 | } 72 | $test->addFile($file); 73 | } 74 | 75 | /** 76 | * Tests for hidden files so as to skip them. Currently 77 | * only tests for Unix hidden files. 78 | * @param string $filename Plain filename. 79 | * @return boolean True if hidden file. 80 | * @access private 81 | */ 82 | protected function isHidden($filename) { 83 | return strncmp($filename, '.', 1) == 0; 84 | } 85 | } 86 | 87 | /** 88 | * An extension to {@link SimpleCollector} that only adds files matching a 89 | * given pattern. 90 | * 91 | * @package SimpleTest 92 | * @subpackage UnitTester 93 | * @see SimpleCollector 94 | */ 95 | class SimplePatternCollector extends SimpleCollector { 96 | private $pattern; 97 | 98 | /** 99 | * 100 | * @param string $pattern Perl compatible regex to test name against 101 | * See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE} 102 | * for full documentation of valid pattern.s 103 | */ 104 | function __construct($pattern = '/php$/i') { 105 | $this->pattern = $pattern; 106 | } 107 | 108 | /** 109 | * Attempts to add files that match a given pattern. 110 | * 111 | * @see SimpleCollector::_handle() 112 | * @param object $test Group test with {@link GroupTest::addTestFile()} method. 113 | * @param string $path Directory to scan. 114 | * @access protected 115 | */ 116 | protected function handle(&$test, $filename) { 117 | if (preg_match($this->pattern, $filename)) { 118 | parent::handle($test, $filename); 119 | } 120 | } 121 | } 122 | ?> -------------------------------------------------------------------------------- /tests/simpletest/compatibility.php: -------------------------------------------------------------------------------- 1 | = 0) { 23 | eval('$copy = clone $object;'); 24 | return $copy; 25 | } 26 | return $object; 27 | } 28 | 29 | /** 30 | * Identity test. Drops back to equality + types for PHP5 31 | * objects as the === operator counts as the 32 | * stronger reference constraint. 33 | * @param mixed $first Test subject. 34 | * @param mixed $second Comparison object. 35 | * @return boolean True if identical. 36 | * @access public 37 | */ 38 | static function isIdentical($first, $second) { 39 | if (version_compare(phpversion(), '5') >= 0) { 40 | return SimpleTestCompatibility::isIdenticalType($first, $second); 41 | } 42 | if ($first != $second) { 43 | return false; 44 | } 45 | return ($first === $second); 46 | } 47 | 48 | /** 49 | * Recursive type test. 50 | * @param mixed $first Test subject. 51 | * @param mixed $second Comparison object. 52 | * @return boolean True if same type. 53 | * @access private 54 | */ 55 | protected static function isIdenticalType($first, $second) { 56 | if (gettype($first) != gettype($second)) { 57 | return false; 58 | } 59 | if (is_object($first) && is_object($second)) { 60 | if (get_class($first) != get_class($second)) { 61 | return false; 62 | } 63 | return SimpleTestCompatibility::isArrayOfIdenticalTypes( 64 | (array) $first, 65 | (array) $second); 66 | } 67 | if (is_array($first) && is_array($second)) { 68 | return SimpleTestCompatibility::isArrayOfIdenticalTypes($first, $second); 69 | } 70 | if ($first !== $second) { 71 | return false; 72 | } 73 | return true; 74 | } 75 | 76 | /** 77 | * Recursive type test for each element of an array. 78 | * @param mixed $first Test subject. 79 | * @param mixed $second Comparison object. 80 | * @return boolean True if identical. 81 | * @access private 82 | */ 83 | protected static function isArrayOfIdenticalTypes($first, $second) { 84 | if (array_keys($first) != array_keys($second)) { 85 | return false; 86 | } 87 | foreach (array_keys($first) as $key) { 88 | $is_identical = SimpleTestCompatibility::isIdenticalType( 89 | $first[$key], 90 | $second[$key]); 91 | if (! $is_identical) { 92 | return false; 93 | } 94 | } 95 | return true; 96 | } 97 | 98 | /** 99 | * Test for two variables being aliases. 100 | * @param mixed $first Test subject. 101 | * @param mixed $second Comparison object. 102 | * @return boolean True if same. 103 | * @access public 104 | */ 105 | static function isReference(&$first, &$second) { 106 | if (version_compare(phpversion(), '5', '>=') && is_object($first)) { 107 | return ($first === $second); 108 | } 109 | if (is_object($first) && is_object($second)) { 110 | $id = uniqid("test"); 111 | $first->$id = true; 112 | $is_ref = isset($second->$id); 113 | unset($first->$id); 114 | return $is_ref; 115 | } 116 | $temp = $first; 117 | $first = uniqid("test"); 118 | $is_ref = ($first === $second); 119 | $first = $temp; 120 | return $is_ref; 121 | } 122 | 123 | /** 124 | * Test to see if an object is a member of a 125 | * class hiearchy. 126 | * @param object $object Object to test. 127 | * @param string $class Root name of hiearchy. 128 | * @return boolean True if class in hiearchy. 129 | * @access public 130 | */ 131 | static function isA($object, $class) { 132 | if (version_compare(phpversion(), '5') >= 0) { 133 | if (! class_exists($class, false)) { 134 | if (function_exists('interface_exists')) { 135 | if (! interface_exists($class, false)) { 136 | return false; 137 | } 138 | } 139 | } 140 | eval("\$is_a = \$object instanceof $class;"); 141 | return $is_a; 142 | } 143 | if (function_exists('is_a')) { 144 | return is_a($object, $class); 145 | } 146 | return ((strtolower($class) == get_class($object)) 147 | or (is_subclass_of($object, $class))); 148 | } 149 | 150 | /** 151 | * Sets a socket timeout for each chunk. 152 | * @param resource $handle Socket handle. 153 | * @param integer $timeout Limit in seconds. 154 | * @access public 155 | */ 156 | static function setTimeout($handle, $timeout) { 157 | if (function_exists('stream_set_timeout')) { 158 | stream_set_timeout($handle, $timeout, 0); 159 | } elseif (function_exists('socket_set_timeout')) { 160 | socket_set_timeout($handle, $timeout, 0); 161 | } elseif (function_exists('set_socket_timeout')) { 162 | set_socket_timeout($handle, $timeout, 0); 163 | } 164 | } 165 | } 166 | ?> -------------------------------------------------------------------------------- /tests/simpletest/default_reporter.php: -------------------------------------------------------------------------------- 1 | 'case', 'c' => 'case', 28 | 'test' => 'test', 't' => 'test', 29 | ); 30 | private $case = ''; 31 | private $test = ''; 32 | private $xml = false; 33 | private $help = false; 34 | private $no_skips = false; 35 | 36 | /** 37 | * Parses raw command line arguments into object properties. 38 | * @param string $arguments Raw commend line arguments. 39 | */ 40 | function __construct($arguments) { 41 | if (! is_array($arguments)) { 42 | return; 43 | } 44 | foreach ($arguments as $i => $argument) { 45 | if (preg_match('/^--?(test|case|t|c)=(.+)$/', $argument, $matches)) { 46 | $property = $this->to_property[$matches[1]]; 47 | $this->$property = $matches[2]; 48 | } elseif (preg_match('/^--?(test|case|t|c)$/', $argument, $matches)) { 49 | $property = $this->to_property[$matches[1]]; 50 | if (isset($arguments[$i + 1])) { 51 | $this->$property = $arguments[$i + 1]; 52 | } 53 | } elseif (preg_match('/^--?(xml|x)$/', $argument)) { 54 | $this->xml = true; 55 | } elseif (preg_match('/^--?(no-skip|no-skips|s)$/', $argument)) { 56 | $this->no_skips = true; 57 | } elseif (preg_match('/^--?(help|h)$/', $argument)) { 58 | $this->help = true; 59 | } 60 | } 61 | } 62 | 63 | /** 64 | * Run only this test. 65 | * @return string Test name to run. 66 | */ 67 | function getTest() { 68 | return $this->test; 69 | } 70 | 71 | /** 72 | * Run only this test suite. 73 | * @return string Test class name to run. 74 | */ 75 | function getTestCase() { 76 | return $this->case; 77 | } 78 | 79 | /** 80 | * Output should be XML or not. 81 | * @return boolean True if XML desired. 82 | */ 83 | function isXml() { 84 | return $this->xml; 85 | } 86 | 87 | /** 88 | * Output should suppress skip messages. 89 | * @return boolean True for no skips. 90 | */ 91 | function noSkips() { 92 | return $this->no_skips; 93 | } 94 | 95 | /** 96 | * Output should be a help message. Disabled during XML mode. 97 | * @return boolean True if help message desired. 98 | */ 99 | function help() { 100 | return $this->help && ! $this->xml; 101 | } 102 | 103 | /** 104 | * Returns plain-text help message for command line runner. 105 | * @return string String help message 106 | */ 107 | function getHelpText() { 108 | return << [args...] 111 | 112 | -c Run only the test-case 113 | -t Run only the test method 114 | -s Suppress skip messages 115 | -x Return test results in XML 116 | -h Display this help message 117 | 118 | HELP; 119 | } 120 | 121 | } 122 | 123 | /** 124 | * The default reporter used by SimpleTest's autorun 125 | * feature. The actual reporters used are dependency 126 | * injected and can be overridden. 127 | * @package SimpleTest 128 | * @subpackage UnitTester 129 | */ 130 | class DefaultReporter extends SimpleReporterDecorator { 131 | 132 | /** 133 | * Assembles the appropriate reporter for the environment. 134 | */ 135 | function __construct() { 136 | if (SimpleReporter::inCli()) { 137 | $parser = new SimpleCommandLineParser($_SERVER['argv']); 138 | $interfaces = $parser->isXml() ? array('XmlReporter') : array('TextReporter'); 139 | if ($parser->help()) { 140 | // I'm not sure if we should do the echo'ing here -- ezyang 141 | echo $parser->getHelpText(); 142 | exit(1); 143 | } 144 | $reporter = new SelectiveReporter( 145 | SimpleTest::preferred($interfaces), 146 | $parser->getTestCase(), 147 | $parser->getTest()); 148 | if ($parser->noSkips()) { 149 | $reporter = new NoSkipsReporter($reporter); 150 | } 151 | } else { 152 | $reporter = new SelectiveReporter( 153 | SimpleTest::preferred('HtmlReporter'), 154 | @$_GET['c'], 155 | @$_GET['t']); 156 | if (@$_GET['skips'] == 'no' || @$_GET['show-skips'] == 'no') { 157 | $reporter = new NoSkipsReporter($reporter); 158 | } 159 | } 160 | parent::__construct($reporter); 161 | } 162 | } 163 | ?> -------------------------------------------------------------------------------- /tests/simpletest/detached.php: -------------------------------------------------------------------------------- 1 | command = $command; 34 | $this->dry_command = $dry_command ? $dry_command : $command; 35 | $this->size = false; 36 | } 37 | 38 | /** 39 | * Accessor for the test name for subclasses. 40 | * @return string Name of the test. 41 | * @access public 42 | */ 43 | function getLabel() { 44 | return $this->command; 45 | } 46 | 47 | /** 48 | * Runs the top level test for this class. Currently 49 | * reads the data as a single chunk. I'll fix this 50 | * once I have added iteration to the browser. 51 | * @param SimpleReporter $reporter Target of test results. 52 | * @returns boolean True if no failures. 53 | * @access public 54 | */ 55 | function run(&$reporter) { 56 | $shell = &new SimpleShell(); 57 | $shell->execute($this->command); 58 | $parser = &$this->createParser($reporter); 59 | if (! $parser->parse($shell->getOutput())) { 60 | trigger_error('Cannot parse incoming XML from [' . $this->command . ']'); 61 | return false; 62 | } 63 | return true; 64 | } 65 | 66 | /** 67 | * Accessor for the number of subtests. 68 | * @return integer Number of test cases. 69 | * @access public 70 | */ 71 | function getSize() { 72 | if ($this->size === false) { 73 | $shell = &new SimpleShell(); 74 | $shell->execute($this->dry_command); 75 | $reporter = &new SimpleReporter(); 76 | $parser = &$this->createParser($reporter); 77 | if (! $parser->parse($shell->getOutput())) { 78 | trigger_error('Cannot parse incoming XML from [' . $this->dry_command . ']'); 79 | return false; 80 | } 81 | $this->size = $reporter->getTestCaseCount(); 82 | } 83 | return $this->size; 84 | } 85 | 86 | /** 87 | * Creates the XML parser. 88 | * @param SimpleReporter $reporter Target of test results. 89 | * @return SimpleTestXmlListener XML reader. 90 | * @access protected 91 | */ 92 | protected function &createParser(&$reporter) { 93 | return new SimpleTestXmlParser($reporter); 94 | } 95 | } 96 | ?> -------------------------------------------------------------------------------- /tests/simpletest/docs/en/docs.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-left: 3%; 3 | padding-right: 3%; 4 | } 5 | h1, h2, h3 { 6 | font-family: sans-serif; 7 | } 8 | h1 { 9 | text-align: center; 10 | } 11 | pre { 12 | font-family: "courier new", courier, typewriter, monospace; 13 | font-size: 90%; 14 | border: 1px solid; 15 | border-color: #999966; 16 | background-color: #ffffcc; 17 | padding: 5px; 18 | margin-left: 20px; 19 | margin-right: 40px; 20 | } 21 | .code, .new_code, pre.new_code { 22 | font-family: "courier new", courier, typewriter, monospace; 23 | font-weight: bold; 24 | } 25 | div.copyright { 26 | font-size: 80%; 27 | color: gray; 28 | } 29 | div.copyright a { 30 | margin-top: 1em; 31 | color: gray; 32 | } 33 | ul.api { 34 | border: 2px outset; 35 | border-color: gray; 36 | background-color: white; 37 | margin: 5px; 38 | margin-left: 5%; 39 | margin-right: 5%; 40 | } 41 | ul.api li { 42 | margin-top: 0.2em; 43 | margin-bottom: 0.2em; 44 | list-style: none; 45 | text-indent: -3em; 46 | padding-left: 1em; 47 | } 48 | div.demo { 49 | border: 4px ridge; 50 | border-color: gray; 51 | padding: 10px; 52 | margin: 5px; 53 | margin-left: 20px; 54 | margin-right: 40px; 55 | background-color: white; 56 | } 57 | div.demo span.fail { 58 | color: red; 59 | } 60 | div.demo span.pass { 61 | color: green; 62 | } 63 | div.demo h1 { 64 | font-size: 12pt; 65 | text-align: left; 66 | font-weight: bold; 67 | } 68 | div.menu { 69 | text-align: center; 70 | } 71 | table { 72 | border: 2px outset; 73 | border-color: gray; 74 | background-color: white; 75 | margin: 5px; 76 | margin-left: 5%; 77 | margin-right: 5%; 78 | } 79 | td { 80 | font-size: 90%; 81 | } 82 | .shell { 83 | color: white; 84 | } 85 | pre.shell { 86 | border: 4px ridge; 87 | border-color: gray; 88 | padding: 10px; 89 | margin: 5px; 90 | margin-left: 20px; 91 | margin-right: 40px; 92 | background-color: #000100; 93 | color: #99ff99; 94 | font-size: 90%; 95 | } 96 | pre.file { 97 | color: black; 98 | border: 1px solid; 99 | border-color: black; 100 | padding: 10px; 101 | margin: 5px; 102 | margin-left: 20px; 103 | margin-right: 40px; 104 | background-color: white; 105 | font-size: 90%; 106 | } 107 | form.demo { 108 | background-color: lightgray; 109 | border: 4px outset; 110 | border-color: lightgray; 111 | padding: 10px; 112 | margin-right: 40%; 113 | } 114 | dl, dd { 115 | margin: 10px; 116 | margin-left: 30px; 117 | } 118 | em { 119 | font-weight: bold; 120 | font-family: "courier new", courier, typewriter, monospace; 121 | } 122 | -------------------------------------------------------------------------------- /tests/simpletest/docs/fr/docs.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-left: 3%; 3 | padding-right: 3%; 4 | } 5 | pre { 6 | font-family: "courier new", courier; 7 | font-size: 80%; 8 | border: 1px solid; 9 | background-color: #cccccc; 10 | padding: 5px; 11 | margin-left: 5%; 12 | margin-right: 8%; 13 | } 14 | .code, .new_code, pre.new_code { 15 | font-weight: bold; 16 | } 17 | div.copyright { 18 | font-size: 80%; 19 | color: gray; 20 | } 21 | div.copyright a { 22 | color: gray; 23 | } 24 | ul.api { 25 | padding-left: 0em; 26 | padding-right: 25%; 27 | } 28 | ul.api li { 29 | margin-top: 0.2em; 30 | margin-bottom: 0.2em; 31 | list-style: none; 32 | text-indent: -3em; 33 | padding-left: 3em; 34 | } 35 | div.demo { 36 | border: 4px ridge; 37 | border-color: gray; 38 | padding: 10px; 39 | margin: 5px; 40 | margin-left: 20px; 41 | margin-right: 40px; 42 | background-color: white; 43 | } 44 | div.demo span.fail { 45 | color: red; 46 | } 47 | div.demo span.pass { 48 | color: green; 49 | } 50 | div.demo h1 { 51 | font-size: 12pt; 52 | text-align: left; 53 | font-weight: bold; 54 | } 55 | table { 56 | border: 2px outset; 57 | border-color: gray; 58 | background-color: white; 59 | margin: 5px; 60 | margin-left: 5%; 61 | margin-right: 5%; 62 | } 63 | td { 64 | font-size: 80%; 65 | } 66 | .shell { 67 | color: white; 68 | } 69 | pre.shell { 70 | border: 4px ridge; 71 | border-color: gray; 72 | padding: 10px; 73 | margin: 5px; 74 | margin-left: 20px; 75 | margin-right: 40px; 76 | background-color: black; 77 | } 78 | form.demo { 79 | background-color: lightgray; 80 | border: 4px outset; 81 | border-color: lightgray; 82 | padding: 10px; 83 | margin-right: 40%; 84 | } 85 | -------------------------------------------------------------------------------- /tests/simpletest/errors.php: -------------------------------------------------------------------------------- 1 | createErrorQueue(); 41 | set_error_handler('SimpleTestErrorHandler'); 42 | parent::invoke($method); 43 | restore_error_handler(); 44 | $queue->tally(); 45 | } 46 | 47 | /** 48 | * Wires up the error queue for a single test. 49 | * @return SimpleErrorQueue Queue connected to the test. 50 | * @access private 51 | */ 52 | protected function createErrorQueue() { 53 | $context = SimpleTest::getContext(); 54 | $test = $this->getTestCase(); 55 | $queue = $context->get('SimpleErrorQueue'); 56 | $queue->setTestCase($test); 57 | return $queue; 58 | } 59 | } 60 | 61 | /** 62 | * Error queue used to record trapped 63 | * errors. 64 | * @package SimpleTest 65 | * @subpackage UnitTester 66 | */ 67 | class SimpleErrorQueue { 68 | private $queue; 69 | private $expectation_queue; 70 | private $test; 71 | private $using_expect_style = false; 72 | 73 | /** 74 | * Starts with an empty queue. 75 | */ 76 | function __construct() { 77 | $this->clear(); 78 | } 79 | 80 | /** 81 | * Discards the contents of the error queue. 82 | * @access public 83 | */ 84 | function clear() { 85 | $this->queue = array(); 86 | $this->expectation_queue = array(); 87 | } 88 | 89 | /** 90 | * Sets the currently running test case. 91 | * @param SimpleTestCase $test Test case to send messages to. 92 | * @access public 93 | */ 94 | function setTestCase($test) { 95 | $this->test = $test; 96 | } 97 | 98 | /** 99 | * Sets up an expectation of an error. If this is 100 | * not fulfilled at the end of the test, a failure 101 | * will occour. If the error does happen, then this 102 | * will cancel it out and send a pass message. 103 | * @param SimpleExpectation $expected Expected error match. 104 | * @param string $message Message to display. 105 | * @access public 106 | */ 107 | function expectError($expected, $message) { 108 | array_push($this->expectation_queue, array($expected, $message)); 109 | } 110 | 111 | /** 112 | * Adds an error to the front of the queue. 113 | * @param integer $severity PHP error code. 114 | * @param string $content Text of error. 115 | * @param string $filename File error occoured in. 116 | * @param integer $line Line number of error. 117 | * @access public 118 | */ 119 | function add($severity, $content, $filename, $line) { 120 | $content = str_replace('%', '%%', $content); 121 | $this->testLatestError($severity, $content, $filename, $line); 122 | } 123 | 124 | /** 125 | * Any errors still in the queue are sent to the test 126 | * case. Any unfulfilled expectations trigger failures. 127 | * @access public 128 | */ 129 | function tally() { 130 | while (list($severity, $message, $file, $line) = $this->extract()) { 131 | $severity = $this->getSeverityAsString($severity); 132 | $this->test->error($severity, $message, $file, $line); 133 | } 134 | while (list($expected, $message) = $this->extractExpectation()) { 135 | $this->test->assert($expected, false, "%s -> Expected error not caught"); 136 | } 137 | } 138 | 139 | /** 140 | * Tests the error against the most recent expected 141 | * error. 142 | * @param integer $severity PHP error code. 143 | * @param string $content Text of error. 144 | * @param string $filename File error occoured in. 145 | * @param integer $line Line number of error. 146 | * @access private 147 | */ 148 | protected function testLatestError($severity, $content, $filename, $line) { 149 | if ($expectation = $this->extractExpectation()) { 150 | list($expected, $message) = $expectation; 151 | $this->test->assert($expected, $content, sprintf( 152 | $message, 153 | "%s -> PHP error [$content] severity [" . 154 | $this->getSeverityAsString($severity) . 155 | "] in [$filename] line [$line]")); 156 | } else { 157 | $this->test->error($severity, $content, $filename, $line); 158 | } 159 | } 160 | 161 | /** 162 | * Pulls the earliest error from the queue. 163 | * @return mixed False if none, or a list of error 164 | * information. Elements are: severity 165 | * as the PHP error code, the error message, 166 | * the file with the error, the line number 167 | * and a list of PHP super global arrays. 168 | * @access public 169 | */ 170 | function extract() { 171 | if (count($this->queue)) { 172 | return array_shift($this->queue); 173 | } 174 | return false; 175 | } 176 | 177 | /** 178 | * Pulls the earliest expectation from the queue. 179 | * @return SimpleExpectation False if none. 180 | * @access private 181 | */ 182 | protected function extractExpectation() { 183 | if (count($this->expectation_queue)) { 184 | return array_shift($this->expectation_queue); 185 | } 186 | return false; 187 | } 188 | 189 | /** 190 | * Converts an error code into it's string 191 | * representation. 192 | * @param $severity PHP integer error code. 193 | * @return String version of error code. 194 | * @access public 195 | */ 196 | static function getSeverityAsString($severity) { 197 | static $map = array( 198 | E_STRICT => 'E_STRICT', 199 | E_ERROR => 'E_ERROR', 200 | E_WARNING => 'E_WARNING', 201 | E_PARSE => 'E_PARSE', 202 | E_NOTICE => 'E_NOTICE', 203 | E_CORE_ERROR => 'E_CORE_ERROR', 204 | E_CORE_WARNING => 'E_CORE_WARNING', 205 | E_COMPILE_ERROR => 'E_COMPILE_ERROR', 206 | E_COMPILE_WARNING => 'E_COMPILE_WARNING', 207 | E_USER_ERROR => 'E_USER_ERROR', 208 | E_USER_WARNING => 'E_USER_WARNING', 209 | E_USER_NOTICE => 'E_USER_NOTICE'); 210 | if (defined('E_RECOVERABLE_ERROR')) { 211 | $map[E_RECOVERABLE_ERROR] = 'E_RECOVERABLE_ERROR'; 212 | } 213 | if (defined('E_DEPRECATED')) { 214 | $map[E_DEPRECATED] = 'E_DEPRECATED'; 215 | } 216 | return $map[$severity]; 217 | } 218 | } 219 | 220 | /** 221 | * Error handler that simply stashes any errors into the global 222 | * error queue. Simulates the existing behaviour with respect to 223 | * logging errors, but this feature may be removed in future. 224 | * @param $severity PHP error code. 225 | * @param $message Text of error. 226 | * @param $filename File error occoured in. 227 | * @param $line Line number of error. 228 | * @param $super_globals Hash of PHP super global arrays. 229 | * @access public 230 | */ 231 | function SimpleTestErrorHandler($severity, $message, $filename = null, $line = null, $super_globals = null, $mask = null) { 232 | $severity = $severity & error_reporting(); 233 | if ($severity) { 234 | restore_error_handler(); 235 | if (IsNotCausedBySimpleTest($message) && IsNotTimeZoneNag($message)) { 236 | if (ini_get('log_errors')) { 237 | $label = SimpleErrorQueue::getSeverityAsString($severity); 238 | error_log("$label: $message in $filename on line $line"); 239 | } 240 | $queue = SimpleTest::getContext()->get('SimpleErrorQueue'); 241 | $queue->add($severity, $message, $filename, $line); 242 | } 243 | set_error_handler('SimpleTestErrorHandler'); 244 | } 245 | return true; 246 | } 247 | 248 | /** 249 | * Certain messages can be caused by the unit tester itself. 250 | * These have to be filtered. 251 | * @param string $message Message to filter. 252 | * @return boolean True if genuine failure. 253 | */ 254 | function IsNotCausedBySimpleTest($message) { 255 | return ! preg_match('/returned by reference/', $message); 256 | } 257 | 258 | /** 259 | * Certain messages caused by PHP are just noise. 260 | * These have to be filtered. 261 | * @param string $message Message to filter. 262 | * @return boolean True if genuine failure. 263 | */ 264 | function IsNotTimeZoneNag($message) { 265 | return ! preg_match('/not safe to rely .* timezone settings/', $message); 266 | } 267 | ?> -------------------------------------------------------------------------------- /tests/simpletest/exceptions.php: -------------------------------------------------------------------------------- 1 | get('SimpleExceptionTrap'); 40 | $trap->clear(); 41 | try { 42 | $has_thrown = false; 43 | parent::invoke($method); 44 | } catch (Exception $exception) { 45 | $has_thrown = true; 46 | if (! $trap->isExpected($this->getTestCase(), $exception)) { 47 | $this->getTestCase()->exception($exception); 48 | } 49 | $trap->clear(); 50 | } 51 | if ($message = $trap->getOutstanding()) { 52 | $this->getTestCase()->fail($message); 53 | } 54 | if ($has_thrown) { 55 | try { 56 | parent::getTestCase()->tearDown(); 57 | } catch (Exception $e) { } 58 | } 59 | } 60 | } 61 | 62 | /** 63 | * Tests exceptions either by type or the exact 64 | * exception. This could be improved to accept 65 | * a pattern expectation to test the error 66 | * message, but that will have to come later. 67 | * @package SimpleTest 68 | * @subpackage UnitTester 69 | */ 70 | class ExceptionExpectation extends SimpleExpectation { 71 | private $expected; 72 | 73 | /** 74 | * Sets up the conditions to test against. 75 | * If the expected value is a string, then 76 | * it will act as a test of the class name. 77 | * An exception as the comparison will 78 | * trigger an identical match. Writing this 79 | * down now makes it look doubly dumb. I hope 80 | * come up with a better scheme later. 81 | * @param mixed $expected A class name or an actual 82 | * exception to compare with. 83 | * @param string $message Message to display. 84 | */ 85 | function __construct($expected, $message = '%s') { 86 | $this->expected = $expected; 87 | parent::__construct($message); 88 | } 89 | 90 | /** 91 | * Carry out the test. 92 | * @param Exception $compare Value to check. 93 | * @return boolean True if matched. 94 | */ 95 | function test($compare) { 96 | if (is_string($this->expected)) { 97 | return ($compare instanceof $this->expected); 98 | } 99 | if (get_class($compare) != get_class($this->expected)) { 100 | return false; 101 | } 102 | return $compare->getMessage() == $this->expected->getMessage(); 103 | } 104 | 105 | /** 106 | * Create the message to display describing the test. 107 | * @param Exception $compare Exception to match. 108 | * @return string Final message. 109 | */ 110 | function testMessage($compare) { 111 | if (is_string($this->expected)) { 112 | return "Exception [" . $this->describeException($compare) . 113 | "] should be type [" . $this->expected . "]"; 114 | } 115 | return "Exception [" . $this->describeException($compare) . 116 | "] should match [" . 117 | $this->describeException($this->expected) . "]"; 118 | } 119 | 120 | /** 121 | * Summary of an Exception object. 122 | * @param Exception $compare Exception to describe. 123 | * @return string Text description. 124 | */ 125 | protected function describeException($exception) { 126 | return get_class($exception) . ": " . $exception->getMessage(); 127 | } 128 | } 129 | 130 | /** 131 | * Stores expected exceptions for when they 132 | * get thrown. Saves the irritating try...catch 133 | * block. 134 | * @package SimpleTest 135 | * @subpackage UnitTester 136 | */ 137 | class SimpleExceptionTrap { 138 | private $expected; 139 | private $ignored; 140 | private $message; 141 | 142 | /** 143 | * Clears down the queue ready for action. 144 | */ 145 | function __construct() { 146 | $this->clear(); 147 | } 148 | 149 | /** 150 | * Sets up an expectation of an exception. 151 | * This has the effect of intercepting an 152 | * exception that matches. 153 | * @param SimpleExpectation $expected Expected exception to match. 154 | * @param string $message Message to display. 155 | * @access public 156 | */ 157 | function expectException($expected = false, $message = '%s') { 158 | $this->expected = $this->coerceToExpectation($expected); 159 | $this->message = $message; 160 | } 161 | 162 | /** 163 | * Adds an exception to the ignore list. This is the list 164 | * of exceptions that when thrown do not affect the test. 165 | * @param SimpleExpectation $ignored Exception to skip. 166 | * @access public 167 | */ 168 | function ignoreException($ignored) { 169 | $this->ignored[] = $this->coerceToExpectation($ignored); 170 | } 171 | 172 | /** 173 | * Compares the expected exception with any 174 | * in the queue. Issues a pass or fail and 175 | * returns the state of the test. 176 | * @param SimpleTestCase $test Test case to send messages to. 177 | * @param Exception $exception Exception to compare. 178 | * @return boolean False on no match. 179 | */ 180 | function isExpected($test, $exception) { 181 | if ($this->expected) { 182 | return $test->assert($this->expected, $exception, $this->message); 183 | } 184 | foreach ($this->ignored as $ignored) { 185 | if ($ignored->test($exception)) { 186 | return true; 187 | } 188 | } 189 | return false; 190 | } 191 | 192 | /** 193 | * Turns an expected exception into a SimpleExpectation object. 194 | * @param mixed $exception Exception, expectation or 195 | * class name of exception. 196 | * @return SimpleExpectation Expectation that will match the 197 | * exception. 198 | */ 199 | private function coerceToExpectation($exception) { 200 | if ($exception === false) { 201 | return new AnythingExpectation(); 202 | } 203 | if (! SimpleExpectation::isExpectation($exception)) { 204 | return new ExceptionExpectation($exception); 205 | } 206 | return $exception; 207 | } 208 | 209 | /** 210 | * Tests for any left over exception. 211 | * @return string/false The failure message or false if none. 212 | */ 213 | function getOutstanding() { 214 | return sprintf($this->message, 'Failed to trap exception'); 215 | } 216 | 217 | /** 218 | * Discards the contents of the error queue. 219 | */ 220 | function clear() { 221 | $this->expected = false; 222 | $this->message = false; 223 | $this->ignored = array(); 224 | } 225 | } 226 | ?> -------------------------------------------------------------------------------- /tests/simpletest/extensions/pear_test_case.php: -------------------------------------------------------------------------------- 1 | _loosely_typed = false; 35 | } 36 | 37 | /** 38 | * Will test straight equality if set to loose 39 | * typing, or identity if not. 40 | * @param $first First value. 41 | * @param $second Comparison value. 42 | * @param $message Message to display. 43 | * @public 44 | */ 45 | function assertEquals($first, $second, $message = "%s", $delta = 0) { 46 | if ($this->_loosely_typed) { 47 | $expectation = new EqualExpectation($first); 48 | } else { 49 | $expectation = new IdenticalExpectation($first); 50 | } 51 | $this->assert($expectation, $second, $message); 52 | } 53 | 54 | /** 55 | * Passes if the value tested is not null. 56 | * @param $value Value to test against. 57 | * @param $message Message to display. 58 | * @public 59 | */ 60 | function assertNotNull($value, $message = "%s") { 61 | parent::assert(new TrueExpectation(), isset($value), $message); 62 | } 63 | 64 | /** 65 | * Passes if the value tested is null. 66 | * @param $value Value to test against. 67 | * @param $message Message to display. 68 | * @public 69 | */ 70 | function assertNull($value, $message = "%s") { 71 | parent::assert(new TrueExpectation(), !isset($value), $message); 72 | } 73 | 74 | /** 75 | * Identity test tests for the same object. 76 | * @param $first First object handle. 77 | * @param $second Hopefully the same handle. 78 | * @param $message Message to display. 79 | * @public 80 | */ 81 | function assertSame($first, $second, $message = "%s") { 82 | $dumper = new SimpleDumper(); 83 | $message = sprintf( 84 | $message, 85 | "[" . $dumper->describeValue($first) . 86 | "] and [" . $dumper->describeValue($second) . 87 | "] should reference the same object"); 88 | return $this->assert( 89 | new TrueExpectation(), 90 | SimpleTestCompatibility::isReference($first, $second), 91 | $message); 92 | } 93 | 94 | /** 95 | * Inverted identity test. 96 | * @param $first First object handle. 97 | * @param $second Hopefully a different handle. 98 | * @param $message Message to display. 99 | * @public 100 | */ 101 | function assertNotSame($first, $second, $message = "%s") { 102 | $dumper = new SimpleDumper(); 103 | $message = sprintf( 104 | $message, 105 | "[" . $dumper->describeValue($first) . 106 | "] and [" . $dumper->describeValue($second) . 107 | "] should not be the same object"); 108 | return $this->assert( 109 | new falseExpectation(), 110 | SimpleTestCompatibility::isReference($first, $second), 111 | $message); 112 | } 113 | 114 | /** 115 | * Sends pass if the test condition resolves true, 116 | * a fail otherwise. 117 | * @param $condition Condition to test true. 118 | * @param $message Message to display. 119 | * @public 120 | */ 121 | function assertTrue($condition, $message = "%s") { 122 | parent::assert(new TrueExpectation(), $condition, $message); 123 | } 124 | 125 | /** 126 | * Sends pass if the test condition resolves false, 127 | * a fail otherwise. 128 | * @param $condition Condition to test false. 129 | * @param $message Message to display. 130 | * @public 131 | */ 132 | function assertFalse($condition, $message = "%s") { 133 | parent::assert(new FalseExpectation(), $condition, $message); 134 | } 135 | 136 | /** 137 | * Tests a regex match. Needs refactoring. 138 | * @param $pattern Regex to match. 139 | * @param $subject String to search in. 140 | * @param $message Message to display. 141 | * @public 142 | */ 143 | function assertRegExp($pattern, $subject, $message = "%s") { 144 | $this->assert(new PatternExpectation($pattern), $subject, $message); 145 | } 146 | 147 | /** 148 | * Tests the type of a value. 149 | * @param $value Value to take type of. 150 | * @param $type Hoped for type. 151 | * @param $message Message to display. 152 | * @public 153 | */ 154 | function assertType($value, $type, $message = "%s") { 155 | parent::assert(new TrueExpectation(), gettype($value) == strtolower($type), $message); 156 | } 157 | 158 | /** 159 | * Sets equality operation to act as a simple equal 160 | * comparison only, allowing a broader range of 161 | * matches. 162 | * @param $loosely_typed True for broader comparison. 163 | * @public 164 | */ 165 | function setLooselyTyped($loosely_typed) { 166 | $this->_loosely_typed = $loosely_typed; 167 | } 168 | 169 | /** 170 | * For progress indication during 171 | * a test amongst other things. 172 | * @return Usually one. 173 | * @public 174 | */ 175 | function countTestCases() { 176 | return $this->getSize(); 177 | } 178 | 179 | /** 180 | * Accessor for name, normally just the class 181 | * name. 182 | * @public 183 | */ 184 | function getName() { 185 | return $this->getLabel(); 186 | } 187 | 188 | /** 189 | * Does nothing. For compatibility only. 190 | * @param $name Dummy 191 | * @public 192 | */ 193 | function setName($name) { 194 | } 195 | } 196 | ?> -------------------------------------------------------------------------------- /tests/simpletest/extensions/testdox.php: -------------------------------------------------------------------------------- 1 | _test_case_pattern = empty($test_case_pattern) ? '/^(.*)$/' : $test_case_pattern; 21 | } 22 | 23 | function paintCaseStart($test_name) { 24 | preg_match($this->_test_case_pattern, $test_name, $matches); 25 | if (!empty($matches[1])) { 26 | echo $matches[1] . "\n"; 27 | } else { 28 | echo $test_name . "\n"; 29 | } 30 | } 31 | 32 | function paintCaseEnd($test_name) { 33 | echo "\n"; 34 | } 35 | 36 | function paintMethodStart($test_name) { 37 | if (!preg_match('/^test(.*)$/i', $test_name, $matches)) { 38 | return; 39 | } 40 | $test_name = $matches[1]; 41 | $test_name = preg_replace('/([A-Z])([A-Z])/', '$1 $2', $test_name); 42 | echo '- ' . strtolower(preg_replace('/([a-zA-Z])([A-Z0-9])/', '$1 $2', $test_name)); 43 | } 44 | 45 | function paintMethodEnd($test_name) { 46 | echo "\n"; 47 | } 48 | 49 | function paintFail($message) { 50 | echo " [FAILED]"; 51 | } 52 | } 53 | ?> 54 | -------------------------------------------------------------------------------- /tests/simpletest/extensions/testdox/test.php: -------------------------------------------------------------------------------- 1 | assertIsA($dox, 'SimpleScorer'); 14 | $this->assertIsA($dox, 'SimpleReporter'); 15 | } 16 | 17 | function testOutputsNameOfTestCase() { 18 | $dox = new TestDoxReporter(); 19 | ob_start(); 20 | $dox->paintCaseStart('TestOfTestDoxReporter'); 21 | $buffer = ob_get_clean(); 22 | $this->assertPattern('/^TestDoxReporter/', $buffer); 23 | } 24 | 25 | function testOutputOfTestCaseNameFilteredByConstructParameter() { 26 | $dox = new TestDoxReporter('/^(.*)Test$/'); 27 | ob_start(); 28 | $dox->paintCaseStart('SomeGreatWidgetTest'); 29 | $buffer = ob_get_clean(); 30 | $this->assertPattern('/^SomeGreatWidget/', $buffer); 31 | } 32 | 33 | function testIfTest_case_patternIsEmptyAssumeEverythingMatches() { 34 | $dox = new TestDoxReporter(''); 35 | ob_start(); 36 | $dox->paintCaseStart('TestOfTestDoxReporter'); 37 | $buffer = ob_get_clean(); 38 | $this->assertPattern('/^TestOfTestDoxReporter/', $buffer); 39 | } 40 | 41 | function testEmptyLineInsertedWhenCaseEnds() { 42 | $dox = new TestDoxReporter(); 43 | ob_start(); 44 | $dox->paintCaseEnd('TestOfTestDoxReporter'); 45 | $buffer = ob_get_clean(); 46 | $this->assertEqual("\n", $buffer); 47 | } 48 | 49 | function testPaintsTestMethodInTestDoxFormat() { 50 | $dox = new TestDoxReporter(); 51 | ob_start(); 52 | $dox->paintMethodStart('testSomeGreatTestCase'); 53 | $buffer = ob_get_clean(); 54 | $this->assertEqual("- some great test case", $buffer); 55 | unset($buffer); 56 | 57 | $random = rand(100, 200); 58 | ob_start(); 59 | $dox->paintMethodStart("testRandomNumberIs{$random}"); 60 | $buffer = ob_get_clean(); 61 | $this->assertEqual("- random number is {$random}", $buffer); 62 | } 63 | 64 | function testDoesNotOutputAnythingOnNoneTestMethods() { 65 | $dox = new TestDoxReporter(); 66 | ob_start(); 67 | $dox->paintMethodStart('nonMatchingMethod'); 68 | $buffer = ob_get_clean(); 69 | $this->assertEqual('', $buffer); 70 | } 71 | 72 | function testPaintMethodAddLineBreak() { 73 | $dox = new TestDoxReporter(); 74 | ob_start(); 75 | $dox->paintMethodEnd('someMethod'); 76 | $buffer = ob_get_clean(); 77 | $this->assertEqual("\n", $buffer); 78 | } 79 | 80 | function testProperlySpacesSingleLettersInMethodName() { 81 | $dox = new TestDoxReporter(); 82 | ob_start(); 83 | $dox->paintMethodStart('testAVerySimpleAgainAVerySimpleMethod'); 84 | $buffer = ob_get_clean(); 85 | $this->assertEqual('- a very simple again a very simple method', $buffer); 86 | } 87 | 88 | function testOnFailureThisPrintsFailureNotice() { 89 | $dox = new TestDoxReporter(); 90 | ob_start(); 91 | $dox->paintFail(''); 92 | $buffer = ob_get_clean(); 93 | $this->assertEqual(' [FAILED]', $buffer); 94 | } 95 | 96 | function testWhenMatchingMethodNamesTestPrefixIsCaseInsensitive() { 97 | $dox = new TestDoxReporter(); 98 | ob_start(); 99 | $dox->paintMethodStart('TESTSupportsAllUppercaseTestPrefixEvenThoughIDoNotKnowWhyYouWouldDoThat'); 100 | $buffer = ob_get_clean(); 101 | $this->assertEqual( 102 | '- supports all uppercase test prefix even though i do not know why you would do that', 103 | $buffer 104 | ); 105 | } 106 | } 107 | ?> -------------------------------------------------------------------------------- /tests/simpletest/invoker.php: -------------------------------------------------------------------------------- 1 | test_case = $test_case; 39 | } 40 | 41 | /** 42 | * Accessor for test case being run. 43 | * @return SimpleTestCase Test case. 44 | * @access public 45 | */ 46 | function getTestCase() { 47 | return $this->test_case; 48 | } 49 | 50 | /** 51 | * Runs test level set up. Used for changing 52 | * the mechanics of base test cases. 53 | * @param string $method Test method to call. 54 | * @access public 55 | */ 56 | function before($method) { 57 | $this->test_case->before($method); 58 | } 59 | 60 | /** 61 | * Invokes a test method and buffered with setUp() 62 | * and tearDown() calls. 63 | * @param string $method Test method to call. 64 | * @access public 65 | */ 66 | function invoke($method) { 67 | $this->test_case->setUp(); 68 | $this->test_case->$method(); 69 | $this->test_case->tearDown(); 70 | } 71 | 72 | /** 73 | * Runs test level clean up. Used for changing 74 | * the mechanics of base test cases. 75 | * @param string $method Test method to call. 76 | * @access public 77 | */ 78 | function after($method) { 79 | $this->test_case->after($method); 80 | } 81 | } 82 | 83 | /** 84 | * Do nothing decorator. Just passes the invocation 85 | * straight through. 86 | * @package SimpleTest 87 | * @subpackage UnitTester 88 | */ 89 | class SimpleInvokerDecorator { 90 | private $invoker; 91 | 92 | /** 93 | * Stores the invoker to wrap. 94 | * @param SimpleInvoker $invoker Test method runner. 95 | */ 96 | function __construct($invoker) { 97 | $this->invoker = $invoker; 98 | } 99 | 100 | /** 101 | * Accessor for test case being run. 102 | * @return SimpleTestCase Test case. 103 | * @access public 104 | */ 105 | function getTestCase() { 106 | return $this->invoker->getTestCase(); 107 | } 108 | 109 | /** 110 | * Runs test level set up. Used for changing 111 | * the mechanics of base test cases. 112 | * @param string $method Test method to call. 113 | * @access public 114 | */ 115 | function before($method) { 116 | $this->invoker->before($method); 117 | } 118 | 119 | /** 120 | * Invokes a test method and buffered with setUp() 121 | * and tearDown() calls. 122 | * @param string $method Test method to call. 123 | * @access public 124 | */ 125 | function invoke($method) { 126 | $this->invoker->invoke($method); 127 | } 128 | 129 | /** 130 | * Runs test level clean up. Used for changing 131 | * the mechanics of base test cases. 132 | * @param string $method Test method to call. 133 | * @access public 134 | */ 135 | function after($method) { 136 | $this->invoker->after($method); 137 | } 138 | } 139 | ?> -------------------------------------------------------------------------------- /tests/simpletest/recorder.php: -------------------------------------------------------------------------------- 1 | time, $this->breadcrumb, $this->message) = 34 | array(time(), $breadcrumb, $message); 35 | } 36 | } 37 | 38 | /** 39 | * A single pass captured for later. 40 | * @package SimpleTest 41 | * @subpackage Extensions 42 | */ 43 | class SimpleResultOfPass extends SimpleResult { } 44 | 45 | /** 46 | * A single failure captured for later. 47 | * @package SimpleTest 48 | * @subpackage Extensions 49 | */ 50 | class SimpleResultOfFail extends SimpleResult { } 51 | 52 | /** 53 | * A single exception captured for later. 54 | * @package SimpleTest 55 | * @subpackage Extensions 56 | */ 57 | class SimpleResultOfException extends SimpleResult { } 58 | 59 | /** 60 | * Array-based test recorder. Returns an array 61 | * with timestamp, status, test name and message for each pass and failure. 62 | * @package SimpleTest 63 | * @subpackage Extensions 64 | */ 65 | class Recorder extends SimpleReporterDecorator { 66 | public $results = array(); 67 | 68 | /** 69 | * Stashes the pass as a SimpleResultOfPass 70 | * for later retrieval. 71 | * @param string $message Pass message to be displayed 72 | * eventually. 73 | */ 74 | function paintPass($message) { 75 | parent::paintPass($message); 76 | $this->results[] = new SimpleResultOfPass(parent::getTestList(), $message); 77 | } 78 | 79 | /** 80 | * Stashes the fail as a SimpleResultOfFail 81 | * for later retrieval. 82 | * @param string $message Failure message to be displayed 83 | * eventually. 84 | */ 85 | function paintFail($message) { 86 | parent::paintFail($message); 87 | $this->results[] = new SimpleResultOfFail(parent::getTestList(), $message); 88 | } 89 | 90 | /** 91 | * Stashes the exception as a SimpleResultOfException 92 | * for later retrieval. 93 | * @param string $message Exception message to be displayed 94 | * eventually. 95 | */ 96 | function paintException($message) { 97 | parent::paintException($message); 98 | $this->results[] = new SimpleResultOfException(parent::getTestList(), $message); 99 | } 100 | } 101 | ?> -------------------------------------------------------------------------------- /tests/simpletest/reflection_php4.php: -------------------------------------------------------------------------------- 1 | _interface = $interface; 25 | } 26 | 27 | /** 28 | * Checks that a class has been declared. 29 | * @return boolean True if defined. 30 | * @access public 31 | */ 32 | function classExists() { 33 | return class_exists($this->_interface); 34 | } 35 | 36 | /** 37 | * Needed to kill the autoload feature in PHP5 38 | * for classes created dynamically. 39 | * @return boolean True if defined. 40 | * @access public 41 | */ 42 | function classExistsSansAutoload() { 43 | return class_exists($this->_interface); 44 | } 45 | 46 | /** 47 | * Checks that a class or interface has been 48 | * declared. 49 | * @return boolean True if defined. 50 | * @access public 51 | */ 52 | function classOrInterfaceExists() { 53 | return class_exists($this->_interface); 54 | } 55 | 56 | /** 57 | * Needed to kill the autoload feature in PHP5 58 | * for classes created dynamically. 59 | * @return boolean True if defined. 60 | * @access public 61 | */ 62 | function classOrInterfaceExistsSansAutoload() { 63 | return class_exists($this->_interface); 64 | } 65 | 66 | /** 67 | * Gets the list of methods on a class or 68 | * interface. 69 | * @returns array List of method names. 70 | * @access public 71 | */ 72 | function getMethods() { 73 | return get_class_methods($this->_interface); 74 | } 75 | 76 | /** 77 | * Gets the list of interfaces from a class. If the 78 | * class name is actually an interface then just that 79 | * interface is returned. 80 | * @returns array List of interfaces. 81 | * @access public 82 | */ 83 | function getInterfaces() { 84 | return array(); 85 | } 86 | 87 | /** 88 | * Finds the parent class name. 89 | * @returns string Parent class name. 90 | * @access public 91 | */ 92 | function getParent() { 93 | return strtolower(get_parent_class($this->_interface)); 94 | } 95 | 96 | /** 97 | * Determines if the class is abstract, which for PHP 4 98 | * will never be the case. 99 | * @returns boolean True if abstract. 100 | * @access public 101 | */ 102 | function isAbstract() { 103 | return false; 104 | } 105 | 106 | /** 107 | * Determines if the the entity is an interface, which for PHP 4 108 | * will never be the case. 109 | * @returns boolean True if interface. 110 | * @access public 111 | */ 112 | function isInterface() { 113 | return false; 114 | } 115 | 116 | /** 117 | * Scans for final methods, but as it's PHP 4 there 118 | * aren't any. 119 | * @returns boolean True if the class has a final method. 120 | * @access public 121 | */ 122 | function hasFinal() { 123 | return false; 124 | } 125 | 126 | /** 127 | * Gets the source code matching the declaration 128 | * of a method. 129 | * @param string $method Method name. 130 | * @access public 131 | */ 132 | function getSignature($method) { 133 | return "function &$method()"; 134 | } 135 | } 136 | ?> -------------------------------------------------------------------------------- /tests/simpletest/remote.php: -------------------------------------------------------------------------------- 1 | url = $url; 35 | $this->dry_url = $dry_url ? $dry_url : $url; 36 | $this->size = false; 37 | } 38 | 39 | /** 40 | * Accessor for the test name for subclasses. 41 | * @return string Name of the test. 42 | * @access public 43 | */ 44 | function getLabel() { 45 | return $this->url; 46 | } 47 | 48 | /** 49 | * Runs the top level test for this class. Currently 50 | * reads the data as a single chunk. I'll fix this 51 | * once I have added iteration to the browser. 52 | * @param SimpleReporter $reporter Target of test results. 53 | * @returns boolean True if no failures. 54 | * @access public 55 | */ 56 | function run($reporter) { 57 | $browser = $this->createBrowser(); 58 | $xml = $browser->get($this->url); 59 | if (! $xml) { 60 | trigger_error('Cannot read remote test URL [' . $this->url . ']'); 61 | return false; 62 | } 63 | $parser = $this->createParser($reporter); 64 | if (! $parser->parse($xml)) { 65 | trigger_error('Cannot parse incoming XML from [' . $this->url . ']'); 66 | return false; 67 | } 68 | return true; 69 | } 70 | 71 | /** 72 | * Creates a new web browser object for fetching 73 | * the XML report. 74 | * @return SimpleBrowser New browser. 75 | * @access protected 76 | */ 77 | protected function createBrowser() { 78 | return new SimpleBrowser(); 79 | } 80 | 81 | /** 82 | * Creates the XML parser. 83 | * @param SimpleReporter $reporter Target of test results. 84 | * @return SimpleTestXmlListener XML reader. 85 | * @access protected 86 | */ 87 | protected function createParser($reporter) { 88 | return new SimpleTestXmlParser($reporter); 89 | } 90 | 91 | /** 92 | * Accessor for the number of subtests. 93 | * @return integer Number of test cases. 94 | * @access public 95 | */ 96 | function getSize() { 97 | if ($this->size === false) { 98 | $browser = $this->createBrowser(); 99 | $xml = $browser->get($this->dry_url); 100 | if (! $xml) { 101 | trigger_error('Cannot read remote test URL [' . $this->dry_url . ']'); 102 | return false; 103 | } 104 | $reporter = new SimpleReporter(); 105 | $parser = $this->createParser($reporter); 106 | if (! $parser->parse($xml)) { 107 | trigger_error('Cannot parse incoming XML from [' . $this->dry_url . ']'); 108 | return false; 109 | } 110 | $this->size = $reporter->getTestCaseCount(); 111 | } 112 | return $this->size; 113 | } 114 | } 115 | ?> -------------------------------------------------------------------------------- /tests/simpletest/selector.php: -------------------------------------------------------------------------------- 1 | name = $name; 31 | } 32 | 33 | /** 34 | * Accessor for name. 35 | * @returns string $name Name to match. 36 | */ 37 | function getName() { 38 | return $this->name; 39 | } 40 | 41 | /** 42 | * Compares with name attribute of widget. 43 | * @param SimpleWidget $widget Control to compare. 44 | * @access public 45 | */ 46 | function isMatch($widget) { 47 | return ($widget->getName() == $this->name); 48 | } 49 | } 50 | 51 | /** 52 | * Used to extract form elements for testing against. 53 | * Searches by visible label or alt text. 54 | * @package SimpleTest 55 | * @subpackage WebTester 56 | */ 57 | class SimpleByLabel { 58 | private $label; 59 | 60 | /** 61 | * Stashes the name for later comparison. 62 | * @param string $label Visible text to match. 63 | */ 64 | function __construct($label) { 65 | $this->label = $label; 66 | } 67 | 68 | /** 69 | * Comparison. Compares visible text of widget or 70 | * related label. 71 | * @param SimpleWidget $widget Control to compare. 72 | * @access public 73 | */ 74 | function isMatch($widget) { 75 | if (! method_exists($widget, 'isLabel')) { 76 | return false; 77 | } 78 | return $widget->isLabel($this->label); 79 | } 80 | } 81 | 82 | /** 83 | * Used to extract form elements for testing against. 84 | * Searches dy id attribute. 85 | * @package SimpleTest 86 | * @subpackage WebTester 87 | */ 88 | class SimpleById { 89 | private $id; 90 | 91 | /** 92 | * Stashes the name for later comparison. 93 | * @param string $id ID atribute to match. 94 | */ 95 | function __construct($id) { 96 | $this->id = $id; 97 | } 98 | 99 | /** 100 | * Comparison. Compares id attribute of widget. 101 | * @param SimpleWidget $widget Control to compare. 102 | * @access public 103 | */ 104 | function isMatch($widget) { 105 | return $widget->isId($this->id); 106 | } 107 | } 108 | 109 | /** 110 | * Used to extract form elements for testing against. 111 | * Searches by visible label, name or alt text. 112 | * @package SimpleTest 113 | * @subpackage WebTester 114 | */ 115 | class SimpleByLabelOrName { 116 | private $label; 117 | 118 | /** 119 | * Stashes the name/label for later comparison. 120 | * @param string $label Visible text to match. 121 | */ 122 | function __construct($label) { 123 | $this->label = $label; 124 | } 125 | 126 | /** 127 | * Comparison. Compares visible text of widget or 128 | * related label or name. 129 | * @param SimpleWidget $widget Control to compare. 130 | * @access public 131 | */ 132 | function isMatch($widget) { 133 | if (method_exists($widget, 'isLabel')) { 134 | if ($widget->isLabel($this->label)) { 135 | return true; 136 | } 137 | } 138 | return ($widget->getName() == $this->label); 139 | } 140 | } 141 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/adapter_test.php: -------------------------------------------------------------------------------- 1 | assertTrue(true, "PEAR true"); 13 | $this->assertFalse(false, "PEAR false"); 14 | } 15 | 16 | function testName() { 17 | $this->assertTrue($this->getName() == get_class($this)); 18 | } 19 | 20 | function testPass() { 21 | $this->pass("PEAR pass"); 22 | } 23 | 24 | function testNulls() { 25 | $value = null; 26 | $this->assertNull($value, "PEAR null"); 27 | $value = 0; 28 | $this->assertNotNull($value, "PEAR not null"); 29 | } 30 | 31 | function testType() { 32 | $this->assertType("Hello", "string", "PEAR type"); 33 | } 34 | 35 | function testEquals() { 36 | $this->assertEquals(12, 12, "PEAR identity"); 37 | $this->setLooselyTyped(true); 38 | $this->assertEquals("12", 12, "PEAR equality"); 39 | } 40 | 41 | function testSame() { 42 | $same = new SameTestClass(); 43 | $this->assertSame($same, $same, "PEAR same"); 44 | } 45 | 46 | function testRegExp() { 47 | $this->assertRegExp('/hello/', "A big hello from me", "PEAR regex"); 48 | } 49 | } 50 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/all_tests.php: -------------------------------------------------------------------------------- 1 | TestSuite('All tests for SimpleTest ' . SimpleTest::getVersion()); 7 | $this->addFile(dirname(__FILE__) . '/unit_tests.php'); 8 | $this->addFile(dirname(__FILE__) . '/shell_test.php'); 9 | $this->addFile(dirname(__FILE__) . '/live_test.php'); 10 | $this->addFile(dirname(__FILE__) . '/acceptance_test.php'); 11 | } 12 | } 13 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/arguments_test.php: -------------------------------------------------------------------------------- 1 | assertIdentical($arguments->a, false); 10 | $this->assertIdentical($arguments->all(), array()); 11 | } 12 | 13 | function testSingleArgumentNameRecordedAsTrue() { 14 | $arguments = new SimpleArguments(array('me', '-a')); 15 | $this->assertIdentical($arguments->a, true); 16 | } 17 | 18 | function testSingleArgumentCanBeGivenAValue() { 19 | $arguments = new SimpleArguments(array('me', '-a=AAA')); 20 | $this->assertIdentical($arguments->a, 'AAA'); 21 | } 22 | 23 | function testSingleArgumentCanBeGivenSpaceSeparatedValue() { 24 | $arguments = new SimpleArguments(array('me', '-a', 'AAA')); 25 | $this->assertIdentical($arguments->a, 'AAA'); 26 | } 27 | 28 | function testWillBuildArrayFromRepeatedValue() { 29 | $arguments = new SimpleArguments(array('me', '-a', 'A', '-a', 'AA')); 30 | $this->assertIdentical($arguments->a, array('A', 'AA')); 31 | } 32 | 33 | function testWillBuildArrayFromMultiplyRepeatedValues() { 34 | $arguments = new SimpleArguments(array('me', '-a', 'A', '-a', 'AA', '-a', 'AAA')); 35 | $this->assertIdentical($arguments->a, array('A', 'AA', 'AAA')); 36 | } 37 | 38 | function testCanParseLongFormArguments() { 39 | $arguments = new SimpleArguments(array('me', '--aa=AA', '--bb', 'BB')); 40 | $this->assertIdentical($arguments->aa, 'AA'); 41 | $this->assertIdentical($arguments->bb, 'BB'); 42 | } 43 | 44 | function testGetsFullSetOfResultsAsHash() { 45 | $arguments = new SimpleArguments(array('me', '-a', '-b=1', '-b', '2', '--aa=AA', '--bb', 'BB', '-c')); 46 | $this->assertEqual($arguments->all(), 47 | array('a' => true, 'b' => array('1', '2'), 'aa' => 'AA', 'bb' => 'BB', 'c' => true)); 48 | } 49 | } 50 | 51 | class TestOfHelpOutput extends UnitTestCase { 52 | function testDisplaysGeneralHelpBanner() { 53 | $help = new SimpleHelp('Cool program'); 54 | $this->assertEqual($help->render(), "Cool program\n"); 55 | } 56 | 57 | function testDisplaysOnlySingleLineEndings() { 58 | $help = new SimpleHelp("Cool program\n"); 59 | $this->assertEqual($help->render(), "Cool program\n"); 60 | } 61 | 62 | function testDisplaysHelpOnShortFlag() { 63 | $help = new SimpleHelp('Cool program'); 64 | $help->explainFlag('a', 'Enables A'); 65 | $this->assertEqual($help->render(), "Cool program\n-a Enables A\n"); 66 | } 67 | 68 | function testHasAtleastFourSpacesAfterLongestFlag() { 69 | $help = new SimpleHelp('Cool program'); 70 | $help->explainFlag('a', 'Enables A'); 71 | $help->explainFlag('long', 'Enables Long'); 72 | $this->assertEqual($help->render(), 73 | "Cool program\n-a Enables A\n--long Enables Long\n"); 74 | } 75 | 76 | function testCanDisplaysMultipleFlagsForEachOption() { 77 | $help = new SimpleHelp('Cool program'); 78 | $help->explainFlag(array('a', 'aa'), 'Enables A'); 79 | $this->assertEqual($help->render(), "Cool program\n-a Enables A\n --aa\n"); 80 | } 81 | } 82 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/authentication_test.php: -------------------------------------------------------------------------------- 1 | assertTrue($realm->isWithin( 15 | new SimpleUrl('http://www.here.com/path/hello.html'))); 16 | } 17 | 18 | function testInsideWithLongerUrl() { 19 | $realm = new SimpleRealm( 20 | 'Basic', 21 | new SimpleUrl('http://www.here.com/path/')); 22 | $this->assertTrue($realm->isWithin( 23 | new SimpleUrl('http://www.here.com/path/hello.html'))); 24 | } 25 | 26 | function testBelowRootIsOutside() { 27 | $realm = new SimpleRealm( 28 | 'Basic', 29 | new SimpleUrl('http://www.here.com/path/')); 30 | $this->assertTrue($realm->isWithin( 31 | new SimpleUrl('http://www.here.com/path/more/hello.html'))); 32 | } 33 | 34 | function testOldNetscapeDefinitionIsOutside() { 35 | $realm = new SimpleRealm( 36 | 'Basic', 37 | new SimpleUrl('http://www.here.com/path/')); 38 | $this->assertFalse($realm->isWithin( 39 | new SimpleUrl('http://www.here.com/pathmore/hello.html'))); 40 | } 41 | 42 | function testInsideWithMissingTrailingSlash() { 43 | $realm = new SimpleRealm( 44 | 'Basic', 45 | new SimpleUrl('http://www.here.com/path/')); 46 | $this->assertTrue($realm->isWithin( 47 | new SimpleUrl('http://www.here.com/path'))); 48 | } 49 | 50 | function testDifferentPageNameStillInside() { 51 | $realm = new SimpleRealm( 52 | 'Basic', 53 | new SimpleUrl('http://www.here.com/path/hello.html')); 54 | $this->assertTrue($realm->isWithin( 55 | new SimpleUrl('http://www.here.com/path/goodbye.html'))); 56 | } 57 | 58 | function testNewUrlInSameDirectoryDoesNotChangeRealm() { 59 | $realm = new SimpleRealm( 60 | 'Basic', 61 | new SimpleUrl('http://www.here.com/path/hello.html')); 62 | $realm->stretch(new SimpleUrl('http://www.here.com/path/goodbye.html')); 63 | $this->assertTrue($realm->isWithin( 64 | new SimpleUrl('http://www.here.com/path/index.html'))); 65 | $this->assertFalse($realm->isWithin( 66 | new SimpleUrl('http://www.here.com/index.html'))); 67 | } 68 | 69 | function testNewUrlMakesRealmTheCommonPath() { 70 | $realm = new SimpleRealm( 71 | 'Basic', 72 | new SimpleUrl('http://www.here.com/path/here/hello.html')); 73 | $realm->stretch(new SimpleUrl('http://www.here.com/path/there/goodbye.html')); 74 | $this->assertTrue($realm->isWithin( 75 | new SimpleUrl('http://www.here.com/path/here/index.html'))); 76 | $this->assertTrue($realm->isWithin( 77 | new SimpleUrl('http://www.here.com/path/there/index.html'))); 78 | $this->assertTrue($realm->isWithin( 79 | new SimpleUrl('http://www.here.com/path/index.html'))); 80 | $this->assertFalse($realm->isWithin( 81 | new SimpleUrl('http://www.here.com/index.html'))); 82 | $this->assertFalse($realm->isWithin( 83 | new SimpleUrl('http://www.here.com/paths/index.html'))); 84 | $this->assertFalse($realm->isWithin( 85 | new SimpleUrl('http://www.here.com/pathindex.html'))); 86 | } 87 | } 88 | 89 | class TestOfAuthenticator extends UnitTestCase { 90 | 91 | function testNoRealms() { 92 | $request = new MockSimpleHttpRequest(); 93 | $request->expectNever('addHeaderLine'); 94 | $authenticator = new SimpleAuthenticator(); 95 | $authenticator->addHeaders($request, new SimpleUrl('http://here.com/')); 96 | } 97 | 98 | function &createSingleRealm() { 99 | $authenticator = new SimpleAuthenticator(); 100 | $authenticator->addRealm( 101 | new SimpleUrl('http://www.here.com/path/hello.html'), 102 | 'Basic', 103 | 'Sanctuary'); 104 | $authenticator->setIdentityForRealm('www.here.com', 'Sanctuary', 'test', 'secret'); 105 | return $authenticator; 106 | } 107 | 108 | function testOutsideRealm() { 109 | $request = new MockSimpleHttpRequest(); 110 | $request->expectNever('addHeaderLine'); 111 | $authenticator = &$this->createSingleRealm(); 112 | $authenticator->addHeaders( 113 | $request, 114 | new SimpleUrl('http://www.here.com/hello.html')); 115 | } 116 | 117 | function testWithinRealm() { 118 | $request = new MockSimpleHttpRequest(); 119 | $request->expectOnce('addHeaderLine'); 120 | $authenticator = &$this->createSingleRealm(); 121 | $authenticator->addHeaders( 122 | $request, 123 | new SimpleUrl('http://www.here.com/path/more/hello.html')); 124 | } 125 | 126 | function testRestartingClearsRealm() { 127 | $request = new MockSimpleHttpRequest(); 128 | $request->expectNever('addHeaderLine'); 129 | $authenticator = &$this->createSingleRealm(); 130 | $authenticator->restartSession(); 131 | $authenticator->addHeaders( 132 | $request, 133 | new SimpleUrl('http://www.here.com/hello.html')); 134 | } 135 | 136 | function testDifferentHostIsOutsideRealm() { 137 | $request = new MockSimpleHttpRequest(); 138 | $request->expectNever('addHeaderLine'); 139 | $authenticator = &$this->createSingleRealm(); 140 | $authenticator->addHeaders( 141 | $request, 142 | new SimpleUrl('http://here.com/path/hello.html')); 143 | } 144 | } 145 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/autorun_test.php: -------------------------------------------------------------------------------- 1 | addFile(dirname(__FILE__) . '/support/test1.php'); 9 | $this->assertEqual($tests->getSize(), 1); 10 | } 11 | 12 | function testExitStatusOneIfTestsFail() { 13 | exec('php ' . dirname(__FILE__) . '/support/failing_test.php', $output, $exit_status); 14 | $this->assertEqual($exit_status, 1); 15 | } 16 | 17 | function testExitStatusZeroIfTestsPass() { 18 | exec('php ' . dirname(__FILE__) . '/support/passing_test.php', $output, $exit_status); 19 | $this->assertEqual($exit_status, 0); 20 | } 21 | } 22 | 23 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/bad_test_suite.php: -------------------------------------------------------------------------------- 1 | TestSuite('Two bad test cases'); 7 | $this->addFile(dirname(__FILE__) . '/support/empty_test_file.php'); 8 | } 9 | } 10 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/collector_test.php: -------------------------------------------------------------------------------- 1 | expectMinimumCallCount('addFile', 2); 22 | $suite->expect( 23 | 'addFile', 24 | array(new PatternExpectation('/collectable\\.(1|2)$/'))); 25 | $collector = new SimpleCollector(); 26 | $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); 27 | } 28 | } 29 | 30 | class TestOfPatternCollector extends UnitTestCase { 31 | 32 | function testAddingEverythingToGroup() { 33 | $suite = new MockTestSuite(); 34 | $suite->expectCallCount('addFile', 2); 35 | $suite->expect( 36 | 'addFile', 37 | array(new PatternExpectation('/collectable\\.(1|2)$/'))); 38 | $collector = new SimplePatternCollector('/.*/'); 39 | $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); 40 | } 41 | 42 | function testOnlyMatchedFilesAreAddedToGroup() { 43 | $suite = new MockTestSuite(); 44 | $suite->expectOnce('addFile', array(new PathEqualExpectation( 45 | dirname(__FILE__) . '/support/collector/collectable.1'))); 46 | $collector = new SimplePatternCollector('/1$/'); 47 | $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); 48 | } 49 | } 50 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/command_line_test.php: -------------------------------------------------------------------------------- 1 | assertIdentical($parser->getTest(), ''); 10 | $this->assertIdentical($parser->getTestCase(), ''); 11 | } 12 | 13 | function testNotXmlByDefault() { 14 | $parser = new SimpleCommandLineParser(array()); 15 | $this->assertFalse($parser->isXml()); 16 | } 17 | 18 | function testCanDetectRequestForXml() { 19 | $parser = new SimpleCommandLineParser(array('--xml')); 20 | $this->assertTrue($parser->isXml()); 21 | } 22 | 23 | function testCanReadAssignmentSyntax() { 24 | $parser = new SimpleCommandLineParser(array('--test=myTest')); 25 | $this->assertEqual($parser->getTest(), 'myTest'); 26 | } 27 | 28 | function testCanReadFollowOnSyntax() { 29 | $parser = new SimpleCommandLineParser(array('--test', 'myTest')); 30 | $this->assertEqual($parser->getTest(), 'myTest'); 31 | } 32 | 33 | function testCanReadShortForms() { 34 | $parser = new SimpleCommandLineParser(array('-t', 'myTest', '-c', 'MyClass', '-x')); 35 | $this->assertEqual($parser->getTest(), 'myTest'); 36 | $this->assertEqual($parser->getTestCase(), 'MyClass'); 37 | $this->assertTrue($parser->isXml()); 38 | } 39 | } 40 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/compatibility_test.php: -------------------------------------------------------------------------------- 1 | assertTrue(SimpleTestCompatibility::isA( 15 | new ComparisonClass(), 16 | 'ComparisonClass')); 17 | $this->assertFalse(SimpleTestCompatibility::isA( 18 | new ComparisonClass(), 19 | 'ComparisonSubclass')); 20 | $this->assertTrue(SimpleTestCompatibility::isA( 21 | new ComparisonSubclass(), 22 | 'ComparisonClass')); 23 | } 24 | 25 | function testIdentityOfNumericStrings() { 26 | $numericString1 = "123"; 27 | $numericString2 = "00123"; 28 | $this->assertNotIdentical($numericString1, $numericString2); 29 | } 30 | 31 | function testIdentityOfObjects() { 32 | $object1 = new ComparisonClass(); 33 | $object2 = new ComparisonClass(); 34 | $this->assertIdentical($object1, $object2); 35 | } 36 | 37 | function testReferences () { 38 | $thing = "Hello"; 39 | $thing_reference = &$thing; 40 | $thing_copy = $thing; 41 | $this->assertTrue(SimpleTestCompatibility::isReference( 42 | $thing, 43 | $thing)); 44 | $this->assertTrue(SimpleTestCompatibility::isReference( 45 | $thing, 46 | $thing_reference)); 47 | $this->assertFalse(SimpleTestCompatibility::isReference( 48 | $thing, 49 | $thing_copy)); 50 | } 51 | 52 | function testObjectReferences () { 53 | $object = new ComparisonClass(); 54 | $object_reference = $object; 55 | $object_copy = new ComparisonClass(); 56 | $object_assignment = $object; 57 | $this->assertTrue(SimpleTestCompatibility::isReference( 58 | $object, 59 | $object)); 60 | $this->assertTrue(SimpleTestCompatibility::isReference( 61 | $object, 62 | $object_reference)); 63 | $this->assertFalse(SimpleTestCompatibility::isReference( 64 | $object, 65 | $object_copy)); 66 | if (version_compare(phpversion(), '5', '>=')) { 67 | $this->assertTrue(SimpleTestCompatibility::isReference( 68 | $object, 69 | $object_assignment)); 70 | } else { 71 | $this->assertFalse(SimpleTestCompatibility::isReference( 72 | $object, 73 | $object_assignment)); 74 | } 75 | } 76 | 77 | function testInteraceComparison() { 78 | $object = new ComparisonClassWithInterface(); 79 | $this->assertFalse(SimpleTestCompatibility::isA( 80 | new ComparisonClass(), 81 | 'ComparisonInterface')); 82 | $this->assertTrue(SimpleTestCompatibility::isA( 83 | new ComparisonClassWithInterface(), 84 | 'ComparisonInterface')); 85 | } 86 | } 87 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/detached_test.php: -------------------------------------------------------------------------------- 1 | add(new DetachedTestCase($command)); 11 | if (SimpleReporter::inCli()) { 12 | exit ($test->run(new TextReporter()) ? 0 : 1); 13 | } 14 | $test->run(new HtmlReporter()); 15 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/dumper_test.php: -------------------------------------------------------------------------------- 1 | assertEqual( 13 | $dumper->clipString("Hello", 6), 14 | "Hello", 15 | "Hello, 6->%s"); 16 | $this->assertEqual( 17 | $dumper->clipString("Hello", 5), 18 | "Hello", 19 | "Hello, 5->%s"); 20 | $this->assertEqual( 21 | $dumper->clipString("Hello world", 3), 22 | "Hel...", 23 | "Hello world, 3->%s"); 24 | $this->assertEqual( 25 | $dumper->clipString("Hello world", 6, 3), 26 | "Hello ...", 27 | "Hello world, 6, 3->%s"); 28 | $this->assertEqual( 29 | $dumper->clipString("Hello world", 3, 6), 30 | "...o w...", 31 | "Hello world, 3, 6->%s"); 32 | $this->assertEqual( 33 | $dumper->clipString("Hello world", 4, 11), 34 | "...orld", 35 | "Hello world, 4, 11->%s"); 36 | $this->assertEqual( 37 | $dumper->clipString("Hello world", 4, 12), 38 | "...orld", 39 | "Hello world, 4, 12->%s"); 40 | } 41 | 42 | function testDescribeNull() { 43 | $dumper = new SimpleDumper(); 44 | $this->assertPattern('/null/i', $dumper->describeValue(null)); 45 | } 46 | 47 | function testDescribeBoolean() { 48 | $dumper = new SimpleDumper(); 49 | $this->assertPattern('/boolean/i', $dumper->describeValue(true)); 50 | $this->assertPattern('/true/i', $dumper->describeValue(true)); 51 | $this->assertPattern('/false/i', $dumper->describeValue(false)); 52 | } 53 | 54 | function testDescribeString() { 55 | $dumper = new SimpleDumper(); 56 | $this->assertPattern('/string/i', $dumper->describeValue('Hello')); 57 | $this->assertPattern('/Hello/', $dumper->describeValue('Hello')); 58 | } 59 | 60 | function testDescribeInteger() { 61 | $dumper = new SimpleDumper(); 62 | $this->assertPattern('/integer/i', $dumper->describeValue(35)); 63 | $this->assertPattern('/35/', $dumper->describeValue(35)); 64 | } 65 | 66 | function testDescribeFloat() { 67 | $dumper = new SimpleDumper(); 68 | $this->assertPattern('/float/i', $dumper->describeValue(0.99)); 69 | $this->assertPattern('/0\.99/', $dumper->describeValue(0.99)); 70 | } 71 | 72 | function testDescribeArray() { 73 | $dumper = new SimpleDumper(); 74 | $this->assertPattern('/array/i', $dumper->describeValue(array(1, 4))); 75 | $this->assertPattern('/2/i', $dumper->describeValue(array(1, 4))); 76 | } 77 | 78 | function testDescribeObject() { 79 | $dumper = new SimpleDumper(); 80 | $this->assertPattern( 81 | '/object/i', 82 | $dumper->describeValue(new DumperDummy())); 83 | $this->assertPattern( 84 | '/DumperDummy/i', 85 | $dumper->describeValue(new DumperDummy())); 86 | } 87 | } 88 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/eclipse_test.php: -------------------------------------------------------------------------------- 1 | expectOnce('write',array($expected)); 22 | $listener->setReturnValue('write',-1); 23 | 24 | $pathparts = pathinfo($fullpath); 25 | $filename = $pathparts['basename']; 26 | $test= &new TestSuite($filename); 27 | $test->addTestFile($fullpath); 28 | $test->run(new EclipseReporter($listener)); 29 | $this->assertEqual($expected,$listener->output); 30 | } 31 | } 32 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/encoding_test.php: -------------------------------------------------------------------------------- 1 | assertEqual($pair->asRequest(), 'a=A'); 14 | } 15 | 16 | function testMimeEncodedAsHeadersAndContent() { 17 | $pair = new SimpleEncodedPair('a', 'A'); 18 | $this->assertEqual( 19 | $pair->asMime(), 20 | "Content-Disposition: form-data; name=\"a\"\r\n\r\nA"); 21 | } 22 | 23 | function testAttachmentEncodedAsHeadersWithDispositionAndContent() { 24 | $part = new SimpleAttachment('a', 'A', 'aaa.txt'); 25 | $this->assertEqual( 26 | $part->asMime(), 27 | "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . 28 | "Content-Type: text/plain\r\n\r\nA"); 29 | } 30 | } 31 | 32 | class TestOfEncoding extends UnitTestCase { 33 | private $content_so_far; 34 | 35 | function write($content) { 36 | $this->content_so_far .= $content; 37 | } 38 | 39 | function clear() { 40 | $this->content_so_far = ''; 41 | } 42 | 43 | function assertWritten($encoding, $content, $message = '%s') { 44 | $this->clear(); 45 | $encoding->writeTo($this); 46 | $this->assertIdentical($this->content_so_far, $content, $message); 47 | } 48 | 49 | function testGetEmpty() { 50 | $encoding = new SimpleGetEncoding(); 51 | $this->assertIdentical($encoding->getValue('a'), false); 52 | $this->assertIdentical($encoding->asUrlRequest(), ''); 53 | } 54 | 55 | function testPostEmpty() { 56 | $encoding = new SimplePostEncoding(); 57 | $this->assertIdentical($encoding->getValue('a'), false); 58 | $this->assertWritten($encoding, ''); 59 | } 60 | 61 | function testPrefilled() { 62 | $encoding = new SimplePostEncoding(array('a' => 'aaa')); 63 | $this->assertIdentical($encoding->getValue('a'), 'aaa'); 64 | $this->assertWritten($encoding, 'a=aaa'); 65 | } 66 | 67 | function testPrefilledWithTwoLevels() { 68 | $query = array('a' => array('aa' => 'aaa')); 69 | $encoding = new SimplePostEncoding($query); 70 | $this->assertTrue($encoding->hasMoreThanOneLevel($query)); 71 | $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa]' => 'aaa')); 72 | $this->assertIdentical($encoding->getValue('a[aa]'), 'aaa'); 73 | $this->assertWritten($encoding, 'a%5Baa%5D=aaa'); 74 | } 75 | 76 | function testPrefilledWithThreeLevels() { 77 | $query = array('a' => array('aa' => array('aaa' => 'aaaa'))); 78 | $encoding = new SimplePostEncoding($query); 79 | $this->assertTrue($encoding->hasMoreThanOneLevel($query)); 80 | $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa][aaa]' => 'aaaa')); 81 | $this->assertIdentical($encoding->getValue('a[aa][aaa]'), 'aaaa'); 82 | $this->assertWritten($encoding, 'a%5Baa%5D%5Baaa%5D=aaaa'); 83 | } 84 | 85 | function testPrefilledWithObject() { 86 | $encoding = new SimplePostEncoding(new SimpleEncoding(array('a' => 'aaa'))); 87 | $this->assertIdentical($encoding->getValue('a'), 'aaa'); 88 | $this->assertWritten($encoding, 'a=aaa'); 89 | } 90 | 91 | function testMultiplePrefilled() { 92 | $query = array('a' => array('a1', 'a2')); 93 | $encoding = new SimplePostEncoding($query); 94 | $this->assertTrue($encoding->hasMoreThanOneLevel($query)); 95 | $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[0]' => 'a1', 'a[1]' => 'a2')); 96 | $this->assertIdentical($encoding->getValue('a[0]'), 'a1'); 97 | $this->assertIdentical($encoding->getValue('a[1]'), 'a2'); 98 | $this->assertWritten($encoding, 'a%5B0%5D=a1&a%5B1%5D=a2'); 99 | } 100 | 101 | function testSingleParameter() { 102 | $encoding = new SimplePostEncoding(); 103 | $encoding->add('a', 'Hello'); 104 | $this->assertEqual($encoding->getValue('a'), 'Hello'); 105 | $this->assertWritten($encoding, 'a=Hello'); 106 | } 107 | 108 | function testFalseParameter() { 109 | $encoding = new SimplePostEncoding(); 110 | $encoding->add('a', false); 111 | $this->assertEqual($encoding->getValue('a'), false); 112 | $this->assertWritten($encoding, ''); 113 | } 114 | 115 | function testUrlEncoding() { 116 | $encoding = new SimplePostEncoding(); 117 | $encoding->add('a', 'Hello there!'); 118 | $this->assertWritten($encoding, 'a=Hello+there%21'); 119 | } 120 | 121 | function testUrlEncodingOfKey() { 122 | $encoding = new SimplePostEncoding(); 123 | $encoding->add('a!', 'Hello'); 124 | $this->assertWritten($encoding, 'a%21=Hello'); 125 | } 126 | 127 | function testMultipleParameter() { 128 | $encoding = new SimplePostEncoding(); 129 | $encoding->add('a', 'Hello'); 130 | $encoding->add('b', 'Goodbye'); 131 | $this->assertWritten($encoding, 'a=Hello&b=Goodbye'); 132 | } 133 | 134 | function testEmptyParameters() { 135 | $encoding = new SimplePostEncoding(); 136 | $encoding->add('a', ''); 137 | $encoding->add('b', ''); 138 | $this->assertWritten($encoding, 'a=&b='); 139 | } 140 | 141 | function testRepeatedParameter() { 142 | $encoding = new SimplePostEncoding(); 143 | $encoding->add('a', 'Hello'); 144 | $encoding->add('a', 'Goodbye'); 145 | $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); 146 | $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); 147 | } 148 | 149 | function testAddingLists() { 150 | $encoding = new SimplePostEncoding(); 151 | $encoding->add('a', array('Hello', 'Goodbye')); 152 | $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); 153 | $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); 154 | } 155 | 156 | function testMergeInHash() { 157 | $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); 158 | $encoding->merge(array('a' => 'A2')); 159 | $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); 160 | $this->assertIdentical($encoding->getValue('b'), 'B'); 161 | } 162 | 163 | function testMergeInObject() { 164 | $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); 165 | $encoding->merge(new SimpleEncoding(array('a' => 'A2'))); 166 | $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); 167 | $this->assertIdentical($encoding->getValue('b'), 'B'); 168 | } 169 | 170 | function testPrefilledMultipart() { 171 | $encoding = new SimpleMultipartEncoding(array('a' => 'aaa'), 'boundary'); 172 | $this->assertIdentical($encoding->getValue('a'), 'aaa'); 173 | $this->assertwritten($encoding, 174 | "--boundary\r\n" . 175 | "Content-Disposition: form-data; name=\"a\"\r\n" . 176 | "\r\n" . 177 | "aaa\r\n" . 178 | "--boundary--\r\n"); 179 | } 180 | 181 | function testAttachment() { 182 | $encoding = new SimpleMultipartEncoding(array(), 'boundary'); 183 | $encoding->attach('a', 'aaa', 'aaa.txt'); 184 | $this->assertIdentical($encoding->getValue('a'), 'aaa.txt'); 185 | $this->assertwritten($encoding, 186 | "--boundary\r\n" . 187 | "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . 188 | "Content-Type: text/plain\r\n" . 189 | "\r\n" . 190 | "aaa\r\n" . 191 | "--boundary--\r\n"); 192 | } 193 | 194 | function testEntityEncodingDefaultContentType() { 195 | $encoding = new SimpleEntityEncoding(); 196 | $this->assertIdentical($encoding->getContentType(), 'application/x-www-form-urlencoded'); 197 | $this->assertWritten($encoding, ''); 198 | } 199 | 200 | function testEntityEncodingTextBody() { 201 | $encoding = new SimpleEntityEncoding('plain text'); 202 | $this->assertIdentical($encoding->getContentType(), 'text/plain'); 203 | $this->assertWritten($encoding, 'plain text'); 204 | } 205 | 206 | function testEntityEncodingXmlBody() { 207 | $encoding = new SimpleEntityEncoding('

xmltext

', 'text/xml'); 208 | $this->assertIdentical($encoding->getContentType(), 'text/xml'); 209 | $this->assertWritten($encoding, '

xmltext

'); 210 | } 211 | } 212 | 213 | class TestOfEncodingHeaders extends UnitTestCase { 214 | 215 | function testEmptyEncodingWritesZeroContentLength() { 216 | $socket = new MockSimpleSocket(); 217 | $socket->expectAt(0, 'write', array("Content-Length: 0\r\n")); 218 | $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); 219 | $encoding = new SimpleEntityEncoding(); 220 | $encoding->writeHeadersTo($socket); 221 | } 222 | 223 | function testTextEncodingWritesDefaultContentType() { 224 | $socket = new MockSimpleSocket(); 225 | $socket->expectAt(0, 'write', array("Content-Length: 18\r\n")); 226 | $socket->expectAt(1, 'write', array("Content-Type: text/plain\r\n")); 227 | $encoding = new SimpleEntityEncoding('one two three four'); 228 | $encoding->writeHeadersTo($socket); 229 | } 230 | 231 | function testEmptyMultipartEncodingWritesEndBoundaryContentLength() { 232 | $socket = new MockSimpleSocket(); 233 | $socket->expectAt(0, 'write', array("Content-Length: 14\r\n")); 234 | $socket->expectAt(1, 'write', array("Content-Type: multipart/form-data; boundary=boundary\r\n")); 235 | $encoding = new SimpleMultipartEncoding(array(), 'boundary'); 236 | $encoding->writeHeadersTo($socket); 237 | } 238 | 239 | } 240 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/errors_test.php: -------------------------------------------------------------------------------- 1 | get('SimpleErrorQueue'); 15 | $queue->clear(); 16 | } 17 | 18 | function tearDown() { 19 | $context = SimpleTest::getContext(); 20 | $queue = $context->get('SimpleErrorQueue'); 21 | $queue->clear(); 22 | } 23 | 24 | function testExpectationMatchCancelsIncomingError() { 25 | $test = new MockSimpleTestCase(); 26 | $test->expectOnce('assert', array( 27 | new IdenticalExpectation(new AnythingExpectation()), 28 | 'B', 29 | 'a message')); 30 | $test->setReturnValue('assert', true); 31 | $test->expectNever('error'); 32 | $queue = new SimpleErrorQueue(); 33 | $queue->setTestCase($test); 34 | $queue->expectError(new AnythingExpectation(), 'a message'); 35 | $queue->add(1024, 'B', 'b.php', 100); 36 | } 37 | } 38 | 39 | class TestOfErrorTrap extends UnitTestCase { 40 | private $old; 41 | 42 | function setUp() { 43 | $this->old = error_reporting(E_ALL); 44 | set_error_handler('SimpleTestErrorHandler'); 45 | } 46 | 47 | function tearDown() { 48 | restore_error_handler(); 49 | error_reporting($this->old); 50 | } 51 | 52 | function testQueueStartsEmpty() { 53 | $context = SimpleTest::getContext(); 54 | $queue = $context->get('SimpleErrorQueue'); 55 | $this->assertFalse($queue->extract()); 56 | } 57 | 58 | function testErrorsAreSwallowedByMatchingExpectation() { 59 | $this->expectError('Ouch!'); 60 | trigger_error('Ouch!'); 61 | } 62 | 63 | function testErrorsAreSwallowedInOrder() { 64 | $this->expectError('a'); 65 | $this->expectError('b'); 66 | trigger_error('a'); 67 | trigger_error('b'); 68 | } 69 | 70 | function testAnyErrorCanBeSwallowed() { 71 | $this->expectError(); 72 | trigger_error('Ouch!'); 73 | } 74 | 75 | function testErrorCanBeSwallowedByPatternMatching() { 76 | $this->expectError(new PatternExpectation('/ouch/i')); 77 | trigger_error('Ouch!'); 78 | } 79 | 80 | function testErrorWithPercentsPassesWithNoSprintfError() { 81 | $this->expectError("%"); 82 | trigger_error('%'); 83 | } 84 | } 85 | 86 | class TestOfErrors extends UnitTestCase { 87 | private $old; 88 | 89 | function setUp() { 90 | $this->old = error_reporting(E_ALL); 91 | } 92 | 93 | function tearDown() { 94 | error_reporting($this->old); 95 | } 96 | 97 | function testDefaultWhenAllReported() { 98 | error_reporting(E_ALL); 99 | $this->expectError('Ouch!'); 100 | trigger_error('Ouch!'); 101 | } 102 | 103 | function testNoticeWhenReported() { 104 | error_reporting(E_ALL); 105 | $this->expectError('Ouch!'); 106 | trigger_error('Ouch!', E_USER_NOTICE); 107 | } 108 | 109 | function testWarningWhenReported() { 110 | error_reporting(E_ALL); 111 | $this->expectError('Ouch!'); 112 | trigger_error('Ouch!', E_USER_WARNING); 113 | } 114 | 115 | function testErrorWhenReported() { 116 | error_reporting(E_ALL); 117 | $this->expectError('Ouch!'); 118 | trigger_error('Ouch!', E_USER_ERROR); 119 | } 120 | 121 | function testNoNoticeWhenNotReported() { 122 | error_reporting(0); 123 | trigger_error('Ouch!', E_USER_NOTICE); 124 | } 125 | 126 | function testNoWarningWhenNotReported() { 127 | error_reporting(0); 128 | trigger_error('Ouch!', E_USER_WARNING); 129 | } 130 | 131 | function testNoticeSuppressedWhenReported() { 132 | error_reporting(E_ALL); 133 | @trigger_error('Ouch!', E_USER_NOTICE); 134 | } 135 | 136 | function testWarningSuppressedWhenReported() { 137 | error_reporting(E_ALL); 138 | @trigger_error('Ouch!', E_USER_WARNING); 139 | } 140 | 141 | function testErrorWithPercentsReportedWithNoSprintfError() { 142 | $this->expectError('%'); 143 | trigger_error('%'); 144 | } 145 | } 146 | 147 | class TestOfPHP52RecoverableErrors extends UnitTestCase { 148 | function skip() { 149 | $this->skipIf( 150 | version_compare(phpversion(), '5.2', '<'), 151 | 'E_RECOVERABLE_ERROR not tested for PHP below 5.2'); 152 | } 153 | 154 | function testError() { 155 | eval(' 156 | class RecoverableErrorTestingStub { 157 | function ouch(RecoverableErrorTestingStub $obj) { 158 | } 159 | } 160 | '); 161 | 162 | $stub = new RecoverableErrorTestingStub(); 163 | $this->expectError(new PatternExpectation('/must be an instance of RecoverableErrorTestingStub/i')); 164 | $stub->ouch(new stdClass()); 165 | } 166 | } 167 | 168 | class TestOfErrorsExcludingPHP52AndAbove extends UnitTestCase { 169 | function skip() { 170 | $this->skipIf( 171 | version_compare(phpversion(), '5.2', '>='), 172 | 'E_USER_ERROR not tested for PHP 5.2 and above'); 173 | } 174 | 175 | function testNoErrorWhenNotReported() { 176 | error_reporting(0); 177 | trigger_error('Ouch!', E_USER_ERROR); 178 | } 179 | 180 | function testErrorSuppressedWhenReported() { 181 | error_reporting(E_ALL); 182 | @trigger_error('Ouch!', E_USER_ERROR); 183 | } 184 | } 185 | 186 | SimpleTest::ignore('TestOfNotEnoughErrors'); 187 | /** 188 | * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} 189 | * to verify that it fails as expected. 190 | * 191 | * @ignore 192 | */ 193 | class TestOfNotEnoughErrors extends UnitTestCase { 194 | function testExpectTwoErrorsThrowOne() { 195 | $this->expectError('Error 1'); 196 | trigger_error('Error 1'); 197 | $this->expectError('Error 2'); 198 | } 199 | } 200 | 201 | SimpleTest::ignore('TestOfLeftOverErrors'); 202 | /** 203 | * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} 204 | * to verify that it fails as expected. 205 | * 206 | * @ignore 207 | */ 208 | class TestOfLeftOverErrors extends UnitTestCase { 209 | function testExpectOneErrorGetTwo() { 210 | $this->expectError('Error 1'); 211 | trigger_error('Error 1'); 212 | trigger_error('Error 2'); 213 | } 214 | } 215 | 216 | class TestRunnerForLeftOverAndNotEnoughErrors extends UnitTestCase { 217 | function testRunLeftOverErrorsTestCase() { 218 | $test = new TestOfLeftOverErrors(); 219 | $this->assertFalse($test->run(new SimpleReporter())); 220 | } 221 | 222 | function testRunNotEnoughErrors() { 223 | $test = new TestOfNotEnoughErrors(); 224 | $this->assertFalse($test->run(new SimpleReporter())); 225 | } 226 | } 227 | 228 | // TODO: Add stacked error handler test 229 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/exceptions_test.php: -------------------------------------------------------------------------------- 1 | assertTrue($expectation->test(new MyTestException())); 19 | $this->assertTrue($expectation->test(new HigherTestException())); 20 | $this->assertFalse($expectation->test(new OtherTestException())); 21 | } 22 | 23 | function testMatchesClassAndMessageWhenExceptionExpected() { 24 | $expectation = new ExceptionExpectation(new MyTestException('Hello')); 25 | $this->assertTrue($expectation->test(new MyTestException('Hello'))); 26 | $this->assertFalse($expectation->test(new HigherTestException('Hello'))); 27 | $this->assertFalse($expectation->test(new OtherTestException('Hello'))); 28 | $this->assertFalse($expectation->test(new MyTestException('Goodbye'))); 29 | $this->assertFalse($expectation->test(new MyTestException())); 30 | } 31 | 32 | function testMessagelessExceptionMatchesOnlyOnClass() { 33 | $expectation = new ExceptionExpectation(new MyTestException()); 34 | $this->assertTrue($expectation->test(new MyTestException())); 35 | $this->assertFalse($expectation->test(new HigherTestException())); 36 | } 37 | } 38 | 39 | class TestOfExceptionTrap extends UnitTestCase { 40 | 41 | function testNoExceptionsInQueueMeansNoTestMessages() { 42 | $test = new MockSimpleTestCase(); 43 | $test->expectNever('assert'); 44 | $queue = new SimpleExceptionTrap(); 45 | $this->assertFalse($queue->isExpected($test, new Exception())); 46 | } 47 | 48 | function testMatchingExceptionGivesTrue() { 49 | $expectation = new MockSimpleExpectation(); 50 | $expectation->setReturnValue('test', true); 51 | $test = new MockSimpleTestCase(); 52 | $test->setReturnValue('assert', true); 53 | $queue = new SimpleExceptionTrap(); 54 | $queue->expectException($expectation, 'message'); 55 | $this->assertTrue($queue->isExpected($test, new Exception())); 56 | } 57 | 58 | function testMatchingExceptionTriggersAssertion() { 59 | $test = new MockSimpleTestCase(); 60 | $test->expectOnce('assert', array( 61 | '*', 62 | new ExceptionExpectation(new Exception()), 63 | 'message')); 64 | $queue = new SimpleExceptionTrap(); 65 | $queue->expectException(new ExceptionExpectation(new Exception()), 'message'); 66 | $queue->isExpected($test, new Exception()); 67 | } 68 | } 69 | 70 | class TestOfCatchingExceptions extends UnitTestCase { 71 | 72 | function testCanCatchAnyExpectedException() { 73 | $this->expectException(); 74 | throw new Exception(); 75 | } 76 | 77 | function testCanMatchExceptionByClass() { 78 | $this->expectException('MyTestException'); 79 | throw new HigherTestException(); 80 | } 81 | 82 | function testCanMatchExceptionExactly() { 83 | $this->expectException(new Exception('Ouch')); 84 | throw new Exception('Ouch'); 85 | } 86 | 87 | function testLastListedExceptionIsTheOneThatCounts() { 88 | $this->expectException('OtherTestException'); 89 | $this->expectException('MyTestException'); 90 | throw new HigherTestException(); 91 | } 92 | } 93 | 94 | class TestOfIgnoringExceptions extends UnitTestCase { 95 | 96 | function testCanIgnoreAnyException() { 97 | $this->ignoreException(); 98 | throw new Exception(); 99 | } 100 | 101 | function testCanIgnoreSpecificException() { 102 | $this->ignoreException('MyTestException'); 103 | throw new MyTestException(); 104 | } 105 | 106 | function testCanIgnoreExceptionExactly() { 107 | $this->ignoreException(new Exception('Ouch')); 108 | throw new Exception('Ouch'); 109 | } 110 | 111 | function testIgnoredExceptionsDoNotMaskExpectedExceptions() { 112 | $this->ignoreException('Exception'); 113 | $this->expectException('MyTestException'); 114 | throw new MyTestException(); 115 | } 116 | 117 | function testCanIgnoreMultipleExceptions() { 118 | $this->ignoreException('MyTestException'); 119 | $this->ignoreException('OtherTestException'); 120 | throw new OtherTestException(); 121 | } 122 | } 123 | 124 | class TestOfCallingTearDownAfterExceptions extends UnitTestCase { 125 | private $debri = 0; 126 | 127 | function tearDown() { 128 | $this->debri--; 129 | } 130 | 131 | function testLeaveSomeDebri() { 132 | $this->debri++; 133 | $this->expectException(); 134 | throw new Exception(__FUNCTION__); 135 | } 136 | 137 | function testDebriWasRemovedOnce() { 138 | $this->assertEqual($this->debri, 0); 139 | } 140 | } 141 | 142 | class TestOfExceptionThrownInSetUpDoesNotRunTestBody extends UnitTestCase { 143 | 144 | function setUp() { 145 | $this->expectException(); 146 | throw new Exception(); 147 | } 148 | 149 | function testShouldNotBeRun() { 150 | $this->fail('This test body should not be run'); 151 | } 152 | 153 | function testShouldNotBeRunEither() { 154 | $this->fail('This test body should not be run either'); 155 | } 156 | } 157 | 158 | class TestOfExpectExceptionWithSetUp extends UnitTestCase { 159 | 160 | function setUp() { 161 | $this->expectException(); 162 | } 163 | 164 | function testThisExceptionShouldBeCaught() { 165 | throw new Exception(); 166 | } 167 | 168 | function testJustThrowingMyTestException() { 169 | throw new MyTestException(); 170 | } 171 | } 172 | 173 | class TestOfThrowingExceptionsInTearDown extends UnitTestCase { 174 | 175 | function tearDown() { 176 | throw new Exception(); 177 | } 178 | 179 | function testDoesntFatal() { 180 | $this->expectException(); 181 | } 182 | } 183 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/interfaces_test.php: -------------------------------------------------------------------------------- 1 | =')) { 8 | include(dirname(__FILE__) . '/interfaces_test_php5_1.php'); 9 | } 10 | 11 | interface DummyInterface { 12 | function aMethod(); 13 | function anotherMethod($a); 14 | function &referenceMethod(&$a); 15 | } 16 | 17 | Mock::generate('DummyInterface'); 18 | Mock::generatePartial('DummyInterface', 'PartialDummyInterface', array()); 19 | 20 | class TestOfMockInterfaces extends UnitTestCase { 21 | 22 | function testCanMockAnInterface() { 23 | $mock = new MockDummyInterface(); 24 | $this->assertIsA($mock, 'SimpleMock'); 25 | $this->assertIsA($mock, 'MockDummyInterface'); 26 | $this->assertTrue(method_exists($mock, 'aMethod')); 27 | $this->assertTrue(method_exists($mock, 'anotherMethod')); 28 | $this->assertNull($mock->aMethod()); 29 | } 30 | 31 | function testMockedInterfaceExpectsParameters() { 32 | $mock = new MockDummyInterface(); 33 | $this->expectError(); 34 | $mock->anotherMethod(); 35 | } 36 | 37 | function testCannotPartiallyMockAnInterface() { 38 | $this->assertFalse(class_exists('PartialDummyInterface')); 39 | } 40 | } 41 | 42 | class TestOfSpl extends UnitTestCase { 43 | 44 | function skip() { 45 | $this->skipUnless(function_exists('spl_classes'), 'No SPL module loaded'); 46 | } 47 | 48 | function testCanMockAllSplClasses() { 49 | if (! function_exists('spl_classes')) { 50 | return; 51 | } 52 | foreach(spl_classes() as $class) { 53 | if ($class == 'SplHeap' or $class = 'SplFileObject') { 54 | continue; 55 | } 56 | if (version_compare(PHP_VERSION, '5.1', '<') && 57 | $class == 'CachingIterator' || 58 | $class == 'CachingRecursiveIterator' || 59 | $class == 'FilterIterator' || 60 | $class == 'LimitIterator' || 61 | $class == 'ParentIterator') { 62 | // These iterators require an iterator be passed to them during 63 | // construction in PHP 5.0; there is no way for SimpleTest 64 | // to supply such an iterator, however, so support for it is 65 | // disabled. 66 | continue; 67 | } 68 | $mock_class = "Mock$class"; 69 | Mock::generate($class); 70 | $this->assertIsA(new $mock_class(), $mock_class); 71 | } 72 | } 73 | 74 | function testExtensionOfCommonSplClasses() { 75 | Mock::generate('IteratorImplementation'); 76 | $this->assertIsA( 77 | new IteratorImplementation(), 78 | 'IteratorImplementation'); 79 | Mock::generate('IteratorAggregateImplementation'); 80 | $this->assertIsA( 81 | new IteratorAggregateImplementation(), 82 | 'IteratorAggregateImplementation'); 83 | } 84 | } 85 | 86 | class WithHint { 87 | function hinted(DummyInterface $object) { } 88 | } 89 | 90 | class ImplementsDummy implements DummyInterface { 91 | function aMethod() { } 92 | function anotherMethod($a) { } 93 | function &referenceMethod(&$a) { } 94 | function extraMethod($a = false) { } 95 | } 96 | Mock::generate('ImplementsDummy'); 97 | 98 | class TestOfImplementations extends UnitTestCase { 99 | 100 | function testMockedInterfaceCanPassThroughTypeHint() { 101 | $mock = new MockDummyInterface(); 102 | $hinter = new WithHint(); 103 | $hinter->hinted($mock); 104 | } 105 | 106 | function testImplementedInterfacesAreCarried() { 107 | $mock = new MockImplementsDummy(); 108 | $hinter = new WithHint(); 109 | $hinter->hinted($mock); 110 | } 111 | 112 | function testNoSpuriousWarningsWhenSkippingDefaultedParameter() { 113 | $mock = new MockImplementsDummy(); 114 | $mock->extraMethod(); 115 | } 116 | } 117 | 118 | interface SampleInterfaceWithConstruct { 119 | function __construct($something); 120 | } 121 | 122 | class TestOfInterfaceMocksWithConstruct extends UnitTestCase { 123 | function TODO_testBasicConstructOfAnInterface() { // Fails in PHP 5.3dev 124 | Mock::generate('SampleInterfaceWithConstruct'); 125 | } 126 | } 127 | 128 | interface SampleInterfaceWithClone { 129 | function __clone(); 130 | } 131 | 132 | class TestOfSampleInterfaceWithClone extends UnitTestCase { 133 | function testCanMockWithoutErrors() { 134 | Mock::generate('SampleInterfaceWithClone'); 135 | } 136 | } 137 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/interfaces_test_php5_1.php: -------------------------------------------------------------------------------- 1 | assertIsA($mock, 'SampleInterfaceWithHintInSignature'); 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /tests/simpletest/test/live_test.php: -------------------------------------------------------------------------------- 1 | assertTrue($socket->isError()); 17 | $this->assertPattern( 18 | '/Cannot open \\[bad_url:111\\] with \\[/', 19 | $socket->getError()); 20 | $this->assertFalse($socket->isOpen()); 21 | $this->assertFalse($socket->write('A message')); 22 | } 23 | 24 | function testSocketClosure() { 25 | $socket = new SimpleSocket('www.lastcraft.com', 80, 15, 8); 26 | $this->assertTrue($socket->isOpen()); 27 | $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); 28 | $socket->write("Host: www.lastcraft.com\r\n"); 29 | $socket->write("Connection: close\r\n\r\n"); 30 | $this->assertEqual($socket->read(), "HTTP/1.1"); 31 | $socket->close(); 32 | $this->assertIdentical($socket->read(), false); 33 | } 34 | 35 | function testRecordOfSentCharacters() { 36 | $socket = new SimpleSocket('www.lastcraft.com', 80, 15); 37 | $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); 38 | $socket->write("Host: www.lastcraft.com\r\n"); 39 | $socket->write("Connection: close\r\n\r\n"); 40 | $socket->close(); 41 | $this->assertEqual($socket->getSent(), 42 | "GET /test/network_confirm.php HTTP/1.0\r\n" . 43 | "Host: www.lastcraft.com\r\n" . 44 | "Connection: close\r\n\r\n"); 45 | } 46 | } 47 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/page_test.php: -------------------------------------------------------------------------------- 1 | assertEqual($page->getTransportError(), 'No page fetched yet'); 14 | $this->assertIdentical($page->getRaw(), false); 15 | $this->assertIdentical($page->getHeaders(), false); 16 | $this->assertIdentical($page->getMimeType(), false); 17 | $this->assertIdentical($page->getResponseCode(), false); 18 | $this->assertIdentical($page->getAuthentication(), false); 19 | $this->assertIdentical($page->getRealm(), false); 20 | $this->assertFalse($page->hasFrames()); 21 | $this->assertIdentical($page->getUrls(), array()); 22 | $this->assertIdentical($page->getTitle(), false); 23 | } 24 | } 25 | 26 | class TestOfPageHeaders extends UnitTestCase { 27 | 28 | function testUrlAccessor() { 29 | $headers = new MockSimpleHttpHeaders(); 30 | 31 | $response = new MockSimpleHttpResponse(); 32 | $response->setReturnValue('getHeaders', $headers); 33 | $response->setReturnValue('getMethod', 'POST'); 34 | $response->setReturnValue('getUrl', new SimpleUrl('here')); 35 | $response->setReturnValue('getRequestData', array('a' => 'A')); 36 | 37 | $page = new SimplePage($response); 38 | $this->assertEqual($page->getMethod(), 'POST'); 39 | $this->assertEqual($page->getUrl(), new SimpleUrl('here')); 40 | $this->assertEqual($page->getRequestData(), array('a' => 'A')); 41 | } 42 | 43 | function testTransportError() { 44 | $response = new MockSimpleHttpResponse(); 45 | $response->setReturnValue('getError', 'Ouch'); 46 | 47 | $page = new SimplePage($response); 48 | $this->assertEqual($page->getTransportError(), 'Ouch'); 49 | } 50 | 51 | function testHeadersAccessor() { 52 | $headers = new MockSimpleHttpHeaders(); 53 | $headers->setReturnValue('getRaw', 'My: Headers'); 54 | 55 | $response = new MockSimpleHttpResponse(); 56 | $response->setReturnValue('getHeaders', $headers); 57 | 58 | $page = new SimplePage($response); 59 | $this->assertEqual($page->getHeaders(), 'My: Headers'); 60 | } 61 | 62 | function testMimeAccessor() { 63 | $headers = new MockSimpleHttpHeaders(); 64 | $headers->setReturnValue('getMimeType', 'text/html'); 65 | 66 | $response = new MockSimpleHttpResponse(); 67 | $response->setReturnValue('getHeaders', $headers); 68 | 69 | $page = new SimplePage($response); 70 | $this->assertEqual($page->getMimeType(), 'text/html'); 71 | } 72 | 73 | function testResponseAccessor() { 74 | $headers = new MockSimpleHttpHeaders(); 75 | $headers->setReturnValue('getResponseCode', 301); 76 | 77 | $response = new MockSimpleHttpResponse(); 78 | $response->setReturnValue('getHeaders', $headers); 79 | 80 | $page = new SimplePage($response); 81 | $this->assertIdentical($page->getResponseCode(), 301); 82 | } 83 | 84 | function testAuthenticationAccessors() { 85 | $headers = new MockSimpleHttpHeaders(); 86 | $headers->setReturnValue('getAuthentication', 'Basic'); 87 | $headers->setReturnValue('getRealm', 'Secret stuff'); 88 | 89 | $response = new MockSimpleHttpResponse(); 90 | $response->setReturnValue('getHeaders', $headers); 91 | 92 | $page = new SimplePage($response); 93 | $this->assertEqual($page->getAuthentication(), 'Basic'); 94 | $this->assertEqual($page->getRealm(), 'Secret stuff'); 95 | } 96 | } 97 | 98 | class TestOfHtmlStrippingAndNormalisation extends UnitTestCase { 99 | 100 | function testImageSuppressionWhileKeepingParagraphsAndAltText() { 101 | $this->assertEqual( 102 | SimplePage::normalise('

some text

bar'), 103 | 'some text bar'); 104 | } 105 | 106 | function testSpaceNormalisation() { 107 | $this->assertEqual( 108 | SimplePage::normalise("\nOne\tTwo \nThree\t"), 109 | 'One Two Three'); 110 | } 111 | 112 | function testMultilinesCommentSuppression() { 113 | $this->assertEqual( 114 | SimplePage::normalise(''), 115 | ''); 116 | } 117 | 118 | function testCommentSuppression() { 119 | $this->assertEqual( 120 | SimplePage::normalise(''), 121 | ''); 122 | } 123 | 124 | function testJavascriptSuppression() { 125 | $this->assertEqual( 126 | SimplePage::normalise(''), 127 | ''); 128 | $this->assertEqual( 129 | SimplePage::normalise(''), 130 | ''); 131 | $this->assertEqual( 132 | SimplePage::normalise(''), 133 | ''); 134 | } 135 | 136 | function testTagSuppression() { 137 | $this->assertEqual( 138 | SimplePage::normalise('Hello'), 139 | 'Hello'); 140 | } 141 | 142 | function testAdjoiningTagSuppression() { 143 | $this->assertEqual( 144 | SimplePage::normalise('HelloGoodbye'), 145 | 'HelloGoodbye'); 146 | } 147 | 148 | function testExtractImageAltTextWithDifferentQuotes() { 149 | $this->assertEqual( 150 | SimplePage::normalise('One\'Two\'Three'), 151 | 'One Two Three'); 152 | } 153 | 154 | function testExtractImageAltTextMultipleTimes() { 155 | $this->assertEqual( 156 | SimplePage::normalise('OneTwoThree'), 157 | 'One Two Three'); 158 | } 159 | 160 | function testHtmlEntityTranslation() { 161 | $this->assertEqual( 162 | SimplePage::normalise('<>"&''), 163 | '<>"&\''); 164 | } 165 | } 166 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/parse_error_test.php: -------------------------------------------------------------------------------- 1 | addFile('test_with_parse_error.php'); 8 | $test->run(new HtmlReporter()); 9 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/php_parser_test.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philios33/PHP-AES-File-Encryption/e8f5901afcd51bfc19aa4a40bd50ef7f5ab6f627/tests/simpletest/test/php_parser_test.php -------------------------------------------------------------------------------- /tests/simpletest/test/recorder_test.php: -------------------------------------------------------------------------------- 1 | addFile(dirname(__FILE__) . '/support/recorder_sample.php'); 11 | $recorder = new Recorder(new SimpleReporter()); 12 | $test->run($recorder); 13 | $this->assertEqual(count($recorder->results), 2); 14 | $this->assertIsA($recorder->results[0], 'SimpleResultOfPass'); 15 | $this->assertEqual('testTrueIsTrue', array_pop($recorder->results[0]->breadcrumb)); 16 | $this->assertPattern('/ at \[.*\Wrecorder_sample\.php line 7\]/', $recorder->results[0]->message); 17 | $this->assertIsA($recorder->results[1], 'SimpleResultOfFail'); 18 | $this->assertEqual('testFalseIsTrue', array_pop($recorder->results[1]->breadcrumb)); 19 | $this->assertPattern("/Expected false, got \[Boolean: true\] at \[.*\Wrecorder_sample\.php line 11\]/", 20 | $recorder->results[1]->message); 21 | } 22 | } 23 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/reflection_php5_test.php: -------------------------------------------------------------------------------- 1 | assertTrue($reflection->classOrInterfaceExists()); 80 | $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); 81 | $this->assertFalse($reflection->isAbstract()); 82 | $this->assertFalse($reflection->isInterface()); 83 | } 84 | 85 | function testClassNonExistence() { 86 | $reflection = new SimpleReflection('UnknownThing'); 87 | $this->assertFalse($reflection->classOrInterfaceExists()); 88 | $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); 89 | } 90 | 91 | function testDetectionOfAbstractClass() { 92 | $reflection = new SimpleReflection('AnyOldClass'); 93 | $this->assertTrue($reflection->isAbstract()); 94 | } 95 | 96 | function testDetectionOfFinalMethods() { 97 | $reflection = new SimpleReflection('AnyOldClass'); 98 | $this->assertFalse($reflection->hasFinal()); 99 | $reflection = new SimpleReflection('AnyOldLeafClassWithAFinal'); 100 | $this->assertTrue($reflection->hasFinal()); 101 | } 102 | 103 | function testFindingParentClass() { 104 | $reflection = new SimpleReflection('AnyOldSubclass'); 105 | $this->assertEqual($reflection->getParent(), 'AnyOldImplementation'); 106 | } 107 | 108 | function testInterfaceExistence() { 109 | $reflection = new SimpleReflection('AnyOldInterface'); 110 | $this->assertTrue($reflection->classOrInterfaceExists()); 111 | $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); 112 | $this->assertTrue($reflection->isInterface()); 113 | } 114 | 115 | function testMethodsListFromClass() { 116 | $reflection = new SimpleReflection('AnyOldClass'); 117 | $this->assertIdentical($reflection->getMethods(), array('aMethod')); 118 | } 119 | 120 | function testMethodsListFromInterface() { 121 | $reflection = new SimpleReflection('AnyOldInterface'); 122 | $this->assertIdentical($reflection->getMethods(), array('aMethod')); 123 | $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); 124 | } 125 | 126 | function testMethodsComeFromDescendentInterfacesASWell() { 127 | $reflection = new SimpleReflection('AnyDescendentInterface'); 128 | $this->assertIdentical($reflection->getMethods(), array('aMethod')); 129 | } 130 | 131 | function testCanSeparateInterfaceMethodsFromOthers() { 132 | $reflection = new SimpleReflection('AnyOldImplementation'); 133 | $this->assertIdentical($reflection->getMethods(), array('aMethod', 'extraMethod')); 134 | $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); 135 | } 136 | 137 | function testMethodsComeFromDescendentInterfacesInAbstractClass() { 138 | $reflection = new SimpleReflection('AnyAbstractImplementation'); 139 | $this->assertIdentical($reflection->getMethods(), array('aMethod')); 140 | } 141 | 142 | function testInterfaceHasOnlyItselfToImplement() { 143 | $reflection = new SimpleReflection('AnyOldInterface'); 144 | $this->assertEqual( 145 | $reflection->getInterfaces(), 146 | array('AnyOldInterface')); 147 | } 148 | 149 | function testInterfacesListedForClass() { 150 | $reflection = new SimpleReflection('AnyOldImplementation'); 151 | $this->assertEqual( 152 | $reflection->getInterfaces(), 153 | array('AnyOldInterface')); 154 | } 155 | 156 | function testInterfacesListedForSubclass() { 157 | $reflection = new SimpleReflection('AnyOldSubclass'); 158 | $this->assertEqual( 159 | $reflection->getInterfaces(), 160 | array('AnyOldInterface')); 161 | } 162 | 163 | function testNoParameterCreationWhenNoInterface() { 164 | $reflection = new SimpleReflection('AnyOldArgumentClass'); 165 | $function = $reflection->getSignature('aMethod'); 166 | if (version_compare(phpversion(), '5.0.2', '<=')) { 167 | $this->assertEqual('function amethod($argument)', strtolower($function)); 168 | } else { 169 | $this->assertEqual('function aMethod($argument)', $function); 170 | } 171 | } 172 | 173 | function testParameterCreationWithoutTypeHinting() { 174 | $reflection = new SimpleReflection('AnyOldArgumentImplementation'); 175 | $function = $reflection->getSignature('aMethod'); 176 | if (version_compare(phpversion(), '5.0.2', '<=')) { 177 | $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); 178 | } else { 179 | $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); 180 | } 181 | } 182 | 183 | function testParameterCreationForTypeHinting() { 184 | $reflection = new SimpleReflection('AnyOldTypeHintedClass'); 185 | $function = $reflection->getSignature('aMethod'); 186 | if (version_compare(phpversion(), '5.0.2', '<=')) { 187 | $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); 188 | } else { 189 | $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); 190 | } 191 | } 192 | 193 | function testIssetFunctionSignature() { 194 | $reflection = new SimpleReflection('AnyOldOverloadedClass'); 195 | $function = $reflection->getSignature('__isset'); 196 | $this->assertEqual('function __isset($key)', $function); 197 | } 198 | 199 | function testUnsetFunctionSignature() { 200 | $reflection = new SimpleReflection('AnyOldOverloadedClass'); 201 | $function = $reflection->getSignature('__unset'); 202 | $this->assertEqual('function __unset($key)', $function); 203 | } 204 | 205 | function testProperlyReflectsTheFinalInterfaceWhenObjectImplementsAnExtendedInterface() { 206 | $reflection = new SimpleReflection('AnyDescendentImplementation'); 207 | $interfaces = $reflection->getInterfaces(); 208 | $this->assertEqual(1, count($interfaces)); 209 | $this->assertEqual('AnyDescendentInterface', array_shift($interfaces)); 210 | } 211 | 212 | function testCreatingSignatureForAbstractMethod() { 213 | $reflection = new SimpleReflection('AnotherOldAbstractClass'); 214 | $this->assertEqual($reflection->getSignature('aMethod'), 'function aMethod(AnyOldInterface $argument)'); 215 | } 216 | 217 | function testCanProperlyGenerateStaticMethodSignatures() { 218 | $reflection = new SimpleReflection('AnyOldClassWithStaticMethods'); 219 | $this->assertEqual('static function aStatic()', $reflection->getSignature('aStatic')); 220 | $this->assertEqual( 221 | 'static function aStaticWithParameters($arg1, $arg2)', 222 | $reflection->getSignature('aStaticWithParameters') 223 | ); 224 | } 225 | } 226 | 227 | class TestOfReflectionWithTypeHints extends UnitTestCase { 228 | function skip() { 229 | $this->skipIf(version_compare(phpversion(), '5.1.0', '<'), 'Reflection with type hints only tested for PHP 5.1.0 and above'); 230 | } 231 | 232 | function testParameterCreationForTypeHintingWithArray() { 233 | eval('interface AnyOldArrayTypeHintedInterface { 234 | function amethod(array $argument); 235 | } 236 | class AnyOldArrayTypeHintedClass implements AnyOldArrayTypeHintedInterface { 237 | function amethod(array $argument) {} 238 | }'); 239 | $reflection = new SimpleReflection('AnyOldArrayTypeHintedClass'); 240 | $function = $reflection->getSignature('amethod'); 241 | $this->assertEqual('function amethod(array $argument)', $function); 242 | } 243 | } 244 | 245 | class TestOfAbstractsWithAbstractMethods extends UnitTestCase { 246 | function testCanProperlyGenerateAbstractMethods() { 247 | $reflection = new SimpleReflection('AnyOldAbstractClassWithAbstractMethods'); 248 | $this->assertEqual( 249 | 'function anAbstract()', 250 | $reflection->getSignature('anAbstract') 251 | ); 252 | $this->assertEqual( 253 | 'function anAbstractWithParameter($foo)', 254 | $reflection->getSignature('anAbstractWithParameter') 255 | ); 256 | $this->assertEqual( 257 | 'function anAbstractWithMultipleParameters($foo, $bar)', 258 | $reflection->getSignature('anAbstractWithMultipleParameters') 259 | ); 260 | } 261 | } 262 | 263 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/remote_test.php: -------------------------------------------------------------------------------- 1 | add(new RemoteTestCase($test_url . '?xml=yes', $test_url . '?xml=yes&dry=yes')); 16 | if (SimpleReporter::inCli()) { 17 | exit ($test->run(new TextReporter()) ? 0 : 1); 18 | } 19 | $test->run(new HtmlReporter()); 20 | -------------------------------------------------------------------------------- /tests/simpletest/test/shell_test.php: -------------------------------------------------------------------------------- 1 | assertIdentical($shell->execute('echo Hello'), 0); 11 | $this->assertPattern('/Hello/', $shell->getOutput()); 12 | } 13 | 14 | function testBadCommand() { 15 | $shell = new SimpleShell(); 16 | $this->assertNotEqual($ret = $shell->execute('blurgh! 2>&1'), 0); 17 | } 18 | } 19 | 20 | class TestOfShellTesterAndShell extends ShellTestCase { 21 | 22 | function testEcho() { 23 | $this->assertTrue($this->execute('echo Hello')); 24 | $this->assertExitCode(0); 25 | $this->assertoutput('Hello'); 26 | } 27 | 28 | function testFileExistence() { 29 | $this->assertFileExists(dirname(__FILE__) . '/all_tests.php'); 30 | $this->assertFileNotExists('wibble'); 31 | } 32 | 33 | function testFilePatterns() { 34 | $this->assertFilePattern('/all[_ ]tests/i', dirname(__FILE__) . '/all_tests.php'); 35 | $this->assertNoFilePattern('/sputnik/i', dirname(__FILE__) . '/all_tests.php'); 36 | } 37 | } 38 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/shell_tester_test.php: -------------------------------------------------------------------------------- 1 | mock_shell; 12 | } 13 | 14 | function testGenericEquality() { 15 | $this->assertEqual('a', 'a'); 16 | $this->assertNotEqual('a', 'A'); 17 | } 18 | 19 | function testExitCode() { 20 | $this->mock_shell = new MockSimpleShell(); 21 | $this->mock_shell->setReturnValue('execute', 0); 22 | $this->mock_shell->expectOnce('execute', array('ls')); 23 | $this->assertTrue($this->execute('ls')); 24 | $this->assertExitCode(0); 25 | } 26 | 27 | function testOutput() { 28 | $this->mock_shell = new MockSimpleShell(); 29 | $this->mock_shell->setReturnValue('execute', 0); 30 | $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); 31 | $this->assertOutput("Line 1\nLine 2\n"); 32 | } 33 | 34 | function testOutputPatterns() { 35 | $this->mock_shell = new MockSimpleShell(); 36 | $this->mock_shell->setReturnValue('execute', 0); 37 | $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); 38 | $this->assertOutputPattern('/line/i'); 39 | $this->assertNoOutputPattern('/line 2/'); 40 | } 41 | } 42 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/simpletest_test.php: -------------------------------------------------------------------------------- 1 | fail('Should be ignored'); 11 | } 12 | } 13 | 14 | class ShouldNeverBeRunEither extends ShouldNeverBeRun { } 15 | 16 | class TestOfStackTrace extends UnitTestCase { 17 | 18 | function testCanFindAssertInTrace() { 19 | $trace = new SimpleStackTrace(array('assert')); 20 | $this->assertEqual( 21 | $trace->traceMethod(array(array( 22 | 'file' => '/my_test.php', 23 | 'line' => 24, 24 | 'function' => 'assertSomething'))), 25 | ' at [/my_test.php line 24]'); 26 | } 27 | } 28 | 29 | class DummyResource { } 30 | 31 | class TestOfContext extends UnitTestCase { 32 | 33 | function testCurrentContextIsUnique() { 34 | $this->assertSame( 35 | SimpleTest::getContext(), 36 | SimpleTest::getContext()); 37 | } 38 | 39 | function testContextHoldsCurrentTestCase() { 40 | $context = SimpleTest::getContext(); 41 | $this->assertSame($this, $context->getTest()); 42 | } 43 | 44 | function testResourceIsSingleInstanceWithContext() { 45 | $context = new SimpleTestContext(); 46 | $this->assertSame( 47 | $context->get('DummyResource'), 48 | $context->get('DummyResource')); 49 | } 50 | 51 | function testClearingContextResetsResources() { 52 | $context = new SimpleTestContext(); 53 | $resource = $context->get('DummyResource'); 54 | $context->clear(); 55 | $this->assertClone($resource, $context->get('DummyResource')); 56 | } 57 | } 58 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/site/file.html: -------------------------------------------------------------------------------- 1 | 2 | Link to SimpleTest 3 | 4 |
Link to SimpleTest 5 | 6 | -------------------------------------------------------------------------------- /tests/simpletest/test/socket_test.php: -------------------------------------------------------------------------------- 1 | assertFalse($error->isError()); 12 | $error->setError('Ouch'); 13 | $this->assertTrue($error->isError()); 14 | $this->assertEqual($error->getError(), 'Ouch'); 15 | } 16 | 17 | function testClearingError() { 18 | $error = new SimpleStickyError(); 19 | $error->setError('Ouch'); 20 | $this->assertTrue($error->isError()); 21 | $error->clearError(); 22 | $this->assertFalse($error->isError()); 23 | } 24 | } 25 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/support/collector/collectable.1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philios33/PHP-AES-File-Encryption/e8f5901afcd51bfc19aa4a40bd50ef7f5ab6f627/tests/simpletest/test/support/collector/collectable.1 -------------------------------------------------------------------------------- /tests/simpletest/test/support/collector/collectable.2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philios33/PHP-AES-File-Encryption/e8f5901afcd51bfc19aa4a40bd50ef7f5ab6f627/tests/simpletest/test/support/collector/collectable.2 -------------------------------------------------------------------------------- /tests/simpletest/test/support/empty_test_file.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/simpletest/test/support/failing_test.php: -------------------------------------------------------------------------------- 1 | assertEqual(1,2); 7 | } 8 | } 9 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/support/latin1_sample: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philios33/PHP-AES-File-Encryption/e8f5901afcd51bfc19aa4a40bd50ef7f5ab6f627/tests/simpletest/test/support/latin1_sample -------------------------------------------------------------------------------- /tests/simpletest/test/support/passing_test.php: -------------------------------------------------------------------------------- 1 | assertEqual(2,2); 7 | } 8 | } 9 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/support/recorder_sample.php: -------------------------------------------------------------------------------- 1 | assertTrue(true); 8 | } 9 | 10 | function testFalseIsTrue() { 11 | $this->assertFalse(true); 12 | } 13 | } 14 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/support/spl_examples.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/simpletest/test/support/supplementary_upload_sample.txt: -------------------------------------------------------------------------------- 1 | Some more text content -------------------------------------------------------------------------------- /tests/simpletest/test/support/test1.php: -------------------------------------------------------------------------------- 1 | assertEqual(3,1+2, "pass1"); 5 | } 6 | } 7 | ?> 8 | -------------------------------------------------------------------------------- /tests/simpletest/test/support/upload_sample.txt: -------------------------------------------------------------------------------- 1 | Sample for testing file upload -------------------------------------------------------------------------------- /tests/simpletest/test/test_with_parse_error.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/simpletest/test/unit_tester_test.php: -------------------------------------------------------------------------------- 1 | assertTrue($this->assertTrue(true)); 12 | } 13 | 14 | function testAssertFalseReturnsAssertionAsBoolean() { 15 | $this->assertTrue($this->assertFalse(false)); 16 | } 17 | 18 | function testAssertEqualReturnsAssertionAsBoolean() { 19 | $this->assertTrue($this->assertEqual(5, 5)); 20 | } 21 | 22 | function testAssertIdenticalReturnsAssertionAsBoolean() { 23 | $this->assertTrue($this->assertIdentical(5, 5)); 24 | } 25 | 26 | function testCoreAssertionsDoNotThrowErrors() { 27 | $this->assertIsA($this, 'UnitTestCase'); 28 | $this->assertNotA($this, 'WebTestCase'); 29 | } 30 | 31 | function testReferenceAssertionOnObjects() { 32 | $a = new ReferenceForTesting(); 33 | $b = $a; 34 | $this->assertSame($a, $b); 35 | } 36 | 37 | function testReferenceAssertionOnScalars() { 38 | $a = 25; 39 | $b = &$a; 40 | $this->assertReference($a, $b); 41 | } 42 | 43 | function testCloneOnObjects() { 44 | $a = new ReferenceForTesting(); 45 | $b = new ReferenceForTesting(); 46 | $this->assertClone($a, $b); 47 | } 48 | 49 | function TODO_testCloneOnScalars() { 50 | $a = 25; 51 | $b = 25; 52 | $this->assertClone($a, $b); 53 | } 54 | 55 | function testCopyOnScalars() { 56 | $a = 25; 57 | $b = 25; 58 | $this->assertCopy($a, $b); 59 | } 60 | } 61 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/unit_tests.php: -------------------------------------------------------------------------------- 1 | TestSuite('Unit tests'); 13 | $path = dirname(__FILE__); 14 | $this->addFile($path . '/errors_test.php'); 15 | $this->addFile($path . '/exceptions_test.php'); 16 | $this->addFile($path . '/arguments_test.php'); 17 | $this->addFile($path . '/autorun_test.php'); 18 | $this->addFile($path . '/compatibility_test.php'); 19 | $this->addFile($path . '/simpletest_test.php'); 20 | $this->addFile($path . '/dumper_test.php'); 21 | $this->addFile($path . '/expectation_test.php'); 22 | $this->addFile($path . '/unit_tester_test.php'); 23 | $this->addFile($path . '/reflection_php5_test.php'); 24 | $this->addFile($path . '/mock_objects_test.php'); 25 | $this->addFile($path . '/interfaces_test.php'); 26 | $this->addFile($path . '/collector_test.php'); 27 | $this->addFile($path . '/recorder_test.php'); 28 | $this->addFile($path . '/adapter_test.php'); 29 | $this->addFile($path . '/socket_test.php'); 30 | $this->addFile($path . '/encoding_test.php'); 31 | $this->addFile($path . '/url_test.php'); 32 | $this->addFile($path . '/cookies_test.php'); 33 | $this->addFile($path . '/http_test.php'); 34 | $this->addFile($path . '/authentication_test.php'); 35 | $this->addFile($path . '/user_agent_test.php'); 36 | $this->addFile($path . '/php_parser_test.php'); 37 | $this->addFile($path . '/parsing_test.php'); 38 | $this->addFile($path . '/tag_test.php'); 39 | $this->addFile($path . '/form_test.php'); 40 | $this->addFile($path . '/page_test.php'); 41 | $this->addFile($path . '/frames_test.php'); 42 | $this->addFile($path . '/browser_test.php'); 43 | $this->addFile($path . '/web_tester_test.php'); 44 | $this->addFile($path . '/shell_tester_test.php'); 45 | $this->addFile($path . '/xml_test.php'); 46 | $this->addFile($path . '/../extensions/testdox/test.php'); 47 | } 48 | } 49 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/web_tester_test.php: -------------------------------------------------------------------------------- 1 | assertTrue($expectation->test('a')); 11 | $this->assertTrue($expectation->test(array('a'))); 12 | $this->assertFalse($expectation->test('A')); 13 | } 14 | 15 | function testMatchesInteger() { 16 | $expectation = new FieldExpectation('1'); 17 | $this->assertTrue($expectation->test('1')); 18 | $this->assertTrue($expectation->test(1)); 19 | $this->assertTrue($expectation->test(array('1'))); 20 | $this->assertTrue($expectation->test(array(1))); 21 | } 22 | 23 | function testNonStringFailsExpectation() { 24 | $expectation = new FieldExpectation('a'); 25 | $this->assertFalse($expectation->test(null)); 26 | } 27 | 28 | function testUnsetFieldCanBeTestedFor() { 29 | $expectation = new FieldExpectation(false); 30 | $this->assertTrue($expectation->test(false)); 31 | } 32 | 33 | function testMultipleValuesCanBeInAnyOrder() { 34 | $expectation = new FieldExpectation(array('a', 'b')); 35 | $this->assertTrue($expectation->test(array('a', 'b'))); 36 | $this->assertTrue($expectation->test(array('b', 'a'))); 37 | $this->assertFalse($expectation->test(array('a', 'a'))); 38 | $this->assertFalse($expectation->test('a')); 39 | } 40 | 41 | function testSingleItemCanBeArrayOrString() { 42 | $expectation = new FieldExpectation(array('a')); 43 | $this->assertTrue($expectation->test(array('a'))); 44 | $this->assertTrue($expectation->test('a')); 45 | } 46 | } 47 | 48 | class TestOfHeaderExpectations extends UnitTestCase { 49 | 50 | function testExpectingOnlyTheHeaderName() { 51 | $expectation = new HttpHeaderExpectation('a'); 52 | $this->assertIdentical($expectation->test(false), false); 53 | $this->assertIdentical($expectation->test('a: A'), true); 54 | $this->assertIdentical($expectation->test('A: A'), true); 55 | $this->assertIdentical($expectation->test('a: B'), true); 56 | $this->assertIdentical($expectation->test(' a : A '), true); 57 | } 58 | 59 | function testHeaderValueAsWell() { 60 | $expectation = new HttpHeaderExpectation('a', 'A'); 61 | $this->assertIdentical($expectation->test(false), false); 62 | $this->assertIdentical($expectation->test('a: A'), true); 63 | $this->assertIdentical($expectation->test('A: A'), true); 64 | $this->assertIdentical($expectation->test('A: a'), false); 65 | $this->assertIdentical($expectation->test('a: B'), false); 66 | $this->assertIdentical($expectation->test(' a : A '), true); 67 | $this->assertIdentical($expectation->test(' a : AB '), false); 68 | } 69 | 70 | function testHeaderValueWithColons() { 71 | $expectation = new HttpHeaderExpectation('a', 'A:B:C'); 72 | $this->assertIdentical($expectation->test('a: A'), false); 73 | $this->assertIdentical($expectation->test('a: A:B'), false); 74 | $this->assertIdentical($expectation->test('a: A:B:C'), true); 75 | $this->assertIdentical($expectation->test('a: A:B:C:D'), false); 76 | } 77 | 78 | function testMultilineSearch() { 79 | $expectation = new HttpHeaderExpectation('a', 'A'); 80 | $this->assertIdentical($expectation->test("aa: A\r\nb: B\r\nc: C"), false); 81 | $this->assertIdentical($expectation->test("aa: A\r\na: A\r\nb: B"), true); 82 | } 83 | 84 | function testMultilineSearchWithPadding() { 85 | $expectation = new HttpHeaderExpectation('a', ' A '); 86 | $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), false); 87 | $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), true); 88 | } 89 | 90 | function testPatternMatching() { 91 | $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/')); 92 | $this->assertIdentical($expectation->test('a: A'), true); 93 | $this->assertIdentical($expectation->test('A: A'), true); 94 | $this->assertIdentical($expectation->test('A: a'), false); 95 | $this->assertIdentical($expectation->test('a: B'), false); 96 | $this->assertIdentical($expectation->test(' a : A '), true); 97 | $this->assertIdentical($expectation->test(' a : AB '), true); 98 | } 99 | 100 | function testCaseInsensitivePatternMatching() { 101 | $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/i')); 102 | $this->assertIdentical($expectation->test('a: a'), true); 103 | $this->assertIdentical($expectation->test('a: B'), false); 104 | $this->assertIdentical($expectation->test(' a : A '), true); 105 | $this->assertIdentical($expectation->test(' a : BAB '), true); 106 | $this->assertIdentical($expectation->test(' a : bab '), true); 107 | } 108 | 109 | function testUnwantedHeader() { 110 | $expectation = new NoHttpHeaderExpectation('a'); 111 | $this->assertIdentical($expectation->test(''), true); 112 | $this->assertIdentical($expectation->test('stuff'), true); 113 | $this->assertIdentical($expectation->test('b: B'), true); 114 | $this->assertIdentical($expectation->test('a: A'), false); 115 | $this->assertIdentical($expectation->test('A: A'), false); 116 | } 117 | 118 | function testMultilineUnwantedSearch() { 119 | $expectation = new NoHttpHeaderExpectation('a'); 120 | $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), true); 121 | $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), false); 122 | } 123 | 124 | function testLocationHeaderSplitsCorrectly() { 125 | $expectation = new HttpHeaderExpectation('Location', 'http://here/'); 126 | $this->assertIdentical($expectation->test('Location: http://here/'), true); 127 | } 128 | } 129 | 130 | class TestOfTextExpectations extends UnitTestCase { 131 | 132 | function testMatchingSubString() { 133 | $expectation = new TextExpectation('wanted'); 134 | $this->assertIdentical($expectation->test(''), false); 135 | $this->assertIdentical($expectation->test('Wanted'), false); 136 | $this->assertIdentical($expectation->test('wanted'), true); 137 | $this->assertIdentical($expectation->test('the wanted text is here'), true); 138 | } 139 | 140 | function testNotMatchingSubString() { 141 | $expectation = new NoTextExpectation('wanted'); 142 | $this->assertIdentical($expectation->test(''), true); 143 | $this->assertIdentical($expectation->test('Wanted'), true); 144 | $this->assertIdentical($expectation->test('wanted'), false); 145 | $this->assertIdentical($expectation->test('the wanted text is here'), false); 146 | } 147 | } 148 | 149 | class TestOfGenericAssertionsInWebTester extends WebTestCase { 150 | function testEquality() { 151 | $this->assertEqual('a', 'a'); 152 | $this->assertNotEqual('a', 'A'); 153 | } 154 | } 155 | ?> -------------------------------------------------------------------------------- /tests/simpletest/test/xml_test.php: -------------------------------------------------------------------------------- 1 | 2)); 15 | $this->assertEqual($nesting->getSize(), 2); 16 | } 17 | } 18 | 19 | class TestOfXmlStructureParsing extends UnitTestCase { 20 | function testValidXml() { 21 | $listener = new MockSimpleScorer(); 22 | $listener->expectNever('paintGroupStart'); 23 | $listener->expectNever('paintGroupEnd'); 24 | $listener->expectNever('paintCaseStart'); 25 | $listener->expectNever('paintCaseEnd'); 26 | $parser = new SimpleTestXmlParser($listener); 27 | $this->assertTrue($parser->parse("\n")); 28 | $this->assertTrue($parser->parse("\n")); 29 | $this->assertTrue($parser->parse("\n")); 30 | } 31 | 32 | function testEmptyGroup() { 33 | $listener = new MockSimpleScorer(); 34 | $listener->expectOnce('paintGroupStart', array('a_group', 7)); 35 | $listener->expectOnce('paintGroupEnd', array('a_group')); 36 | $parser = new SimpleTestXmlParser($listener); 37 | $parser->parse("\n"); 38 | $parser->parse("\n"); 39 | $this->assertTrue($parser->parse("\n")); 40 | $this->assertTrue($parser->parse("a_group\n")); 41 | $this->assertTrue($parser->parse("\n")); 42 | $parser->parse("\n"); 43 | } 44 | 45 | function testEmptyCase() { 46 | $listener = new MockSimpleScorer(); 47 | $listener->expectOnce('paintCaseStart', array('a_case')); 48 | $listener->expectOnce('paintCaseEnd', array('a_case')); 49 | $parser = new SimpleTestXmlParser($listener); 50 | $parser->parse("\n"); 51 | $parser->parse("\n"); 52 | $this->assertTrue($parser->parse("\n")); 53 | $this->assertTrue($parser->parse("a_case\n")); 54 | $this->assertTrue($parser->parse("\n")); 55 | $parser->parse("\n"); 56 | } 57 | 58 | function testEmptyMethod() { 59 | $listener = new MockSimpleScorer(); 60 | $listener->expectOnce('paintCaseStart', array('a_case')); 61 | $listener->expectOnce('paintCaseEnd', array('a_case')); 62 | $listener->expectOnce('paintMethodStart', array('a_method')); 63 | $listener->expectOnce('paintMethodEnd', array('a_method')); 64 | $parser = new SimpleTestXmlParser($listener); 65 | $parser->parse("\n"); 66 | $parser->parse("\n"); 67 | $parser->parse("\n"); 68 | $parser->parse("a_case\n"); 69 | $this->assertTrue($parser->parse("\n")); 70 | $this->assertTrue($parser->parse("a_method\n")); 71 | $this->assertTrue($parser->parse("\n")); 72 | $parser->parse("\n"); 73 | $parser->parse("\n"); 74 | } 75 | 76 | function testNestedGroup() { 77 | $listener = new MockSimpleScorer(); 78 | $listener->expectAt(0, 'paintGroupStart', array('a_group', 7)); 79 | $listener->expectAt(1, 'paintGroupStart', array('b_group', 3)); 80 | $listener->expectCallCount('paintGroupStart', 2); 81 | $listener->expectAt(0, 'paintGroupEnd', array('b_group')); 82 | $listener->expectAt(1, 'paintGroupEnd', array('a_group')); 83 | $listener->expectCallCount('paintGroupEnd', 2); 84 | 85 | $parser = new SimpleTestXmlParser($listener); 86 | $parser->parse("\n"); 87 | $parser->parse("\n"); 88 | 89 | $this->assertTrue($parser->parse("\n")); 90 | $this->assertTrue($parser->parse("a_group\n")); 91 | $this->assertTrue($parser->parse("\n")); 92 | $this->assertTrue($parser->parse("b_group\n")); 93 | $this->assertTrue($parser->parse("\n")); 94 | $this->assertTrue($parser->parse("\n")); 95 | $parser->parse("\n"); 96 | } 97 | } 98 | 99 | class AnyOldSignal { 100 | public $stuff = true; 101 | } 102 | 103 | class TestOfXmlResultsParsing extends UnitTestCase { 104 | 105 | function sendValidStart(&$parser) { 106 | $parser->parse("\n"); 107 | $parser->parse("\n"); 108 | $parser->parse("\n"); 109 | $parser->parse("a_case\n"); 110 | $parser->parse("\n"); 111 | $parser->parse("a_method\n"); 112 | } 113 | 114 | function sendValidEnd(&$parser) { 115 | $parser->parse("\n"); 116 | $parser->parse("\n"); 117 | $parser->parse("\n"); 118 | } 119 | 120 | function testPass() { 121 | $listener = new MockSimpleScorer(); 122 | $listener->expectOnce('paintPass', array('a_message')); 123 | $parser = new SimpleTestXmlParser($listener); 124 | $this->sendValidStart($parser); 125 | $this->assertTrue($parser->parse("a_message\n")); 126 | $this->sendValidEnd($parser); 127 | } 128 | 129 | function testFail() { 130 | $listener = new MockSimpleScorer(); 131 | $listener->expectOnce('paintFail', array('a_message')); 132 | $parser = new SimpleTestXmlParser($listener); 133 | $this->sendValidStart($parser); 134 | $this->assertTrue($parser->parse("a_message\n")); 135 | $this->sendValidEnd($parser); 136 | } 137 | 138 | function testException() { 139 | $listener = new MockSimpleScorer(); 140 | $listener->expectOnce('paintError', array('a_message')); 141 | $parser = new SimpleTestXmlParser($listener); 142 | $this->sendValidStart($parser); 143 | $this->assertTrue($parser->parse("a_message\n")); 144 | $this->sendValidEnd($parser); 145 | } 146 | 147 | function testSkip() { 148 | $listener = new MockSimpleScorer(); 149 | $listener->expectOnce('paintSkip', array('a_message')); 150 | $parser = new SimpleTestXmlParser($listener); 151 | $this->sendValidStart($parser); 152 | $this->assertTrue($parser->parse("a_message\n")); 153 | $this->sendValidEnd($parser); 154 | } 155 | 156 | function testSignal() { 157 | $signal = new AnyOldSignal(); 158 | $signal->stuff = "Hello"; 159 | $listener = new MockSimpleScorer(); 160 | $listener->expectOnce('paintSignal', array('a_signal', $signal)); 161 | $parser = new SimpleTestXmlParser($listener); 162 | $this->sendValidStart($parser); 163 | $this->assertTrue($parser->parse( 164 | "\n")); 166 | $this->sendValidEnd($parser); 167 | } 168 | 169 | function testMessage() { 170 | $listener = new MockSimpleScorer(); 171 | $listener->expectOnce('paintMessage', array('a_message')); 172 | $parser = new SimpleTestXmlParser($listener); 173 | $this->sendValidStart($parser); 174 | $this->assertTrue($parser->parse("a_message\n")); 175 | $this->sendValidEnd($parser); 176 | } 177 | 178 | function testFormattedMessage() { 179 | $listener = new MockSimpleScorer(); 180 | $listener->expectOnce('paintFormattedMessage', array("\na\tmessage\n")); 181 | $parser = new SimpleTestXmlParser($listener); 182 | $this->sendValidStart($parser); 183 | $this->assertTrue($parser->parse("\n")); 184 | $this->sendValidEnd($parser); 185 | } 186 | } 187 | ?> --------------------------------------------------------------------------------