├── .gitignore
├── tests
├── simpletest
│ ├── VERSION
│ ├── test
│ │ ├── support
│ │ │ ├── collector
│ │ │ │ ├── collectable.1
│ │ │ │ └── collectable.2
│ │ │ ├── upload_sample.txt
│ │ │ ├── supplementary_upload_sample.txt
│ │ │ ├── empty_test_file.php
│ │ │ ├── latin1_sample
│ │ │ ├── test1.php
│ │ │ ├── failing_test.php
│ │ │ ├── passing_test.php
│ │ │ └── spl_examples.php
│ │ ├── parser_test.php
│ │ ├── php_parser_test.php
│ │ ├── site
│ │ │ └── file.html
│ │ ├── test_with_parse_error.php
│ │ ├── parse_error_test.php
│ │ ├── bad_test_suite.php
│ │ ├── interfaces_test_php5_1.php
│ │ ├── all_tests.php
│ │ ├── detached_test.php
│ │ ├── remote_test.php
│ │ ├── autorun_test.php
│ │ ├── socket_test.php
│ │ ├── eclipse_test.php
│ │ ├── shell_test.php
│ │ ├── adapter_test.php
│ │ ├── shell_tester_test.php
│ │ ├── command_line_test.php
│ │ ├── unit_tester_test.php
│ │ ├── simpletest_test.php
│ │ ├── collector_test.php
│ │ ├── live_test.php
│ │ ├── reflection_php4_test.php
│ │ ├── unit_tests.php
│ │ ├── dumper_test.php
│ │ ├── compatibility_test.php
│ │ ├── interfaces_test.php
│ │ ├── authentication_test.php
│ │ ├── page_test.php
│ │ ├── exceptions_test.php
│ │ ├── errors_test.php
│ │ ├── web_tester_test.php
│ │ ├── xml_test.php
│ │ ├── reflection_php5_test.php
│ │ └── encoding_test.php
│ ├── docs
│ │ ├── fr
│ │ │ ├── server_stubs_documentation.html
│ │ │ └── docs.css
│ │ └── en
│ │ │ └── docs.css
│ ├── xmltime.php
│ ├── extensions
│ │ ├── testdox.php
│ │ ├── cli_reporter.php
│ │ ├── phpunit_test_case.php
│ │ ├── testdox
│ │ │ └── test.php
│ │ └── pear_test_case.php
│ ├── detached.php
│ ├── autorun.php
│ ├── remote.php
│ ├── selector.php
│ ├── reflection_php4.php
│ ├── invoker.php
│ ├── collector.php
│ ├── README
│ ├── default_reporter.php
│ ├── compatibility.php
│ ├── exceptions.php
│ ├── authentication.php
│ └── errors.php
├── bugs
│ ├── index.html
│ └── test_123_bug.php
├── models
│ ├── index.html
│ └── test_users_model.php
├── views
│ └── index.html
├── controllers
│ └── index.html
├── helpers
│ └── index.html
├── libraries
│ └── index.html
├── unit_test.css
└── test_gui.php
├── screenshots
├── failed.png
└── passed.png
├── phing
├── README.md
└── TestRunnerTask.php
├── LICENSE.txt
├── README.md
├── unit_test.php
└── unit_test_xml.php
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
--------------------------------------------------------------------------------
/tests/simpletest/VERSION:
--------------------------------------------------------------------------------
1 | 1.1alpha3
2 |
--------------------------------------------------------------------------------
/tests/simpletest/test/support/collector/collectable.1:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/simpletest/test/support/collector/collectable.2:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/simpletest/docs/fr/server_stubs_documentation.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/simpletest/test/support/upload_sample.txt:
--------------------------------------------------------------------------------
1 | Sample for testing file upload
--------------------------------------------------------------------------------
/tests/simpletest/test/support/supplementary_upload_sample.txt:
--------------------------------------------------------------------------------
1 | Some more text content
--------------------------------------------------------------------------------
/screenshots/failed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ericlbarnes/codeigniter-simpletest/HEAD/screenshots/failed.png
--------------------------------------------------------------------------------
/screenshots/passed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ericlbarnes/codeigniter-simpletest/HEAD/screenshots/passed.png
--------------------------------------------------------------------------------
/tests/simpletest/test/support/empty_test_file.php:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/simpletest/test/parser_test.php:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ericlbarnes/codeigniter-simpletest/HEAD/tests/simpletest/test/parser_test.php
--------------------------------------------------------------------------------
/tests/simpletest/test/php_parser_test.php:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ericlbarnes/codeigniter-simpletest/HEAD/tests/simpletest/test/php_parser_test.php
--------------------------------------------------------------------------------
/tests/simpletest/test/support/latin1_sample:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ericlbarnes/codeigniter-simpletest/HEAD/tests/simpletest/test/support/latin1_sample
--------------------------------------------------------------------------------
/tests/simpletest/test/support/test1.php:
--------------------------------------------------------------------------------
1 | assertEqual(3,1+2, "pass1");
5 | }
6 | }
7 | ?>
8 |
--------------------------------------------------------------------------------
/tests/bugs/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | 403 Forbidden
4 |
5 |
6 |
7 | Directory access is forbidden.
8 |
9 |
10 |
--------------------------------------------------------------------------------
/tests/models/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | 403 Forbidden
4 |
5 |
6 |
7 | Directory access is forbidden.
8 |
9 |
10 |
--------------------------------------------------------------------------------
/tests/views/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | 403 Forbidden
4 |
5 |
6 |
7 | Directory access is forbidden.
8 |
9 |
10 |
--------------------------------------------------------------------------------
/tests/controllers/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | 403 Forbidden
4 |
5 |
6 |
7 | Directory access is forbidden.
8 |
9 |
10 |
--------------------------------------------------------------------------------
/tests/helpers/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | 403 Forbidden
4 |
5 |
6 |
7 | Directory access is forbidden.
8 |
9 |
10 |
--------------------------------------------------------------------------------
/tests/libraries/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | 403 Forbidden
4 |
5 |
6 |
7 | Directory access is forbidden.
8 |
9 |
10 |
--------------------------------------------------------------------------------
/tests/simpletest/test/site/file.html:
--------------------------------------------------------------------------------
1 |
2 | Link to SimpleTest
3 |
4 | Link to SimpleTest
5 |
6 |
--------------------------------------------------------------------------------
/tests/simpletest/test/test_with_parse_error.php:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/simpletest/test/support/failing_test.php:
--------------------------------------------------------------------------------
1 | assertEqual(1,2);
7 | }
8 | }
9 | ?>
--------------------------------------------------------------------------------
/tests/simpletest/test/support/passing_test.php:
--------------------------------------------------------------------------------
1 | assertEqual(2,2);
7 | }
8 | }
9 | ?>
--------------------------------------------------------------------------------
/tests/simpletest/test/parse_error_test.php:
--------------------------------------------------------------------------------
1 | addFile('test_with_parse_error.php');
8 | $test->run(new HtmlReporter());
9 | ?>
--------------------------------------------------------------------------------
/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 | ?>
--------------------------------------------------------------------------------
/phing/README.md:
--------------------------------------------------------------------------------
1 | # Phing Integration
2 |
3 | Credits:
4 | Frank Hmeidan -
5 |
6 | # Installation
7 |
8 | Place the TestRunnerTask.php file in the following location: "phing/tasks/ext/TestRunnerTask.php"
9 |
10 | Next create this in your Phing build file:
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/tests/simpletest/test/support/spl_examples.php:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/simpletest/test/interfaces_test_php5_1.php:
--------------------------------------------------------------------------------
1 | assertIsA($mock, 'SampleInterfaceWithHintInSignature');
12 | }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/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/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/bugs/test_123_bug.php:
--------------------------------------------------------------------------------
1 | dump('Just some dump data');
23 | $this->assertEqual(11,11);
24 | }
25 |
26 | public function test_issue2()
27 | {
28 | $this->assertEqual(12,12);
29 | }
30 |
31 | public function test_issue1()
32 | {
33 | $this->assertEqual(1,1, '1 equals 1');
34 | }
35 | }
36 |
37 | /* End of file test_123_bug.php */
38 | /* Location: ./tests/bugs/test_123_bug.php */
39 |
--------------------------------------------------------------------------------
/tests/simpletest/xmltime.php:
--------------------------------------------------------------------------------
1 | pre = microtime();
12 | parent::__construct($test_name);
13 | }
14 |
15 | function paintMethodEnd($test_name) {
16 | $post = microtime();
17 | if ($this->pre != null) {
18 | $duration = $post - $this->pre;
19 | // how can post time be less than pre? assuming zero if this happens..
20 | if ($post < $this->pre) $duration = 0;
21 | print $this->getIndent(1);
22 | print "\n";
23 | }
24 | parent::paintMethodEnd($test_name);
25 | $this->pre = null;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/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/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/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 | ?>
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | DON'T BE A DICK PUBLIC LICENSE
2 |
3 | Copyright (C) 2010 Eric Barnes
4 |
5 | Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed.
6 |
7 | DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
8 |
9 | 1. Do whatever you like with the original work, just don't be a dick.
10 |
11 | Being a dick includes - but is not limited to - the following instances:
12 |
13 | 1a. Outright copyright infringement - Don't just copy this and change the name.
14 | 1b. Selling the unmodified original with no work done what-so-ever, that's REALLY being a dick.
15 | 1c. Modifying the original work to contain hidden harmful content. That would make you a PROPER dick.
16 |
17 | 2. If you become rich through modifications, related works/services, or supporting the original work, share the love. Only a dick would make loads off this work and not buy the original works creator(s) a pint.
18 |
19 | 3. Code is provided with no warranty. Using somebody else's code and bitching when it goes wrong makes you a DONKEY dick. Fix the problem yourself. A non-dick would submit the fix back.
--------------------------------------------------------------------------------
/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/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/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/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/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/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 | ?>
--------------------------------------------------------------------------------
/phing/TestRunnerTask.php:
--------------------------------------------------------------------------------
1 | url) || filter_var($this->url, FILTER_VALIDATE_URL) === FALSE) {
21 | throw new BuildException('Invalid URL: You must specify a valid URL.');
22 | }
23 |
24 | echo "Running unit tests...\n";
25 |
26 | $testResults = $this->doPOST($this->url, 'all', '1');
27 |
28 | if ($testResults == NULL || $testResults == '' || !isset($testResults))
29 | {
30 | throw new BuildException('No results page returned from POST request on $url');
31 | }
32 |
33 | /* Check if there is the string 'FAILED' anywhere in the output - if not, we've succeeded. */
34 | if (strpos($testResults, 'FAILED') != FALSE)
35 | {
36 | throw new BuildException("There were test case failures - build terminated.");
37 | }
38 | else
39 | {
40 | echo "\n ----- all tested PASSED ----- \n";
41 | }
42 |
43 | return;
44 | }
45 |
46 | public function setURL($url)
47 | {
48 | $this->url = $url;
49 | }
50 |
51 | function doPOST($url, $key, $value)
52 | {
53 | $context = stream_context_create(array(
54 | 'http' => array(
55 | 'method' => 'POST',
56 | 'header' => "Content-type: application/x-www-form-urlencoded\r\n",
57 | 'content' => http_build_query(array($key => $value)),
58 | )));
59 |
60 | $ret = file_get_contents($url, false, $context);
61 |
62 | return $ret;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/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/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/extensions/cli_reporter.php:
--------------------------------------------------------------------------------
1 | gmail com
6 | */
7 | class CliReporter extends TextReporter {
8 |
9 | public $esc_start;
10 | /**
11 | * Set font color
12 | * @options
13 | * Regular colors:
14 | * Red = '0;31m'
15 | * Green = '0;32m'
16 | * bold:
17 | * Red = '1;31m'
18 | * Green = '1;32m'
19 | * background:
20 | * Red = '41m'
21 | * Green = '42m'
22 | * high intensivy colors:
23 | * Red = '0;91m'
24 | * Green = '0;92m'
25 | * Bold High Intensity:
26 | * Red = '1;91m'
27 | * Green = '1;92m'
28 | * High Intensity backgrounds:
29 | * Red ='0;101m'
30 | * Green ='0;102m'
31 | */
32 | public $red_color = '1;91m';
33 | public $green_color = '1;92m';
34 | public $default = '0;0m';
35 |
36 | function __construct() {
37 | parent::__construct();
38 | $this->esc_start = chr(27).'[';
39 | }
40 |
41 | function resetColors() {
42 | print $this->esc_start . $this->default . "\n";
43 | }
44 |
45 | function paintFooter($test_name) {
46 | if($this->getFailCount() + $this->getExceptionCount() == 0) {
47 | print $this->esc_start . $this->green_color;
48 | print "OK\n";
49 | }else{
50 | print $this->esc_start . $this->red_color;
51 | print "FAILURES!!!\n";
52 | }
53 |
54 | print "Test cases run: " . $this->getTestCaseProgress() .
55 | "/" . $this->getTestCaseCount() .
56 | ", Passes: " . $this->getPassCount() .
57 | ", Failures: " . $this->getFailCount() .
58 | ", Exceptions: " . $this->getExceptionCount();
59 |
60 | $this->resetColors();
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/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/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/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/reflection_php4_test.php:
--------------------------------------------------------------------------------
1 | assertTrue($reflection->classOrInterfaceExists());
17 | $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload());
18 | }
19 |
20 | function testClassNonExistence() {
21 | $reflection = new SimpleReflection('UnknownThing');
22 | $this->assertFalse($reflection->classOrInterfaceExists());
23 | $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload());
24 | }
25 |
26 | function testDetectionOfInterfacesAlwaysFalse() {
27 | $reflection = new SimpleReflection('AnyOldThing');
28 | $this->assertFalse($reflection->isAbstract());
29 | $this->assertFalse($reflection->isInterface());
30 | }
31 |
32 | function testFindingParentClass() {
33 | $reflection = new SimpleReflection('AnyOldChildThing');
34 | $this->assertEqual(strtolower($reflection->getParent()), 'anyoldthing');
35 | }
36 |
37 | function testMethodsListFromClass() {
38 | $reflection = new SimpleReflection('AnyOldThing');
39 | $methods = $reflection->getMethods();
40 | $this->assertEqualIgnoringCase($methods[0], 'aMethod');
41 | }
42 |
43 | function testNoInterfacesForPHP4() {
44 | $reflection = new SimpleReflection('AnyOldThing');
45 | $this->assertEqual(
46 | $reflection->getInterfaces(),
47 | array());
48 | }
49 |
50 | function testMostGeneralPossibleSignature() {
51 | $reflection = new SimpleReflection('AnyOldThing');
52 | $this->assertEqualIgnoringCase(
53 | $reflection->getSignature('aMethod'),
54 | 'function &aMethod()');
55 | }
56 |
57 | function assertEqualIgnoringCase($a, $b) {
58 | return $this->assertEqual(strtolower($a), strtolower($b));
59 | }
60 | }
61 | ?>
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CodeIgniter with SimpleTest
2 |
3 | Updates:
4 |
5 | The CodeIgniter core is now being converted to using phpUnit so I'm using simpletest as a stopgap measure.
6 |
7 | In additon to the original version I've added the ability to output the test results in Junit format for use in continuous integration systems based on work from
8 |
9 | ## Overview
10 |
11 | This has been adopted from:
12 | [jamieonsoftware](http://jamieonsoftware.com/blog/entry/setting-up-the-perfect-codeigniter-tdd-environment "CodeIgniter TDD")
13 |
14 | With help from:
15 | John S. -
16 |
17 | Design From:
18 | Istvan Pusztai -
19 |
20 | ## Installation
21 |
22 | The unit_test.php file should go in your CodeIgniter root. The same place as index.php
23 |
24 | You should open that file and alter your paths at the top.
25 |
26 | The tests directory can be moved any where you want but they are setup to be in the root as well.
27 |
28 | All test files need to be named `test_name_folder.php`. For example:
29 |
30 | test_whatever_bug.php
31 | test_string_helper.php
32 | test_auth_library.php
33 | test_core_model.php
34 |
35 |
36 | I have included a full download of simpletest and the only customization I have made is to the `simpletest/extensions/my_reporter.php`.
37 |
38 | ## Usage:
39 |
40 | Once you have installed you can either run tests through the browser or via command line.
41 |
42 | * Browser - Visit yoursite.com/unit_test.php
43 | * Command Link - `$ php unit_test.php`
44 | * XML Results - `$ php unit_test_xml.php`
45 |
46 | ## NOTES:
47 |
48 | Inside the "tests" directory I include two example test files. The test_users_model.php will not run on its own because your application would not include the same users model as the example file. It is supplied just as a guide.
49 |
50 | This version is now compatible with PHP 5.3
51 |
52 | ## Credits
53 |
54 | * Joe Tsui -
55 | * Jamie Rumbelow - [jamieonsoftware](http://jamieonsoftware.com/blog/entry/setting-up-the-perfect-codeigniter-tdd-environment "CodeIgniter TDD")
56 | * RT Wolf -
57 | * John S. -
58 | * Istvan Pusztai -
59 | * Oliver Smith
60 |
--------------------------------------------------------------------------------
/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/unit_test.css:
--------------------------------------------------------------------------------
1 | body {
2 | font: 0.75em "Helvetica Neue", Arial, Helvetica, sans-serif;
3 | color: #000;
4 | margin: 0;
5 | padding: 0;
6 | }
7 | code, pre {
8 | background-color: #f9f9f9;
9 | border: 1px solid #D0D0D0;
10 | color: #002166;
11 | display: block;
12 | font-family: "Bitstream Vera Sans Mono", monospace;
13 | font-size: 12px;
14 | margin: 14px 5px 14px 5px;
15 | padding: 12px 10px 12px 10px;
16 | }
17 | #header {
18 | background: #eee;
19 | border-bottom: 1px solid #ddd;
20 | padding: 10px;
21 | }
22 | #header h2 {
23 | color: #900;
24 | margin: 0;
25 | }
26 | #nav {
27 | margin: 10px 20px;
28 | }
29 |
30 |
31 | #report {
32 | padding: 50px 0 0 0;
33 | margin: 0 20px 20px;
34 | position: relative;
35 | }
36 | .test {
37 | border-bottom: 1px solid #ddd;
38 | padding: 5px 0;
39 | }
40 | .test h3 {
41 | display: inline;
42 | font-weight: normal;
43 | }
44 | .test.pass h3 { color: #090; }
45 | .test.fail h3 { color: #e00; }
46 | .test div.result {
47 | color: #fff;
48 | float: left;
49 | font-weight: bold;
50 | margin-right: 8px;
51 | text-align: center;
52 | width: 55px;
53 | }
54 | .test.fail div.result, .summary.fail {
55 | background: #c00;
56 | border: 1px solid #900;
57 | }
58 | .test.pass div.result, .summary.pass {
59 | background: #0a0;
60 | border: 1px solid #080;
61 | }
62 | .summary {
63 | color: #fff;
64 | font-weight: bold;
65 | font-size: 1.5em;
66 | padding: 10px;
67 | margin: 10px 0;
68 | position: absolute;
69 | top: 0;
70 | }
71 | .test div.time {
72 | background-color: #f9f9f9;
73 | border: 1px solid #D0D0D0;
74 | color: #666 !important;
75 | float: left;
76 | font: 1.15em 'Courier New', monospace;
77 | margin-left: -65px;
78 | text-align: center;
79 | width: 55px;
80 | }
81 | .test .details {
82 | padding-top: 5px;
83 | padding-left: 65px;
84 | }
85 | .test.pass .details {
86 | color: #999;
87 | }
88 | .test.fail .details {
89 | color: #444;
90 | }
91 | .test.fail .details strong {
92 | color: #900;
93 | }
94 | form {
95 | margin: 0;
96 | padding: 0;
97 | display: inline;
98 | }
99 | #running {
100 | display:none;
101 | border: #999 1px solid;
102 | line-height: 30px;
103 | vertical-align:middle;
104 | background-color: #fff;
105 | padding: 20px 20px 12px 20px;
106 | }
107 |
108 | #running img {
109 | margin:10px;
110 | width:15px;
111 | height:15px;
112 | vertical-align:middle;
113 | }
114 |
--------------------------------------------------------------------------------
/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/models/test_users_model.php:
--------------------------------------------------------------------------------
1 | load->model('users/users_model');
11 |
12 | $this->rand = rand(500,15000);
13 | }
14 |
15 | public function setUp()
16 | {
17 | $this->db->truncate('users');
18 |
19 | $insert_data = array(
20 | 'user_email' => 'demo'.$this->rand.'@demo.com',
21 | 'user_username' => 'test_'.$this->rand,
22 | 'user_password' => 'demo_'.$this->rand,
23 | 'user_join_date' => time(),
24 | 'user_group' => 1
25 | );
26 | $user_id = $this->users_model->add_user($insert_data);
27 | $this->user = $this->users_model->get_user($user_id);
28 | }
29 |
30 | public function tearDown()
31 | {
32 |
33 | }
34 |
35 | public function test_included()
36 | {
37 | $this->assertTrue(class_exists('users_model'));
38 | }
39 |
40 | public function test_add_user()
41 | {
42 | $insert_data = array(
43 | 'user_email' => 'demo'.$this->rand.'@demo.com',
44 | 'user_username' => 'test_'.$this->rand,
45 | 'user_password' => 'demo_'.$this->rand,
46 | 'user_join_date' => time(),
47 | 'user_group' => 1
48 | );
49 | $user_id = $this->users_model->add_user($insert_data);
50 |
51 | //$this->dump($user_id);
52 | $this->assertEqual($user_id, 1, 'user id = 1');
53 | }
54 |
55 | public function test_get_user_by_id()
56 | {
57 | $user = $this->users_model->get_user(1);
58 | $this->assertEqual($user['user_id'], 1);
59 | }
60 |
61 | public function test_get_user_by_username()
62 | {
63 | $user = $this->users_model->get_user('test_'.$this->rand);
64 | $this->assertEqual($user['user_id'], 1);
65 | }
66 |
67 | public function test_edit_user()
68 | {
69 | $insert_data = array(
70 | 'user_email' => 'edit_demo'.$this->rand.'@demo.com',
71 | );
72 | $user = $this->users_model->edit_user(1, $insert_data);
73 | $this->assertTrue($user);
74 | }
75 |
76 | public function test_delete_user()
77 | {
78 | $user = $this->users_model->delete_user(1);
79 | $this->assertTrue($user);
80 | }
81 |
82 | public function test_username_exists()
83 | {
84 | $user = $this->users_model->username_check('test_'.$this->rand);
85 | $this->assertFalse($user);
86 | }
87 |
88 | public function test_username_does_not_exists()
89 | {
90 | $user = $this->users_model->username_check('my_super_test_'.$this->rand);
91 | $this->assertTrue($user);
92 | }
93 |
94 | public function test_email_exists()
95 | {
96 | $user = $this->users_model->email_check('demo'.$this->rand.'@demo.com');
97 | $this->assertFalse($user);
98 | }
99 |
100 | public function test_email_does_not_exists()
101 | {
102 | $user = $this->users_model->email_check('my_super_test_'.$this->rand.'@demo.com');
103 | $this->assertTrue($user);
104 | }
105 | }
106 |
107 | /* End of file test_users_model.php */
108 | /* Location: ./tests/models/test_users_model.php */
109 |
--------------------------------------------------------------------------------
/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/autorun.php:
--------------------------------------------------------------------------------
1 | createSuiteFromClasses(
50 | basename(initial_file()),
51 | $loader->selectRunnableTests($candidates));
52 | return $suite->run(new DefaultReporter());
53 | } catch (Exception $stack_frame_fix) {
54 | print $stack_frame_fix->getMessage();
55 | return false;
56 | }
57 | }
58 |
59 | /**
60 | * Checks the current test context to see if a test has
61 | * ever been run.
62 | * @return boolean True if tests have run.
63 | */
64 | function tests_have_run() {
65 | if ($context = SimpleTest::getContext()) {
66 | return (boolean)$context->getTest();
67 | }
68 | return false;
69 | }
70 |
71 | /**
72 | * The first autorun file.
73 | * @return string Filename of first autorun script.
74 | */
75 | function initial_file() {
76 | static $file = false;
77 | if (! $file) {
78 | if (isset($_SERVER, $_SERVER['SCRIPT_FILENAME'])) {
79 | $file = $_SERVER['SCRIPT_FILENAME'];
80 | } else {
81 | $included_files = get_included_files();
82 | $file = reset($included_files);
83 | }
84 | }
85 | return $file;
86 | }
87 |
88 | /**
89 | * Every class since the first autorun include. This
90 | * is safe enough if require_once() is always used.
91 | * @return array Class names.
92 | */
93 | function capture_new_classes() {
94 | global $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES;
95 | return array_map('strtolower', array_diff(get_declared_classes(),
96 | $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES ?
97 | $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES : array()));
98 | }
99 | ?>
--------------------------------------------------------------------------------
/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/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/extensions/phpunit_test_case.php:
--------------------------------------------------------------------------------
1 | getLabel();
94 | }
95 | }
96 | ?>
97 |
--------------------------------------------------------------------------------
/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/test_gui.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CodeIgniter › Unit Testing › Index
6 |
7 |
8 |
9 |
10 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
55 |
56 |
57 |
89 |
90 |
91 |
92 |
93 |
94 |
95 | run(new MyReporter());
98 | ob_end_flush();
99 | ?>
100 |
101 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/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/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/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/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/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/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 | ?>
--------------------------------------------------------------------------------
/unit_test.php:
--------------------------------------------------------------------------------
1 | _label = 'CodeIgniter Test Suite';
33 |
34 | class CodeIgniterUnitTestCase extends UnitTestCase {
35 | protected $_ci;
36 |
37 | public function __construct($name = '')
38 | {
39 | parent::__construct($name);
40 | $this->_ci =& get_instance();
41 | }
42 |
43 | public function __get($var)
44 | {
45 | return $this->_ci->$var;
46 | }
47 | }
48 |
49 | class CodeIgniterWebTestCase extends WebTestCase {
50 | protected $_ci;
51 |
52 | public function __construct($name = '')
53 | {
54 | parent::__construct($name);
55 | $this->_ci =& get_instance();
56 | }
57 |
58 | public function __get($var)
59 | {
60 | return $this->_ci->$var;
61 | }
62 | }
63 |
64 | // Because get is removed in ci we pull it out here.
65 | $run_all = FALSE;
66 | if (isset($_GET['all']) || isset($_POST['all']))
67 | {
68 | $run_all = TRUE;
69 | }
70 |
71 | //Capture CodeIgniter output, discard and load system into $CI variable
72 | ob_start();
73 | include(ROOT.'index.php');
74 | $CI =& get_instance();
75 | ob_end_clean();
76 |
77 | $CI->load->library('session');
78 | $CI->session->sess_destroy();
79 |
80 | $CI->load->helper('directory');
81 | $CI->load->helper('form');
82 |
83 | // Get all main tests
84 | if ($run_all OR ( ! empty($_POST) && ! isset($_POST['test'])))
85 | {
86 | $test_objs = array('controllers','models','views','libraries','bugs','helpers');
87 |
88 | foreach ($test_objs as $obj)
89 | {
90 | if (isset($_POST[$obj]) OR $run_all)
91 | {
92 | $dir = TESTS_DIR.$obj;
93 | $dir_files = directory_map($dir);
94 | foreach ($dir_files as $file)
95 | {
96 | if ($file != 'index.html')
97 | {
98 | $test_suite->addFile($dir.'/'.$file);
99 | }
100 | }
101 | }
102 | }
103 | }
104 | elseif (isset($_POST['test'])) //single test
105 | {
106 | $file = $_POST['test'];
107 |
108 | if (file_exists(TESTS_DIR.$file))
109 | {
110 | $test_suite->addFile(TESTS_DIR.$file);
111 | }
112 | }
113 |
114 | // ------------------------------------------------------------------------
115 |
116 | /**
117 | * Function to determine if in cli mode and if so set up variables to make it work
118 | *
119 | * @param Array of commandline args
120 | * @return Boolean true or false if commandline mode setup
121 | *
122 | */
123 | function setup_cli($argv)
124 | {
125 | if (php_sapi_name() == 'cli')
126 | {
127 | if (isset($argv[1]))
128 | {
129 | if (stripos($argv[1],'.php') !== false)
130 | {
131 | $_POST['test'] = $argv[1];
132 | }
133 | else
134 | {
135 | $_POST[$argv[1]] = $argv[1];
136 | }
137 | }
138 | else
139 | {
140 | $_POST['all'] = 'all';
141 | }
142 | $_SERVER['HTTP_HOST'] = '';
143 | $_SERVER['REQUEST_URI'] = '';
144 | return true;
145 | }
146 | return false;
147 | }
148 |
149 | /**
150 | * Function to map tests and strip .html files.
151 | *
152 | *
153 | * @param string
154 | * @return array
155 | */
156 | function map_tests($location = '')
157 | {
158 | if (empty($location))
159 | {
160 | return FALSE;
161 | }
162 |
163 | $files = directory_map($location);
164 | $return = array();
165 |
166 | foreach ($files as $file)
167 | {
168 | if ($file != 'index.html')
169 | {
170 | $return[] = $file;
171 | }
172 | }
173 | return $return;
174 | }
175 |
176 | //variables for report
177 | $controllers = map_tests(TESTS_DIR.'controllers');
178 | $models = map_tests(TESTS_DIR.'models');
179 | $views = map_tests(TESTS_DIR.'views');
180 | $libraries = map_tests(TESTS_DIR.'libraries');
181 | $bugs = map_tests(TESTS_DIR.'bugs');
182 | $helpers = map_tests(TESTS_DIR.'helpers');
183 | $form_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
184 |
185 | //display the form
186 | if (isset($cli_mode))
187 | {
188 | exit ($test_suite->run(new CliReporter()) ? 0 : 1);
189 | }
190 | else
191 | {
192 | include(TESTS_DIR.'test_gui.php');
193 | }
--------------------------------------------------------------------------------
/unit_test_xml.php:
--------------------------------------------------------------------------------
1 | _label = 'CodeIgniter Test Suite';
36 |
37 | class CodeIgniterUnitTestCase extends UnitTestCase {
38 | protected $_ci;
39 |
40 | public function __construct($name = '')
41 | {
42 | parent::__construct($name);
43 | $this->_ci =& get_instance();
44 | }
45 |
46 | public function __get($var)
47 | {
48 | return $this->_ci->$var;
49 | }
50 | }
51 |
52 | class CodeIgniterWebTestCase extends WebTestCase {
53 | protected $_ci;
54 |
55 | public function __construct($name = '')
56 | {
57 | parent::__construct($name);
58 | $this->_ci =& get_instance();
59 | }
60 |
61 | public function __get($var)
62 | {
63 | return $this->_ci->$var;
64 | }
65 | }
66 |
67 | // Because get is removed in ci we pull it out here.
68 | $run_all = FALSE;
69 | if (isset($_GET['all']) || isset($_POST['all']))
70 | {
71 | $run_all = TRUE;
72 | }
73 |
74 | //Capture CodeIgniter output, discard and load system into $CI variable
75 | ob_start();
76 | include(ROOT . 'index.php');
77 | $CI =& get_instance();
78 | ob_end_clean();
79 |
80 | $CI->load->library('session');
81 | $CI->session->sess_destroy();
82 | $CI->load->helper('directory');
83 |
84 | // Get all main tests
85 | if ($run_all OR ( ! empty($_POST) && ! isset($_POST['test'])))
86 | {
87 | $test_objs = array('controllers','models','views','libraries','bugs','helpers');
88 |
89 | foreach ($test_objs as $obj)
90 | {
91 | if (isset($_POST[$obj]) OR $run_all)
92 | {
93 | $dir = TESTS_DIR . $obj;
94 | $dir_files = directory_map($dir);
95 | foreach ($dir_files as $file)
96 | {
97 | if ($file != 'index.html')
98 | {
99 | $test_suite->addFile($dir . '/' . $file);
100 | }
101 | }
102 | }
103 | }
104 | }
105 | elseif (isset($_POST['test'])) //single test
106 | {
107 | $file = $_POST['test'];
108 |
109 | if (file_exists(TESTS_DIR . $file))
110 | {
111 | $test_suite->addFile(TESTS_DIR . $file);
112 | }
113 | }
114 |
115 | // ------------------------------------------------------------------------
116 |
117 | /**
118 | * Function to determine if in cli mode and if so set up variables to make it work
119 | *
120 | * @param Array of commandline args
121 | * @return Boolean true or false if commandline mode setup
122 | *
123 | */
124 | function setup_cli($argv)
125 | {
126 | if (php_sapi_name() == 'cli')
127 | {
128 | if(isset($argv[1]))
129 | {
130 | if(stripos($argv[1],'.php') !== false)
131 | {
132 | $_POST['test'] = $argv[1];
133 | }
134 | else
135 | {
136 | $_POST[$argv[1]] = $argv[1];
137 | }
138 | }
139 | else
140 | {
141 | $_POST['all'] = 'all';
142 | }
143 | $_SERVER['HTTP_HOST'] = '';
144 | $_SERVER['REQUEST_URI'] = '';
145 | return true;
146 | }
147 | return false;
148 | }
149 |
150 | /**
151 | * Function to map tests and strip .html files.
152 | *
153 | *
154 | * @param string
155 | * @return array
156 | */
157 | function map_tests($location = '')
158 | {
159 | if (empty($location))
160 | {
161 | return FALSE;
162 | }
163 |
164 | $files = directory_map($location);
165 | $return = array();
166 |
167 | foreach ($files as $file)
168 | {
169 | if ($file != 'index.html')
170 | {
171 | $return[] = $file;
172 | }
173 | }
174 | return $return;
175 | }
176 |
177 | //variables for report
178 | $controllers = map_tests(TESTS_DIR . 'controllers');
179 | $models = map_tests(TESTS_DIR . 'models');
180 | $views = map_tests(TESTS_DIR . 'views');
181 | $libraries = map_tests(TESTS_DIR . 'libraries');
182 | $bugs = map_tests(TESTS_DIR . 'bugs');
183 | $helpers = map_tests(TESTS_DIR . 'helpers');
184 | $form_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
185 |
186 | if ($cli_mode)
187 | {
188 | exit ($test_suite->run(new XMLtimeReporter()) ? 0 : 1);
189 | }
190 | else
191 | {
192 | include(TESTS_DIR . 'test_gui.php');
193 | }
194 |
--------------------------------------------------------------------------------
/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/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/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/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
'),
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\']()
'),
151 | 'One Two Three');
152 | }
153 |
154 | function testExtractImageAltTextMultipleTimes() {
155 | $this->assertEqual(
156 | SimplePage::normalise('![One]()
![Two]()
'),
157 | 'One Two Three');
158 | }
159 |
160 | function testHtmlEntityTranslation() {
161 | $this->assertEqual(
162 | SimplePage::normalise('<>"&''),
163 | '<>"&\'');
164 | }
165 | }
166 | ?>
--------------------------------------------------------------------------------
/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/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/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/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/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 | ?>
--------------------------------------------------------------------------------
/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/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/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/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/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 | ?>
--------------------------------------------------------------------------------