-
Notifications
You must be signed in to change notification settings - Fork 0
/
gunet.js
350 lines (311 loc) · 11.2 KB
/
gunet.js
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
const assert = require('assert');
const axios = require('axios');
const https = require('https');
const {spawn} = require('child_process');
const waitOn = require('wait-on');
const colors = require('colors');
const fs = require("fs");
const {ImgurClient} = require('imgur');
const path = require("path");
const BROWSER_OPTIONS = {
acceptInsecureCerts: true,
headless: process.env.HEADLESS === "true",
// devtools: process.env.CI !== "true",
defaultViewport: null,
slowMo: process.env.CI === "true" ? 0 : 10,
args: ['--start-maximized', "--window-size=1920,1080", '--incognito']
};
exports.browserOptions = () => BROWSER_OPTIONS;
exports.browserOptions = (opt) => {
return {
...BROWSER_OPTIONS,
...opt
};
};
exports.removeDirectory = async (directory) => {
console.log(colors.green(`Removing directory ${directory}`));
fs.rmdir(directory, {recursive: true}, () => {
});
}
exports.click = async (page, button) => {
await page.evaluate((button) => {
document.querySelector(button).click();
}, button);
}
exports.clickLast = async (page, button) => {
await page.evaluate((button) => {
let buttons = document.querySelectorAll(button);
buttons[buttons.length - 1].click();
}, button);
}
exports.clickNthButton = async (page, button, n) => {
const buttons = await page.$$(button);
await buttons[n].click();
}
exports.innerText = async (page, selector) => {
let text = await page.$eval(selector, el => el.innerText.trim());
console.log(`Text for selector [${selector}] is: [${text}]`);
return text;
}
exports.textContent = async (page, selector) => {
let element = await page.$(selector);
let text = await page.evaluate(element => element.textContent.trim(), element);
console.log(`Text content for selector [${selector}] is: [${text}]`);
return text;
}
exports.inputValue = async (page, selector) => {
const element = await page.$(selector);
const text = await page.evaluate(element => element.value, element);
console.log(`Input value for selector [${selector}] is: [${text}]`);
return text;
}
exports.uploadImage = async (imagePath) => {
let clientId = process.env.IMGUR_CLIENT_ID;
if (clientId !== null && clientId !== undefined) {
console.log(`Uploading image ${imagePath}`);
const client = new ImgurClient({clientId: clientId});
const response = await client.upload(imagePath);
console.log(colors.green(response.data.link));
}
}
exports.loginWith = async (page, user, password,
usernameField = "#username",
passwordField = "#password") => {
console.log('Checking for username and password field visibility')
await this.waitForVisible(page, usernameField)
await this.waitForVisible(page, passwordField)
console.log(`Logging in with ${user} and ******`);
await this.type(page, usernameField, user);
await this.type(page, passwordField, password);
await page.keyboard.press('Enter');
await page.waitForNavigation();
}
exports.fetchGoogleAuthenticatorScratchCode = async (user = "casuser") => {
console.log(`Fetching Scratch codes for ${user}...`);
const response = await this.doRequest(`${process.env.CAS_SERVER_NAME}/actuator/gauthCredentialRepository/${user}`,
"GET", {
'Accept': 'application/json'
});
return JSON.stringify(JSON.parse(response)[0].scratchCodes[0]);
}
// based on https://stackoverflow.com/a/55212494
exports.waitForVisible = async (page, selector) => {
await page.waitForSelector(selector, {visible: true})
}
exports.isVisible = async (page, selector) => {
let element = await page.$(selector);
console.log(`Checking visibility for ${selector}`);
return (element != null && await element.boundingBox() != null);
}
exports.assertVisibility = async (page, selector) => {
assert(await this.isVisible(page, selector));
}
exports.assertInvisibility = async (page, selector) => {
let element = await page.$(selector);
console.log(`Checking element invisibility for ${selector}`);
assert(element == null || await element.boundingBox() == null);
}
exports.assertTicketGrantingCookie = async (page) => {
const tgc = (await page.cookies()).filter(value => {
console.log(`Checking cookie ${value.name}`)
return value.name === "TGC"
});
assert(tgc.length !== 0);
console.log(`Asserting ticket-granting cookie: ${tgc[0].value}`);
return tgc[0];
}
exports.assertNoTicketGrantingCookie = async (page) => {
let tgc = (await page.cookies()).filter(value => {
console.log(`Checking cookie ${value.name}`)
return value.name === "TGC"
});
console.log(`Asserting no ticket-granting cookie: ${tgc}`);
assert(tgc.length === 0);
}
exports.casLogin = async (page, user, password, cas_type = 'simple-cas', cas_lang = "en") => {
await page.waitForTimeout(1000)
await this.loginWith(page, user, password);
await this.assertTicketGrantingCookie(page);
await page.waitForTimeout(2000)
if (cas_type == 'simple-cas') {
if (cas_lang === 'en') {
await this.assertInnerText(page, '#content div h2', "Log In Successful");
}
else if (cas_lang === 'el') {
await this.assertInnerText(page, '#content div h2', "Επιτυχής Σύνδεση");
}
}
else if (cas_type == 'gunet_cas') {
if (cas_lang === 'en') {
await this.assertInnerTextContains(page, '#content div h2', "Welcome");
}
else if (cas_lang === 'el') {
await this.assertInnerTextContains(page, '#content div h2', "Kαλώς ήρθες");
}
}
}
exports.submitForm = async (page, selector) => {
console.log(`Submitting form ${selector}`);
await page.$eval(selector, form => form.submit());
await page.waitForTimeout(2500)
}
exports.type = async (page, selector, value) => {
console.log(`Typing in field ${selector}`);
await page.$eval(selector, el => el.value = '');
await page.type(selector, value);
}
exports.newPage = async (browser) => {
console.clear();
let page = (await browser.pages())[0];
if (page === undefined) {
page = await browser.newPage();
}
await page.setDefaultNavigationTimeout(0);
// await page.setRequestInterception(true);
await page.bringToFront();
return page;
}
exports.assertParameter = async (page, param) => {
console.log(`Asserting parameter ${param} in URL: ${page.url()}`);
let result = new URL(page.url());
let value = result.searchParams.get(param);
console.log(`Parameter ${param} with value ${value}`);
assert(value != null);
return value;
}
exports.assertMissingParameter = async (page, param) => {
let result = new URL(page.url());
assert(result.searchParams.has(param) === false);
}
exports.sleep = async (ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
exports.assertTicketParameter = async (page) => {
console.log(`Page URL: ${page.url()}`);
let result = new URL(page.url());
assert(result.searchParams.has("ticket"))
let ticket = result.searchParams.get("ticket");
console.log(`Ticket: ${ticket}`);
assert(ticket != null);
return ticket;
}
exports.doRequest = async (url, method = "GET", headers = {}, statusCode = 200, requestBody = undefined) => {
return new Promise((resolve, reject) => {
let options = {
method: method,
rejectUnauthorized: false,
headers: headers
};
console.log(`Contacting ${url} via ${method}`)
const handler = (res) => {
console.log(`Response status code: ${res.statusCode}`)
if (statusCode > 0) {
assert(res.statusCode === statusCode);
}
res.setEncoding("utf8");
const body = [];
res.on("data", chunk => body.push(chunk));
res.on("end", () => resolve(body.join("")));
};
if (requestBody !== undefined) {
let request = https.request(url, options, res => {
handler(res);
}).on("error", reject);
request.write(requestBody);
} else {
https.get(url, options, res => {
handler(res);
}).on("error", reject);
}
});
}
exports.doGet = async (url, successHandler, failureHandler) => {
const instance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
});
await instance
.get(url)
.then(res => {
console.log(res.data);
successHandler(res);
})
.catch(error => {
failureHandler(error);
})
}
exports.doPost = async (url, params, headers, successHandler, failureHandler) => {
const instance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
});
let urlParams = params instanceof URLSearchParams ? params : new URLSearchParams(params);
await instance
.post(url, urlParams, {headers: headers})
.then(res => {
console.log(res.data);
successHandler(res);
})
.catch(error => {
failureHandler(error);
})
}
exports.waitFor = async (url, successHandler, failureHandler) => {
let opts = {
resources: [url],
delay: 1000,
interval: 2000,
timeout: 120000
};
await waitOn(opts)
.then(function () {
successHandler("good")
})
.catch(function (err) {
failureHandler(err);
});
}
exports.assertInnerTextStartsWith = async (page, selector, value) => {
const header = await this.innerText(page, selector);
assert(header.startsWith(value));
}
exports.assertInnerTextContains = async (page, selector, value) => {
const header = await this.innerText(page, selector);
assert(header.includes(value));
}
exports.assertInnerText = async (page, selector, value) => {
const header = await this.innerText(page, selector);
assert(header === value)
}
exports.assertPageTitle = async (page, value) => {
const title = await page.title();
console.log(`Page Title: ${title}`);
assert(title === value)
}
exports.screenshot = async (page) => {
let index = Math.floor(Math.random() * 10000);
let filePath = path.join(__dirname, `/screenshot${index}.png`)
await page.screenshot({path: filePath, fullPage: true});
console.log(colors.green(`Screenshot saved at ${filePath}`));
await this.uploadImage(filePath);
}
exports.assertTextContent = async (page, selector, value) => {
await page.waitForSelector(selector, {visible: true});
let header = await this.textContent(page, selector);
assert(header === value);
}
exports.assertTextContentStartsWith = async (page, selector, value) => {
await page.waitForSelector(selector, {visible: true});
let header = await this.textContent(page, selector);
assert(header.startsWith(value));
}
exports.assertTextInSource = async (page, value) => {
let source = await page.content();
let position = await source.search(value);
console.log(`Position for value [${value}]: [${position}]`);
assert(position != -1);
}