aboutsummaryrefslogtreecommitdiffstats
path: root/it/it-tests/src/test/java/selenium/SeleneseTest.java
blob: f78438a80b03e35a4b399c5c959e08e8df4f5197 (plain)
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
/*
 * SonarQube, open source software quality management tool.
 * Copyright (C) 2008-2014 SonarSource
 * mailto:contact AT sonarsource DOT com
 *
 * SonarQube is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * SonarQube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package selenium;

import com.sonar.orchestrator.Orchestrator;
import com.sonar.orchestrator.selenium.Selenese;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static java.util.regex.Pattern.DOTALL;
import static org.assertj.core.api.Assertions.assertThat;
import static selenium.Retry._5_SECONDS;

public class SeleneseTest {
  private final Selenese suite;

  private Map<String, String> variables;
  private String baseUrl;
  private SeleniumDriver driver;

  public SeleneseTest(Selenese suite) {
    this.suite = suite;
  }

  public void runOn(Orchestrator orchestrator) {
    this.variables = new HashMap<>();
    this.baseUrl = orchestrator.getServer().getUrl();
    this.driver = Browser.FIREFOX.getDriverForThread();

    driver.manage().deleteAllCookies();

    for (File file : suite.getHtmlTests()) {
      System.out.println();
      System.out.println("============ " + file.getName() + " ============");
      Document doc = parse(file);
      for (Element table : doc.getElementsByTag("table")) {
        for (Element tbody : table.getElementsByTag("tbody")) {
          for (Element tr : tbody.getElementsByTag("tr")) {
            String action = tr.child(0).text();
            String param1 = tr.child(1).text();
            String param2 = tr.child(2).text();

            action(action, param1, param2);
          }
        }
      }
    }
  }

  private static Document parse(File file) {
    try {
      return Jsoup.parse(file, UTF_8.name());
    } catch (IOException e) {
      throw new RuntimeException("Unable to parse file: " + file, e);
    }
  }

  public SeleneseTest action(String action, String param1, String param2) {
    switch (action) {
      case "open":
        open(param1);
        return this;
      case "type":
        type(param1, param2);
        return this;
      case "select":
        select(param1, param2);
        return this;
      case "clickAndWait":
      case "click":
        click(param1);
        return this;
      case "check":
        check(param1);
        return this;
      case "selectFrame":
        selectFrame(param1);
        return this;
      case "assertElementPresent":
        assertElementPresent(param1);
        return this;
      case "assertElementNotPresent":
        assertElementNotPresent(param1);
        return this;
      case "storeText":
        storeText(param1, param2);
        return this;
      case "storeEval":
        storeEval(param1, param2);
        return this;
      case "assertText":
      case "waitForText":
        assertText(param1, param2);
        return this;
      case "assertNotText":
      case "waitForNotText":
        assertNotText(param1, param2);
        return this;
      case "assertTextPresent":
        assertTextPresent(param1);
      case "assertTextNotPresent":
        assertTextNotPresent(param1);
        return this;
      case "assertLocation":
        assertLocation(param1);
        return this;
      case "waitForElementPresent":
        waitForElementPresent(param1);
        return this;
      case "waitForVisible":
        waitForVisible(param1);
        return this;
      case "assertValue":
      case "waitForValue":
      case "verifyValue":
        assertInputValue(param1, param2);
        return this;
      case "assertConfirmation":
        confirm(param1);
        return this;
      case "setTimeout":
        // Ignore
        return this;
    }

    throw new IllegalArgumentException("Unsupported action: " + action);
  }

  private void open(String url) {
    if (url.startsWith("/sonar/")) {
      goTo(url.substring(6));
    } else {
      goTo(url);
    }
  }

  private void goTo(String url) {
    requireNonNull(url, "The url cannot be null");

    URI uri = URI.create(url.replace(" ", "%20"));
    if (!uri.isAbsolute()) {
      url = baseUrl + url;
    }

    System.out.println("goTo " + url);
    driver.get(url);
    System.out.println(" - current url " + driver.getCurrentUrl());
  }

  private LazyDomElement find(String selector) {
    selector = replacePlaceholders(selector);

    if (selector.startsWith("link=")) {
      return find("a").withText(selector.substring(5));
    }

    By by;
    if (selector.startsWith("//")) {
      by = new By.ByXPath(selector);
    } else if (selector.startsWith("xpath=")) {
      by = new By.ByXPath(selector.substring(6));
    } else if (selector.startsWith("id=")) {
      by = new By.ById(selector.substring(3));
    } else if (selector.startsWith("name=")) {
      by = new By.ByName(selector.substring(5));
    } else if (selector.startsWith("css=")) {
      by = new By.ByCssSelector(selector.substring(4));
    } else if (selector.startsWith("class=")) {
      by = new By.ByCssSelector("." + selector.substring(6));
    } else {
      by = new ByCssSelectorOrByNameOrById(selector);
    }

    return new LazyDomElement(driver, by);
  }

  private void click(String selector) {
    find(selector).click();
  }

  private void check(String selector) {
    find(selector).check();
  }

  private void selectFrame(final String id) {
    if ("relative=parent".equals(id)) {
      return;
    }

    System.out.println(" - selectFrame(" + id + ")");
    _5_SECONDS.execute(new Runnable() {
      @Override
      public void run() {
        driver.switchTo().frame(id);
      }
    });
  }

  private void type(String selector, String text) {
    find(selector).fill(replacePlaceholders(text));
  }

  private void select(String selector, String text) {
    if (text.startsWith("label=")) {
      find(selector).select(text.substring(6));
    } else {
      find(selector).select(text);
    }
  }

  private void assertElementPresent(String selector) {
    find(selector).should().beDisplayed();
  }

  private void assertElementNotPresent(String selector) {
    find(selector).should().not().beDisplayed();
  }

  private void storeText(String selector, String name) {
    find(selector).execute(new ExtractVariable(name));
  }

  private void storeEval(String expression, String name) {
    variables.put(name, driver.executeScript("return " + expression).toString());
  }

  private class ExtractVariable implements Consumer<WebElement> {
    private final String name;

    ExtractVariable(String name) {
      this.name = name;
    }

    @Override
    public void accept(WebElement webElement) {
      variables.put(name, webElement.getText());
    }

    public String toString() {
      return "read value into " + name;
    }
  }

  private void assertText(String selector, String pattern) {
    pattern = replacePlaceholders(pattern);

    if (pattern.startsWith("exact:")) {
      String expectedText = pattern.substring(6);
      find(selector).withText(expectedText).should().exist();
      return;
    }

    if (pattern.startsWith("regexp:")) {
      find(selector).should().match(regex(pattern));
      return;
    }

    find(selector).should().match(glob(pattern));
  }

  private void assertNotText(String selector, String pattern) {
    pattern = replacePlaceholders(pattern);

    if (pattern.startsWith("exact:")) {
      String expectedText = pattern.substring(6);
      find(selector).withText(expectedText).should().not().exist();
      return;
    }

    if (pattern.startsWith("regexp:")) {
      find(selector).should().not().match(regex(pattern));
      return;
    }

    find(selector).should().not().match(glob(pattern));
  }

  private static Pattern glob(String pattern) {
    String regexp = pattern.replaceFirst("glob:", "");
    regexp = regexp.replaceAll("([\\]\\[\\\\{\\}$\\(\\)\\|\\^\\+.])", "\\\\$1");
    regexp = regexp.replaceAll("\\*", ".*");
    regexp = regexp.replaceAll("\\?", ".");
    return Pattern.compile(regexp, DOTALL);
  }

  private static Pattern regex(String pattern) {
    String regexp = pattern.replaceFirst("regexp:", ".*") + ".*";
    return Pattern.compile(regexp, DOTALL);
  }

  private void assertTextPresent(String text) {
    find("body").should().contain(text);
  }

  private void assertTextNotPresent(String text) {
    find("body").should().not().contain(text);
  }

  private void waitForElementPresent(String selector) {
    find(selector).should().exist();
  }

  private void waitForVisible(String selector) {
    find(selector).should().beDisplayed();
  }

  private void assertInputValue(String selector, String text) {
    find(selector).should().contain(text);
  }

  private void confirm(final String message) {
    System.out.println(" - confirm(" + message + ")");

    _5_SECONDS.execute(new Runnable() {
      @Override
      public void run() {
        driver.switchTo().alert().accept();
      }
    });
  }

  private void assertLocation(String urlPattern) {
    assertThat(driver.getCurrentUrl()).matches(glob(urlPattern));
  }

  private String replacePlaceholders(String text) {
    for (Map.Entry<String, String> entry : variables.entrySet()) {
      text = text.replace("${" + entry.getKey() + "}", entry.getValue());
    }
    return text;
  }
}