This repository has been archived by the owner on Aug 13, 2018. It is now read-only.
/
BasicContext.php
322 lines (280 loc) · 10.2 KB
/
BasicContext.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
<?php
namespace SilverStripe\Test\Behaviour;
use Behat\Behat\Context\ClosuredContextInterface,
Behat\Behat\Context\TranslatedContextInterface,
Behat\Behat\Context\BehatContext,
Behat\Behat\Context\Step,
Behat\Behat\Event\StepEvent,
Behat\Behat\Exception\PendingException;
use Behat\Mink\Driver\Selenium2Driver;
use Behat\Gherkin\Node\PyStringNode,
Behat\Gherkin\Node\TableNode;
// PHPUnit
require_once 'PHPUnit/Autoload.php';
require_once 'PHPUnit/Framework/Assert/Functions.php';
/**
* BasicContext
*
* Context used to define generic steps like following anchors or pressing buttons.
* Handles timeouts.
* Handles redirections.
* Handles AJAX enabled links, buttons and forms - jQuery is assumed.
*/
class BasicContext extends BehatContext
{
protected $context;
/**
* Initializes context.
* Every scenario gets it's own context object.
*
* @param array $parameters context parameters (set them up through behat.yml)
*/
public function __construct(array $parameters)
{
// Initialize your context here
$this->context = $parameters;
}
/**
* Get Mink session from MinkContext
*/
public function getSession($name = null)
{
return $this->getMainContext()->getSession($name);
}
/**
* @AfterStep ~@modal
*
* Excluding scenarios with @modal tag is required,
* because modal dialogs stop any JS interaction
*/
public function appendErrorHandlerBeforeStep(StepEvent $event)
{
$javascript = <<<JS
window.onerror = function(msg) {
var body = document.getElementsByTagName('body')[0];
body.setAttribute('data-jserrors', '[captured JavaScript error] ' + msg);
}
if ('undefined' !== typeof window.jQuery) {
window.jQuery('body').ajaxError(function(event, jqxhr, settings, exception) {
window.onerror(event.type + ': ' + settings.type + ' ' + settings.url + ' ' + exception);
});
}
JS;
$this->getSession()->executeScript($javascript);
}
/**
* @AfterStep ~@modal
*
* Excluding scenarios with @modal tag is required,
* because modal dialogs stop any JS interaction
*/
public function readErrorHandlerAfterStep(StepEvent $event)
{
$page = $this->getSession()->getPage();
$jserrors = $page->find('xpath', '//body[@data-jserrors]');
if (null !== $jserrors) {
$this->takeScreenshot($event);
throw new \Exception($jserrors->getAttribute('data-jserrors'));
}
}
/**
* Hook into jQuery ajaxStart, ajaxSuccess and ajaxComplete events.
* Prepare __ajaxStatus() functions and attach them to these handlers.
* Event handlers are removed after one run.
*
* @BeforeStep
*/
public function handleAjaxBeforeStep(StepEvent $event)
{
$ajax_enabled_steps = $this->getMainContext()->getAjaxEnabledSteps();
$ajax_enabled_steps = implode('|', array_filter($ajax_enabled_steps));
if (empty($ajax_enabled_steps) || !preg_match('/(' . $ajax_enabled_steps . ')/i', $event->getStep()->getText())) {
return;
}
$javascript = <<<JS
if ('undefined' !== typeof window.jQuery) {
window.jQuery(document).on('ajaxStart.ss.test.behaviour', function(){
window.__ajaxStatus = function() {
return 'waiting';
};
});
window.jQuery(document).on('ajaxComplete.ss.test.behaviour', function(e, jqXHR){
if (null === jqXHR.getResponseHeader('X-ControllerURL')) {
window.__ajaxStatus = function() {
return 'no ajax';
};
}
});
window.jQuery(document).on('ajaxSuccess.ss.test.behaviour', function(e, jqXHR){
if (null === jqXHR.getResponseHeader('X-ControllerURL')) {
window.__ajaxStatus = function() {
return 'success';
};
}
});
}
JS;
$this->getSession()->executeScript($javascript);
}
/**
* Wait for the __ajaxStatus()to return anything but 'waiting'.
* Don't wait longer than 5 seconds.
*
* Don't unregister handler if we're dealing with modal windows
*
* @AfterStep ~@modal
*/
public function handleAjaxAfterStep(StepEvent $event)
{
$ajax_enabled_steps = $this->getMainContext()->getAjaxEnabledSteps();
$ajax_enabled_steps = implode('|', array_filter($ajax_enabled_steps));
if (empty($ajax_enabled_steps) || !preg_match('/(' . $ajax_enabled_steps . ')/i', $event->getStep()->getText())) {
return;
}
$this->handleAjaxTimeout();
$javascript = <<<JS
if ('undefined' !== typeof window.jQuery) {
window.jQuery(document).off('ajaxStart.ss.test.behaviour');
window.jQuery(document).off('ajaxComplete.ss.test.behaviour');
window.jQuery(document).off('ajaxSuccess.ss.test.behaviour');
}
JS;
$this->getSession()->executeScript($javascript);
}
public function handleAjaxTimeout()
{
$this->getSession()->wait(5000,
"(typeof window.__ajaxStatus !== 'undefined' ? window.__ajaxStatus() : 'no ajax') !== 'waiting'"
);
// wait additional 100ms to allow DOM to update
$this->getSession()->wait(100);
}
/**
* Take screenshot when step fails.
* Works only with Selenium2Driver.
*
* @AfterStep
*/
public function takeScreenshotAfterFailedStep(StepEvent $event)
{
if (4 === $event->getResult()) {
$this->takeScreenshot($event);
}
}
public function takeScreenshot(StepEvent $event) {
$driver = $this->getSession()->getDriver();
// quit silently when unsupported
if (!($driver instanceof Selenium2Driver)) {
return;
}
$parent = $event->getLogicalParent();
$feature = $parent->getFeature();
$step = $event->getStep();
$screenshot_path = null;
if (isset($this->context['screenshot_path'])) {
$screenshot_path = realpath($this->context['screenshot_path']);
if (!$screenshot_path) {
\Filesystem::makeFolder($this->context['screenshot_path']);
$screenshot_path = realpath($this->context['screenshot_path']);
}
}
if (!$screenshot_path) {
$screenshot_path = realpath(sys_get_temp_dir());
}
if (!file_exists($screenshot_path)) {
file_put_contents('php://stderr', sprintf('"%s" is not valid directory and failed to create it' . PHP_EOL, $this->context['screenshot_path']));
return;
}
if (file_exists($screenshot_path) && !is_dir($screenshot_path)) {
file_put_contents('php://stderr', sprintf('"%s" is not valid directory' . PHP_EOL, $this->context['screenshot_path']));
return;
}
if (file_exists($screenshot_path) && !is_writable($screenshot_path)) {
file_put_contents('php://stderr', sprintf('"%s" directory is not writable' . PHP_EOL, $screenshot_path));
return;
}
$screenshot_path = sprintf('%s/%s_%d.png', $screenshot_path, basename($feature->getFile()), $step->getLine());
$screenshot = $driver->wdSession->screenshot();
file_put_contents($screenshot_path, base64_decode($screenshot));
file_put_contents('php://stderr', sprintf('Saving screenshot into %s' . PHP_EOL, $screenshot_path));
}
/**
* @Then /^I should be redirected to "([^"]+)"/
*/
public function stepIShouldBeRedirectedTo($url)
{
if ($this->getMainContext()->canIntercept()) {
$client = $this->getSession()->getDriver()->getClient();
$client->followRedirects(true);
$client->followRedirect();
$url = $this->getMainContext()->joinUrlParts($this->context['base_url'], $url);
assertTrue($this->getMainContext()->isCurrentUrlSimilarTo($url), sprintf('Current URL is not %s', $url));
}
}
/**
* @Given /^I wait for "(\d+)"$/
*/
public function stepIWaitFor($ms)
{
$this->getSession()->wait($ms);
}
/**
* @Given /^I press "([^"]*)" button$/
*/
public function stepIPressButton($button)
{
$page = $this->getSession()->getPage();
$button_element = $page->find('named', array('link_or_button', "'$button'"));
assertNotNull($button_element, sprintf('%s button not found', $button));
$button_element->click();
}
/**
* @Given /^I click "([^"]*)" in the "([^"]*)" element$/
*/
public function iClickInTheElement($text, $selector)
{
$page = $this->getSession()->getPage();
$parent_element = $page->find('css', $selector);
assertNotNull($parent_element, sprintf('"%s" element not found', $selector));
$element = $parent_element->find('xpath', sprintf('//*[count(*)=0 and contains(.,"%s")]', $text));
assertNotNull($element, sprintf('"%s" not found', $text));
$element->click();
}
/**
* @Given /^I type "([^"]*)" into the dialog$/
*/
public function iTypeIntoTheDialog($data)
{
$data = array(
'text' => $data,
);
$this->getSession()->getDriver()->wdSession->postAlert_text($data);
}
/**
* @Given /^I confirm the dialog$/
*/
public function iConfirmTheDialog()
{
$this->getSession()->getDriver()->wdSession->accept_alert();
$this->handleAjaxTimeout();
}
/**
* @Given /^I dismiss the dialog$/
*/
public function iDismissTheDialog()
{
$this->getSession()->getDriver()->wdSession->dismiss_alert();
$this->handleAjaxTimeout();
}
/**
* @Given /^(I attach the file .*) with HTML5$/
*/
public function iAttachTheFileTo($step)
{
$this->getSession()->evaluateScript("jQuery('.ss-uploadfield-editandorganize').show()");
$this->getSession()->evaluateScript("jQuery('[name=\"AssetUploadField\"]').css({opacity:1,visibility:'visible',height:'1px',width:'1px'})");
$this->getSession()->evaluateScript("jQuery('[name=\"files[]\"]').css({opacity:1,visibility:'visible',height:'1px',width:'1px'})");
$this->getSession()->wait(1000);
return new Step\Given($step);
}
}