1: <?php
2:
3: /**
4: * Jyxo PHP Library
5: *
6: * LICENSE
7: *
8: * This source file is subject to the new BSD license that is bundled
9: * with this package in the file license.txt.
10: * It is also available through the world-wide-web at this URL:
11: * https://github.com/jyxo/php/blob/master/license.txt
12: */
13:
14: /**
15: * Common HTTP response test.
16: * Checks only availability in the default form, but can be easily extended with additional checks.
17: *
18: * Example:
19: * <code>
20: * new Jyxo_Beholder_TestCase_HttpResponse('Foo', 'http://example.com/', array('body' => '/this text must be in body/m'))
21: * </code>
22: *
23: * @category Jyxo
24: * @package Jyxo_Beholder
25: * @copyright Copyright (c) 2005-2011 Jyxo, s.r.o.
26: * @license https://github.com/jyxo/php/blob/master/license.txt
27: * @author Jan Kaštánek
28: */
29: class Jyxo_Beholder_TestCase_HttpResponse extends Jyxo_Beholder_TestCase
30: {
31: /**
32: * Tested URL.
33: *
34: * @var string
35: */
36: private $url;
37:
38: /**
39: * Custom tests.
40: *
41: * @var array
42: */
43: private $tests;
44:
45: /**
46: * Constructor. Gets the testing URL and optional custom tests.
47: *
48: * @param string $description Test description
49: * @param string $url Tested URL
50: * @param array $tests Custom tests
51: */
52: public function __construct($description, $url, array $tests = array())
53: {
54: parent::__construct($description);
55:
56: $this->url = (string) $url;
57: $this->tests = $tests;
58: }
59:
60: /**
61: * Performs the test.
62: *
63: * @return Jyxo_Beholder_Result
64: */
65: public function run()
66: {
67: // The http extension is required
68: if (!extension_loaded('http')) {
69: return new Jyxo_Beholder_Result(Jyxo_Beholder_Result::NOT_APPLICABLE, 'Extension http missing');
70: }
71:
72: $http = new HttpRequest(
73: $this->url, HttpRequest::METH_GET, array(
74: 'connecttimeout' => 5, 'timeout' => 10, 'useragent' => 'JyxoBeholder'
75: )
76: );
77:
78: try {
79: $http->send();
80: if (200 !== $http->getResponseCode()) {
81: throw new Exception(sprintf('Http error: %s', $http->getResponseCode()));
82: }
83: if (isset($this->tests['body'])) {
84: $body = $http->getResponseBody();
85: if (!preg_match($this->tests['body'], $body)) {
86: $body = trim(strip_tags($body));
87: throw new Exception(sprintf('Invalid body: %s', Jyxo_String::cut($body, 16)));
88: }
89: }
90:
91: // OK
92: return new Jyxo_Beholder_Result(Jyxo_Beholder_Result::SUCCESS);
93:
94: } catch (HttpException $e) {
95: $inner = $e;
96: while (null !== $inner->innerException) {
97: $inner = $inner->innerException;
98: }
99: return new Jyxo_Beholder_Result(Jyxo_Beholder_Result::FAILURE, $inner->getMessage());
100:
101: } catch (Exception $e) {
102: return new Jyxo_Beholder_Result(Jyxo_Beholder_Result::FAILURE, $e->getMessage());
103: }
104: }
105: }
106: