]> source.dussan.org Git - archiva.git/blob
d48072dddcffb872df6f6afd2124ef03408509db
[archiva.git] /
1 package org.apache.archiva.web.test.tools;
2 /*
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  */
20
21 import com.gargoylesoftware.htmlunit.WebClient;
22 import org.apache.commons.io.FileUtils;
23 import org.apache.commons.lang3.StringUtils;
24 import org.openqa.selenium.*;
25 import org.openqa.selenium.chrome.ChromeDriver;
26 import org.openqa.selenium.chrome.ChromeOptions;
27 import org.openqa.selenium.firefox.FirefoxDriver;
28 import org.openqa.selenium.htmlunit.HtmlUnitDriver;
29 import org.openqa.selenium.ie.InternetExplorerDriver;
30 import org.openqa.selenium.remote.DesiredCapabilities;
31 import org.openqa.selenium.remote.RemoteWebDriver;
32 import org.openqa.selenium.safari.SafariDriver;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import java.io.File;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.net.MalformedURLException;
41 import java.net.URL;
42 import java.nio.file.Files;
43 import java.nio.file.Path;
44 import java.nio.file.Paths;
45 import java.util.Properties;
46 import java.util.function.Consumer;
47 import java.util.function.Function;
48
49 /**
50  * Created by martin_s on 04.06.17.
51  */
52 public class WebdriverUtility
53 {
54
55     static final Logger log = LoggerFactory.getLogger( WebdriverUtility.class );
56
57     public static WebDriver newWebDriver() {
58         String seleniumBrowser = System.getProperty("selenium.browser");
59         String seleniumHost = System.getProperty("seleniumHost", "localhost");
60         int seleniumPort = Integer.getInteger("seleniumPort", 4444);
61         boolean seleniumRemote = Boolean.parseBoolean(System.getProperty("seleniumRemote","false"));
62         return newWebDriver(seleniumBrowser,seleniumHost, seleniumPort,seleniumRemote);
63     }
64
65     public static WebDriver newWebDriver(String seleniumBrowser, String seleniumHost, int seleniumPort, boolean seleniumRemote) {
66         log.info("WebDriver {}, {}, {}, {}", seleniumBrowser, seleniumHost, seleniumPort, seleniumRemote);
67         if (seleniumRemote && StringUtils.isEmpty( seleniumHost )) {
68             throw new IllegalArgumentException( "seleniumHost must be set, when seleniumRemote=true" );
69         }
70         try {
71
72             if ( StringUtils.contains(seleniumBrowser, "chrome")) {
73                 ChromeOptions options = new ChromeOptions();
74                 options.addArguments("start-maximized");
75                 if (seleniumRemote)
76                 {
77                     DesiredCapabilities capabilities = DesiredCapabilities.chrome();
78                     capabilities.setCapability( ChromeOptions.CAPABILITY, options );
79                     return new RemoteWebDriver( new URL( "http://" + seleniumHost + ":" + seleniumPort + "/wd/hub" ),
80                         capabilities
81                     );
82                 } else {
83                     return new ChromeDriver( options );
84                 }
85             }
86
87             if (StringUtils.contains(seleniumBrowser, "safari")) {
88                 if (seleniumRemote)
89                 {
90                     return new RemoteWebDriver( new URL( "http://" + seleniumHost + ":" + seleniumPort + "/wd/hub" ),
91                         DesiredCapabilities.safari()
92                     );
93                 } else {
94                     return new SafariDriver();
95                 }
96             }
97
98             if (StringUtils.contains(seleniumBrowser, "iexplore")) {
99                 DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
100                 capabilities.setCapability( InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true );
101                 WebDriver driver;
102                 if (seleniumRemote)
103                 {
104                     driver = new RemoteWebDriver( new URL( "http://" + seleniumHost + ":" + seleniumPort + "/wd/hub" ),
105                         capabilities
106                     );
107                 } else {
108                     driver = new InternetExplorerDriver( capabilities );
109                 }
110                 driver.manage().window().maximize();
111                 return driver;
112
113             }
114
115             if (StringUtils.contains( seleniumBrowser, "firefox" ))
116             {
117                 if ( seleniumRemote )
118                 {
119                     return new RemoteWebDriver( new URL( "http://" + seleniumHost + ":" + seleniumPort + "/wd/hub" ),
120                         DesiredCapabilities.firefox()
121                     );
122                 }
123                 else
124                 {
125                     return new FirefoxDriver();
126                 }
127             }
128
129             // Default driver
130             DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
131             capabilities.setJavascriptEnabled( true );
132             capabilities.setVersion( "firefox-52" );
133             WebDriver driver;
134             if ( seleniumRemote )
135             {
136                 driver = new RemoteWebDriver( new URL( "http://" + seleniumHost + ":" + seleniumPort + "/wd/hub" ),
137                     capabilities
138                 );
139             }
140             else
141             {
142                 driver = new HtmlUnitDriver( capabilities  ) {
143                     @Override
144                     protected WebClient modifyWebClient( WebClient client )
145                     {
146                         client.getOptions().setThrowExceptionOnFailingStatusCode( false );
147                         client.getOptions().setThrowExceptionOnScriptError( false );
148                         client.getOptions().setCssEnabled( true );
149                         return client;
150                     }
151                 };
152             }
153             return driver;
154
155         } catch (MalformedURLException e) {
156             throw new RuntimeException("Initializion of remote driver failed");
157         }
158
159     }
160
161     public static String getBaseUrl() {
162
163         if (System.getProperties().containsKey( "baseUrl" )) {
164             return System.getProperty("baseUrl");
165         }
166         int containerPort = 7777;
167         if (System.getProperties().containsKey("container.http.port")) {
168             containerPort = Integer.parseInt(System.getProperty("container.http.port"));
169         } else if (System.getProperties().containsKey("container.propertiesPortFilePath"))
170         {
171             Properties portProperties = new Properties();
172             try (InputStream inputStream = Files.newInputStream(Paths.get(System.getProperty("container.propertiesPortFilePath"))))
173             {
174                 portProperties.load(inputStream);
175             }
176             catch ( IOException e )
177             {
178                 log.error("Error during property loading with containger.propertiesPortFilePath");
179             }
180             if ( portProperties.containsKey( "tomcat.maven.http.port" ) )
181             {
182                 containerPort = Integer.parseInt( portProperties.getProperty( "tomcat.maven.http.port" ) );
183             }
184             else
185             {
186                 containerPort = Integer.parseInt( portProperties.getProperty( "container.http.port" ) );
187             }
188         }
189         return "http://localhost:" + containerPort+"/archiva";
190     }
191
192     public static Path takeScreenShot( String fileName, WebDriver driver) {
193         Path result = null;
194         try
195         {
196             Path snapDir = Paths.get( "target", "errorshtmlsnap" );
197             Path screenShotDir = Paths.get("target","screenshots");
198             if ( !Files.exists( snapDir ) )
199             {
200                 Files.createDirectories( snapDir );
201             }
202             Path htmlFile = snapDir.resolve( fileName + ".html" );
203             Path screenShotFile = screenShotDir.resolve( fileName );
204             String pageSource=null;
205             String encoding="ISO-8859-1";
206             try
207             {
208                 pageSource = ( (JavascriptExecutor) driver ).executeScript( "return document.documentElement.outerHTML;" ).toString();
209             } catch (Exception e) {
210                 log.info("Could not create html source by javascript");
211                 pageSource = driver.getPageSource();
212             }
213             if (pageSource.contains("encoding=\"")) {
214                 encoding = pageSource.replaceFirst( ".*encoding=\"([^\"]+)\".*", "$1" );
215             }
216             FileUtils.writeStringToFile( htmlFile.toFile(), pageSource, encoding);
217             try
218             {
219                 File scrs = ((TakesScreenshot)driver).getScreenshotAs( OutputType.FILE );
220                 result = scrs.toPath();
221                 Files.copy(result, screenShotFile);
222             }
223             catch ( Exception e )
224             {
225                 log.info( "Could not create screenshot: " + e.getMessage() );
226             }
227
228         }
229         catch ( IOException e )
230         {
231             log.info( "Creating screenshot failed " + e.getMessage() );
232         }
233         return result;
234     }
235 }