-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtips.html
More file actions
464 lines (414 loc) · 21.4 KB
/
tips.html
File metadata and controls
464 lines (414 loc) · 21.4 KB
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<link href='https://fonts.googleapis.com/css?family=Chivo:900' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
<link rel="stylesheet" type="text/css" href="stylesheets/pygment_trac.css" media="screen">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script>hljs.initHighlightingOnLoad();</script>
<title>Testing With Node by NickTulett</title>
</head>
<body>
<div id="container">
<div class="inner">
<header>
<h1>Tips and Tricks</h1>
<h2></h2>
</header>
<!--
<section id="downloads" class="clearfix">
<a href="https://github.com/NickTulett/TestingWithNode/zipball/master" id="download-zip" class="button">
<span>Download .zip</span>
</a>
<a href="https://github.com/NickTulett/TestingWithNode/tarball/master" id="download-tar-gz" class="button">
<span>Download .tar.gz</span>
</a>
<a href="https://github.com/NickTulett/TestingWithNode" id="view-on-github" class="button">
<span>View on GitHub</span>
</a>
</section>
-->
<hr>
<section id="main_content">
<h2>
<a name="using-nodejs-a-an-automated-test-engine" class="anchor" href="#using-nodejs-a-an-automated-test-engine">
<span class="octicon octicon-link"></span>
</a>Random list of useful things</h2>
<h3>What development branch are we on?</h3>
<p>Example for Mercurial but could easily be adapted for git, svn, etc.</p>
<pre><code class="javascript">
require("execSync").exec("hg branch").stdout.replace(/\n|\r/g, "");
</code></pre>
<h3>What machine are we running on?</h3>
<pre><code class="javascript">
require("os").hostname();
</code></pre>
<h3>Maximise the browser window</h3>
<pre><code class="javascript">
driver.manage().window().maximize();
</code></pre>
<h3>Compare numbers with tolerance</h3>
<p>Different answers between test runs are not always wrong, if you have a known tolerance for differences.</p>
<p>This extends the number prototype to compare numbers to within 1%:</p>
<pre><code class="javascript">
Number.prototype.roughly = function (comparedTo) {
if (this == comparedTo) {
return true;
}
var diff = ((Math.abs(comparedTo - this)) / this) || 1;
return (diff < 0.01);
};
assert(latestValue.roughly(expectedValue),
"Value mismatch in latest run!");
</code></pre>
<h3>Get User's home directory cross-OS</h3>
<pre><code class="javascript">
var HOME = (process.platform.match(/win32/)
? process.env["USERPROFILE"]
: process.env["HOME"]).replace(/\\/g, "/");
</code></pre>
<h3>Select elements only if visible</h3>
<p>Using CSS property selectors you can select visible elements or elements that are inside a visible container.</p>
<p>e.g. a locator for specific class of icon in a modal dialog that can have one of a choice of divs showing</p>
<pre><code class="javascript">
div[style*='display: block'] li[tooltip='Chart']
</code></pre>
<h3>Check for a broken image</h3>
<p>If you have an image with a broken link, your users will just see an ugly icon.</p>
<p>You can check that an image is present by getting its naturalWidth property (supported by browsers and IE11).</p>
<pre><code class="javascript">
assert($("span[ng-show='report.attachment.id'] img", 1).getAttribute("naturalWidth"),
"PDF icon missing");
</code></pre>
<h3>Pull data from a text file in slices</h3>
<pre><code class="javascript">
//in this example I want to fill a comments array
//with the first 100 characters
//then the next 200
//then the next 300 and so on up to 1000 characters
var comments = [];
var comment;
var buffer = new Buffer(1024);
var lastPosition = 0;
var commentsFile = fs.openSync(testing.TEST_HOME + "Comments/Aeneidos.txt", "r");
for (var i = 1; i <= 10; i++) {
fs.readSync(commentsFile, buffer, 0, 100 * i, lastPosition);
comment = buffer.toString().slice(0, 100*i);
lastPosition += 100*i;
comments.push(comment);
}
fs.closeSync(commentsFile);
</code></pre>
<h3>Capture screenshots</h3>
<pre><code class="javascript">
//assuming HOME is the root for npm modules
var OutputType = require(HOME + "/node_modules/webdriver-sync/src/interfaces/OutputType.js");
if (driver.getScreenshotAs) {
var screenshot = driver.getScreenshotAs(OutputType.BASE64);
fs.writeFileSync(HOME + "/screenshots/UniqueScreenshotName.png",
screenshot, "base64");
}
</code></pre>
<h3 id="sh">Run commands on a remote (linux) server</h3>
<p>You might need to control the web server to set up the test environment or poll a log to check server side progress or errors.</p>
<p>To avoid having to enter an ssh password every time, <a href="http://www.thegeekstuff.com/2008/11/3-steps-to-perform-ssh-login-without-password-using-ssh-keygen-ssh-copy-id/">set up an ssh key</a>.</p>
<p>On Windows, download and run the full <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html">putty</a> installer to get the plink ssh client.</p>
<pre><code class="javascript">
function ssh(commands, user, host) {
if (typeof commands == "string") {
commands = [commands];
}
console.log("SSH to " + host);
var sshCall;
if (process.platform.match(/win32/)) {
sshCall = require("child_process").spawnSync(
"plink",
["-ssh", "-pw", "Y0rPassW0rd!",
user + "@" + host,
commands.join("; ")]
);
} else {
sshCall = require("child_process").spawnSync(
"ssh",
[user + "@" + host,
commands.join("; ")]
);
}
try {
if (sshCall.stderr.length) {
console.error("SSH FAILED " + sshCall.stderr.toString());
return sshCall.stderr.toString();
}
} catch (e) {
console.dir(sshCall);
}
return sshCall.stdout.toString();
}
//e.g.
log.startCase("Check no invalid files are left in the upload folder");
assert(!ssh("ls /home/tomcat/ROOT/uploads", true).length,
"Bad files left in the upload folder");
var sh = require("child_process").execSync;
function taillog(n, reverse) {
n = n || 10;
console.log("FETCHING LAST " + n + " LINES OF THE LOG");
var tailedLog = sh.exec("ssh tester@" + this.host + " \" tail -n " + n
+ " /var/log/tomcat7/AUT.log\"").stdout;
//if you are looking for specific messages by regex matching
//you might want to reverse the order so the last messages
//appear first
if (reverse) {
tailedLog = tailedLog.split(/\n/).reverse().join("\n");
}
//return the log as a String object augmented with a "top" method
//for getting the earliest (or latest if reversed) messages
tailedLog = new String(tailedLog);
tailedLog.top = function tailTop(lineCount) {
return this.split(/\n/).slice(0,lineCount).join();
}
return tailedLog;
}
aggregationLog = taillog(5, true);
//last line could be blank, so check last 2 for completion message
while (!aggregationLog.top(2).match(/Long running server-side job complete/)) {
//do something else, such as check for errors in the other 3 lines
}
function greplog(greppee, count, reverse) {
console.log("GREPPING LOG FOR '" + greppee + "'");
var greppedLog = sh.exec("ssh tester@" + this.host + " \" grep '" + greppee
+ "' /var/log/tomcat7/AUT.log\"").stdout;
if (count) {
greppedLog = greppedLog.split(/\n/).slice(-count).join("\n");
}
if (reverse) {
greppedLog = greppedLog.split(/\n/).reverse().join("\n");
}
return greppedLog;//will be empty (false) if the greppee phrase is not found
}
function MYSQL_dump() {
var dumpCMD = "mysqldump --user=testuser --max_allowed_packet=1G --host=" + host
+ " --port=3306 --default-character-set=utf8 \"testdb\" -ptestPassword > "
+ "dumps/" + host.split(/\./)[0] + "_DBdump.sql";
return sh.exec(dumpCMD);
}
</code></pre>
<h3>Testing session timeouts</h3>
<p>Assuming your session lifetime is controlled by a cookie, then it's simply a case of:</p>
<pre><code class="javascript">
//start a session
//do stuff
browser.manage().deleteAllCookies();
//now test the session has timed out
</code></pre>
<h3>CSS audits</h3>
<p>If you use a 3rd-party CSS framework, you will end up shipping a lot of styles you don't use. You might also want to limit the number of fonts and font-sizes to stop your site looking a mess. Webdriver can run a javascript routine in the browser's console to produce a quick CSS audit. This can be easily extended to look for other CSS properties.</p>
<pre><code class="javascript">
function PTL_cssAudit() {
var cssTally =
'var used = 0; ' +
'var count = 0;' +
'var tallies = {' +
'"fontSize": {},' +
'"fontFamily": {},' +
'"color": {},' +
'"backgroundColor": {}' +
'};' +
' [].forEach.call(document.styleSheets, function (styleSheet) {' +
'styleSheet.rules && [].forEach.call(styleSheet.rules, function (rule) {' +
'if (rule.style) {' +
'(rule.selectorText|| "").split(/, /).forEach(function (selector) {' +
'count++; ' +
'if (selector && !selector.match(/:/) ' +
'&& document.querySelectorAll(selector).length) {' +
'used++;' +
'for (var tally in tallies) {' +
'if (rule.style[tally] && (rule.style[tally] != "inherit")) {' +
'tallies[tally][rule.style[tally]] = ' +
'tallies[tally][rule.style[tally]] || [];' +
'tallies[tally][rule.style[tally]].push(rule.selectorText);' +
'}' +
'}' +
'}' +
'});' +
'}' +
'});' +
'});' +
'tallies.count = count;' +
'tallies.used = used;' +
'tallies.usage = Math.floor(100*used/count);' +
'return JSON.stringify(tallies);';
var audit = browser.executeScript(cssTally);
return JSON.parse(audit);
}
</code></pre>
<h3>Check for duplicate ids</h3>
<pre><code class="javascript">
log.startCase("Checking for duplicate element ids");
assert(!$("[id]").map(function (e) {
return e.getAttribute("id");
}).filter(function(e,i,a) {
return ((a.lastIndexOf(e) !== i) && !console.log(e));
}),
"Duplicate ids present");
</code></pre>
<h3>Making things stand out in console logs</h3>
<p>Allow a string or array of strings to be wrapped in a rectangular border:</p>
<pre><code class="javascript">
String.prototype.padded = function (finalLength) {
//pad a string with spaces to make it finalLength long
return (this + (new Array(120)).join(" ")).slice(0,finalLength);
};
Array.prototype.bordered = function (bChar) {
//find the length of the longest string in this array
var bWidth = this.reduce(function (a, b) { return a.length > b.length ? a : b; }).length;
//create a line of bChars to border this string
var bLine = (new Array(bWidth + 5)).join(bChar).slice(0,120);
//return the array as a newline-separated string with a bChar border
return "\n" + bLine + "\n"
+ this.map(function (a) {
return bChar + " " + (a.padded(bWidth)) + " " + bChar;
}).join("\n")
+ "\n" + bLine + "\n";
};
String.prototype.bordered = function (bChar) {
return this.split(/\n/).bordered(bChar);
};
</code></pre>
<h3 id="POSTjson">POSTing JSON to the server</h3>
<p>Often someone will tap you on the shoulder and ask if you can use your automation scripts to fill in a web-based form for them to save them having to do it hundreds of times. This is a perfectly cromulent reason to use automation but driving the front-end is fraught with danger from timing issues. A far better idea is to work out what data the page is POSTing and replicate that request directly.</p>
<p>There is no need to employ any external libraries or npm modules to POST data, you can use the browser itself. This has the benefit of occuring within the existing session, so you don't need to worry about spoofing credentials or cookies.</p>
<pre><code class="javascript">
function WD_postJSON(url, payload) {
var xhr = driver.executeScript(
"xhr = new XMLHttpRequest();" +
"xhr.open('POST', '" + url + "', false);" +
"xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8');" +
"xhr.send('" + JSON.stringify(payload) + "');" +
"return (xhr.status + '###' + xhr.responseText);"
);
xhr = xhr.split("###");
return {status: xhr[0], responseText: xhr[1]};
}
</code></pre>
<h3>Dealing with iframes</h3>
<p>Webdriver deals with iframes by switching context.</p>
<p>If you want the $() method to work inside an iframe rather than the page's root document, do this:</p>
<pre><code = "javascript">
browser.switchTo().frame("frmContent");//for an iframe with id frmContent
</code></pre>
<p>To return to the main document:</p>
<pre><code = "javascript">
browser.switchTo().defaultContent();
</code></pre>
<h3>Reading resource headers</h3>
<p>Let's assume you bundle your javascript to reduce request counts, want to ensure it is being gzipped but the name of the javascript resource changes between builds so that the browser does not fall back to the cached version when your javascript is updated</p>
<p>You can query the page itself to find the current URL for the javascript bundle, request it separately and check its headers:</p>
<pre><code class="javascript">
function getHeaders(url, specificHeader) {
var xhr_headers = driver.executeScript(
"xhr = new XMLHttpRequest();" +
"xhr.open('GET', '" + url + "', false);" +
"xhr.setRequestHeader('Accept-Encoding', 'gzip');" +
"xhr.send();" +
(specificHeader ?
"return xhr.getResponseHeader('" + specificHeader + "');" :
"return xhr.getAllResponseHeaders();")
);
return xhr_headers;
}
log.startCase("Check javascript bundle is gzipped");
var firstJS = browser.executeScript("return document.scripts[0].src;");
var CEheader = PTL.getHeaders(firstJS, "Content-Encoding");
assert(CEheader == "gzip", "gzip not enabled");
</code></pre>
<h3>Using a proxy server</h3>
<p>You might want to use a proxy server while you are testing, for instance to run the tests past <a href='https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project'>OWASP ZAPROXY</a> for additional security testing. You can do this in Firefox by editing the Profile and in Chrome via the ChromeOptions object:</p>
<pre><code class="javascript">
var wd = require("webdriver-sync");
var profile = new wd.FirefoxProfile();
profile.setPreference("network.proxy.http", "192.168.10.130");
profile.setPreference("network.proxy.http_port", 8080);
profile.setPreference("network.proxy.type", 1);//set to manual
var driver = new wd["FirefoxDriver"](profile);
//or in Chrome:
var chromeOptions = new wd.ChromeOptions();
chromeOptions.addArguments("proxy-server=192.168.10.130:8080");
var caps = new wd.DesiredCapabilities["chrome"]();
caps.setCapability("chromeOptions", chromeOptions);
var driver = new wd["ChromeDriver"](caps);
</code></pre>
<h3>Using ZAP proxy server in testing</h3>
<p>ZAP has a JSON API we can use during testing. We cannot use the XHR object in the browser because the ZAP server is not the same domain as the AUT, so we run wget as a child process and save the responses to a temporary file.</p>
<p>These are some routines to start a new ZAP session (call this at the start of your test script) and 2 routines to return a summary or a detailed breakdown of every HTTP request logged during the test:</p>
<pre><code class="javascript">
var sh = require("child_process").execSync;
var fs = require("fs");
function WD_zapGET(URL) {//helper routine for the methods below
var zapTemp = "ZAPtemp.json";
sh(`wget -O ${zapTemp} "${URL}"`);
var zapResponse = fs.readFileSync(zapTemp).toString();
fs.unlinkSync(zapTemp);
return JSON.parse(zapResponse);
}
function WD_zapSession(baseURL) {//create a new test session
//cannot use getJSON due to CORS, so use wget
var zapResponse = WD_zapGET(
`http://192.168.10.130:8080/JSON/core/action/newSession/?
zapapiformat=JSON&apikey=APIKEY&name=WD&overwrite=true`);
assert(zapResponse.Result,
"Could not start ZAP session");
}
function WD_zapRequestSummary(baseURL) {//request summary from test session
var zapResponse = WD_zapGET(
`http://192.168.10.130:8080/JSON/search/view/urlsByRequestRegex/
?zapapiformat=JSON&regex=.*&baseurl=${baseURL}&start=&count=`);
//id, url, status code, method, time
return zapResponse.urlsByRequestRegex;
}
function WD_zapRequestDetail(baseURL, start, count) {//full requests and responses from test session
start = start || "";
count = count || "";
var zapResponse = WD_zapGET(
`http://192.168.10.130:8080/JSON/search/view/messagesByRequestRegex/
?zapapiformat=JSON&regex=.*&baseurl=${baseURL}
&start=${start}&count=${count}`);
//id, requestHeader, requestBody, cookieParams, responseHeader, responseBody
return zapResponse.messagesByRequestRegex;
}
</code></pre>
<h3>Useful Sublime Text plugins</h3>
<ul>
<li><a href="https://sublime.wbond.net/">Package Control</a> - look for all the others here</li>
<li>Alignment</li>
<li>All Autocomplete</li>
<li>ColorPicker</li>
<li>Git</li>
<li>GitGutter</li>
<li>Github Color Theme</li>
<li>HTML-CSS-JS Prettify</li>
<li>Javascript & NodeJS Snippets</li>
<li>JSHint Gutter</li>
<li>Mercurial</li>
<li>Modific</li>
<li>Node Completions</li>
<li>SideBarEnhancements</li>
<li>Sublime REPL</li>
<li>SubliMerge Pro</li>
<li>Terminal</li>
</section>
<p>Note that to get JSHint Gutter to play nicely with ES6 (e.g. template strings), you need to copy or symlink the latest jshint npm module from /usr/lib/node_modules/jshint to ~/.config/sublime-text-3/Packages/JSHint Gutter/scripts/node_modules/jshint (or equivalent for your OS).</p>
<footer>
<a href="/TestingWithNode/">Testing With Node</a> is maintained by <a href="https://github.com/NickTulett">NickTulett</a>
<br>This page was generated by <a href="http://pages.github.com">GitHub Pages</a>. Tactile theme by <a href="https://twitter.com/jasonlong">Jason Long</a>.
</footer>
</div>
</div>
</body>
</html>