InteractsWithPages.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2015 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\testing;
  12. use Exception;
  13. use InvalidArgumentException;
  14. use PHPUnit\Framework\ExpectationFailedException as PHPUnitException;
  15. use Symfony\Component\DomCrawler\Crawler;
  16. use Symfony\Component\DomCrawler\Form;
  17. use think\facade\Request;
  18. use think\facade\Url;
  19. use think\File;
  20. use think\helper\Str;
  21. use think\response\Redirect;
  22. trait InteractsWithPages
  23. {
  24. /** @var \Symfony\Component\DomCrawler\Crawler */
  25. protected $crawler;
  26. /**
  27. * All of the stored inputs for the current page.
  28. *
  29. * @var array
  30. */
  31. protected $inputs = [];
  32. /**
  33. * All of the stored uploads for the current page.
  34. *
  35. * @var array
  36. */
  37. protected $uploads = [];
  38. public function visit($uri)
  39. {
  40. return $this->makeRequest('GET', $uri);
  41. }
  42. protected function submitForm($buttonText, $inputs = [], $uploads = [])
  43. {
  44. $this->makeRequestUsingForm($this->fillForm($buttonText, $inputs), $uploads);
  45. return $this;
  46. }
  47. protected function see($text, $negate = false)
  48. {
  49. $method = $negate ? 'assertNotRegExp' : 'assertRegExp';
  50. $rawPattern = preg_quote($text, '/');
  51. $escapedPattern = preg_quote(htmlentities($text, ENT_QUOTES, 'UTF-8', false), '/');
  52. $pattern = $rawPattern == $escapedPattern
  53. ? $rawPattern : "({$rawPattern}|{$escapedPattern})";
  54. $this->$method("/$pattern/i", $this->response->getContent());
  55. return $this;
  56. }
  57. protected function notSee($text)
  58. {
  59. return $this->see($text, true);
  60. }
  61. public function seeInElement($element, $text, $negate = false)
  62. {
  63. if ($negate) {
  64. return $this->notSeeInElement($element, $text);
  65. }
  66. $this->assertTrue(
  67. $this->hasInElement($element, $text),
  68. "Element [$element] should contain the expected text [{$text}]"
  69. );
  70. return $this;
  71. }
  72. public function notSeeInElement($element, $text)
  73. {
  74. $this->assertFalse(
  75. $this->hasInElement($element, $text),
  76. "Element [$element] should not contain the expected text [{$text}]"
  77. );
  78. return $this;
  79. }
  80. public function seeLink($text, $url = null)
  81. {
  82. $message = "No links were found with expected text [{$text}]";
  83. if ($url) {
  84. $message .= " and URL [{$url}]";
  85. }
  86. $this->assertTrue($this->hasLink($text, $url), "{$message}.");
  87. return $this;
  88. }
  89. public function notSeeLink($text, $url = null)
  90. {
  91. $message = "A link was found with expected text [{$text}]";
  92. if ($url) {
  93. $message .= " and URL [{$url}]";
  94. }
  95. $this->assertFalse($this->hasLink($text, $url), "{$message}.");
  96. return $this;
  97. }
  98. protected function hasLink($text, $url = null)
  99. {
  100. $links = $this->crawler->selectLink($text);
  101. if ($links->count() == 0) {
  102. return false;
  103. }
  104. // If the URL is null, we assume the developer only wants to find a link
  105. // with the given text regardless of the URL. So, if we find the link
  106. // we will return true now. Otherwise, we look for the given URL.
  107. if (null == $url) {
  108. return true;
  109. }
  110. $url = $this->addRootToRelativeUrl($url);
  111. /** @var \DOMElement $link */
  112. foreach ($links as $link) {
  113. if ($link->getAttribute('href') == $url) {
  114. return true;
  115. }
  116. }
  117. return false;
  118. }
  119. protected function addRootToRelativeUrl($url)
  120. {
  121. if (!Str::startsWith($url, ['http', 'https'])) {
  122. return Url::build($url);
  123. }
  124. return $url;
  125. }
  126. public function seeInField($selector, $expected)
  127. {
  128. $this->assertSame(
  129. $expected, $this->getInputOrTextAreaValue($selector),
  130. "The field [{$selector}] does not contain the expected value [{$expected}]."
  131. );
  132. return $this;
  133. }
  134. public function notSeeInField($selector, $value)
  135. {
  136. $this->assertNotSame(
  137. $this->getInputOrTextAreaValue($selector), $value,
  138. "The input [{$selector}] should not contain the value [{$value}]."
  139. );
  140. return $this;
  141. }
  142. public function seeIsChecked($selector)
  143. {
  144. $this->assertTrue(
  145. $this->isChecked($selector),
  146. "The checkbox [{$selector}] is not checked."
  147. );
  148. return $this;
  149. }
  150. public function notSeeIsChecked($selector)
  151. {
  152. $this->assertFalse(
  153. $this->isChecked($selector),
  154. "The checkbox [{$selector}] is checked."
  155. );
  156. return $this;
  157. }
  158. protected function isChecked($selector)
  159. {
  160. $checkbox = $this->filterByNameOrId($selector, "input[type='checkbox']");
  161. if ($checkbox->count() == 0) {
  162. throw new Exception("There are no checkbox elements with the name or ID [$selector].");
  163. }
  164. return $checkbox->attr('checked') !== null;
  165. }
  166. public function seeIsSelected($selector, $expected)
  167. {
  168. $this->assertEquals(
  169. $expected, $this->getSelectedValue($selector),
  170. "The field [{$selector}] does not contain the selected value [{$expected}]."
  171. );
  172. return $this;
  173. }
  174. public function notSeeIsSelected($selector, $value)
  175. {
  176. $this->assertNotEquals(
  177. $value, $this->getSelectedValue($selector),
  178. "The field [{$selector}] contains the selected value [{$value}]."
  179. );
  180. return $this;
  181. }
  182. protected function getSelectedValue($selector)
  183. {
  184. $field = $this->filterByNameOrId($selector);
  185. if ($field->count() == 0) {
  186. throw new Exception("There are no elements with the name or ID [$selector].");
  187. }
  188. $element = $field->nodeName();
  189. if ('select' == $element) {
  190. return $this->getSelectedValueFromSelect($field);
  191. }
  192. if ('input' == $element) {
  193. return $this->getCheckedValueFromRadioGroup($field);
  194. }
  195. throw new Exception("Given selector [$selector] is not a select or radio group.");
  196. }
  197. protected function getSelectedValueFromSelect(Crawler $field)
  198. {
  199. if ($field->nodeName() !== 'select') {
  200. throw new Exception('Given element is not a select element.');
  201. }
  202. /** @var \DOMElement $option */
  203. foreach ($field->children() as $option) {
  204. if ($option->hasAttribute('selected')) {
  205. return $option->getAttribute('value');
  206. }
  207. }
  208. }
  209. protected function getCheckedValueFromRadioGroup(Crawler $radioGroup)
  210. {
  211. if ($radioGroup->nodeName() !== 'input' || $radioGroup->attr('type') !== 'radio') {
  212. throw new Exception('Given element is not a radio button.');
  213. }
  214. /** @var \DOMElement $radio */
  215. foreach ($radioGroup as $radio) {
  216. if ($radio->hasAttribute('checked')) {
  217. return $radio->getAttribute('value');
  218. }
  219. }
  220. }
  221. protected function click($name)
  222. {
  223. $link = $this->crawler->selectLink($name);
  224. if (!count($link)) {
  225. $link = $this->filterByNameOrId($name, 'a');
  226. if (!count($link)) {
  227. throw new InvalidArgumentException(
  228. "Could not find a link with a body, name, or ID attribute of [{$name}]."
  229. );
  230. }
  231. }
  232. $this->visit($link->link()->getUri());
  233. return $this;
  234. }
  235. protected function type($text, $element)
  236. {
  237. return $this->storeInput($element, $text);
  238. }
  239. protected function check($element)
  240. {
  241. return $this->storeInput($element, true);
  242. }
  243. protected function uncheck($element)
  244. {
  245. return $this->storeInput($element, false);
  246. }
  247. protected function select($option, $element)
  248. {
  249. return $this->storeInput($element, $option);
  250. }
  251. protected function attach($absolutePath, $element)
  252. {
  253. $this->uploads[$element] = $absolutePath;
  254. return $this->storeInput($element, $absolutePath);
  255. }
  256. protected function press($buttonText)
  257. {
  258. return $this->submitForm($buttonText, $this->inputs, $this->uploads);
  259. }
  260. protected function getInputOrTextAreaValue($selector)
  261. {
  262. $field = $this->filterByNameOrId($selector, ['input', 'textarea']);
  263. if ($field->count() == 0) {
  264. throw new Exception("There are no elements with the name or ID [$selector].");
  265. }
  266. $element = $field->nodeName();
  267. if ('input' == $element) {
  268. return $field->attr('value');
  269. }
  270. if ('textarea' == $element) {
  271. return $field->text();
  272. }
  273. throw new Exception("Given selector [$selector] is not an input or textarea.");
  274. }
  275. protected function seePageIs($uri)
  276. {
  277. $this->assertPageLoaded($uri = $this->prepareUrlForRequest($uri));
  278. $this->assertEquals(
  279. $uri, $this->currentUri, "Did not land on expected page [{$uri}].\n"
  280. );
  281. return $this;
  282. }
  283. protected function hasInElement($element, $text)
  284. {
  285. $elements = $this->crawler->filter($element);
  286. $rawPattern = preg_quote($text, '/');
  287. $escapedPattern = preg_quote(htmlentities($text, ENT_QUOTES, 'UTF-8', false), '/');
  288. $pattern = $rawPattern == $escapedPattern
  289. ? $rawPattern : "({$rawPattern}|{$escapedPattern})";
  290. foreach ($elements as $element) {
  291. $element = new Crawler($element);
  292. if (preg_match("/$pattern/i", $element->html())) {
  293. return true;
  294. }
  295. }
  296. return false;
  297. }
  298. protected function storeInput($element, $text)
  299. {
  300. $this->assertFilterProducesResults($element);
  301. $element = str_replace('#', '', $element);
  302. $this->inputs[$element] = $text;
  303. return $this;
  304. }
  305. protected function assertFilterProducesResults($filter)
  306. {
  307. $crawler = $this->filterByNameOrId($filter);
  308. if (!count($crawler)) {
  309. throw new InvalidArgumentException(
  310. "Nothing matched the filter [{$filter}] CSS query provided for [{$this->currentUri}]."
  311. );
  312. }
  313. }
  314. protected function fillForm($buttonText, $inputs = [])
  315. {
  316. if (!is_string($buttonText)) {
  317. $inputs = $buttonText;
  318. $buttonText = null;
  319. }
  320. return $this->getForm($buttonText)->setValues($inputs);
  321. }
  322. protected function getForm($buttonText = null)
  323. {
  324. try {
  325. if ($buttonText) {
  326. return $this->crawler->selectButton($buttonText)->form();
  327. }
  328. return $this->crawler->filter('form')->form();
  329. } catch (InvalidArgumentException $e) {
  330. throw new InvalidArgumentException(
  331. "Could not find a form that has submit button [{$buttonText}]."
  332. );
  333. }
  334. }
  335. protected function filterByNameOrId($name, $elements = '*')
  336. {
  337. $name = str_replace('#', '', $name);
  338. $id = str_replace(['[', ']'], ['\\[', '\\]'], $name);
  339. $elements = is_array($elements) ? $elements : [$elements];
  340. array_walk($elements, function (&$element) use ($name, $id) {
  341. $element = "{$element}#{$id}, {$element}[name='{$name}']";
  342. });
  343. return $this->crawler->filter(implode(', ', $elements));
  344. }
  345. protected function makeRequest($method, $uri, $parameters = [], $cookies = [], $files = [])
  346. {
  347. $uri = $this->prepareUrlForRequest($uri);
  348. $this->call($method, $uri, $parameters, $cookies, $files);
  349. $this->clearInputs()->followRedirects()->assertPageLoaded($uri);
  350. $this->currentUri = Request::url(true);
  351. $this->crawler = new Crawler($this->response->getContent(), $this->currentUri);
  352. return $this;
  353. }
  354. protected function makeRequestUsingForm(Form $form, array $uploads = [])
  355. {
  356. $files = $this->convertUploadsForTesting($form, $uploads);
  357. return $this->makeRequest(
  358. $form->getMethod(), $form->getUri(), $this->extractParametersFromForm($form), [], $files
  359. );
  360. }
  361. protected function assertPageLoaded($uri, $message = null)
  362. {
  363. $status = $this->response->getCode();
  364. try {
  365. $this->assertEquals(200, $status);
  366. } catch (PHPUnitException $e) {
  367. $message = $message ?: "A request to [{$uri}] failed. Received status code [{$status}].";
  368. throw new HttpException($message);
  369. }
  370. }
  371. protected function convertUploadsForTesting(Form $form, array $uploads)
  372. {
  373. $files = $form->getFiles();
  374. $names = array_keys($files);
  375. $files = array_map(function (array $file, $name) use ($uploads) {
  376. return isset($uploads[$name])
  377. ? $this->getUploadedFileForTesting($file, $uploads, $name)
  378. : $file;
  379. }, $files, $names);
  380. return array_combine($names, $files);
  381. }
  382. protected function getUploadedFileForTesting($file, $uploads, $name)
  383. {
  384. $file['name'] = basename($uploads[$name]);
  385. return new File(
  386. $file['tmp_name'], $file, true
  387. );
  388. }
  389. protected function extractParametersFromForm(Form $form)
  390. {
  391. parse_str(http_build_query($form->getValues()), $parameters);
  392. return $parameters;
  393. }
  394. protected function clearInputs()
  395. {
  396. $this->inputs = [];
  397. $this->uploads = [];
  398. return $this;
  399. }
  400. protected function followRedirects()
  401. {
  402. while ($this->response instanceof Redirect) {
  403. $this->makeRequest('GET', $this->response->getTargetUrl());
  404. }
  405. return $this;
  406. }
  407. protected function prepareUrlForRequest($uri)
  408. {
  409. if (Str::startsWith($uri, '/')) {
  410. $uri = substr($uri, 1);
  411. }
  412. if (!Str::startsWith($uri, 'http')) {
  413. $uri = $this->baseUrl . '/' . $uri;
  414. }
  415. return trim($uri, '/');
  416. }
  417. }