forked from testcontainers/testcontainers-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BrowserWebDriverContainer.java
335 lines (279 loc) · 11.8 KB
/
BrowserWebDriverContainer.java
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
package org.testcontainers.containers;
import com.github.dockerjava.api.model.AccessMode;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Volume;
import com.google.common.collect.ImmutableSet;
import com.github.dockerjava.api.command.InspectContainerResponse;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.BrowserType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.rnorth.ducttape.timeouts.Timeouts;
import org.rnorth.ducttape.unreliables.Unreliables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.traits.LinkableContainer;
import org.testcontainers.containers.traits.VncService;
import org.testcontainers.containers.wait.HostPortWaitStrategy;
import org.testcontainers.containers.wait.LogMessageWaitStrategy;
import org.testcontainers.containers.wait.WaitAllStrategy;
import org.testcontainers.containers.wait.WaitStrategy;
import org.testcontainers.lifecycle.TestDescription;
import org.testcontainers.lifecycle.TestLifecycleAware;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.time.Duration;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static java.time.temporal.ChronoUnit.SECONDS;
/**
* A chrome/firefox/custom container based on SeleniumHQ's standalone container sets.
* <p>
* The container should expose Selenium remote control protocol and VNC.
*/
public class BrowserWebDriverContainer<SELF extends BrowserWebDriverContainer<SELF>> extends GenericContainer<SELF> implements VncService, LinkableContainer, TestLifecycleAware {
private static final String CHROME_IMAGE = "selenium/standalone-chrome-debug:%s";
private static final String FIREFOX_IMAGE = "selenium/standalone-firefox-debug:%s";
private static final String DEFAULT_PASSWORD = "secret";
private static final int SELENIUM_PORT = 4444;
private static final int VNC_PORT = 5900;
private static final String NO_PROXY_KEY = "no_proxy";
private static final String TC_TEMP_DIR_PREFIX = "tc";
@Nullable
private Capabilities capabilities;
private boolean customImageNameIsSet = false;
@Nullable
private RemoteWebDriver driver;
private VncRecordingMode recordingMode = VncRecordingMode.RECORD_FAILING;
private RecordingFileFactory recordingFileFactory;
private File vncRecordingDirectory;
private VncRecordingContainer vncRecordingContainer = null;
private static final Logger LOGGER = LoggerFactory.getLogger(BrowserWebDriverContainer.class);
/**
*/
public BrowserWebDriverContainer() {
final WaitStrategy logWaitStrategy = new LogMessageWaitStrategy()
.withRegEx(".*(RemoteWebDriver instances should connect to|Selenium Server is up and running).*\n")
.withStartupTimeout(Duration.of(15, SECONDS));
this.waitStrategy = new WaitAllStrategy()
.withStrategy(logWaitStrategy)
.withStrategy(new HostPortWaitStrategy())
.withStartupTimeout(Duration.of(15, SECONDS));
this.withRecordingFileFactory(new DefaultRecordingFileFactory());
}
/**
* Constructor taking a specific webdriver container name and tag
* @param dockerImageName Name of the docker image to pull
*/
public BrowserWebDriverContainer(String dockerImageName) {
this();
super.setDockerImageName(dockerImageName);
this.customImageNameIsSet = true;
// We have to force SKIP mode for the recording by default because we don't know if the image has VNC or not
recordingMode = VncRecordingMode.SKIP;
}
public SELF withCapabilities(Capabilities capabilities) {
this.capabilities = capabilities;
return self();
}
/**
* @deprecated Use withCapabilities(Capabilities capabilities) instead:
* withCapabilities(new FirefoxOptions())
*
* @param capabilities DesiredCapabilities
* @return SELF
* */
@Deprecated
public SELF withDesiredCapabilities(DesiredCapabilities capabilities) {
this.capabilities = capabilities;
return self();
}
@NotNull
@Override
protected Set<Integer> getLivenessCheckPorts() {
Integer seleniumPort = getMappedPort(SELENIUM_PORT);
if (recordingMode == VncRecordingMode.SKIP) {
return ImmutableSet.of(seleniumPort);
} else {
return ImmutableSet.of(seleniumPort, getMappedPort(VNC_PORT));
}
}
@Override
protected void configure() {
String seleniumVersion = SeleniumUtils.determineClasspathSeleniumVersion();
if (capabilities == null) {
if (seleniumVersion.startsWith("2.")) {
logger().info("No capabilities provided, falling back to DesiredCapabilities.chrome()");
capabilities = DesiredCapabilities.chrome();
} else {
logger().info("No capabilities provided, falling back to ChromeOptions");
capabilities = new ChromeOptions();
}
}
if (recordingMode != VncRecordingMode.SKIP) {
if (vncRecordingDirectory == null) {
try {
vncRecordingDirectory = Files.createTempDirectory(TC_TEMP_DIR_PREFIX).toFile();
} catch (IOException e) {
// should never happen as per javadoc, since we use valid prefix
logger().error("Exception while trying to create temp directory " + vncRecordingDirectory.getAbsolutePath(), e);
throw new ContainerLaunchException("Exception while trying to create temp directory", e);
}
}
if (getNetwork() == null) {
withNetwork(Network.SHARED);
}
vncRecordingContainer = new VncRecordingContainer(this)
.withVncPassword(DEFAULT_PASSWORD)
.withVncPort(VNC_PORT);
}
if (!customImageNameIsSet) {
super.setDockerImageName(getImageForCapabilities(capabilities, seleniumVersion));
}
String timeZone = System.getProperty("user.timezone");
if (timeZone == null || timeZone.isEmpty()) {
timeZone = "Etc/UTC";
}
addExposedPorts(SELENIUM_PORT, VNC_PORT);
addEnv("TZ", timeZone);
if (!getEnvMap().containsKey(NO_PROXY_KEY)) {
addEnv(NO_PROXY_KEY, "localhost");
}
setCommand("/opt/bin/entry_point.sh");
if (getShmSize() == null) {
this.getBinds().add(new Bind("/dev/shm", new Volume("/dev/shm"), AccessMode.rw));
}
/*
* Some unreliability of the selenium browser containers has been observed, so allow multiple attempts to start.
*/
setStartupAttempts(3);
}
public static String getImageForCapabilities(Capabilities capabilities, String seleniumVersion) {
String browserName = capabilities.getBrowserName();
switch (browserName) {
case BrowserType.CHROME:
return String.format(CHROME_IMAGE, seleniumVersion);
case BrowserType.FIREFOX:
return String.format(FIREFOX_IMAGE, seleniumVersion);
default:
throw new UnsupportedOperationException("Browser name must be 'chrome' or 'firefox'; provided '" + browserName + "' is not supported");
}
}
public URL getSeleniumAddress() {
try {
return new URL("http", getContainerIpAddress(), getMappedPort(SELENIUM_PORT), "/wd/hub");
} catch (MalformedURLException e) {
e.printStackTrace();// TODO
return null;
}
}
@Override
public String getVncAddress() {
return "vnc://vnc:secret@" + getContainerIpAddress() + ":" + getMappedPort(VNC_PORT);
}
@Override
public String getPassword() {
return DEFAULT_PASSWORD;
}
@Override
public int getPort() {
return VNC_PORT;
}
@Override
protected void containerIsStarted(InspectContainerResponse containerInfo) {
driver = Unreliables.retryUntilSuccess(30, TimeUnit.SECONDS,
Timeouts.getWithTimeout(10, TimeUnit.SECONDS,
() ->
() -> new RemoteWebDriver(getSeleniumAddress(), capabilities)));
if (vncRecordingContainer != null) {
LOGGER.debug("Starting VNC recording");
vncRecordingContainer.start();
}
}
/**
* Obtain a RemoteWebDriver instance that is bound to an instance of the browser running inside a new container.
* <p>
* All containers and drivers will be automatically shut down after the test method finishes (if used as a @Rule) or the test
* class (if used as a @ClassRule)
*
* @return a new Remote Web Driver instance
*/
public RemoteWebDriver getWebDriver() {
return driver;
}
@Override
public void afterTest(TestDescription description, Optional<Throwable> throwable) {
retainRecordingIfNeeded(description.getFilesystemFriendlyName(), !throwable.isPresent());
}
@Override
public void stop() {
if (driver != null) {
try {
driver.quit();
} catch (Exception e) {
LOGGER.debug("Failed to quit the driver", e);
}
}
if (vncRecordingContainer != null) {
try {
vncRecordingContainer.stop();
} catch (Exception e) {
LOGGER.debug("Failed to stop vncRecordingContainer", e);
}
}
super.stop();
}
private void retainRecordingIfNeeded(String prefix, boolean succeeded) {
final boolean shouldRecord;
switch (recordingMode) {
case RECORD_ALL:
shouldRecord = true;
break;
case RECORD_FAILING:
shouldRecord = !succeeded;
break;
default:
shouldRecord = false;
break;
}
if (shouldRecord) {
File recordingFile = recordingFileFactory.recordingFileForTest(vncRecordingDirectory, prefix, succeeded);
LOGGER.info("Screen recordings for test {} will be stored at: {}", prefix, recordingFile);
vncRecordingContainer.saveRecordingToFile(recordingFile);
}
}
/**
* Remember any other containers this needs to link to. We have to pass these down to the container so that
* the other containers will be initialized before linking occurs.
*
* @param otherContainer the container rule to link to
* @param alias the alias (hostname) that this other container should be referred to by
* @return this
*
* @deprecated Links are deprecated (see <a href="https://github.com/testcontainers/testcontainers-java/issues/465">#465</a>). Please use {@link Network} features instead.
*/
@Deprecated
public SELF withLinkToContainer(LinkableContainer otherContainer, String alias) {
addLink(otherContainer, alias);
return self();
}
public SELF withRecordingMode(VncRecordingMode recordingMode, File vncRecordingDirectory) {
this.recordingMode = recordingMode;
this.vncRecordingDirectory = vncRecordingDirectory;
return self();
}
public SELF withRecordingFileFactory(RecordingFileFactory recordingFileFactory) {
this.recordingFileFactory = recordingFileFactory;
return self();
}
public enum VncRecordingMode {
SKIP, RECORD_ALL, RECORD_FAILING
}
}