1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace whm\Smoke\Rules\Html; |
4
|
|
|
|
5
|
|
|
use phm\HttpWebdriverClient\Http\Response\DomAwareResponse; |
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
7
|
|
|
use whm\Smoke\Rules\StandardRule; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* This rule checks if xpath is found in a html document. |
11
|
|
|
*/ |
12
|
|
|
class XPathExistsRule extends StandardRule |
13
|
|
|
{ |
14
|
|
|
// protected $contentTypes = ['text/html']; |
15
|
|
|
private $xPaths; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var boolean |
19
|
|
|
*/ |
20
|
|
|
private $useDom = true; |
21
|
|
|
|
22
|
|
|
public function init(array $xPaths, $useDom = true) |
23
|
|
|
{ |
24
|
|
|
$this->xPaths = $xPaths; |
25
|
|
|
$this->useDom = $useDom; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function doValidation(ResponseInterface $response) |
29
|
|
|
{ |
30
|
|
|
$domDocument = new \DOMDocument(); |
31
|
|
|
|
32
|
|
|
// @todo this could be part of an abstract class |
33
|
|
|
if ($this->useDom) { |
34
|
|
|
$content = (string)$response->getBody(); |
35
|
|
|
} else { |
36
|
|
|
if ($response instanceof DomAwareResponse) { |
37
|
|
|
$content = $response->getHtmlBody(); |
38
|
|
|
} else { |
39
|
|
|
$content = (string)$response->getBody(); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
@$domDocument->loadHTML($content); |
|
|
|
|
44
|
|
|
|
45
|
|
|
$domXPath = new \DOMXPath($domDocument); |
46
|
|
|
|
47
|
|
|
foreach ($this->xPaths as $xpath) { |
48
|
|
|
$count = $domXPath->query($xpath['pattern'])->length; |
49
|
|
|
|
50
|
|
|
if ($xpath['relation'] === 'equals') { |
51
|
|
|
$result = $count === (int)$xpath['value']; |
52
|
|
|
$message = 'The xpath "' . $xpath['pattern'] . '" was found ' . $count . ' times. Expected were exact ' . $xpath['value'] . ' occurencies.'; |
53
|
|
|
} elseif ($xpath['relation'] === 'less than') { |
54
|
|
|
$result = $count < (int)$xpath['value']; |
55
|
|
|
$message = 'The xpath "' . $xpath['pattern'] . '" was found ' . $count . ' times. Expected were less than ' . $xpath['value'] . '.'; |
56
|
|
|
} elseif ($xpath['relation'] === 'greater than') { |
57
|
|
|
$result = $count > (int)$xpath['value']; |
58
|
|
|
$message = 'The xpath "' . $xpath['pattern'] . '" was found ' . $count . ' times. Expected were more than ' . $xpath['value'] . '.'; |
59
|
|
|
} else { |
60
|
|
|
throw new \RuntimeException('Relation not defined. Given "' . $xpath['relation'] . '" expected [equals, greater than, less than]'); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$this->assert($result, $message); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: