pgfouine-1.2/ 0000755 0001750 0001750 00000000000 11516212335 011563 5 ustar acme acme pgfouine-1.2/tests/ 0000755 0001750 0001750 00000000000 11516212335 012725 5 ustar acme acme pgfouine-1.2/tests/logs/ 0000755 0001750 0001750 00000000000 11516212335 013671 5 ustar acme acme pgfouine-1.2/tests/logs/TestGenericLogReader/ 0000755 0001750 0001750 00000000000 11516212335 017672 5 ustar acme acme pgfouine-1.2/tests/logs/TestGenericLogReader/testReadLogFile.log 0000644 0001750 0001750 00000000027 10334504440 023407 0 ustar acme acme line1 line2 line3 line4 pgfouine-1.2/tests/logs/TestLogFiles/ 0000755 0001750 0001750 00000000000 11516212335 016235 5 ustar acme acme pgfouine-1.2/tests/logs/TestLogFiles/test_double_duration.log 0000644 0001750 0001750 00000007132 11172430455 023164 0 ustar acme acme 2008 Jan 9 16:16:34 hostname postgres[30059]: [12-1] LOG: duration: 3617.465 ms 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-1] LOG: duration: 3617.465 ms statement: select 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-2] t.tid,t.title,m.name,gn.name,to_char( t.retail_reldate, 'mm-dd-yy' ) as retail_reldate,coalesce(s0c100r0.units,0) as 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-3] w0c100r0units,'NA' as w0c100r0dollars,'NA' as w0c100r0arp,coalesce(s0c1r0.units,0) as w0c1r0units,'NA' as w0c1r0dollars,'NA' as 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-4] w0c1r0arp,coalesce(s0c2r0.units,0) as w0c2r0units,coalesce(s0c2r0.dollars,0) as w0c2r0dollars,arp(s0c2r0.dollars, s0c2r0.units) 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-5] as w0c2r0arp from title t left outer join sublabel sl on t.sublabel_rel = sl.key left outer join label s on sl.lid = s.id left 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-6] outer join label d on s.did = d.id left outer join sale_200601 s0c100r0 on t.tid = s0c100r0.tid and s0c100r0.week = 200601 and 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-7] s0c100r0.channel = 100 and s0c100r0.region = 0 left outer join sale_200601 s0c1r0 on t.tid = s0c1r0.tid and s0c1r0.week = 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-8] 200601 and s0c1r0.channel = 1 and s0c1r0.region = 0 left outer join sale_200601 s0c2r0 on t.tid = s0c2r0.tid and s0c2r0.week = 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-9] 200601 and s0c2r0.channel = 2 and s0c2r0.region = 0 left outer join media m on t.media = m.key left outer join genre_n gn on 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-10] t.genre_n = gn.key where ((((upper(t.title) like '%MATRIX%' or upper(t.artist) like '%MATRIX%') ))) and t.blob in ('L', 'M', 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-11] 'R') and t.source_dvd != 'IN' order by t.title asc limit 100 2008 Jan 9 16:16:34 hostname postgres[30059]: [14-1] LOG: duration: 3.358 ms 2008 Jan 9 16:16:36 hostname postgres[30059]: [15-1] LOG: duration: 1982.460 ms 2008 Jan 9 16:16:36 hostname postgres[30059]: [16-1] LOG: duration: 1982.460 ms statement: select sum(coalesce(s0c100r0.units,0)) as 2008 Jan 9 16:16:36 hostname postgres[30059]: [16-2] w0c100r0units,'' as w0c100r0dollars,'' as w0c100r0arp,sum(coalesce(s0c1r0.units,0)) as w0c1r0units,'' as w0c1r0dollars,'' as 2008 Jan 9 16:16:36 hostname postgres[30059]: [16-3] w0c1r0arp,sum(coalesce(s0c2r0.units,0)) as w0c2r0units,sum(coalesce(s0c2r0.dollars,0)) as w0c2r0dollars,NULL as w0c2r0arp from 2008 Jan 9 16:16:36 hostname postgres[30059]: [16-4] title t left outer join sublabel sl on t.sublabel_rel = sl.key left outer join label s on sl.lid = s.id left outer join label d 2008 Jan 9 16:16:36 hostname postgres[30059]: [16-5] on s.did = d.id left outer join sale_200601 s0c100r0 on t.tid = s0c100r0.tid and s0c100r0.week = 200601 and s0c100r0.channel = 2008 Jan 9 16:16:36 hostname postgres[30059]: [16-6] 100 and s0c100r0.region = 0 left outer join sale_200601 s0c1r0 on t.tid = s0c1r0.tid and s0c1r0.week = 200601 and 2008 Jan 9 16:16:36 hostname postgres[30059]: [16-7] s0c1r0.channel = 1 and s0c1r0.region = 0 left outer join sale_200601 s0c2r0 on t.tid = s0c2r0.tid and s0c2r0.week = 200601 and 2008 Jan 9 16:16:36 hostname postgres[30059]: [16-8] s0c2r0.channel = 2 and s0c2r0.region = 0 where ((((upper(t.title) like '%MATRIX%' or upper(t.artist) like '%MATRIX%') ))) and 2008 Jan 9 16:16:36 hostname postgres[30059]: [16-9] t.blob in ('L', 'M', 'R') and t.source_dvd != 'IN' pgfouine-1.2/tests/logs/TestLogFiles/test_carriage_return.log 0000644 0001750 0001750 00000003665 11172431647 023174 0 ustar acme acme 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-1] LOG: duration: 3617.465 ms statement: 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-2] select 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-3] t.tid,t.title,m.name,gn.name,to_char( t.retail_reldate, 'mm-dd-yy' ) as retail_reldate,coalesce(s0c100r0.units,0) as 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-4] w0c100r0units,'NA' as w0c100r0dollars,'NA' as w0c100r0arp,coalesce(s0c1r0.units,0) as w0c1r0units,'NA' as w0c1r0dollars,'NA' as 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-5] w0c1r0arp,coalesce(s0c2r0.units,0) as w0c2r0units,coalesce(s0c2r0.dollars,0) as w0c2r0dollars,arp(s0c2r0.dollars, s0c2r0.units) 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-6] as w0c2r0arp from title t left outer join sublabel sl on t.sublabel_rel = sl.key left outer join label s on sl.lid = s.id left 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-7] outer join label d on s.did = d.id left outer join sale_200601 s0c100r0 on t.tid = s0c100r0.tid and s0c100r0.week = 200601 and 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-8] s0c100r0.channel = 100 and s0c100r0.region = 0 left outer join sale_200601 s0c1r0 on t.tid = s0c1r0.tid and s0c1r0.week = 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-9] 200601 and s0c1r0.channel = 1 and s0c1r0.region = 0 left outer join sale_200601 s0c2r0 on t.tid = s0c2r0.tid and s0c2r0.week = 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-10] 200601 and s0c2r0.channel = 2 and s0c2r0.region = 0 left outer join media m on t.media = m.key left outer join genre_n gn on 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-11] t.genre_n = gn.key where ((((upper(t.title) like '%MATRIX%' or upper(t.artist) like '%MATRIX%') ))) and t.blob in ('L', 'M', 2008 Jan 9 16:16:34 hostname postgres[30059]: [13-12] 'R') and t.source_dvd != 'IN' order by t.title asc limit 100 2008 Jan 9 16:16:34 hostname postgres[30059]: [14-1] LOG: duration: 3.358 ms pgfouine-1.2/tests/TestSlowestQueryList.class.php 0000644 0001750 0001750 00000002715 10411317325 020727 0 ustar acme acme setDuration(1.2); $query2 = new QueryLogObject(TEST_USER, TEST_DB, ''); $query2->setDuration(1.5); $query3 = new QueryLogObject(TEST_USER, TEST_DB, ''); $query3->setDuration(1.7); $query4 = new QueryLogObject(TEST_USER, TEST_DB, ''); $query4->setDuration(1.3); $list = new SlowestQueryList(2); $list->addQuery($query1); $queries =& $list->getQueries(); $this->assertEqual(1, count($queries)); $this->assertReference($queries['1.2'][0], $query1); $list->addQuery($query2); $queries =& $list->getQueries(); $this->assertEqual(2, count($queries)); $this->assertReference($queries['1.2'][0], $query1); $this->assertReference($queries['1.5'][0], $query2); $list->addQuery($query3); $queries =& $list->getQueries(); $this->assertEqual(2, count($queries)); $this->assertReference($queries['1.5'][0], $query2); $this->assertReference($queries['1.7'][0], $query3); $list->addQuery($query4); $queries =& $list->getQueries(); $this->assertEqual(2, count($queries)); $this->assertReference($queries['1.5'][0], $query2); $this->assertReference($queries['1.7'][0], $query3); } } ?> pgfouine-1.2/tests/TestSyslogPostgreSQLParser.class.php 0000644 0001750 0001750 00000010176 10334504437 021774 0 ustar acme acme parser = new SyslogPostgreSQLParser(); } function testPostgreSQLLineDetection() { $this->assertTrue($this->parser->parse(QUERY_LINE)); $this->assertTrue($this->parser->parse(QUERY_LINE_WITH_DASH_IN_CONNECTION_ID)); $this->assertTrue($this->parser->parse(DURATION_LINE)); $this->assertFalse($this->parser->parse(RANDOM_SYSLOG_LINE)); } function testConnectionId() { $line =& $this->parser->parse(QUERY_LINE_WITH_DASH_IN_CONNECTION_ID); $this->assertEqual('4545', $line->getConnectionId()); } function testCommandNumber() { $line =& $this->parser->parse(QUERY_LINE); $this->assertEqual('2755', $line->getCommandNumber()); } function testCommandNumberWithDash() { $line =& $this->parser->parse(QUERY_LINE_WITH_DASH_IN_CONNECTION_ID); $this->assertEqual('2755', $line->getCommandNumber()); } function testLineNumber() { $line =& $this->parser->parse(QUERY_LINE); $this->assertEqual('1', $line->getLineNumber()); } function testLineNumberWithDash() { $line =& $this->parser->parse(QUERY_LINE_WITH_DASH_IN_CONNECTION_ID); $this->assertEqual('4', $line->getLineNumber()); } function testQueryLineDetection() { $line =& $this->parser->parse(DETECTION_QUERY_LINE_1); $this->assertTrue(is_a($line, 'PostgreSQLQueryStartWithDurationLine')); $line =& $this->parser->parse(DETECTION_QUERY_LINE_2); $this->assertTrue(is_a($line, 'PostgreSQLQueryStartWithDurationLine')); } function testContinuationLineDetection() { $line =& $this->parser->parse(DETECTION_CONTINUATION_LINE); $this->assertTrue(is_a($line, 'PostgreSQLContinuationLine')); } function testStatementLineDetection() { $line =& $this->parser->parse(DETECTION_STATEMENT_LINE); $this->assertTrue(is_a($line, 'PostgreSQLStatementLine')); } function testStatusLineDetection() { $line =& $this->parser->parse(DETECTION_CONNECTION_RECEIVED_LINE); $this->assertTrue(is_a($line, 'PostgreSQLStatusLine')); $line =& $this->parser->parse(DETECTION_CONNECTION_AUTHORIZED_LINE); $this->assertTrue(is_a($line, 'PostgreSQLStatusLine')); } function testErrorLineDetection() { $line =& $this->parser->parse(DETECTION_ERROR_LINE); $this->assertTrue(is_a($line, 'PostgreSQLErrorLine')); } function testDetailLineDetection() { $line =& $this->parser->parse(DETECTION_DETAIL_LINE); $this->assertTrue(is_a($line, 'PostgreSQLDetailLine')); } } ?> pgfouine-1.2/tests/TestCase.class.php 0000644 0001750 0001750 00000002703 11174670072 016265 0 ustar acme acme addTestFile('TestRegExp.class.php'); //$commonTests->addTestFile('TestProfiler.class.php'); $commonTests->addTestFile('TestGenericLogReader.class.php'); $commonTests->addTestFile('TestLogObject.class.php'); $commonTests->addTestFile('TestQueryLogObject.class.php'); $commonTests->addTestFile('TestErrorLogObject.class.php'); $commonTests->addTestFile('TestLogStream.class.php'); $commonTests->addTestFile('TestSlowestQueryList.class.php'); $commonTests->run(new TextReporter()); $postgresqlTests = &new GroupTest('PostgreSQL tests'); $postgresqlTests->addTestFile('TestSyslogPostgreSQLParser.class.php'); $postgresqlTests->addTestFile('TestLogFiles.class.php'); $postgresqlTests->run(new TextReporter()); fclose($stderr); ?> pgfouine-1.2/tests/TestQueryLogObject.class.php 0000644 0001750 0001750 00000010345 10466203202 020277 0 ustar acme acme assertEqual(EVENT_QUERY, $query->getEventType()); $this->assertFalse($query->isIgnored()); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, TEST_TEXT, true); $this->assertTrue($query->isIgnored()); $this->assertEqual(TEST_TEXT, $query->getText()); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, TEST_TEXT, false); $this->assertFalse($query->isIgnored()); } function testSettersAndGetters() { define('TEST_TEXT', 'test text'); define('TEST_DB', 'test_db'); define('TEST_USER', 'test_user'); define('TEST_DURATION', 100); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, TEST_TEXT); $query->setDuration(TEST_DURATION); $this->assertEqual(TEST_DURATION, $query->getDuration()); } function testTypeDetection() { $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, 'select * from mytable'); $this->assertTrue($query->isSelect()); $this->assertFalse($query->isDelete()); $this->assertFalse($query->isInsert()); $this->assertFalse($query->isUpdate()); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, 'SELECT * FROM mytable'); $this->assertTrue($query->isSelect()); $this->assertFalse($query->isDelete()); $this->assertFalse($query->isInsert()); $this->assertFalse($query->isUpdate()); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, 'delete from mytable'); $this->assertFalse($query->isSelect()); $this->assertTrue($query->isDelete()); $this->assertFalse($query->isInsert()); $this->assertFalse($query->isUpdate()); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, 'DELETE FROM mytable'); $this->assertFalse($query->isSelect()); $this->assertTrue($query->isDelete()); $this->assertFalse($query->isInsert()); $this->assertFalse($query->isUpdate()); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, 'insert into mytable values(4)'); $this->assertFalse($query->isSelect()); $this->assertFalse($query->isDelete()); $this->assertTrue($query->isInsert()); $this->assertFalse($query->isUpdate()); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, 'INSERT INTO mytable VALUES(4)'); $this->assertFalse($query->isSelect()); $this->assertFalse($query->isDelete()); $this->assertTrue($query->isInsert()); $this->assertFalse($query->isUpdate()); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, 'update mytable set field=4'); $this->assertFalse($query->isSelect()); $this->assertFalse($query->isDelete()); $this->assertFalse($query->isInsert()); $this->assertTrue($query->isUpdate()); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, 'UPDATE mytable SET field=4'); $this->assertFalse($query->isSelect()); $this->assertFalse($query->isDelete()); $this->assertFalse($query->isInsert()); $this->assertTrue($query->isUpdate()); } function testSubQuery() { define('TEST_TEXT1', 'test text 1'); define('TEST_TEXT2', 'test text 2'); define('TEST_TEXT3', 'test text 3'); define('TEST_TEXT4', 'test text 4'); $query = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, TEST_TEXT1); $query2 = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, TEST_TEXT2); $query3 = new QueryLogObject(TEST_CONNECTION_ID, TEST_USER, TEST_DB, TEST_TEXT3); $query->addSubQuery($query2); $subQueries = $query->getSubQueries(); $this->assertEqual(1, count($subQueries)); $this->assertReference($query2, $subQueries[0]); $query->addSubQuery($query3); $subQueries = $query->getSubQueries(); $this->assertEqual(2, count($subQueries)); $this->assertReference($query2, $subQueries[0]); $this->assertReference($query3, $subQueries[1]); } } ?> pgfouine-1.2/tests/TestLogFiles.class.php 0000644 0001750 0001750 00000026035 11172431647 017123 0 ustar acme acme syslogParser = new SyslogPostgreSQLParser(); $this->logStream = new LogStream(); } function getLinesFromFile($fileName) { $filePath = 'logs/TestLogFiles/'.$fileName; if(is_readable($filePath)) { $lines = file($filePath); } else { $lines = array(); } return $lines; } function testDoubleDuration() { $textLines = $this->getLinesFromFile('test_double_duration.log'); $step = 0; foreach($textLines AS $textLine) { $line =& $this->syslogParser->parse($textLine); $logObject =& $this->logStream->append($line); switch($step) { case 0: $this->checkLine($line, 'PostgreSQLDurationLine', '1199891794', '30059', '12', '1', '', '3.617465'); $this->assertFalse($logObject); break; case 1: $this->checkLine($line, 'PostgreSQLQueryStartWithDurationLine', '1199891794', '30059', '13', '1', 'select', '3.617465'); $this->assertFalse($logObject); break; case 2: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '2', " t.tid,t.title,m.name,gn.name,to_char( t.retail_reldate, 'mm-dd-yy' ) as retail_reldate,coalesce(s0c100r0.units,0) as", false); $this->assertFalse($logObject); break; case 3: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '3', " w0c100r0units,'NA' as w0c100r0dollars,'NA' as w0c100r0arp,coalesce(s0c1r0.units,0) as w0c1r0units,'NA' as w0c1r0dollars,'NA' as", false); $this->assertFalse($logObject); break; case 4: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '4', " w0c1r0arp,coalesce(s0c2r0.units,0) as w0c2r0units,coalesce(s0c2r0.dollars,0) as w0c2r0dollars,arp(s0c2r0.dollars, s0c2r0.units)", false); $this->assertFalse($logObject); break; case 5: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '5', " as w0c2r0arp from title t left outer join sublabel sl on t.sublabel_rel = sl.key left outer join label s on sl.lid = s.id left", false); $this->assertFalse($logObject); break; case 6: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '6', " outer join label d on s.did = d.id left outer join sale_200601 s0c100r0 on t.tid = s0c100r0.tid and s0c100r0.week = 200601 and", false); $this->assertFalse($logObject); break; case 7: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '7', " s0c100r0.channel = 100 and s0c100r0.region = 0 left outer join sale_200601 s0c1r0 on t.tid = s0c1r0.tid and s0c1r0.week =", false); $this->assertFalse($logObject); break; case 8: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '8', " 200601 and s0c1r0.channel = 1 and s0c1r0.region = 0 left outer join sale_200601 s0c2r0 on t.tid = s0c2r0.tid and s0c2r0.week =", false); $this->assertFalse($logObject); break; case 9: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '9', " 200601 and s0c2r0.channel = 2 and s0c2r0.region = 0 left outer join media m on t.media = m.key left outer join genre_n gn on", false); $this->assertFalse($logObject); break; case 10: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '10', " t.genre_n = gn.key where ((((upper(t.title) like '%MATRIX%' or upper(t.artist) like '%MATRIX%') ))) and t.blob in ('L', 'M',", false); $this->assertFalse($logObject); break; case 11: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891794', '30059', '13', '11', " 'R') and t.source_dvd != 'IN' order by t.title asc limit 100", false); $this->assertFalse($logObject); break; case 12: $this->checkLine($line, 'PostgreSQLDurationLine', '1199891794', '30059', '14', '1', '', '0.003358'); $this->checkQueryLogObject($logObject, 'QueryLogObject', 1199891794, 13, "select t.tid,t.title,m.name,gn.name,to_char( t.retail_reldate, 'mm-dd-yy' ) as retail_reldate,coalesce(s0c100r0.units,0) as w0c100r0units,'NA' as w0c100r0dollars,'NA' as w0c100r0arp,coalesce(s0c1r0.units,0) as w0c1r0units,'NA' as w0c1r0dollars,'NA' as w0c1r0arp,coalesce(s0c2r0.units,0) as w0c2r0units,coalesce(s0c2r0.dollars,0) as w0c2r0dollars,arp(s0c2r0.dollars, s0c2r0.units) as w0c2r0arp from title t left outer join sublabel sl on t.sublabel_rel = sl.key left outer join label s on sl.lid = s.id left outer join label d on s.did = d.id left outer join sale_200601 s0c100r0 on t.tid = s0c100r0.tid and s0c100r0.week = 200601 and s0c100r0.channel = 100 and s0c100r0.region = 0 left outer join sale_200601 s0c1r0 on t.tid = s0c1r0.tid and s0c1r0.week = 200601 and s0c1r0.channel = 1 and s0c1r0.region = 0 left outer join sale_200601 s0c2r0 on t.tid = s0c2r0.tid and s0c2r0.week = 200601 and s0c2r0.channel = 2 and s0c2r0.region = 0 left outer join media m on t.media = m.key left outer join genre_n gn on t.genre_n = gn.key where ((((upper(t.title) like '%MATRIX%' or upper(t.artist) like '%MATRIX%') ))) and t.blob in ('L', 'M', 'R') and t.source_dvd != 'IN' order by t.title asc limit 100", '3.617465'); break; case 13: $this->checkLine($line, 'PostgreSQLDurationLine', '1199891796', '30059', '15', '1', '', '1.98246'); $this->checkQueryLogObject($logObject, 'DurationLogObject', 1199891794, 14, false, '0.003358'); break; case 14: $this->checkLine($line, 'PostgreSQLQueryStartWithDurationLine', '1199891796', '30059', '16', '1', 'select sum(coalesce(s0c100r0.units,0)) as', '1.98246'); $this->assertFalse($logObject); break; case 15: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891796', '30059', '16', '2', " w0c100r0units,'' as w0c100r0dollars,'' as w0c100r0arp,sum(coalesce(s0c1r0.units,0)) as w0c1r0units,'' as w0c1r0dollars,'' as", false); $this->assertFalse($logObject); break; case 16: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891796', '30059', '16', '3', " w0c1r0arp,sum(coalesce(s0c2r0.units,0)) as w0c2r0units,sum(coalesce(s0c2r0.dollars,0)) as w0c2r0dollars,NULL as w0c2r0arp from", false); $this->assertFalse($logObject); break; case 17: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891796', '30059', '16', '4', " title t left outer join sublabel sl on t.sublabel_rel = sl.key left outer join label s on sl.lid = s.id left outer join label d", false); $this->assertFalse($logObject); break; case 18: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891796', '30059', '16', '5', " on s.did = d.id left outer join sale_200601 s0c100r0 on t.tid = s0c100r0.tid and s0c100r0.week = 200601 and s0c100r0.channel =", false); $this->assertFalse($logObject); break; case 19: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891796', '30059', '16', '6', " 100 and s0c100r0.region = 0 left outer join sale_200601 s0c1r0 on t.tid = s0c1r0.tid and s0c1r0.week = 200601 and", false); $this->assertFalse($logObject); break; case 20: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891796', '30059', '16', '7', " s0c1r0.channel = 1 and s0c1r0.region = 0 left outer join sale_200601 s0c2r0 on t.tid = s0c2r0.tid and s0c2r0.week = 200601 and", false); $this->assertFalse($logObject); break; case 21: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891796', '30059', '16', '8', " s0c2r0.channel = 2 and s0c2r0.region = 0 where ((((upper(t.title) like '%MATRIX%' or upper(t.artist) like '%MATRIX%') ))) and", false); $this->assertFalse($logObject); break; case 22: $this->checkLine($line, 'PostgreSQLContinuationLine', '1199891796', '30059', '16', '9', " t.blob in ('L', 'M', 'R') and t.source_dvd != 'IN'", false); $this->assertFalse($logObject); break; default: stderrArray($line); break; } unset($line); unset($logObject); $step ++; } } function testCarriageReturn() { $textLines = $this->getLinesFromFile('test_carriage_return.log'); foreach($textLines AS $textLine) { $line =& $this->syslogParser->parse($textLine); $logObject =& $this->logStream->append($line); } $this->checkQueryLogObject($logObject, 'QueryLogObject', 1199891794, 13, "select t.tid,t.title,m.name,gn.name,to_char( t.retail_reldate, 'mm-dd-yy' ) as retail_reldate,coalesce(s0c100r0.units,0) as w0c100r0units,'NA' as w0c100r0dollars,'NA' as w0c100r0arp,coalesce(s0c1r0.units,0) as w0c1r0units,'NA' as w0c1r0dollars,'NA' as w0c1r0arp,coalesce(s0c2r0.units,0) as w0c2r0units,coalesce(s0c2r0.dollars,0) as w0c2r0dollars,arp(s0c2r0.dollars, s0c2r0.units) as w0c2r0arp from title t left outer join sublabel sl on t.sublabel_rel = sl.key left outer join label s on sl.lid = s.id left outer join label d on s.did = d.id left outer join sale_200601 s0c100r0 on t.tid = s0c100r0.tid and s0c100r0.week = 200601 and s0c100r0.channel = 100 and s0c100r0.region = 0 left outer join sale_200601 s0c1r0 on t.tid = s0c1r0.tid and s0c1r0.week = 200601 and s0c1r0.channel = 1 and s0c1r0.region = 0 left outer join sale_200601 s0c2r0 on t.tid = s0c2r0.tid and s0c2r0.week = 200601 and s0c2r0.channel = 2 and s0c2r0.region = 0 left outer join media m on t.media = m.key left outer join genre_n gn on t.genre_n = gn.key where ((((upper(t.title) like '%MATRIX%' or upper(t.artist) like '%MATRIX%') ))) and t.blob in ('L', 'M', 'R') and t.source_dvd != 'IN' order by t.title asc limit 100", '3.617465'); } function checkLine(& $line, $type, $timestamp, $connectionId, $commandNumber, $lineNumber, $text, $duration, $ignore = false, $database = false, $user = false) { $this->assertIsA($line, $type); $this->assertEqual($timestamp, $line->getTimestamp()); $this->assertEqual($connectionId, $line->getConnectionId()); $this->assertEqual($commandNumber, $line->getCommandNumber()); $this->assertEqual($lineNumber, $line->getLineNumber()); $this->assertEqual($text, $line->getText()); $this->assertEqual(0, bccomp($duration, $line->getDuration())); $this->assertEqual($ignore, $line->isIgnored()); $this->assertEqual($database, $line->getDatabase()); $this->assertEqual($user, $line->getUser()); } function checkQueryLogObject(& $logObject, $type, $timestamp, $commandNumber, $text, $duration, $ignored = false, $database = false, $user = false, $context = false, $subQueries = array()) { $this->assertIsA($logObject, $type); $this->assertEqual($timestamp, $logObject->getTimestamp()); $this->assertEqual($commandNumber, $logObject->getCommandNumber()); $this->assertEqual($text, $logObject->getText()); $this->assertEqual(0, bccomp($duration, $logObject->getDuration())); $this->assertEqual($ignored, $logObject->isIgnored()); $this->assertEqual($database, $logObject->getDatabase()); $this->assertEqual($user, $logObject->getUser()); $this->assertEqual($context, $logObject->getContext()); if($type == 'QueryLogObject') { $this->assertEqual($subQueries, $logObject->getSubQueries()); } } } ?> pgfouine-1.2/tests/TestProfiler.class.php 0000644 0001750 0001750 00000014710 10341157520 017166 0 ustar acme acme assertTrue(is_float(getTime(microtime()))); } function testStage() { define('TEST_PROFILER_STAGE', 'stage1'); $profiler = new Profiler(); $profiler->start(); $profiler->startStage(TEST_PROFILER_STAGE); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE); $profiler->end(); $stages = $profiler->getStages(); $this->assertTrue(isset($stages[TEST_PROFILER_STAGE])); $this->assertEqual(1, $stages[TEST_PROFILER_STAGE]['count']); $this->assertTrue($stages[TEST_PROFILER_STAGE]['duration'] > 1); $this->assertTrue($stages[TEST_PROFILER_STAGE]['duration'] < 2); } function testTwoStages() { define('TEST_PROFILER_STAGE_1', 'stage1'); define('TEST_PROFILER_STAGE_2', 'stage2'); $profiler = new Profiler(); $profiler->start(); $profiler->startStage(TEST_PROFILER_STAGE_1); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_1); $profiler->startStage(TEST_PROFILER_STAGE_2); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_2); $profiler->end(); $stages = $profiler->getStages(); $this->assertTrue(isset($stages[TEST_PROFILER_STAGE_1])); $this->assertEqual(1, $stages[TEST_PROFILER_STAGE_1]['count']); $this->assertTrue($stages[TEST_PROFILER_STAGE_1]['duration'] > 1); $this->assertTrue($stages[TEST_PROFILER_STAGE_1]['duration'] < 2); $this->assertTrue(isset($stages[TEST_PROFILER_STAGE_2])); $this->assertEqual(1, $stages[TEST_PROFILER_STAGE_2]['count']); $this->assertTrue($stages[TEST_PROFILER_STAGE_2]['duration'] > 1); $this->assertTrue($stages[TEST_PROFILER_STAGE_2]['duration'] < 2); } function testTwoIdenticalStages() { define('TEST_PROFILER_STAGE_1', 'stage1'); $profiler = new Profiler(); $profiler->start(); $profiler->startStage(TEST_PROFILER_STAGE_1); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_1); $profiler->startStage(TEST_PROFILER_STAGE_1); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_1); $profiler->end(); $stages = $profiler->getStages(); $this->assertTrue(isset($stages[TEST_PROFILER_STAGE_1])); $this->assertEqual(2, $stages[TEST_PROFILER_STAGE_1]['count']); $this->assertTrue($stages[TEST_PROFILER_STAGE_1]['duration'] > 2); $this->assertTrue($stages[TEST_PROFILER_STAGE_1]['duration'] < 3); } function testInnerStages() { define('TEST_PROFILER_STAGE_1', 'stage1'); define('TEST_PROFILER_STAGE_2', 'stage2'); define('TEST_PROFILER_STAGE_3', 'stage3'); define('TEST_PROFILER_STAGE_4', 'stage4'); $profiler = new Profiler(); $profiler->start(); $profiler->startStage(TEST_PROFILER_STAGE_1); sleep(1); $profiler->startStage(TEST_PROFILER_STAGE_2); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_2); $profiler->startStage(TEST_PROFILER_STAGE_3); sleep(1); $profiler->startStage(TEST_PROFILER_STAGE_4); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_4); $profiler->endStage(TEST_PROFILER_STAGE_3); $profiler->startStage(TEST_PROFILER_STAGE_2); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_2); $profiler->endStage(TEST_PROFILER_STAGE_1); $profiler->startStage(TEST_PROFILER_STAGE_1); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_1); $profiler->end(); $stages = $profiler->getStages(); $this->assertTrue(isset($stages[TEST_PROFILER_STAGE_1])); $this->assertEqual(2, $stages[TEST_PROFILER_STAGE_1]['count']); $this->assertTrue($stages[TEST_PROFILER_STAGE_1]['duration'] > 6); $this->assertTrue($stages[TEST_PROFILER_STAGE_1]['duration'] < 7); $this->assertTrue(isset($stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_2])); $this->assertEqual(2, $stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_2]['count']); $this->assertTrue($stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_2]['duration'] > 2); $this->assertTrue($stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_2]['duration'] < 3); $this->assertTrue(isset($stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_3])); $this->assertEqual(1, $stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_3]['count']); $this->assertTrue($stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_3]['duration'] > 2); $this->assertTrue($stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_3]['duration'] < 3); $this->assertTrue(isset($stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_3.'>'.TEST_PROFILER_STAGE_4])); $this->assertEqual(1, $stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_3.'>'.TEST_PROFILER_STAGE_4]['count']); $this->assertTrue($stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_3.'>'.TEST_PROFILER_STAGE_4]['duration'] > 1); $this->assertTrue($stages[TEST_PROFILER_STAGE_1.'>'.TEST_PROFILER_STAGE_3.'>'.TEST_PROFILER_STAGE_4]['duration'] < 2); } function testTags() { define('TEST_PROFILER_STAGE_1', 'stage1'); define('TEST_PROFILER_STAGE_2', 'stage2'); define('TEST_PROFILER_STAGE_3', 'stage3'); define('TEST_PROFILER_STAGE_4', 'stage4'); define('TEST_PROFILER_TAG_1', 'tag1'); define('TEST_PROFILER_TAG_2', 'tag2'); $profiler = new Profiler(); $profiler->start(); $profiler->startStage(TEST_PROFILER_STAGE_1); sleep(1); $profiler->startStage(TEST_PROFILER_STAGE_2); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_2, TEST_PROFILER_TAG_1); $profiler->startStage(TEST_PROFILER_STAGE_3); sleep(1); $profiler->startStage(TEST_PROFILER_STAGE_4); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_4); $profiler->endStage(TEST_PROFILER_STAGE_3, TEST_PROFILER_TAG_1); $profiler->startStage(TEST_PROFILER_STAGE_2); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_2, TEST_PROFILER_TAG_2); $profiler->endStage(TEST_PROFILER_STAGE_1); $profiler->startStage(TEST_PROFILER_STAGE_1); sleep(1); $profiler->endStage(TEST_PROFILER_STAGE_1); $profiler->end(); $tags = $profiler->getTags(); $this->assertTrue(isset($tags[TEST_PROFILER_TAG_1])); $this->assertEqual(2, $tags[TEST_PROFILER_TAG_1]['count']); $this->assertTrue($tags[TEST_PROFILER_TAG_1]['duration'] > 3); $this->assertTrue($tags[TEST_PROFILER_TAG_1]['duration'] < 4); $this->assertTrue(isset($tags[TEST_PROFILER_TAG_2])); $this->assertEqual(1, $tags[TEST_PROFILER_TAG_2]['count']); $this->assertTrue($tags[TEST_PROFILER_TAG_2]['duration'] > 1); $this->assertTrue($tags[TEST_PROFILER_TAG_2]['duration'] < 2); } } ?> pgfouine-1.2/tests/simpletest/ 0000755 0001750 0001750 00000000000 11516212335 015116 5 ustar acme acme pgfouine-1.2/tests/simpletest/frames.php 0000644 0001750 0001750 00000057614 10334504436 017124 0 ustar acme acme _frameset = &$page; $this->_frames = array(); $this->_focus = false; $this->_names = array(); } /** * Adds a parsed page to the frameset. * @param SimplePage $page Frame page. * @param string $name Name of frame in frameset. * @access public */ function addFrame(&$page, $name = false) { $this->_frames[] = &$page; if ($name) { $this->_names[$name] = count($this->_frames) - 1; } } /** * Replaces existing frame with another. If the * frame is nested, then the call is passed down * one level. * @param array $path Path of frame in frameset. * @param SimplePage $page Frame source. * @access public */ function setFrame($path, &$page) { $name = array_shift($path); if (isset($this->_names[$name])) { $index = $this->_names[$name]; } else { $index = $name - 1; } if (count($path) == 0) { $this->_frames[$index] = &$page; return; } $this->_frames[$index]->setFrame($path, $page); } /** * Accessor for current frame focus. Will be * false if no frame has focus. Will have the nested * frame focus if any. * @return array Labels or indexes of nested frames. * @access public */ function getFrameFocus() { if ($this->_focus === false) { return array(); } return array_merge( array($this->_getPublicNameFromIndex($this->_focus)), $this->_frames[$this->_focus]->getFrameFocus()); } /** * Turns an internal array index into the frames list * into a public name, or if none, then a one offset * index. * @param integer $subject Internal index. * @return integer/string Public name. * @access private */ function _getPublicNameFromIndex($subject) { foreach ($this->_names as $name => $index) { if ($subject == $index) { return $name; } } return $subject + 1; } /** * Sets the focus by index. The integer index starts from 1. * If already focused and the target frame also has frames, * then the nested frame will be focused. * @param integer $choice Chosen frame. * @return boolean True if frame exists. * @access public */ function setFrameFocusByIndex($choice) { if (is_integer($this->_focus)) { if ($this->_frames[$this->_focus]->hasFrames()) { return $this->_frames[$this->_focus]->setFrameFocusByIndex($choice); } } if (($choice < 1) || ($choice > count($this->_frames))) { return false; } $this->_focus = $choice - 1; return true; } /** * Sets the focus by name. If already focused and the * target frame also has frames, then the nested frame * will be focused. * @param string $name Chosen frame. * @return boolean True if frame exists. * @access public */ function setFrameFocus($name) { if (is_integer($this->_focus)) { if ($this->_frames[$this->_focus]->hasFrames()) { return $this->_frames[$this->_focus]->setFrameFocus($name); } } if (in_array($name, array_keys($this->_names))) { $this->_focus = $this->_names[$name]; return true; } return false; } /** * Clears the frame focus. * @access public */ function clearFrameFocus() { $this->_focus = false; $this->_clearNestedFramesFocus(); } /** * Clears the frame focus for any nested frames. * @access private */ function _clearNestedFramesFocus() { for ($i = 0; $i < count($this->_frames); $i++) { $this->_frames[$i]->clearFrameFocus(); } } /** * Test for the presence of a frameset. * @return boolean Always true. * @access public */ function hasFrames() { return true; } /** * Accessor for frames information. * @return array/string Recursive hash of frame URL strings. * The key is either a numerical * index or the name attribute. * @access public */ function getFrames() { $report = array(); for ($i = 0; $i < count($this->_frames); $i++) { $report[$this->_getPublicNameFromIndex($i)] = $this->_frames[$i]->getFrames(); } return $report; } /** * Accessor for raw text of either all the pages or * the frame in focus. * @return string Raw unparsed content. * @access public */ function getRaw() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getRaw(); } $raw = ''; for ($i = 0; $i < count($this->_frames); $i++) { $raw .= $this->_frames[$i]->getRaw(); } return $raw; } /** * Accessor for plain text of either all the pages or * the frame in focus. * @return string Plain text content. * @access public */ function getText() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getText(); } $raw = ''; for ($i = 0; $i < count($this->_frames); $i++) { $raw .= ' ' . $this->_frames[$i]->getText(); } return trim($raw); } /** * Accessor for last error. * @return string Error from last response. * @access public */ function getTransportError() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getTransportError(); } return $this->_frameset->getTransportError(); } /** * Request method used to fetch this frame. * @return string GET, POST or HEAD. * @access public */ function getMethod() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getMethod(); } return $this->_frameset->getMethod(); } /** * Original resource name. * @return SimpleUrl Current url. * @access public */ function getUrl() { if (is_integer($this->_focus)) { $url = $this->_frames[$this->_focus]->getUrl(); $url->setTarget($this->_getPublicNameFromIndex($this->_focus)); } else { $url = $this->_frameset->getUrl(); } return $url; } /** * Original request data. * @return mixed Sent content. * @access public */ function getRequestData() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getRequestData(); } return $this->_frameset->getRequestData(); } /** * Accessor for current MIME type. * @return string MIME type as string; e.g. 'text/html' * @access public */ function getMimeType() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getMimeType(); } return $this->_frameset->getMimeType(); } /** * Accessor for last response code. * @return integer Last HTTP response code received. * @access public */ function getResponseCode() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getResponseCode(); } return $this->_frameset->getResponseCode(); } /** * Accessor for last Authentication type. Only valid * straight after a challenge (401). * @return string Description of challenge type. * @access public */ function getAuthentication() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getAuthentication(); } return $this->_frameset->getAuthentication(); } /** * Accessor for last Authentication realm. Only valid * straight after a challenge (401). * @return string Name of security realm. * @access public */ function getRealm() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getRealm(); } return $this->_frameset->getRealm(); } /** * Accessor for outgoing header information. * @return string Header block. * @access public */ function getRequest() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getRequest(); } return $this->_frameset->getRequest(); } /** * Accessor for raw header information. * @return string Header block. * @access public */ function getHeaders() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getHeaders(); } return $this->_frameset->getHeaders(); } /** * Accessor for parsed title. * @return string Title or false if no title is present. * @access public */ function getTitle() { return $this->_frameset->getTitle(); } /** * Accessor for a list of all fixed links. * @return array List of urls with scheme of * http or https and hostname. * @access public */ function getAbsoluteUrls() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getAbsoluteUrls(); } $urls = array(); foreach ($this->_frames as $frame) { $urls = array_merge($urls, $frame->getAbsoluteUrls()); } return array_values(array_unique($urls)); } /** * Accessor for a list of all relative links. * @return array List of urls without hostname. * @access public */ function getRelativeUrls() { if (is_integer($this->_focus)) { return $this->_frames[$this->_focus]->getRelativeUrls(); } $urls = array(); foreach ($this->_frames as $frame) { $urls = array_merge($urls, $frame->getRelativeUrls()); } return array_values(array_unique($urls)); } /** * Accessor for URLs by the link label. Label will match * regardess of whitespace issues and case. * @param string $label Text of link. * @return array List of links with that label. * @access public */ function getUrlsByLabel($label) { if (is_integer($this->_focus)) { return $this->_tagUrlsWithFrame( $this->_frames[$this->_focus]->getUrlsByLabel($label), $this->_focus); } $urls = array(); foreach ($this->_frames as $index => $frame) { $urls = array_merge( $urls, $this->_tagUrlsWithFrame( $frame->getUrlsByLabel($label), $index)); } return $urls; } /** * Accessor for a URL by the id attribute. If in a frameset * then the first link found with that ID attribute is * returned only. Focus on a frame if you want one from * a specific part of the frameset. * @param string $id Id attribute of link. * @return string URL with that id. * @access public */ function getUrlById($id) { foreach ($this->_frames as $index => $frame) { if ($url = $frame->getUrlById($id)) { if (! $url->gettarget()) { $url->setTarget($this->_getPublicNameFromIndex($index)); } return $url; } } return false; } /** * Attaches the intended frame index to a list of URLs. * @param array $urls List of SimpleUrls. * @param string $frame Name of frame or index. * @return array List of tagged URLs. * @access private */ function _tagUrlsWithFrame($urls, $frame) { $tagged = array(); foreach ($urls as $url) { if (! $url->getTarget()) { $url->setTarget($this->_getPublicNameFromIndex($frame)); } $tagged[] = $url; } return $tagged; } /** * Finds a held form by button label. Will only * search correctly built forms. The first form found * either within the focused frame, or across frames, * will be the one returned. * @param string $label Button label, default 'Submit'. * @return SimpleForm Form object containing the button. * @access public */ function &getFormBySubmitLabel($label) { return $this->_findForm('getFormBySubmitLabel', $label); } /** * Finds a held form by button label. Will only * search correctly built forms. The first form found * either within the focused frame, or across frames, * will be the one returned. * @param string $name Button name attribute. * @return SimpleForm Form object containing the button. * @access public */ function &getFormBySubmitName($name) { return $this->_findForm('getFormBySubmitName', $name); } /** * Finds a held form by button id. Will only * search correctly built forms. The first form found * either within the focused frame, or across frames, * will be the one returned. * @param string $id Button ID attribute. * @return SimpleForm Form object containing the button. * @access public */ function &getFormBySubmitId($id) { return $this->_findForm('getFormBySubmitId', $id); } /** * Finds a held form by image label. Will only * search correctly built forms. The first form found * either within the focused frame, or across frames, * will be the one returned. * @param string $label Usually the alt attribute. * @return SimpleForm Form object containing the image. * @access public */ function &getFormByImageLabel($label) { return $this->_findForm('getFormByImageLabel', $label); } /** * Finds a held form by image button id. Will only * search correctly built forms. The first form found * either within the focused frame, or across frames, * will be the one returned. * @param string $name Image name. * @return SimpleForm Form object containing the image. * @access public */ function &getFormByImageName($name) { return $this->_findForm('getFormByImageName', $name); } /** * Finds a held form by image button id. Will only * search correctly built forms. The first form found * either within the focused frame, or across frames, * will be the one returned. * @param string $id Image ID attribute. * @return SimpleForm Form object containing the image. * @access public */ function &getFormByImageId($id) { return $this->_findForm('getFormByImageId', $id); } /** * Finds a held form by the form ID. A way of * identifying a specific form when we have control * of the HTML code. The first form found * either within the focused frame, or across frames, * will be the one returned. * @param string $id Form label. * @return SimpleForm Form object containing the matching ID. * @access public */ function &getFormById($id) { return $this->_findForm('getFormById', $id); } /** * General form finder. Will search all the frames or * just the one in focus. * @param string $method Method to use to find in a page. * @param string $attribute Label, name or ID. * @return SimpleForm Form object containing the matching ID. * @access private */ function &_findForm($method, $attribute) { if (is_integer($this->_focus)) { return $this->_findFormInFrame( $this->_frames[$this->_focus], $this->_focus, $method, $attribute); } for ($i = 0; $i < count($this->_frames); $i++) { $form = &$this->_findFormInFrame( $this->_frames[$i], $i, $method, $attribute); if ($form) { return $form; } } return null; } /** * Finds a form in a page using a form finding method. Will * also tag the form with the frame name it belongs in. * @param SimplePage $page Page content of frame. * @param integer $index Internal frame representation. * @param string $method Method to use to find in a page. * @param string $attribute Label, name or ID. * @return SimpleForm Form object containing the matching ID. * @access private */ function &_findFormInFrame(&$page, $index, $method, $attribute) { $form = &$this->_frames[$index]->$method($attribute); if (isset($form)) { $form->setDefaultTarget($this->_getPublicNameFromIndex($index)); } return $form; } /** * Sets a field on each form in which the field is * available. * @param string $name Field name. * @param string $value Value to set field to. * @return boolean True if value is valid. * @access public */ function setField($name, $value) { if (is_integer($this->_focus)) { $this->_frames[$this->_focus]->setField($name, $value); } else { for ($i = 0; $i < count($this->_frames); $i++) { $this->_frames[$i]->setField($name, $value); } } } /** * Sets a field on the form in which the unique field is * available. * @param string/integer $id Field ID attribute. * @param string $value Value to set field to. * @return boolean True if value is valid. * @access public */ function setFieldById($id, $value) { if (is_integer($this->_focus)) { $this->_frames[$this->_focus]->setFieldById($id, $value); } else { for ($i = 0; $i < count($this->_frames); $i++) { $this->_frames[$i]->setFieldById($id, $value); } } } /** * Accessor for a form element value within a frameset. * Finds the first match amongst the frames. * @param string $name Field name. * @return string/boolean A string if the field is * present, false if unchecked * and null if missing. * @access public */ function getField($name) { for ($i = 0; $i < count($this->_frames); $i++) { $value = $this->_frames[$i]->getField($name); if (isset($value)) { return $value; } } return null; } /** * Accessor for a form element value within a page. * Finds the first match. * @param string/integer $id Field ID attribute. * @return string/boolean A string if the field is * present, false if unchecked * and null if missing. * @access public */ function getFieldById($id) { for ($i = 0; $i < count($this->_frames); $i++) { $value = $this->_frames[$i]->getFieldById($id); if (isset($value)) { return $value; } } return null; } } ?> pgfouine-1.2/tests/simpletest/mock_objects.php 0000644 0001750 0001750 00000152147 10334504436 020306 0 ustar acme acme SimpleExpectation(); } /** * Tests the expectation. Always true. * @param mixed $compare Ignored. * @return boolean True. * @access public */ function test($compare) { return true; } /** * Returns a human readable test message. * @param mixed $compare Comparison value. * @return string Description of success * or failure. * @access public */ function testMessage($compare) { $dumper = &$this->_getDumper(); return 'Wildcard always matches [' . $dumper->describeValue($compare) . ']'; } } /** * Parameter comparison assertion. * @package SimpleTest * @subpackage MockObjects */ class ParametersExpectation extends SimpleExpectation { var $_expected; /** * Sets the expected parameter list. * @param array $parameters Array of parameters including * those that are wildcarded. * If the value is not an array * then it is considered to match any. * @param mixed $wildcard Any parameter matching this * will always match. * @param string $message Customised message on failure. * @access public */ function ParametersExpectation($expected = false, $message = '%s') { $this->SimpleExpectation($message); $this->_expected = $expected; } /** * Tests the assertion. True if correct. * @param array $parameters Comparison values. * @return boolean True if correct. * @access public */ function test($parameters) { if (! is_array($this->_expected)) { return true; } if (count($this->_expected) != count($parameters)) { return false; } for ($i = 0; $i < count($this->_expected); $i++) { if (! $this->_testParameter($parameters[$i], $this->_expected[$i])) { return false; } } return true; } /** * Tests an individual parameter. * @param mixed $parameter Value to test. * @param mixed $expected Comparison value. * @return boolean True if expectation * fulfilled. * @access private */ function _testParameter($parameter, $expected) { $comparison = $this->_coerceToExpectation($expected); return $comparison->test($parameter); } /** * Returns a human readable test message. * @param array $comparison Incoming parameter list. * @return string Description of success * or failure. * @access public */ function testMessage($parameters) { if ($this->test($parameters)) { return "Expectation of " . count($this->_expected) . " arguments of [" . $this->_renderArguments($this->_expected) . "] is correct"; } else { return $this->_describeDifference($this->_expected, $parameters); } } /** * Message to display if expectation differs from * the parameters actually received. * @param array $expected Expected parameters as list. * @param array $parameters Actual parameters received. * @return string Description of difference. * @access private */ function _describeDifference($expected, $parameters) { if (count($expected) != count($parameters)) { return "Expected " . count($expected) . " arguments of [" . $this->_renderArguments($expected) . "] but got " . count($parameters) . " arguments of [" . $this->_renderArguments($parameters) . "]"; } $messages = array(); for ($i = 0; $i < count($expected); $i++) { $comparison = $this->_coerceToExpectation($expected[$i]); if (! $comparison->test($parameters[$i])) { $messages[] = "parameter " . ($i + 1) . " with [" . $comparison->overlayMessage($parameters[$i]) . "]"; } } return "Parameter expectation differs at " . implode(" and ", $messages); } /** * Creates an identical expectation if the * object/value is not already some type * of expectation. * @param mixed $expected Expected value. * @return SimpleExpectation Expectation object. * @access private */ function _coerceToExpectation($expected) { if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) { return $expected; } return new IdenticalExpectation($expected); } /** * Renders the argument list as a string for * messages. * @param array $args Incoming arguments. * @return string Simple description of type and value. * @access private */ function _renderArguments($args) { $descriptions = array(); if (is_array($args)) { foreach ($args as $arg) { $dumper = &new SimpleDumper(); $descriptions[] = $dumper->describeValue($arg); } } return implode(', ', $descriptions); } } /** * Confirms that the number of calls on a method is as expected. */ class CallCountExpectation extends SimpleExpectation { var $_method; var $_count; /** * Stashes the method and expected count for later * reporting. * @param string $method Name of method to confirm against. * @param integer $count Expected number of calls. * @param string $message Custom error message. */ function CallCountExpectation($method, $count, $message = '%s') { $this->_method = $method; $this->_count = $count; $this->SimpleExpectation($message); } /** * Tests the assertion. True if correct. * @param integer $compare Measured call count. * @return boolean True if expected. * @access public */ function test($compare) { return ($this->_count == $compare); } /** * Reports the comparison. * @param integer $compare Measured call count. * @return string Message to show. * @access public */ function testMessage($compare) { return 'Expected call count for [' . $this->_method . '] was [' . $this->_count . '] got [' . $compare . ']'; } } /** * Confirms that the number of calls on a method is as expected. */ class MinimumCallCountExpectation extends SimpleExpectation { var $_method; var $_count; /** * Stashes the method and expected count for later * reporting. * @param string $method Name of method to confirm against. * @param integer $count Minimum number of calls. * @param string $message Custom error message. */ function MinimumCallCountExpectation($method, $count, $message = '%s') { $this->_method = $method; $this->_count = $count; $this->SimpleExpectation($message); } /** * Tests the assertion. True if correct. * @param integer $compare Measured call count. * @return boolean True if enough. * @access public */ function test($compare) { return ($this->_count <= $compare); } /** * Reports the comparison. * @param integer $compare Measured call count. * @return string Message to show. * @access public */ function testMessage($compare) { return 'Minimum call count for [' . $this->_method . '] was [' . $this->_count . '] got [' . $compare . ']'; } } /** * Confirms that the number of calls on a method is as expected. */ class MaximumCallCountExpectation extends SimpleExpectation { var $_method; var $_count; /** * Stashes the method and expected count for later * reporting. * @param string $method Name of method to confirm against. * @param integer $count Minimum number of calls. * @param string $message Custom error message. */ function MaximumCallCountExpectation($method, $count, $message = '%s') { $this->_method = $method; $this->_count = $count; $this->SimpleExpectation($message); } /** * Tests the assertion. True if correct. * @param integer $compare Measured call count. * @return boolean True if not over. * @access public */ function test($compare) { return ($this->_count >= $compare); } /** * Reports the comparison. * @param integer $compare Measured call count. * @return string Message to show. * @access public */ function testMessage($compare) { return 'Maximum call count for [' . $this->_method . '] was [' . $this->_count . '] got [' . $compare . ']'; } } /** * Retrieves values and references by searching the * parameter lists until a match is found. * @package SimpleTest * @subpackage MockObjects */ class CallMap { var $_map; /** * Creates an empty call map. * @access public */ function CallMap() { $this->_map = array(); } /** * Stashes a value against a method call. * @param array $parameters Arguments including wildcards. * @param mixed $value Value copied into the map. * @access public */ function addValue($parameters, $value) { $this->addReference($parameters, $value); } /** * Stashes a reference against a method call. * @param array $parameters Array of arguments (including wildcards). * @param mixed $reference Array reference placed in the map. * @access public */ function addReference($parameters, &$reference) { $place = count($this->_map); $this->_map[$place] = array(); $this->_map[$place]["params"] = new ParametersExpectation($parameters); $this->_map[$place]["content"] = &$reference; } /** * Searches the call list for a matching parameter * set. Returned by reference. * @param array $parameters Parameters to search by * without wildcards. * @return object Object held in the first matching * slot, otherwise null. * @access public */ function &findFirstMatch($parameters) { $slot = $this->_findFirstSlot($parameters); if (!isset($slot)) { return null; } return $slot["content"]; } /** * Searches the call list for a matching parameter * set. True if successful. * @param array $parameters Parameters to search by * without wildcards. * @return boolean True if a match is present. * @access public */ function isMatch($parameters) { return ($this->_findFirstSlot($parameters) != null); } /** * Searches the map for a matching item. * @param array $parameters Parameters to search by * without wildcards. * @return array Reference to slot or null. * @access private */ function &_findFirstSlot($parameters) { $count = count($this->_map); for ($i = 0; $i < $count; $i++) { if ($this->_map[$i]["params"]->test($parameters)) { return $this->_map[$i]; } } return null; } } /** * An empty collection of methods that can have their * return values set. Used for prototyping. * @package SimpleTest * @subpackage MockObjects */ class SimpleStub { var $_wildcard; var $_is_strict; var $_returns; var $_return_sequence; var $_call_counts; /** * Sets up the wildcard and everything else empty. * @param mixed $wildcard Parameter matching wildcard. * @param boolean $is_strict Enables method name checks. * @access public */ function SimpleStub($wildcard, $is_strict = true) { $this->_wildcard = $wildcard; $this->_is_strict = $is_strict; $this->_returns = array(); $this->_return_sequence = array(); $this->_call_counts = array(); } /** * Replaces wildcard matches with wildcard * expectations in the argument list. * @param array $args Raw argument list. * @return array Argument list with * expectations. * @access private */ function _replaceWildcards($args) { if ($args === false) { return false; } for ($i = 0; $i < count($args); $i++) { if ($args[$i] === $this->_wildcard) { $args[$i] = new WildcardExpectation(); } } return $args; } /** * Returns the expected value for the method name. * @param string $method Name of method to simulate. * @param array $args Arguments as an array. * @return mixed Stored return. * @access private */ function &_invoke($method, $args) { $method = strtolower($method); $step = $this->getCallCount($method); $this->_addCall($method, $args); return $this->_getReturn($method, $args, $step); } /** * Triggers a PHP error if the method is not part * of this object. * @param string $method Name of method. * @param string $task Description of task attempt. * @access protected */ function _dieOnNoMethod($method, $task) { if ($this->_is_strict && !method_exists($this, $method)) { trigger_error( "Cannot $task as no ${method}() in class " . get_class($this), E_USER_ERROR); } } /** * Adds one to the call count of a method. * @param string $method Method called. * @param array $args Arguments as an array. * @access protected */ function _addCall($method, $args) { if (!isset($this->_call_counts[$method])) { $this->_call_counts[$method] = 0; } $this->_call_counts[$method]++; } /** * Fetches the call count of a method so far. * @param string $method Method name called. * @return Number of calls so far. * @access public */ function getCallCount($method) { $this->_dieOnNoMethod($method, "get call count"); $method = strtolower($method); if (! isset($this->_call_counts[$method])) { return 0; } return $this->_call_counts[$method]; } /** * Sets a return for a parameter list that will * be passed by value for all calls to this method. * @param string $method Method name. * @param mixed $value Result of call passed by value. * @param array $args List of parameters to match * including wildcards. * @access public */ function setReturnValue($method, $value, $args = false) { $this->_dieOnNoMethod($method, "set return value"); $args = $this->_replaceWildcards($args); $method = strtolower($method); if (! isset($this->_returns[$method])) { $this->_returns[$method] = new CallMap(); } $this->_returns[$method]->addValue($args, $value); } /** * Sets a return for a parameter list that will * be passed by value only when the required call count * is reached. * @param integer $timing Number of calls in the future * to which the result applies. If * not set then all calls will return * the value. * @param string $method Method name. * @param mixed $value Result of call passed by value. * @param array $args List of parameters to match * including wildcards. * @access public */ function setReturnValueAt($timing, $method, $value, $args = false) { $this->_dieOnNoMethod($method, "set return value sequence"); $args = $this->_replaceWildcards($args); $method = strtolower($method); if (! isset($this->_return_sequence[$method])) { $this->_return_sequence[$method] = array(); } if (! isset($this->_return_sequence[$method][$timing])) { $this->_return_sequence[$method][$timing] = new CallMap(); } $this->_return_sequence[$method][$timing]->addValue($args, $value); } /** * Sets a return for a parameter list that will * be passed by reference for all calls. * @param string $method Method name. * @param mixed $reference Result of the call will be this object. * @param array $args List of parameters to match * including wildcards. * @access public */ function setReturnReference($method, &$reference, $args = false) { $this->_dieOnNoMethod($method, "set return reference"); $args = $this->_replaceWildcards($args); $method = strtolower($method); if (! isset($this->_returns[$method])) { $this->_returns[$method] = new CallMap(); } $this->_returns[$method]->addReference($args, $reference); } /** * Sets a return for a parameter list that will * be passed by value only when the required call count * is reached. * @param integer $timing Number of calls in the future * to which the result applies. If * not set then all calls will return * the value. * @param string $method Method name. * @param mixed $reference Result of the call will be this object. * @param array $args List of parameters to match * including wildcards. * @access public */ function setReturnReferenceAt($timing, $method, &$reference, $args = false) { $this->_dieOnNoMethod($method, "set return reference sequence"); $args = $this->_replaceWildcards($args); $method = strtolower($method); if (! isset($this->_return_sequence[$method])) { $this->_return_sequence[$method] = array(); } if (! isset($this->_return_sequence[$method][$timing])) { $this->_return_sequence[$method][$timing] = new CallMap(); } $this->_return_sequence[$method][$timing]->addReference($args, $reference); } /** * Finds the return value matching the incoming * arguments. If there is no matching value found * then an error is triggered. * @param string $method Method name. * @param array $args Calling arguments. * @param integer $step Current position in the * call history. * @return mixed Stored return. * @access protected */ function &_getReturn($method, $args, $step) { if (isset($this->_return_sequence[$method][$step])) { if ($this->_return_sequence[$method][$step]->isMatch($args)) { return $this->_return_sequence[$method][$step]->findFirstMatch($args); } } if (isset($this->_returns[$method])) { return $this->_returns[$method]->findFirstMatch($args); } return null; } } /** * An empty collection of methods that can have their * return values set and expectations made of the * calls upon them. The mock will assert the * expectations against it's attached test case in * addition to the server stub behaviour. * @package SimpleTest * @subpackage MockObjects */ class SimpleMock extends SimpleStub { var $_test; var $_expected_counts; var $_max_counts; var $_expected_args; var $_expected_args_at; /** * Creates an empty return list and expectation list. * All call counts are set to zero. * @param SimpleTestCase $test Test case to test expectations in. * @param mixed $wildcard Parameter matching wildcard. * @param boolean $is_strict Enables method name checks on * expectations. * @access public */ function SimpleMock(&$test, $wildcard, $is_strict = true) { $this->SimpleStub($wildcard, $is_strict); if (! $test) { trigger_error('No unit tester for mock object', E_USER_ERROR); return; } $this->_test = SimpleMock::registerTest($test); $this->_expected_counts = array(); $this->_max_counts = array(); $this->_expected_args = array(); $this->_expected_args_at = array(); } /** * Accessor for attached unit test so that when * subclassed, new expectations can be added easily. * @return SimpleTestCase Unit test passed in constructor. * @access public */ function &getTest() { return $this->_test; } /** * Die if bad arguments array is passed * @param mixed $args The arguments value to be checked. * @param string $task Description of task attempt. * @return boolean Valid arguments * @access private */ function _checkArgumentsIsArray($args, $task) { if (! is_array($args)) { trigger_error( "Cannot $task as \$args parameter is not an array", E_USER_ERROR); } } /** * Sets up an expected call with a set of * expected parameters in that call. All * calls will be compared to these expectations * regardless of when the call is made. * @param string $method Method call to test. * @param array $args Expected parameters for the call * including wildcards. * @param string $message Overridden message. * @access public */ function expectArguments($method, $args, $message = '%s') { $this->_dieOnNoMethod($method, 'set expected arguments'); $this->_checkArgumentsIsArray($args, 'set expected arguments'); $args = $this->_replaceWildcards($args); $message .= Mock::getExpectationLine(' at line [%d]'); $this->_expected_args[strtolower($method)] = new ParametersExpectation($args, $message); } /** * Sets up an expected call with a set of * expected parameters in that call. The * expected call count will be adjusted if it * is set too low to reach this call. * @param integer $timing Number of calls in the future at * which to test. Next call is 0. * @param string $method Method call to test. * @param array $args Expected parameters for the call * including wildcards. * @param string $message Overridden message. * @access public */ function expectArgumentsAt($timing, $method, $args, $message = '%s') { $this->_dieOnNoMethod($method, 'set expected arguments at time'); $this->_checkArgumentsIsArray($args, 'set expected arguments at time'); $args = $this->_replaceWildcards($args); if (! isset($this->_expected_args_at[$timing])) { $this->_expected_args_at[$timing] = array(); } $method = strtolower($method); $message .= Mock::getExpectationLine(' at line [%d]'); $this->_expected_args_at[$timing][$method] = new ParametersExpectation($args, $message); } /** * Sets an expectation for the number of times * a method will be called. The tally method * is used to check this. * @param string $method Method call to test. * @param integer $count Number of times it should * have been called at tally. * @param string $message Overridden message. * @access public */ function expectCallCount($method, $count, $message = '%s') { $this->_dieOnNoMethod($method, 'set expected call count'); $message .= Mock::getExpectationLine(' at line [%d]'); $this->_expected_counts[strtolower($method)] = new CallCountExpectation($method, $count, $message); } /** * Sets the number of times a method may be called * before a test failure is triggered. * @param string $method Method call to test. * @param integer $count Most number of times it should * have been called. * @param string $message Overridden message. * @access public */ function expectMaximumCallCount($method, $count, $message = '%s') { $this->_dieOnNoMethod($method, 'set maximum call count'); $message .= Mock::getExpectationLine(' at line [%d]'); $this->_max_counts[strtolower($method)] = new MaximumCallCountExpectation($method, $count, $message); } /** * Sets the number of times to call a method to prevent * a failure on the tally. * @param string $method Method call to test. * @param integer $count Least number of times it should * have been called. * @param string $message Overridden message. * @access public */ function expectMinimumCallCount($method, $count, $message = '%s') { $this->_dieOnNoMethod($method, 'set minimum call count'); $message .= Mock::getExpectationLine(' at line [%d]'); $this->_expected_counts[strtolower($method)] = new MinimumCallCountExpectation($method, $count, $message); } /** * Convenience method for barring a method * call. * @param string $method Method call to ban. * @param string $message Overridden message. * @access public */ function expectNever($method, $message = '%s') { $this->expectMaximumCallCount($method, 0, $message); } /** * Convenience method for a single method * call. * @param string $method Method call to track. * @param array $args Expected argument list or * false for any arguments. * @param string $message Overridden message. * @access public */ function expectOnce($method, $args = false, $message = '%s') { $this->expectCallCount($method, 1, $message); if ($args !== false) { $this->expectArguments($method, $args, $message); } } /** * Convenience method for requiring a method * call. * @param string $method Method call to track. * @param array $args Expected argument list or * false for any arguments. * @param string $message Overridden message. * @access public */ function expectAtLeastOnce($method, $args = false, $message = '%s') { $this->expectMinimumCallCount($method, 1, $message); if ($args !== false) { $this->expectArguments($method, $args, $message); } } /** * Totals up the call counts and triggers a test * assertion if a test is present for expected * call counts. * This method must be called explicitly for the call * count assertions to be triggered. * @access public */ function tally() { foreach ($this->_expected_counts as $method => $expectation) { $this->_assertTrue( $expectation->test($this->getCallCount($method)), $expectation->overlayMessage($this->getCallCount($method))); } foreach ($this->_max_counts as $method => $expectation) { if ($expectation->test($this->getCallCount($method))) { $this->_assertTrue( true, $expectation->overlayMessage($this->getCallCount($method))); } } } /** * Returns the expected value for the method name * and checks expectations. Will generate any * test assertions as a result of expectations * if there is a test present. * @param string $method Name of method to simulate. * @param array $args Arguments as an array. * @return mixed Stored return. * @access private */ function &_invoke($method, $args) { $method = strtolower($method); $step = $this->getCallCount($method); $this->_addCall($method, $args); $this->_checkExpectations($method, $args, $step); return $this->_getReturn($method, $args, $step); } /** * Tests the arguments against expectations. * @param string $method Method to check. * @param array $args Argument list to match. * @param integer $timing The position of this call * in the call history. * @access private */ function _checkExpectations($method, $args, $timing) { if (isset($this->_max_counts[$method])) { if (! $this->_max_counts[$method]->test($timing + 1)) { $this->_assertTrue( false, $this->_max_counts[$method]->overlayMessage($timing + 1)); } } if (isset($this->_expected_args_at[$timing][$method])) { $this->_assertTrue( $this->_expected_args_at[$timing][$method]->test($args), "Mock method [$method] at [$timing] -> " . $this->_expected_args_at[$timing][$method]->overlayMessage($args)); } elseif (isset($this->_expected_args[$method])) { $this->_assertTrue( $this->_expected_args[$method]->test($args), "Mock method [$method] -> " . $this->_expected_args[$method]->overlayMessage($args)); } } /** * Triggers an assertion on the held test case. * Should be overridden when using another test * framework other than the SimpleTest one if the * assertion method has a different name. * @param boolean $assertion True will pass. * @param string $message Message that will go with * the test event. * @access protected */ function _assertTrue($assertion, $message) { $test = &SimpleMock::injectTest($this->_test); $test->assertTrue($assertion, $message); } /** * Stashes the test case for later recovery. * @param SimpleTestCase $test Test case. * @return string Key to find it again. * @access public * @static */ function registerTest(&$test) { $registry = &SimpleMock::_getRegistry(); $registry[$class = get_class($test)] = &$test; return $class; } /** * Resolves the dependency on the test case. * @param string $class Key to look up test case in. * @return SimpleTestCase Test case to send results to. * @access public * @static */ function &injectTest($key) { $registry = &SimpleMock::_getRegistry(); return $registry[$key]; } /** * Registry for test cases. The reason for this is * to break the reference between the test cases and * the mocks. It was leading to a fatal error due to * recursive dependencies during comparisons. See * http://bugs.php.net/bug.php?id=31449 for the PHP * bug. * @return array List of references. * @access private * @static */ function &_getRegistry() { static $registry; if (! isset($registry)) { $registry = array(); } return $registry; } } /** * Static methods only service class for code generation of * server stubs. * @package SimpleTest * @subpackage MockObjects */ class Stub { /** * Factory for server stub classes. */ function Stub() { trigger_error('Stub factory methods are class only.'); } /** * Clones a class' interface and creates a stub version * that can have return values set. * @param string $class Class to clone. * @param string $stub_class New class name. Default is * the old name with "Stub" * prepended. * @param array $methods Additional methods to add beyond * those in the cloned class. Use this * to emulate the dynamic addition of * methods in the cloned class or when * the class hasn't been written yet. * @static * @access public */ function generate($class, $stub_class = false, $methods = false) { if (! SimpleTestCompatibility::classExists($class)) { return false; } if (! $stub_class) { $stub_class = "Stub" . $class; } if (SimpleTestCompatibility::classExists($stub_class)) { return false; } return eval(Stub::_createClassCode( $class, $stub_class, $methods ? $methods : array()) . " return true;"); } /** * The new server stub class code in string form. * @param string $class Class to clone. * @param string $mock_class New class name. * @param array $methods Additional methods. * @static * @access private */ function _createClassCode($class, $stub_class, $methods) { $stub_base = SimpleTestOptions::getStubBaseClass(); $code = "class $stub_class extends $stub_base {\n"; $code .= " function $stub_class(\$wildcard = MOCK_WILDCARD) {\n"; $code .= " \$this->$stub_base(\$wildcard);\n"; $code .= " }\n"; $code .= Stub::_createHandlerCode($class, $stub_base, $methods); $code .= "}\n"; return $code; } /** * Creates code within a class to generate replaced * methods. All methods call the _invoke() handler * with the method name and the arguments in an * array. * @param string $class Class to clone. * @param string $base Base mock/stub class with methods that * cannot be cloned. Otherwise you * would be stubbing the accessors used * to set the stubs. * @param array $methods Additional methods. * @static * @access private */ function _createHandlerCode($class, $base, $methods) { $code = ""; $methods = array_merge($methods, get_class_methods($class)); foreach ($methods as $method) { if (Stub::_isSpecialMethod($method)) { continue; } if (in_array($method, get_class_methods($base))) { continue; } $code .= " function &$method() {\n"; $code .= " \$args = func_get_args();\n"; $code .= " return \$this->_invoke(\"$method\", \$args);\n"; $code .= " }\n"; } return $code; } /** * Tests to see if a special PHP method is about to * be stubbed by mistake. * @param string $method Method name. * @return boolean True if special. * @access private * @static */ function _isSpecialMethod($method) { return in_array( strtolower($method), array('__construct', '__clone', '__get', '__set', '__call')); } } /** * Static methods only service class for code generation of * mock objects. * @package SimpleTest * @subpackage MockObjects */ class Mock { /** * Factory for mock object classes. * @access public */ function Mock() { trigger_error("Mock factory methods are class only."); } /** * Clones a class' interface and creates a mock version * that can have return values and expectations set. * @param string $class Class to clone. * @param string $mock_class New class name. Default is * the old name with "Mock" * prepended. * @param array $methods Additional methods to add beyond * those in th cloned class. Use this * to emulate the dynamic addition of * methods in the cloned class or when * the class hasn't been written yet. * @static * @access public */ function generate($class, $mock_class = false, $methods = false) { if (! SimpleTestCompatibility::classExists($class)) { return false; } if (! $mock_class) { $mock_class = "Mock" . $class; } if (SimpleTestCompatibility::classExists($mock_class)) { return false; } return eval(Mock::_createClassCode( $class, $mock_class, $methods ? $methods : array()) . " return true;"); } /** * Generates a version of a class with selected * methods mocked only. Inherits the old class * and chains the mock methods of an aggregated * mock object. * @param string $class Class to clone. * @param string $mock_class New class name. * @param array $methods Methods to be overridden * with mock versions. * @static * @access public */ function generatePartial($class, $mock_class, $methods) { if (! SimpleTestCompatibility::classExists($class)) { return false; } if (SimpleTestCompatibility::classExists($mock_class)) { trigger_error("Partial mock class [$mock_class] already exists"); return false; } return eval(Mock::_extendClassCode($class, $mock_class, $methods)); } /** * The new mock class code as a string. * @param string $class Class to clone. * @param string $mock_class New class name. * @param array $methods Additional methods. * @return string Code for new mock class. * @static * @access private */ function _createClassCode($class, $mock_class, $methods) { $mock_base = SimpleTestOptions::getMockBaseClass(); $code = "class $mock_class extends $mock_base {\n"; $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n"; $code .= " \$this->$mock_base(\$test, \$wildcard);\n"; $code .= " }\n"; $code .= Stub::_createHandlerCode($class, $mock_base, $methods); $code .= "}\n"; return $code; } /** * The extension class code as a string. The class * composites a mock object and chains mocked methods * to it. * @param string $class Class to extend. * @param string $mock_class New class name. * @param array $methods Mocked methods. * @return string Code for a new class. * @static * @access private */ function _extendClassCode($class, $mock_class, $methods) { $mock_base = SimpleTestOptions::getMockBaseClass(); $code = "class $mock_class extends $class {\n"; $code .= " var \$_mock;\n"; $code .= Mock::_addMethodList($methods); $code .= "\n"; $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n"; $code .= " \$this->_mock = &new $mock_base(\$test, \$wildcard, false);\n"; $code .= " }\n"; $code .= Mock::_chainMockReturns(); $code .= Mock::_chainMockExpectations(); $code .= Mock::_overrideMethods($methods); $code .= SimpleTestOptions::getPartialMockCode(); $code .= "}\n"; return $code; } /** * Creates a list of mocked methods for error checking. * @param array $methods Mocked methods. * @return string Code for a method list. * @access private */ function _addMethodList($methods) { return " var \$_mocked_methods = array('" . implode("', '", $methods) . "');\n"; } /** * Creates code to abandon the expectation if not mocked. * @param string $alias Parameter name of method name. * @return string Code for bail out. * @access private */ function _bailOutIfNotMocked($alias) { $code = " if (! in_array($alias, \$this->_mocked_methods)) {\n"; $code .= " trigger_error(\"Method [$alias] is not mocked\");\n"; $code .= " return;\n"; $code .= " }\n"; return $code; } /** * Creates source code for chaining to the composited * mock object. * @return string Code for mock set up. * @access private */ function _chainMockReturns() { $code = " function setReturnValue(\$method, \$value, \$args = false) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->setReturnValue(\$method, \$value, \$args);\n"; $code .= " }\n"; $code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n"; $code .= " }\n"; $code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->setReturnReference(\$method, \$ref, \$args);\n"; $code .= " }\n"; $code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n"; $code .= " }\n"; return $code; } /** * Creates source code for chaining to an aggregated * mock object. * @return string Code for expectations. * @access private */ function _chainMockExpectations() { $code = " function expectArguments(\$method, \$args = false) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectArguments(\$method, \$args);\n"; $code .= " }\n"; $code .= " function expectArgumentsAt(\$timing, \$method, \$args = false) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args);\n"; $code .= " }\n"; $code .= " function expectCallCount(\$method, \$count) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectCallCount(\$method, \$count);\n"; $code .= " }\n"; $code .= " function expectMaximumCallCount(\$method, \$count) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectMaximumCallCount(\$method, \$count);\n"; $code .= " }\n"; $code .= " function expectMinimumCallCount(\$method, \$count) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectMinimumCallCount(\$method, \$count);\n"; $code .= " }\n"; $code .= " function expectNever(\$method) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectNever(\$method);\n"; $code .= " }\n"; $code .= " function expectOnce(\$method, \$args = false) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectOnce(\$method, \$args);\n"; $code .= " }\n"; $code .= " function expectAtLeastOnce(\$method, \$args = false) {\n"; $code .= Mock::_bailOutIfNotMocked("\$method"); $code .= " \$this->_mock->expectAtLeastOnce(\$method, \$args);\n"; $code .= " }\n"; $code .= " function tally() {\n"; $code .= " \$this->_mock->tally();\n"; $code .= " }\n"; return $code; } /** * Creates source code to override a list of methods * with mock versions. * @param array $methods Methods to be overridden * with mock versions. * @return string Code for overridden chains. * @access private */ function _overrideMethods($methods) { $code = ""; foreach ($methods as $method) { $code .= " function &$method() {\n"; $code .= " \$args = func_get_args();\n"; $code .= " return \$this->_mock->_invoke(\"$method\", \$args);\n"; $code .= " }\n"; } return $code; } /** * Uses a stack trace to find the line of an assertion. * @param string $format String formatting. * @param array $stack Stack frames top most first. Only * needed if not using the PHP * backtrace function. * @return string Line number of first expect* * method embedded in format string. * @access public * @static */ function getExpectationLine($format = '%d', $stack = false) { if ($stack === false) { $stack = SimpleTestCompatibility::getStackTrace(); } return SimpleDumper::getFormattedAssertionLine($stack, $format, 'expect'); } } ?> pgfouine-1.2/tests/simpletest/user_agent.php 0000644 0001750 0001750 00000045034 10334504436 017774 0 ustar acme acme _cookies = array(); } /** * Removes expired and temporary cookies as if * the browser was closed and re-opened. * @param string/integer $now Time to test expiry against. * @access public */ function restartSession($date = false) { $surviving_cookies = array(); for ($i = 0; $i < count($this->_cookies); $i++) { if (! $this->_cookies[$i]->getValue()) { continue; } if (! $this->_cookies[$i]->getExpiry()) { continue; } if ($date && $this->_cookies[$i]->isExpired($date)) { continue; } $surviving_cookies[] = $this->_cookies[$i]; } $this->_cookies = $surviving_cookies; } /** * Ages all cookies in the cookie jar. * @param integer $interval The old session is moved * into the past by this number * of seconds. Cookies now over * age will be removed. * @access public */ function agePrematurely($interval) { for ($i = 0; $i < count($this->_cookies); $i++) { $this->_cookies[$i]->agePrematurely($interval); } } /** * Adds a cookie to the jar. This will overwrite * cookies with matching host, paths and keys. * @param SimpleCookie $cookie New cookie. * @access public */ function setCookie($cookie) { for ($i = 0; $i < count($this->_cookies); $i++) { $is_match = $this->_isMatch( $cookie, $this->_cookies[$i]->getHost(), $this->_cookies[$i]->getPath(), $this->_cookies[$i]->getName()); if ($is_match) { $this->_cookies[$i] = $cookie; return; } } $this->_cookies[] = $cookie; } /** * Fetches a hash of all valid cookies filtered * by host, path and keyed by name * Any cookies with missing categories will not * be filtered out by that category. Expired * cookies must be cleared by restarting the session. * @param string $host Host name requirement. * @param string $path Path encompassing cookies. * @return hash Valid cookie objects keyed * on the cookie name. * @access public */ function getValidCookies($host = false, $path = "/") { $valid_cookies = array(); foreach ($this->_cookies as $cookie) { if ($this->_isMatch($cookie, $host, $path, $cookie->getName())) { $valid_cookies[] = $cookie; } } return $valid_cookies; } /** * Tests cookie for matching against search * criteria. * @param SimpleTest $cookie Cookie to test. * @param string $host Host must match. * @param string $path Cookie path must be shorter than * this path. * @param string $name Name must match. * @return boolean True if matched. * @access private */ function _isMatch($cookie, $host, $path, $name) { if ($cookie->getName() != $name) { return false; } if ($host && $cookie->getHost() && !$cookie->isValidHost($host)) { return false; } if (! $cookie->isValidPath($path)) { return false; } return true; } /** * Adds the current cookies to a request. * @param SimpleHttpRequest $request Request to modify. * @param SimpleUrl $url Cookie selector. * @access private */ function addHeaders(&$request, $url) { $cookies = $this->getValidCookies($url->getHost(), $url->getPath()); foreach ($cookies as $cookie) { $request->setCookie($cookie); } } } /** * Fetches web pages whilst keeping track of * cookies and authentication. * @package SimpleTest * @subpackage WebTester */ class SimpleUserAgent { var $_cookie_jar; var $_authenticator; var $_max_redirects; var $_proxy; var $_proxy_username; var $_proxy_password; var $_connection_timeout; var $_additional_headers; /** * Starts with no cookies, realms or proxies. * @access public */ function SimpleUserAgent() { $this->_cookie_jar = &new SimpleCookieJar(); $this->_authenticator = &new SimpleAuthenticator(); $this->setMaximumRedirects(DEFAULT_MAX_REDIRECTS); $this->_proxy = false; $this->_proxy_username = false; $this->_proxy_password = false; $this->setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); $this->_additional_headers = array(); } /** * Removes expired and temporary cookies as if * the browser was closed and re-opened. Authorisation * has to be obtained again as well. * @param string/integer $date Time when session restarted. * If omitted then all persistent * cookies are kept. * @access public */ function restart($date = false) { $this->_cookie_jar->restartSession($date); $this->_authenticator->restartSession(); } /** * Adds a header to every fetch. * @param string $header Header line to add to every * request until cleared. * @access public */ function addHeader($header) { $this->_additional_headers[] = $header; } /** * Ages the cookies by the specified time. * @param integer $interval Amount in seconds. * @access public */ function ageCookies($interval) { $this->_cookie_jar->agePrematurely($interval); } /** * Sets an additional cookie. If a cookie has * the same name and path it is replaced. * @param string $name Cookie key. * @param string $value Value of cookie. * @param string $host Host upon which the cookie is valid. * @param string $path Cookie path if not host wide. * @param string $expiry Expiry date. * @access public */ function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { $cookie = new SimpleCookie($name, $value, $path, $expiry); if ($host) { $cookie->setHost($host); } $this->_cookie_jar->setCookie($cookie); } /** * Reads the most specific cookie value from the * browser cookies. * @param string $host Host to search. * @param string $path Applicable path. * @param string $name Name of cookie to read. * @return string False if not present, else the * value as a string. * @access public */ function getCookieValue($host, $path, $name) { $longest_path = ''; foreach ($this->_cookie_jar->getValidCookies($host, $path) as $cookie) { if ($name == $cookie->getName()) { if (strlen($cookie->getPath()) > strlen($longest_path)) { $value = $cookie->getValue(); $longest_path = $cookie->getPath(); } } } return (isset($value) ? $value : false); } /** * Reads the current cookies within the base URL. * @param string $name Key of cookie to find. * @param SimpleUrl $base Base URL to search from. * @return string Null if there is no base URL, false * if the cookie is not set. * @access public */ function getBaseCookieValue($name, $base) { if (! $base) { return null; } return $this->getCookieValue($base->getHost(), $base->getPath(), $name); } /** * Sets the socket timeout for opening a connection. * @param integer $timeout Maximum time in seconds. * @access public */ function setConnectionTimeout($timeout) { $this->_connection_timeout = $timeout; } /** * Sets the maximum number of redirects before * a page will be loaded anyway. * @param integer $max Most hops allowed. * @access public */ function setMaximumRedirects($max) { $this->_max_redirects = $max; } /** * Sets proxy to use on all requests for when * testing from behind a firewall. Set URL * to false to disable. * @param string $proxy Proxy URL. * @param string $username Proxy username for authentication. * @param string $password Proxy password for authentication. * @access public */ function useProxy($proxy, $username, $password) { if (! $proxy) { $this->_proxy = false; return; } if (strncmp($proxy, 'http://', 7) != 0) { $proxy = 'http://'. $proxy; } $this->_proxy = &new SimpleUrl($proxy); $this->_proxy_username = $username; $this->_proxy_password = $password; } /** * Test to see if the redirect limit is passed. * @param integer $redirects Count so far. * @return boolean True if over. * @access private */ function _isTooManyRedirects($redirects) { return ($redirects > $this->_max_redirects); } /** * Sets the identity for the current realm. * @param string $host Host to which realm applies. * @param string $realm Full name of realm. * @param string $username Username for realm. * @param string $password Password for realm. * @access public */ function setIdentity($host, $realm, $username, $password) { $this->_authenticator->setIdentityForRealm($host, $realm, $username, $password); } /** * Fetches a URL as a response object. Will keep trying if redirected. * It will also collect authentication realm information. * @param string $method GET, POST, etc. * @param string/SimpleUrl $url Target to fetch. * @param SimpleFormEncoding $parameters Additional parameters for request. * @return SimpleHttpResponse Hopefully the target page. * @access public */ function &fetchResponse($method, $url, $parameters = false) { if ($method != 'POST') { $url->addRequestParameters($parameters); $parameters = false; } $response = &$this->_fetchWhileRedirected($method, $url, $parameters); if ($headers = $response->getHeaders()) { if ($headers->isChallenge()) { $this->_authenticator->addRealm( $url, $headers->getAuthentication(), $headers->getRealm()); } } return $response; } /** * Fetches the page until no longer redirected or * until the redirect limit runs out. * @param string $method GET, POST, etc. * @param SimpleUrl $url Target to fetch. * @param SimpelFormEncoding $parameters Additional parameters for request. * @return SimpleHttpResponse Hopefully the target page. * @access private */ function &_fetchWhileRedirected($method, $url, $parameters) { $redirects = 0; do { $response = &$this->_fetch($method, $url, $parameters); if ($response->isError()) { return $response; } $headers = $response->getHeaders(); $location = new SimpleUrl($headers->getLocation()); $url = $location->makeAbsolute($url); $this->_addCookiesToJar($url, $headers->getNewCookies()); if (! $headers->isRedirect()) { break; } $method = 'GET'; $parameters = false; } while (! $this->_isTooManyRedirects(++$redirects)); return $response; } /** * Actually make the web request. * @param string $method GET, POST, etc. * @param SimpleUrl $url Target to fetch. * @param SimpleFormEncoding $parameters Additional parameters for request. * @return SimpleHttpResponse Headers and hopefully content. * @access protected */ function &_fetch($method, $url, $parameters) { if (! $parameters) { $parameters = new SimpleFormEncoding(); } $request = &$this->_createRequest($method, $url, $parameters); return $request->fetch($this->_connection_timeout); } /** * Creates a full page request. * @param string $method Fetching method. * @param SimpleUrl $url Target to fetch as url object. * @param SimpleFormEncoding $parameters POST/GET parameters. * @return SimpleHttpRequest New request. * @access private */ function &_createRequest($method, $url, $parameters) { $request = &$this->_createHttpRequest($method, $url, $parameters); $this->_addAdditionalHeaders($request); $this->_cookie_jar->addHeaders($request, $url); $this->_authenticator->addHeaders($request, $url); return $request; } /** * Builds the appropriate HTTP request object. * @param string $method Fetching method. * @param SimpleUrl $url Target to fetch as url object. * @param SimpleFormEncoding $parameters POST/GET parameters. * @return SimpleHttpRequest New request object. * @access protected */ function &_createHttpRequest($method, $url, $parameters) { if ($method == 'POST') { $request = &new SimpleHttpRequest( $this->_createRoute($url), 'POST', $parameters); return $request; } if ($parameters) { $url->addRequestParameters($parameters); } return new SimpleHttpRequest($this->_createRoute($url), $method); } /** * Sets up either a direct route or via a proxy. * @param SimpleUrl $url Target to fetch as url object. * @return SimpleRoute Route to take to fetch URL. * @access protected */ function &_createRoute($url) { if ($this->_proxy) { return new SimpleProxyRoute( $url, $this->_proxy, $this->_proxy_username, $this->_proxy_password); } return new SimpleRoute($url); } /** * Adds additional manual headers. * @param SimpleHttpRequest $request Outgoing request. * @access private */ function _addAdditionalHeaders(&$request) { foreach ($this->_additional_headers as $header) { $request->addHeaderLine($header); } } /** * Extracts new cookies into the cookie jar. * @param SimpleUrl $url Target to fetch as url object. * @param array $cookies New cookies. * @access private */ function _addCookiesToJar($url, $cookies) { foreach ($cookies as $cookie) { if ($url->getHost()) { $cookie->setHost($url->getHost()); } $this->_cookie_jar->setCookie($cookie); } } } ?> pgfouine-1.2/tests/simpletest/options.php 0000644 0001750 0001750 00000031176 10334504436 017335 0 ustar acme acme 'SimpleStub', 'MockBaseClass' => 'SimpleMock', 'IgnoreList' => array(), 'AdditionalPartialMockCode' => '', 'DefaultProxy' => false, 'DefaultProxyUsername' => false, 'DefaultProxyPassword' => false); } } /** * Static methods for compatibility between different * PHP versions. * @package SimpleTest */ class SimpleTestCompatibility { /** * Identity test. Drops back to equality + types for PHP5 * objects as the === operator counts as the * stronger reference constraint. * @param mixed $first Test subject. * @param mixed $second Comparison object. * @access public * @static */ function isIdentical($first, $second) { if ($first != $second) { return false; } if (version_compare(phpversion(), '5') >= 0) { return SimpleTestCompatibility::_isIdenticalType($first, $second); } return ($first === $second); } /** * Recursive type test. * @param mixed $first Test subject. * @param mixed $second Comparison object. * @access private * @static */ function _isIdenticalType($first, $second) { if (gettype($first) != gettype($second)) { return false; } if (is_object($first) && is_object($second)) { if (get_class($first) != get_class($second)) { return false; } return SimpleTestCompatibility::_isArrayOfIdenticalTypes( get_object_vars($first), get_object_vars($second)); } if (is_array($first) && is_array($second)) { return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second); } return true; } /** * Recursive type test for each element of an array. * @param mixed $first Test subject. * @param mixed $second Comparison object. * @access private * @static */ function _isArrayOfIdenticalTypes($first, $second) { if (array_keys($first) != array_keys($second)) { return false; } foreach (array_keys($first) as $key) { $is_identical = SimpleTestCompatibility::_isIdenticalType( $first[$key], $second[$key]); if (! $is_identical) { return false; } } return true; } /** * Test for two variables being aliases. * @param mixed $first Test subject. * @param mixed $second Comparison object. * @access public * @static */ function isReference(&$first, &$second) { if (version_compare(phpversion(), '5', '>=') && is_object($first)) { return ($first === $second); } $temp = $first; $first = uniqid("test"); $is_ref = ($first === $second); $first = $temp; return $is_ref; } /** * Test to see if an object is a member of a * class hiearchy. * @param object $object Object to test. * @param string $class Root name of hiearchy. * @access public * @static */ function isA($object, $class) { if (version_compare(phpversion(), '5') >= 0) { if (! class_exists($class, false)) { return false; } eval("\$is_a = \$object instanceof $class;"); return $is_a; } if (function_exists('is_a')) { return is_a($object, $class); } return ((strtolower($class) == get_class($object)) or (is_subclass_of($object, $class))); } /** * Autoload safe version of class_exists(). * @param string $class Name of class to look for. * @return boolean True if class is defined. * @access public * @static */ function classExists($class) { if (version_compare(phpversion(), '5') >= 0) { return class_exists($class, false); } else { return class_exists($class); } } /** * Sets a socket timeout for each chunk. * @param resource $handle Socket handle. * @param integer $timeout Limit in seconds. * @access public * @static */ function setTimeout($handle, $timeout) { if (function_exists('stream_set_timeout')) { stream_set_timeout($handle, $timeout, 0); } elseif (function_exists('socket_set_timeout')) { socket_set_timeout($handle, $timeout, 0); } elseif (function_exists('set_socket_timeout')) { set_socket_timeout($handle, $timeout, 0); } } /** * Gets the current stack trace topmost first. * @return array List of stack frames. * @access public * @static */ function getStackTrace() { if (function_exists('debug_backtrace')) { return array_reverse(debug_backtrace()); } return array(); } } ?> pgfouine-1.2/tests/simpletest/tag.php 0000644 0001750 0001750 00000112342 10334504436 016410 0 ustar acme acme _name = $name; $this->_attributes = $attributes; $this->_content = ''; } /** * Check to see if the tag can have both start and * end tags with content in between. * @return boolean True if content allowed. * @access public */ function expectEndTag() { return true; } /** * Appends string content to the current content. * @param string $content Additional text. * @access public */ function addContent($content) { $this->_content .= (string)$content; } /** * Adds an enclosed tag to the content. * @param SimpleTag $tag New tag. * @access public */ function addTag(&$tag) { } /** * Accessor for tag name. * @return string Name of tag. * @access public */ function getTagName() { return $this->_name; } /** * List oflegal child elements. * @return array List of element names. * @access public */ function getChildElements() { return array(); } /** * Accessor for an attribute. * @param string $label Attribute name. * @return string Attribute value. * @access public */ function getAttribute($label) { $label = strtolower($label); if (! isset($this->_attributes[$label])) { return false; } if ($this->_attributes[$label] === '') { return true; } return (string)$this->_attributes[$label]; } /** * Sets an attribute. * @param string $label Attribute name. * @return string $value New attribute value. * @access protected */ function _setAttribute($label, $value) { $this->_attributes[strtolower($label)] = $value; } /** * Accessor for the whole content so far. * @return string Content as big raw string. * @access public */ function getContent() { return $this->_content; } /** * Accessor for content reduced to visible text. Acts * like a text mode browser, normalising space and * reducing images to their alt text. * @return string Content as plain text. * @access public */ function getText() { return SimpleSaxParser::normalise($this->_content); } /** * Test to see if id attribute matches. * @param string $id ID to test against. * @return boolean True on match. * @access public */ function isId($id) { return ($this->getAttribute('id') == $id); } } /** * Page title. * @package SimpleTest * @subpackage WebTester */ class SimpleTitleTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleTitleTag($attributes) { $this->SimpleTag('title', $attributes); } } /** * Link. * @package SimpleTest * @subpackage WebTester */ class SimpleAnchorTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleAnchorTag($attributes) { $this->SimpleTag('a', $attributes); } /** * Accessor for URL as string. * @return string Coerced as string. * @access public */ function getHref() { $url = $this->getAttribute('href'); if (is_bool($url)) { $url = ''; } return $url; } } /** * Form element. * @package SimpleTest * @subpackage WebTester */ class SimpleWidget extends SimpleTag { var $_value; var $_is_set; /** * Starts with a named tag with attributes only. * @param string $name Tag name. * @param hash $attributes Attribute names and * string values. */ function SimpleWidget($name, $attributes) { $this->SimpleTag($name, $attributes); $this->_value = false; $this->_is_set = false; } /** * Accessor for name submitted as the key in * GET/POST variables hash. * @return string Parsed value. * @access public */ function getName() { return $this->getAttribute('name'); } /** * Accessor for default value parsed with the tag. * @return string Parsed value. * @access public */ function getDefault() { $default = $this->getAttribute('value'); if ($default === true) { $default = ''; } if ($default === false) { $default = ''; } return $default; } /** * Accessor for currently set value or default if * none. * @return string Value set by form or default * if none. * @access public */ function getValue() { if (! $this->_is_set) { return $this->getDefault(); } return $this->_value; } /** * Sets the current form element value. * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { $this->_value = $value; $this->_is_set = true; return true; } /** * Resets the form element value back to the * default. * @access public */ function resetValue() { $this->_is_set = false; } } /** * Text, password and hidden field. * @package SimpleTest * @subpackage WebTester */ class SimpleTextTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleTextTag($attributes) { $this->SimpleWidget('input', $attributes); if ($this->getAttribute('value') === false) { $this->_setAttribute('value', ''); } } /** * Tag contains no content. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * Sets the current form element value. Cannot * change the value of a hidden field. * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { if ($this->getAttribute('type') == 'hidden') { return false; } return parent::setValue($value); } } /** * Submit button as input tag. * @package SimpleTest * @subpackage WebTester */ class SimpleSubmitTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleSubmitTag($attributes) { $this->SimpleWidget('input', $attributes); if ($this->getAttribute('name') === false) { $this->_setAttribute('name', 'submit'); } if ($this->getAttribute('value') === false) { $this->_setAttribute('value', 'Submit'); } } /** * Tag contains no end element. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * Disables the setting of the button value. * @param string $value Ignored. * @return boolean True if allowed. * @access public */ function setValue($value) { return false; } /** * Value of browser visible text. * @return string Visible label. * @access public */ function getLabel() { return $this->getValue(); } /** * Gets the values submitted as a form. * @return array Hash of name and values. * @access public */ function getSubmitValues() { return array($this->getName() => $this->getValue()); } } /** * Image button as input tag. * @package SimpleTest * @subpackage WebTester */ class SimpleImageSubmitTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleImageSubmitTag($attributes) { $this->SimpleWidget('input', $attributes); } /** * Tag contains no end element. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * Disables the setting of the button value. * @param string $value Ignored. * @return boolean True if allowed. * @access public */ function setValue($value) { return false; } /** * Value of browser visible text. * @return string Visible label. * @access public */ function getLabel() { if ($this->getAttribute('title')) { return $this->getAttribute('title'); } return $this->getAttribute('alt'); } /** * Gets the values submitted as a form. * @return array Hash of name and values. * @access public */ function getSubmitValues($x, $y) { return array( $this->getName() . '.x' => $x, $this->getName() . '.y' => $y); } } /** * Submit button as button tag. * @package SimpleTest * @subpackage WebTester */ class SimpleButtonTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * Defaults are very browser dependent. * @param hash $attributes Attribute names and * string values. */ function SimpleButtonTag($attributes) { $this->SimpleWidget('button', $attributes); } /** * Check to see if the tag can have both start and * end tags with content in between. * @return boolean True if content allowed. * @access public */ function expectEndTag() { return true; } /** * Disables the setting of the button value. * @param string $value Ignored. * @return boolean True if allowed. * @access public */ function setValue($value) { return false; } /** * Value of browser visible text. * @return string Visible label. * @access public */ function getLabel() { return $this->getContent(); } /** * Gets the values submitted as a form. Gone * for the Mozilla defaults values. * @return array Hash of name and values. * @access public */ function getSubmitValues() { if ($this->getAttribute('name') === false) { return array(); } if ($this->getAttribute('value') === false) { return array($this->getName() => ''); } return array($this->getName() => $this->getValue()); } } /** * Content tag for text area. * @package SimpleTest * @subpackage WebTester */ class SimpleTextAreaTag extends SimpleWidget { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleTextAreaTag($attributes) { $this->SimpleWidget('textarea', $attributes); } /** * Accessor for starting value. * @return string Parsed value. * @access public */ function getDefault() { if ($this->_wrapIsEnabled()) { return wordwrap( $this->getContent(), (integer)$this->getAttribute('cols'), "\n"); } return $this->getContent(); } /** * Applies word wrapping if needed. * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { if ($this->_wrapIsEnabled()) { $value = wordwrap( $value, (integer)$this->getAttribute('cols'), "\n"); } return parent::setValue($value); } /** * Test to see if text should be wrapped. * @return boolean True if wrapping on. * @access private */ function _wrapIsEnabled() { if ($this->getAttribute('cols')) { $wrap = $this->getAttribute('wrap'); if (($wrap == 'physical') || ($wrap == 'hard')) { return true; } } return false; } } /** * Checkbox widget. * @package SimpleTest * @subpackage WebTester */ class SimpleCheckboxTag extends SimpleWidget { /** * Starts with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleCheckboxTag($attributes) { $this->SimpleWidget('input', $attributes); if ($this->getAttribute('value') === false) { $this->_setAttribute('value', 'on'); } } /** * Tag contains no content. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * The only allowed value in the one in the * "value" attribute. The default for this * attribute is "on". * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { if ($value === false) { return parent::setValue($value); } if ($value != $this->getAttribute('value')) { return false; } return parent::setValue($value); } /** * Accessor for starting value. The default * value is "on". * @return string Parsed value. * @access public */ function getDefault() { if ($this->getAttribute('checked')) { return $this->getAttribute('value'); } return false; } } /** * Drop down widget. * @package SimpleTest * @subpackage WebTester */ class SimpleSelectionTag extends SimpleWidget { var $_options; var $_choice; /** * Starts with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleSelectionTag($attributes) { $this->SimpleWidget('select', $attributes); $this->_options = array(); $this->_choice = false; } /** * Adds an option tag to a selection field. * @param SimpleOptionTag $tag New option. * @access public */ function addTag(&$tag) { if ($tag->getTagName() == 'option') { $this->_options[] = &$tag; } } /** * Text within the selection element is ignored. * @param string $content Ignored. * @access public */ function addContent($content) { } /** * Scans options for defaults. If none, then * the first option is selected. * @return string Selected field. * @access public */ function getDefault() { for ($i = 0, $count = count($this->_options); $i < $count; $i++) { if ($this->_options[$i]->getAttribute('selected')) { return $this->_options[$i]->getDefault(); } } if ($count > 0) { return $this->_options[0]->getDefault(); } return ''; } /** * Can only set allowed values. * @param string $value New choice. * @return boolean True if allowed. * @access public */ function setValue($value) { for ($i = 0, $count = count($this->_options); $i < $count; $i++) { if (trim($this->_options[$i]->getContent()) == trim($value)) { $this->_choice = $i; return true; } } return false; } /** * Accessor for current selection value. * @return string Value attribute or * content of opton. * @access public */ function getValue() { if ($this->_choice === false) { return $this->getDefault(); } return $this->_options[$this->_choice]->getValue(); } } /** * Drop down widget. * @package SimpleTest * @subpackage WebTester */ class MultipleSelectionTag extends SimpleWidget { var $_options; var $_values; /** * Starts with attributes only. * @param hash $attributes Attribute names and * string values. */ function MultipleSelectionTag($attributes) { $this->SimpleWidget('select', $attributes); $this->_options = array(); $this->_values = false; } /** * Adds an option tag to a selection field. * @param SimpleOptionTag $tag New option. * @access public */ function addTag(&$tag) { if ($tag->getTagName() == 'option') { $this->_options[] = &$tag; } } /** * Text within the selection element is ignored. * @param string $content Ignored. * @access public */ function addContent($content) { } /** * Scans options for defaults to populate the * value array(). * @return array Selected fields. * @access public */ function getDefault() { $default = array(); for ($i = 0, $count = count($this->_options); $i < $count; $i++) { if ($this->_options[$i]->getAttribute('selected')) { $default[] = $this->_options[$i]->getDefault(); } } return $default; } /** * Can only set allowed values. * @param array $values New choices. * @return boolean True if allowed. * @access public */ function setValue($values) { foreach ($values as $value) { $is_option = false; for ($i = 0, $count = count($this->_options); $i < $count; $i++) { if (trim($this->_options[$i]->getContent()) == trim($value)) { $is_option = true; break; } } if (! $is_option) { return false; } } $this->_values = $values; return true; } /** * Accessor for current selection value. * @return array List of currently set options. * @access public */ function getValue() { if ($this->_values === false) { return $this->getDefault(); } return $this->_values; } } /** * Option for selection field. * @package SimpleTest * @subpackage WebTester */ class SimpleOptionTag extends SimpleWidget { /** * Stashes the attributes. */ function SimpleOptionTag($attributes) { $this->SimpleWidget('option', $attributes); } /** * Does nothing. * @param string $value Ignored. * @return boolean Not allowed. * @access public */ function setValue($value) { return false; } /** * Accessor for starting value. Will be set to * the option label if no value exists. * @return string Parsed value. * @access public */ function getDefault() { if ($this->getAttribute('value') === false) { return $this->getContent(); } return $this->getAttribute('value'); } } /** * Radio button. * @package SimpleTest * @subpackage WebTester */ class SimpleRadioButtonTag extends SimpleWidget { /** * Stashes the attributes. * @param array $attributes Hash of attributes. */ function SimpleRadioButtonTag($attributes) { $this->SimpleWidget('input', $attributes); if ($this->getAttribute('value') === false) { $this->_setAttribute('value', 'on'); } } /** * Tag contains no content. * @return boolean False. * @access public */ function expectEndTag() { return false; } /** * The only allowed value in the one in the * "value" attribute. * @param string $value New value. * @return boolean True if allowed. * @access public */ function setValue($value) { if ($value === false) { return parent::setValue($value); } if ($value != $this->getAttribute('value')) { return false; } return parent::setValue($value); } /** * Accessor for starting value. * @return string Parsed value. * @access public */ function getDefault() { if ($this->getAttribute('checked')) { return $this->getAttribute('value'); } return false; } } /** * A group of tags with the same name within a form. * @package SimpleTest * @subpackage WebTester */ class SimpleCheckboxGroup { var $_widgets; /** * Starts empty. * @access public */ function SimpleCheckboxGroup() { $this->_widgets = array(); } /** * Accessor for an attribute. * @param string $label Attribute name. * @return boolean Always false. * @access public */ function getAttribute($label) { return false; } /** * Scans the checkboxes for one with the appropriate * ID field. * @param string $id ID value to try. * @return boolean True if matched. * @access public */ function isId($id) { for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if ($this->_widgets[$i]->isId($id)) { return true; } } return false; } /** * Adds a tag to the group. * @param SimpleWidget $widget * @access public */ function addWidget(&$widget) { $this->_widgets[] = &$widget; } /** * Fetches the name for the widget from the first * member. * @return string Name of widget. * @access public */ function getName() { if (count($this->_widgets) > 0) { return $this->_widgets[0]->getName(); } } /** * Accessor for current selected widget or false * if none. * @return string/array Widget values or false if none. * @access public */ function getValue() { $values = array(); for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if ($this->_widgets[$i]->getValue()) { $values[] = $this->_widgets[$i]->getValue(); } } return $this->_coerceValues($values); } /** * Accessor for starting value that is active. * @return string/array Widget values or false if none. * @access public */ function getDefault() { $values = array(); for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if ($this->_widgets[$i]->getDefault()) { $values[] = $this->_widgets[$i]->getDefault(); } } return $this->_coerceValues($values); } /** * Accessor for current set values. * @param string/array/boolean $values Either a single string, a * hash or false for nothing set. * @return boolean True if all values can be set. * @access public */ function setValue($values) { $values = $this->_makeArray($values); if (! $this->_valuesArePossible($values)) { return false; } for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { $possible = $this->_widgets[$i]->getAttribute('value'); if (in_array($this->_widgets[$i]->getAttribute('value'), $values)) { $this->_widgets[$i]->setValue($possible); } else { $this->_widgets[$i]->setValue(false); } } return true; } /** * Tests to see if a possible value set is legal. * @param string/array/boolean $values Either a single string, a * hash or false for nothing set. * @return boolean False if trying to set a * missing value. * @access private */ function _valuesArePossible($values) { $matches = array(); for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { $possible = $this->_widgets[$i]->getAttribute('value'); if (in_array($possible, $values)) { $matches[] = $possible; } } return ($values == $matches); } /** * Converts the output to an appropriate format. This means * that no values is false, a single value is just that * value and only two or more are contained in an array. * @param array $values List of values of widgets. * @return string/array/boolean Expected format for a tag. * @access private */ function _coerceValues($values) { if (count($values) == 0) { return false; } elseif (count($values) == 1) { return $values[0]; } else { return $values; } } /** * Converts false or string into array. The opposite of * the coercian method. * @param string/array/boolean $value A single item is converted * to a one item list. False * gives an empty list. * @return array List of values, possibly empty. * @access private */ function _makeArray($value) { if ($value === false) { return array(); } if (is_string($value)) { return array($value); } return $value; } } /** * A group of tags with the same name within a form. * Used for radio buttons. * @package SimpleTest * @subpackage WebTester */ class SimpleRadioGroup { var $_widgets; /** * Starts empty. * @access public */ function SimpleRadioGroup() { $this->_widgets = array(); } /** * Accessor for an attribute. * @param string $label Attribute name. * @return boolean Always false. * @access public */ function getAttribute($label) { return false; } /** * Scans the checkboxes for one with the appropriate * ID field. * @param string $id ID value to try. * @return boolean True if matched. * @access public */ function isId($id) { for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if ($this->_widgets[$i]->isId($id)) { return true; } } return false; } /** * Adds a tag to the group. * @param SimpleWidget $widget * @access public */ function addWidget(&$widget) { $this->_widgets[] = &$widget; } /** * Fetches the name for the widget from the first * member. * @return string Name of widget. * @access public */ function getName() { if (count($this->_widgets) > 0) { return $this->_widgets[0]->getName(); } } /** * Each tag is tried in turn until one is * successfully set. The others will be * unchecked if successful. * @param string $value New value. * @return boolean True if any allowed. * @access public */ function setValue($value) { if (! $this->_valueIsPossible($value)) { return false; } $index = false; for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if (! $this->_widgets[$i]->setValue($value)) { $this->_widgets[$i]->setValue(false); } } return true; } /** * Tests to see if a value is allowed. * @param string Attempted value. * @return boolean True if a valid value. * @access private */ function _valueIsPossible($value) { for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if ($this->_widgets[$i]->getAttribute('value') == $value) { return true; } } return false; } /** * Accessor for current selected widget or false * if none. * @return string/boolean Value attribute or * content of opton. * @access public */ function getValue() { for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if ($this->_widgets[$i]->getValue()) { return $this->_widgets[$i]->getValue(); } } return false; } /** * Accessor for starting value that is active. * @return string/boolean Value of first checked * widget or false if none. * @access public */ function getDefault() { for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) { if ($this->_widgets[$i]->getDefault()) { return $this->_widgets[$i]->getDefault(); } } return false; } } /** * Tag to aid parsing the form. * @package SimpleTest * @subpackage WebTester */ class SimpleFormTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleFormTag($attributes) { $this->SimpleTag('form', $attributes); } } /** * Tag to aid parsing the frames in a page. * @package SimpleTest * @subpackage WebTester */ class SimpleFrameTag extends SimpleTag { /** * Starts with a named tag with attributes only. * @param hash $attributes Attribute names and * string values. */ function SimpleFrameTag($attributes) { $this->SimpleTag('frame', $attributes); } /** * Tag contains no content. * @return boolean False. * @access public */ function expectEndTag() { return false; } } ?> pgfouine-1.2/tests/simpletest/remote.php 0000644 0001750 0001750 00000007414 10334504436 017133 0 ustar acme acme _url = $url; $this->_dry_url = $dry_url ? $dry_url : $url; $this->_size = false; } /** * Accessor for the test name for subclasses. * @return string Name of the test. * @access public */ function getLabel() { return $this->_url; } /** * Runs the top level test for this class. Currently * reads the data as a single chunk. I'll fix this * once I have added iteration to the browser. * @param SimpleReporter $reporter Target of test results. * @returns boolean True if no failures. * @access public */ function run(&$reporter) { $browser = &$this->_createBrowser(); $xml = $browser->get($this->_url); if (! $xml) { trigger_error('Cannot read remote test URL [' . $this->_url . ']'); return false; } $parser = &$this->_createParser($reporter); if (! $parser->parse($xml)) { trigger_error('Cannot parse incoming XML from [' . $this->_url . ']'); return false; } return true; } /** * Creates a new web browser object for fetching * the XML report. * @return SimpleBrowser New browser. * @access protected */ function &_createBrowser() { return new SimpleBrowser(); } /** * Creates the XML parser. * @param SimpleReporter $reporter Target of test results. * @return SimpleTestXmlListener XML reader. * @access protected */ function &_createParser(&$reporter) { return new SimpleTestXmlParser($reporter); } /** * Accessor for the number of subtests. * @return integer Number of test cases. * @access public */ function getSize() { if ($this->_size === false) { $browser = &$this->_createBrowser(); $xml = $browser->get($this->_dry_url); if (! $xml) { trigger_error('Cannot read remote test URL [' . $this->_dry_url . ']'); return false; } $reporter = &new SimpleReporter(); $parser = &$this->_createParser($reporter); if (! $parser->parse($xml)) { trigger_error('Cannot parse incoming XML from [' . $this->_dry_url . ']'); return false; } $this->_size = $reporter->getTestCaseCount(); } return $this->_size; } } ?> pgfouine-1.2/tests/simpletest/test/ 0000755 0001750 0001750 00000000000 11516212335 016075 5 ustar acme acme pgfouine-1.2/tests/simpletest/test/real_sites_test.php 0000644 0001750 0001750 00000002266 10334504436 022010 0 ustar acme acme assertTrue($this->get('http://www.lastcraft.com')); $this->assertResponse(array(200)); $this->assertMime(array('text/html')); $this->clickLink('About'); $this->assertTitle('About Last Craft'); } function testSourceforge() { $this->assertTrue($this->get('http://sourceforge.net/')); $this->setField('words', 'simpletest'); $this->assertTrue($this->clickImageByName('imageField')); $this->assertTitle('SourceForge.net: Search'); $this->assertTrue($this->clickLink('SimpleTest')); $this->clickLink('statistics'); $this->assertWantedPattern('/Statistics for the past 7 days/'); $this->assertTrue($this->setField('report', 'Monthly')); $this->clickSubmit('Change Stats View'); $this->assertWantedPattern('/Statistics for the past \d+ months/'); } } ?> pgfouine-1.2/tests/simpletest/test/browser_test.php 0000644 0001750 0001750 00000120010 10334504436 021325 0 ustar acme acme assertIdentical($history->getMethod(), false); $this->assertIdentical($history->getUrl(), false); $this->assertIdentical($history->getParameters(), false); } function testCannotMoveInEmptyHistory() { $history = &new SimpleBrowserHistory(); $this->assertFalse($history->back()); $this->assertFalse($history->forward()); } function testCurrentTargetAccessors() { $history = &new SimpleBrowserHistory(); $history->recordEntry( 'GET', new SimpleUrl('http://www.here.com/'), new SimpleFormEncoding()); $this->assertIdentical($history->getMethod(), 'GET'); $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.here.com/')); $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); } function testSecondEntryAccessors() { $history = &new SimpleBrowserHistory(); $history->recordEntry( 'GET', new SimpleUrl('http://www.first.com/'), new SimpleFormEncoding()); $history->recordEntry( 'POST', new SimpleUrl('http://www.second.com/'), new SimpleFormEncoding(array('a' => 1))); $this->assertIdentical($history->getMethod(), 'POST'); $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); $this->assertIdentical( $history->getParameters(), new SimpleFormEncoding(array('a' => 1))); } function testGoingBackwards() { $history = &new SimpleBrowserHistory(); $history->recordEntry( 'GET', new SimpleUrl('http://www.first.com/'), new SimpleFormEncoding()); $history->recordEntry( 'POST', new SimpleUrl('http://www.second.com/'), new SimpleFormEncoding(array('a' => 1))); $this->assertTrue($history->back()); $this->assertIdentical($history->getMethod(), 'GET'); $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); } function testGoingBackwardsOffBeginning() { $history = &new SimpleBrowserHistory(); $history->recordEntry( 'GET', new SimpleUrl('http://www.first.com/'), new SimpleFormEncoding()); $this->assertFalse($history->back()); $this->assertIdentical($history->getMethod(), 'GET'); $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); } function testGoingForwardsOffEnd() { $history = &new SimpleBrowserHistory(); $history->recordEntry( 'GET', new SimpleUrl('http://www.first.com/'), new SimpleFormEncoding()); $this->assertFalse($history->forward()); $this->assertIdentical($history->getMethod(), 'GET'); $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); } function testGoingBackwardsAndForwards() { $history = &new SimpleBrowserHistory(); $history->recordEntry( 'GET', new SimpleUrl('http://www.first.com/'), new SimpleFormEncoding()); $history->recordEntry( 'POST', new SimpleUrl('http://www.second.com/'), new SimpleFormEncoding(array('a' => 1))); $this->assertTrue($history->back()); $this->assertTrue($history->forward()); $this->assertIdentical($history->getMethod(), 'POST'); $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); $this->assertIdentical( $history->getParameters(), new SimpleFormEncoding(array('a' => 1))); } function testNewEntryReplacesNextOne() { $history = &new SimpleBrowserHistory(); $history->recordEntry( 'GET', new SimpleUrl('http://www.first.com/'), new SimpleFormEncoding()); $history->recordEntry( 'POST', new SimpleUrl('http://www.second.com/'), new SimpleFormEncoding(array('a' => 1))); $history->back(); $history->recordEntry( 'GET', new SimpleUrl('http://www.third.com/'), new SimpleFormEncoding()); $this->assertIdentical($history->getMethod(), 'GET'); $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.third.com/')); $this->assertIdentical($history->getParameters(), new SimpleFormEncoding()); } function testNewEntryDropsFutureEntries() { $history = &new SimpleBrowserHistory(); $history->recordEntry( 'GET', new SimpleUrl('http://www.first.com/'), new SimpleFormEncoding()); $history->recordEntry( 'GET', new SimpleUrl('http://www.second.com/'), new SimpleFormEncoding()); $history->recordEntry( 'GET', new SimpleUrl('http://www.third.com/'), new SimpleFormEncoding()); $history->back(); $history->back(); $history->recordEntry( 'GET', new SimpleUrl('http://www.fourth.com/'), new SimpleFormEncoding()); $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.fourth.com/')); $this->assertFalse($history->forward()); $history->back(); $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); $this->assertFalse($history->back()); } } class TestOfParsedPageAccess extends UnitTestCase { function &loadPage(&$page) { $response = &new MockSimpleHttpResponse($this); $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', $response); $browser = &new MockParseSimpleBrowser($this); $browser->setReturnReference('_createUserAgent', $agent); $browser->setReturnReference('_parse', $page); $browser->SimpleBrowser(); $browser->get('http://this.com/page.html'); return $browser; } function testAccessorsWhenNoPage() { $agent = &new MockSimpleUserAgent($this); $browser = &new MockParseSimpleBrowser($this); $browser->setReturnReference('_createUserAgent', $agent); $browser->SimpleBrowser(); $this->assertEqual($browser->getContent(), ''); } function testParse() { $page = &new MockSimplePage($this); $page->setReturnValue('getRequest', "GET here.html\r\n\r\n"); $page->setReturnValue('getRaw', 'Raw HTML'); $page->setReturnValue('getTitle', 'Here'); $page->setReturnValue('getFrameFocus', 'Frame'); $page->setReturnValue('getMimeType', 'text/html'); $page->setReturnValue('getResponseCode', 200); $page->setReturnValue('getAuthentication', 'Basic'); $page->setReturnValue('getRealm', 'Somewhere'); $page->setReturnValue('getTransportError', 'Ouch!'); $browser = &$this->loadPage($page); $this->assertEqual($browser->getRequest(), "GET here.html\r\n\r\n"); $this->assertEqual($browser->getContent(), 'Raw HTML'); $this->assertEqual($browser->getTitle(), 'Here'); $this->assertEqual($browser->getFrameFocus(), 'Frame'); $this->assertIdentical($browser->getResponseCode(), 200); $this->assertEqual($browser->getMimeType(), 'text/html'); $this->assertEqual($browser->getAuthentication(), 'Basic'); $this->assertEqual($browser->getRealm(), 'Somewhere'); $this->assertEqual($browser->getTransportError(), 'Ouch!'); } function testLinkAffirmationWhenPresent() { $page = &new MockSimplePage($this); $page->setReturnValue('getUrlsByLabel', array('http://www.nowhere.com')); $page->expectOnce('getUrlsByLabel', array('a link label')); $browser = &$this->loadPage($page); $this->assertTrue($browser->isLink('a link label')); $page->tally(); } function testLinkAffirmationByIdWhenPresent() { $page = &new MockSimplePage($this); $page->setReturnValue('getUrlById', true, array(99)); $page->setReturnValue('getUrlById', false, array('*')); $browser = &$this->loadPage($page); $this->assertTrue($browser->isLinkById(99)); $this->assertFalse($browser->isLinkById(98)); $page->tally(); } function testFormHandling() { $page = &new MockSimplePage($this); $page->setReturnValue('getField', 'Value'); $page->expectOnce('getField', array('key')); $page->expectOnce('setField', array('key', 'Value')); $page->setReturnValue('getFieldById', 'Id value'); $page->expectOnce('getFieldById', array(99)); $page->expectOnce('setFieldById', array(99, 'Id value')); $browser = &$this->loadPage($page); $this->assertEqual($browser->getField('key'), 'Value'); $this->assertEqual($browser->getFieldById(99), 'Id value'); $browser->setField('key', 'Value'); $browser->setFieldById(99, 'Id value'); $page->tally(); } } class TestOfBrowserNavigation extends UnitTestCase { function &createBrowser(&$agent, &$page) { $browser = &new MockParseSimpleBrowser($this); $browser->setReturnReference('_createUserAgent', $agent); $browser->setReturnReference('_parse', $page); $browser->SimpleBrowser(); return $browser; } function testClickLinkRequestsPage() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $agent->expectArgumentsAt( 0, 'fetchResponse', array('GET', new SimpleUrl('http://this.com/page.html'), false)); $agent->expectArgumentsAt( 1, 'fetchResponse', array('GET', new SimpleUrl('http://this.com/new.html'), false)); $agent->expectCallCount('fetchResponse', 2); $page = &new MockSimplePage($this); $page->setReturnValue('getUrlsByLabel', array(new SimpleUrl('http://this.com/new.html'))); $page->expectOnce('getUrlsByLabel', array('New')); $page->setReturnValue('getRaw', 'A page'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickLink('New')); $agent->tally(); $page->tally(); } function testClickLinkWithUnknownFrameStillRequestsWholePage() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $agent->expectArgumentsAt( 0, 'fetchResponse', array('GET', new SimpleUrl('http://this.com/page.html'), false)); $target = new SimpleUrl('http://this.com/new.html'); $target->setTarget('missing'); $agent->expectArgumentsAt( 1, 'fetchResponse', array('GET', $target, false)); $agent->expectCallCount('fetchResponse', 2); $parsed_url = new SimpleUrl('http://this.com/new.html'); $parsed_url->setTarget('missing'); $page = &new MockSimplePage($this); $page->setReturnValue('getUrlsByLabel', array($parsed_url)); $page->setReturnValue('hasFrames', false); $page->expectOnce('getUrlsByLabel', array('New')); $page->setReturnValue('getRaw', 'A page'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickLink('New')); $agent->tally(); $page->tally(); } function testClickingMissingLinkFails() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $page = &new MockSimplePage($this); $page->setReturnValue('getUrlsByLabel', array()); $page->setReturnValue('getRaw', 'stuff'); $browser = &$this->createBrowser($agent, $page); $this->assertTrue($browser->get('http://this.com/page.html')); $this->assertFalse($browser->clickLink('New')); } function testClickIndexedLink() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $agent->expectArgumentsAt( 1, 'fetchResponse', array('GET', new SimpleUrl('1.html'), false)); $agent->expectCallCount('fetchResponse', 2); $page = &new MockSimplePage($this); $page->setReturnValue( 'getUrlsByLabel', array(new SimpleUrl('0.html'), new SimpleUrl('1.html'))); $page->setReturnValue('getRaw', 'A page'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickLink('New', 1)); $agent->tally(); } function testClinkLinkById() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $agent->expectArgumentsAt(1, 'fetchResponse', array( 'GET', new SimpleUrl('http://this.com/link.html'), false)); $agent->expectCallCount('fetchResponse', 2); $page = &new MockSimplePage($this); $page->setReturnValue('getUrlById', new SimpleUrl('http://this.com/link.html')); $page->expectOnce('getUrlById', array(2)); $page->setReturnValue('getRaw', 'A page'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickLinkById(2)); $agent->tally(); $page->tally(); } function testClickingMissingLinkIdFails() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $page = &new MockSimplePage($this); $page->setReturnValue('getUrlById', false); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertFalse($browser->clickLink(0)); } function testSubmitFormByLabel() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $agent->expectArgumentsAt(1, 'fetchResponse', array( 'POST', new SimpleUrl('http://this.com/handler.html'), new SimpleFormEncoding(array('a' => 'A')))); $agent->expectCallCount('fetchResponse', 2); $form = &new MockSimpleForm($this); $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); $form->setReturnValue('getMethod', 'post'); $form->setReturnValue('submitButtonByLabel', new SimpleFormEncoding(array('a' => 'A'))); $form->expectOnce('submitButtonByLabel', array('Go', false)); $page = &new MockSimplePage($this); $page->setReturnReference('getFormBySubmitLabel', $form); $page->expectOnce('getFormBySubmitLabel', array('Go')); $page->setReturnValue('getRaw', 'stuff'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickSubmit('Go')); $agent->tally(); $page->tally(); $form->tally(); } function testDefaultSubmitFormByLabel() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $agent->expectArgumentsAt(1, 'fetchResponse', array( 'GET', new SimpleUrl('http://this.com/page.html'), new SimpleFormEncoding(array('a' => 'A')))); $agent->expectCallCount('fetchResponse', 2); $form = &new MockSimpleForm($this); $form->setReturnValue('getAction', new SimpleUrl('http://this.com/page.html')); $form->setReturnValue('getMethod', 'get'); $form->setReturnValue('submitButtonByLabel', new SimpleFormEncoding(array('a' => 'A'))); $page = &new MockSimplePage($this); $page->setReturnReference('getFormBySubmitLabel', $form); $page->expectOnce('getFormBySubmitLabel', array('Submit')); $page->setReturnValue('getRaw', 'stuff'); $page->setReturnValue('getUrl', new SimpleUrl('http://this.com/page.html')); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickSubmit()); $agent->tally(); $page->tally(); $form->tally(); } function testSubmitFormByName() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $form = &new MockSimpleForm($this); $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); $form->setReturnValue('getMethod', 'post'); $form->setReturnValue('submitButtonByName', new SimpleFormEncoding(array('a' => 'A'))); $page = &new MockSimplePage($this); $page->setReturnReference('getFormBySubmitName', $form); $page->expectOnce('getFormBySubmitName', array('me')); $page->setReturnValue('getRaw', 'stuff'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickSubmitByName('me')); $page->tally(); } function testSubmitFormById() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $form = &new MockSimpleForm($this); $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); $form->setReturnValue('getMethod', 'post'); $form->setReturnValue('submitButtonById', new SimpleFormEncoding(array('a' => 'A'))); $form->expectOnce('submitButtonById', array(99, false)); $page = &new MockSimplePage($this); $page->setReturnReference('getFormBySubmitId', $form); $page->expectOnce('getFormBySubmitId', array(99)); $page->setReturnValue('getRaw', 'stuff'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickSubmitById(99)); $page->tally(); $form->tally(); } function testSubmitFormByImageLabel() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $form = &new MockSimpleForm($this); $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); $form->setReturnValue('getMethod', 'post'); $form->setReturnValue('submitImageByLabel', new SimpleFormEncoding(array('a' => 'A'))); $form->expectOnce('submitImageByLabel', array('Go!', 10, 11, false)); $page = &new MockSimplePage($this); $page->setReturnReference('getFormByImageLabel', $form); $page->expectOnce('getFormByImageLabel', array('Go!')); $page->setReturnValue('getRaw', 'stuff'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickImage('Go!', 10, 11)); $page->tally(); $form->tally(); } function testSubmitFormByImageName() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $form = &new MockSimpleForm($this); $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); $form->setReturnValue('getMethod', 'post'); $form->setReturnValue('submitImageByName', new SimpleFormEncoding(array('a' => 'A'))); $form->expectOnce('submitImageByName', array('a', 10, 11, false)); $page = &new MockSimplePage($this); $page->setReturnReference('getFormByImageName', $form); $page->expectOnce('getFormByImageName', array('a')); $page->setReturnValue('getRaw', 'stuff'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickImageByName('a', 10, 11)); $page->tally(); $form->tally(); } function testSubmitFormByImageId() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $form = &new MockSimpleForm($this); $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); $form->setReturnValue('getMethod', 'post'); $form->setReturnValue('submitImageById', new SimpleFormEncoding(array('a' => 'A'))); $form->expectOnce('submitImageById', array(99, 10, 11, false)); $page = &new MockSimplePage($this); $page->setReturnReference('getFormByImageId', $form); $page->expectOnce('getFormByImageId', array(99)); $page->setReturnValue('getRaw', 'stuff'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->clickImageById(99, 10, 11)); $page->tally(); $form->tally(); } function testSubmitFormByFormId() { $agent = &new MockSimpleUserAgent($this); $agent->setReturnReference('fetchResponse', new MockSimpleHttpResponse($this)); $agent->expectArgumentsAt(1, 'fetchResponse', array( 'POST', new SimpleUrl('http://this.com/handler.html'), new SimpleFormEncoding(array('a' => 'A')))); $agent->expectCallCount('fetchResponse', 2); $form = &new MockSimpleForm($this); $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); $form->setReturnValue('getMethod', 'post'); $form->setReturnValue('submit', new SimpleFormEncoding(array('a' => 'A'))); $page = &new MockSimplePage($this); $page->setReturnReference('getFormById', $form); $page->expectOnce('getFormById', array(33)); $page->setReturnValue('getRaw', 'stuff'); $browser = &$this->createBrowser($agent, $page); $browser->get('http://this.com/page.html'); $this->assertTrue($browser->submitFormById(33)); $agent->tally(); $page->tally(); } } class TestOfBrowserFrames extends UnitTestCase { function &createBrowser(&$agent) { $browser = &new MockUserAgentSimpleBrowser($this); $browser->setReturnReference('_createUserAgent', $agent); $browser->SimpleBrowser(); return $browser; } function &createUserAgent($pages) { $agent = &new MockSimpleUserAgent($this); foreach ($pages as $url => $raw) { $url = new SimpleUrl($url); $response = &new MockSimpleHttpResponse($this); $response->setReturnValue('getUrl', $url); $response->setReturnValue('getContent', $raw); $agent->setReturnReference('fetchResponse', $response, array('*', $url, '*')); } return $agent; } function testSimplePageHasNoFrames() { $browser = &$this->createBrowser($this->createUserAgent( array('http://site.with.no.frames/' => 'A non-framed page'))); $this->assertEqual( $browser->get('http://site.with.no.frames/'), 'A non-framed page'); $this->assertIdentical($browser->getFrames(), 'http://site.with.no.frames/'); } function testFramesetWithNoFrames() { $browser = &$this->createBrowser($this->createUserAgent( array('http://site.with.no.frames/' => '
'))); $this->assertEqual( $browser->get('http://site.with.no.frames/'), ''); $this->assertIdentical($browser->getFrames(), array()); } function testFramesetWithSingleFrame() { $frameset = ''; $browser = &$this->createBrowser($this->createUserAgent(array( 'http://site.with.one.frame/' => $frameset, 'http://site.with.one.frame/frame.html' => 'A frame'))); $this->assertEqual( $browser->get('http://site.with.one.frame/'), 'A frame'); $this->assertIdentical( $browser->getFrames(), array('a' => 'http://site.with.one.frame/frame.html')); } function testTitleTakenFromFramesetPage() { $frameset = '