How to use map method of org.openqa.selenium.docker.ContainerConfig class

Best Selenium code snippet using org.openqa.selenium.docker.ContainerConfig.map

Source:SauceDockerSessionFactory.java Github

copy

Full Screen

...108 }109 @Override110 public boolean test(Capabilities capabilities) {111 return stereotype.getCapabilityNames().stream()112 .map(113 name ->114 Objects.equals(stereotype.getCapability(name), capabilities.getCapability(name)))115 .reduce(Boolean::logicalAnd)116 .orElse(false);117 }118 @Override119 public Either<WebDriverException, ActiveSession> apply(CreateSessionRequest sessionRequest) {120 Optional<Object> accessKey =121 getSauceCapability(sessionRequest.getDesiredCapabilities(), "accessKey");122 Optional<Object> userName =123 getSauceCapability(sessionRequest.getDesiredCapabilities(), "username");124 if (!accessKey.isPresent() && !userName.isPresent()) {125 String message = String.format("Unable to create session. No Sauce Labs accessKey and "126 + "username were found in the '%s' block.", SAUCE_OPTIONS);127 LOG.log(Level.WARNING, message);128 return Either.left(new SessionNotCreatedException(message));129 }130 @SuppressWarnings("OptionalGetWithoutIsPresent")131 UsernameAndPassword usernameAndPassword =132 new UsernameAndPassword(userName.get().toString(), accessKey.get().toString());133 Optional<Object> dc =134 getSauceCapability(sessionRequest.getDesiredCapabilities(), "dataCenter");135 DataCenter dataCenter = DataCenter.US_WEST;136 if (dc.isPresent()) {137 dataCenter = DataCenter.fromString(String.valueOf(dc.get()));138 }139 Capabilities sessionReqCaps = removeSauceKey(sessionRequest.getDesiredCapabilities());140 LOG.info("Starting session for " + sessionReqCaps);141 int port = runningInDocker ? 4444 : PortProber.findFreePort();142 try (Span span = tracer.getCurrentContext().createSpan("docker_session_factory.apply")) {143 Map<String, EventAttributeValue> attributeMap = new HashMap<>();144 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),145 EventAttribute.setValue(this.getClass().getName()));146 String logMessage = runningInDocker ? "Creating container..." :147 "Creating container, mapping container port 4444 to " + port;148 LOG.info(logMessage);149 Container container = createBrowserContainer(port, sessionReqCaps);150 container.start();151 ContainerInfo containerInfo = container.inspect();152 String containerIp = containerInfo.getIp();153 URL remoteAddress = getUrl(port, containerIp);154 HttpClient client = clientFactory.createClient(remoteAddress);155 attributeMap.put("docker.browser.image", EventAttribute.setValue(browserImage.toString()));156 attributeMap.put("container.port", EventAttribute.setValue(port));157 attributeMap.put("container.id", EventAttribute.setValue(container.getId().toString()));158 attributeMap.put("container.ip", EventAttribute.setValue(containerInfo.getIp()));159 attributeMap.put("docker.server.url", EventAttribute.setValue(remoteAddress.toString()));160 LOG.info(161 String.format("Waiting for server to start (container id: %s, url %s)",162 container.getId(),163 remoteAddress));164 try {165 waitForServerToStart(client, Duration.ofMinutes(1));166 } catch (TimeoutException e) {167 span.setAttribute("error", true);168 span.setStatus(Status.CANCELLED);169 EXCEPTION.accept(attributeMap, e);170 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),171 EventAttribute.setValue(172 "Unable to connect to docker server. Stopping container: " +173 e.getMessage()));174 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);175 container.stop(Duration.ofMinutes(1));176 String message = String.format(177 "Unable to connect to docker server (container id: %s)", container.getId());178 LOG.warning(message);179 return Either.left(new RetrySessionRequestException(message));180 }181 LOG.info(String.format("Server is ready (container id: %s)", container.getId()));182 Command command = new Command(183 null,184 DriverCommand.NEW_SESSION(sessionReqCaps));185 ProtocolHandshake.Result result;186 Response response;187 try {188 result = new ProtocolHandshake().createSession(client, command);189 response = result.createResponse();190 attributeMap.put(191 AttributeKey.DRIVER_RESPONSE.getKey(),192 EventAttribute.setValue(response.toString()));193 } catch (IOException | RuntimeException e) {194 span.setAttribute("error", true);195 span.setStatus(Status.CANCELLED);196 EXCEPTION.accept(attributeMap, e);197 attributeMap.put(198 AttributeKey.EXCEPTION_MESSAGE.getKey(),199 EventAttribute200 .setValue("Unable to create session. Stopping and container: " + e.getMessage()));201 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);202 container.stop(Duration.ofMinutes(1));203 String message = "Unable to create session: " + e.getMessage();204 LOG.log(Level.WARNING, message);205 return Either.left(new SessionNotCreatedException(message));206 }207 SessionId id = new SessionId(response.getSessionId());208 Capabilities capabilities = new ImmutableCapabilities((Map<?, ?>) response.getValue());209 Capabilities mergedCapabilities = capabilities.merge(sessionReqCaps);210 Container videoContainer = null;211 Optional<DockerAssetsPath> path = ofNullable(this.assetsPath);212 if (path.isPresent()) {213 // Seems we can store session assets214 String containerPath = path.get().getContainerPath(id);215 saveSessionCapabilities(mergedCapabilities, containerPath);216 String hostPath = path.get().getHostPath(id);217 videoContainer = startVideoContainer(mergedCapabilities, containerInfo.getIp(), hostPath);218 }219 Instant startTime = Instant.now();220 Instant videoStartTime = Instant.now();221 Dialect downstream = sessionRequest.getDownstreamDialects().contains(result.getDialect()) ?222 result.getDialect() :223 W3C;224 attributeMap.put(225 AttributeKey.DOWNSTREAM_DIALECT.getKey(),226 EventAttribute.setValue(downstream.toString()));227 attributeMap.put(228 AttributeKey.DRIVER_RESPONSE.getKey(),229 EventAttribute.setValue(response.toString()));230 SauceCommandInfo commandInfo = new SauceCommandInfo.Builder()231 .setStartTime(startTime.toEpochMilli())232 .setVideoStartTime(videoStartTime.toEpochMilli())233 .setEndTime(Instant.now().toEpochMilli())234 .setRequest(sessionReqCaps)235 .setResult(mergedCapabilities)236 .setPath("/session")237 .setHttpStatus(response.getStatus())238 .setHttpMethod(POST.name())239 .setStatusCode(0)240 .setScreenshotId(-1)241 .build();242 span.addEvent("Docker driver service created session", attributeMap);243 LOG.fine(String.format(244 "Created session: %s - %s (container id: %s)",245 id,246 capabilities,247 container.getId()));248 return Either.right(new SauceDockerSession(249 container,250 videoContainer,251 tracer,252 client,253 id,254 remoteAddress,255 stereotype,256 mergedCapabilities,257 downstream,258 result.getDialect(),259 startTime,260 assetsPath,261 usernameAndPassword,262 dataCenter,263 assetsUploaderImage,264 commandInfo,265 docker));266 }267 }268 private Container createBrowserContainer(int port, Capabilities sessionCapabilities) {269 Map<String, String> browserContainerEnvVars = getBrowserContainerEnvVars(sessionCapabilities);270 long browserContainerShmMemorySize = 2147483648L; //2GB271 ContainerConfig containerConfig = image(browserImage)272 .env(browserContainerEnvVars)273 .shmMemorySize(browserContainerShmMemorySize)274 .network(networkName);275 if (!runningInDocker) {276 containerConfig = containerConfig.map(Port.tcp(4444), Port.tcp(port));277 }278 return docker.create(containerConfig);279 }280 private Map<String, String> getBrowserContainerEnvVars(Capabilities sessionRequestCapabilities) {281 Optional<Dimension> screenResolution =282 ofNullable(getScreenResolution(sessionRequestCapabilities));283 Map<String, String> envVars = new HashMap<>();284 if (screenResolution.isPresent()) {285 envVars.put("SCREEN_WIDTH", String.valueOf(screenResolution.get().getWidth()));286 envVars.put("SCREEN_HEIGHT", String.valueOf(screenResolution.get().getHeight()));287 }288 Optional<TimeZone> timeZone = ofNullable(getTimeZone(sessionRequestCapabilities));289 timeZone.ifPresent(zone -> envVars.put("TZ", zone.getID()));290 return envVars;291 }292 private Container startVideoContainer(Capabilities sessionCapabilities,293 String browserContainerIp, String hostPath) {294 if (!recordVideoForSession(sessionCapabilities)) {295 return null;296 }297 int videoPort = 9000;298 Map<String, String> envVars = getVideoContainerEnvVars(299 sessionCapabilities,300 browserContainerIp);301 Map<String, String> volumeBinds = Collections.singletonMap(hostPath, "/videos");302 ContainerConfig containerConfig = image(videoImage)303 .env(envVars)304 .bind(volumeBinds)305 .network(networkName);306 if (!runningInDocker) {307 videoPort = PortProber.findFreePort();308 containerConfig = containerConfig.map(Port.tcp(9000), Port.tcp(videoPort));309 }310 Container videoContainer = docker.create(containerConfig);311 videoContainer.start();312 String videoContainerIp = runningInDocker ? videoContainer.inspect().getIp() : "localhost";313 try {314 URL videoContainerUrl = new URL(String.format("http://%s:%s", videoContainerIp, videoPort));315 HttpClient videoClient = clientFactory.createClient(videoContainerUrl);316 LOG.fine(String.format("Waiting for video recording... (id: %s)", videoContainer.getId()));317 waitForServerToStart(videoClient, Duration.ofMinutes(1));318 } catch (Exception e) {319 videoContainer.stop(Duration.ofSeconds(10));320 String message = String.format(321 "Unable to verify video recording started (container id: %s), %s", videoContainer.getId(),322 e.getMessage());...

Full Screen

Full Screen

Source:DockerSessionFactory.java Github

copy

Full Screen

...114 }115 @Override116 public boolean test(Capabilities capabilities) {117 return stereotype.getCapabilityNames().stream()118 .map(119 name ->120 Objects.equals(stereotype.getCapability(name), capabilities.getCapability(name)))121 .reduce(Boolean::logicalAnd)122 .orElse(false);123 }124 @Override125 public Either<WebDriverException, ActiveSession> apply(CreateSessionRequest sessionRequest) {126 LOG.info("Starting session for " + sessionRequest.getDesiredCapabilities());127 int port = runningInDocker ? 4444 : PortProber.findFreePort();128 try (Span span = tracer.getCurrentContext().createSpan("docker_session_factory.apply")) {129 Map<String, EventAttributeValue> attributeMap = new HashMap<>();130 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),131 EventAttribute.setValue(this.getClass().getName()));132 String logMessage = runningInDocker ? "Creating container..." :133 "Creating container, mapping container port 4444 to " + port;134 LOG.info(logMessage);135 Container container = createBrowserContainer(port, sessionRequest.getDesiredCapabilities());136 container.start();137 ContainerInfo containerInfo = container.inspect();138 String containerIp = containerInfo.getIp();139 URL remoteAddress = getUrl(port, containerIp);140 HttpClient client = clientFactory.createClient(remoteAddress);141 attributeMap.put("docker.browser.image", EventAttribute.setValue(browserImage.toString()));142 attributeMap.put("container.port", EventAttribute.setValue(port));143 attributeMap.put("container.id", EventAttribute.setValue(container.getId().toString()));144 attributeMap.put("container.ip", EventAttribute.setValue(containerIp));145 attributeMap.put("docker.server.url", EventAttribute.setValue(remoteAddress.toString()));146 LOG.info(147 String.format("Waiting for server to start (container id: %s, url %s)",148 container.getId(),149 remoteAddress));150 try {151 waitForServerToStart(client, Duration.ofMinutes(1));152 } catch (TimeoutException e) {153 span.setAttribute("error", true);154 span.setStatus(Status.CANCELLED);155 EXCEPTION.accept(attributeMap, e);156 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),157 EventAttribute.setValue(158 "Unable to connect to docker server. Stopping container: " +159 e.getMessage()));160 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);161 container.stop(Duration.ofMinutes(1));162 String message = String.format(163 "Unable to connect to docker server (container id: %s)", container.getId());164 LOG.warning(message);165 return Either.left(new RetrySessionRequestException(message));166 }167 LOG.info(String.format("Server is ready (container id: %s)", container.getId()));168 Command command = new Command(169 null,170 DriverCommand.NEW_SESSION(sessionRequest.getDesiredCapabilities()));171 ProtocolHandshake.Result result;172 Response response;173 try {174 result = new ProtocolHandshake().createSession(client, command);175 response = result.createResponse();176 attributeMap.put(AttributeKey.DRIVER_RESPONSE.getKey(),177 EventAttribute.setValue(response.toString()));178 } catch (IOException | RuntimeException e) {179 span.setAttribute("error", true);180 span.setStatus(Status.CANCELLED);181 EXCEPTION.accept(attributeMap, e);182 attributeMap.put(183 AttributeKey.EXCEPTION_MESSAGE.getKey(),184 EventAttribute185 .setValue("Unable to create session. Stopping and container: " + e.getMessage()));186 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);187 container.stop(Duration.ofMinutes(1));188 String message = "Unable to create session: " + e.getMessage();189 LOG.log(Level.WARNING, message, e);190 return Either.left(new SessionNotCreatedException(message));191 }192 SessionId id = new SessionId(response.getSessionId());193 Capabilities capabilities = new ImmutableCapabilities((Map<?, ?>) response.getValue());194 Capabilities mergedCapabilities = capabilities.merge(sessionRequest.getDesiredCapabilities());195 Container videoContainer = null;196 Optional<DockerAssetsPath> path = ofNullable(this.assetsPath);197 if (path.isPresent()) {198 // Seems we can store session assets199 String containerPath = path.get().getContainerPath(id);200 saveSessionCapabilities(mergedCapabilities, containerPath);201 String hostPath = path.get().getHostPath(id);202 videoContainer = startVideoContainer(mergedCapabilities, containerIp, hostPath);203 }204 Dialect downstream = sessionRequest.getDownstreamDialects().contains(result.getDialect()) ?205 result.getDialect() :206 W3C;207 attributeMap.put(208 AttributeKey.DOWNSTREAM_DIALECT.getKey(),209 EventAttribute.setValue(downstream.toString()));210 attributeMap.put(211 AttributeKey.DRIVER_RESPONSE.getKey(),212 EventAttribute.setValue(response.toString()));213 span.addEvent("Docker driver service created session", attributeMap);214 LOG.fine(String.format(215 "Created session: %s - %s (container id: %s)",216 id,217 capabilities,218 container.getId()));219 return Either.right(new DockerSession(220 container,221 videoContainer,222 tracer,223 client,224 id,225 remoteAddress,226 stereotype,227 mergedCapabilities,228 downstream,229 result.getDialect(),230 Instant.now()));231 }232 }233 private Container createBrowserContainer(int port, Capabilities sessionCapabilities) {234 Map<String, String> browserContainerEnvVars = getBrowserContainerEnvVars(sessionCapabilities);235 Map<String, String> devShmMount = Collections.singletonMap("/dev/shm", "/dev/shm");236 ContainerConfig containerConfig = image(browserImage)237 .env(browserContainerEnvVars)238 .bind(devShmMount)239 .network(networkName);240 if (!runningInDocker) {241 containerConfig = containerConfig.map(Port.tcp(4444), Port.tcp(port));242 }243 return docker.create(containerConfig);244 }245 private Map<String, String> getBrowserContainerEnvVars(Capabilities sessionRequestCapabilities) {246 Optional<Dimension> screenResolution =247 ofNullable(getScreenResolution(sessionRequestCapabilities));248 Map<String, String> envVars = new HashMap<>();249 if (screenResolution.isPresent()) {250 envVars.put("SCREEN_WIDTH", String.valueOf(screenResolution.get().getWidth()));251 envVars.put("SCREEN_HEIGHT", String.valueOf(screenResolution.get().getHeight()));252 }253 Optional<TimeZone> timeZone = ofNullable(getTimeZone(sessionRequestCapabilities));254 timeZone.ifPresent(zone -> envVars.put("TZ", zone.getID()));255 return envVars;256 }257 private Container startVideoContainer(Capabilities sessionCapabilities,258 String browserContainerIp, String hostPath) {259 if (!recordVideoForSession(sessionCapabilities)) {260 return null;261 }262 int videoPort = 9000;263 Map<String, String> envVars = getVideoContainerEnvVars(264 sessionCapabilities,265 browserContainerIp);266 Map<String, String> volumeBinds = Collections.singletonMap(hostPath, "/videos");267 ContainerConfig containerConfig = image(videoImage)268 .env(envVars)269 .bind(volumeBinds)270 .network(networkName);271 if (!runningInDocker) {272 videoPort = PortProber.findFreePort();273 containerConfig = containerConfig.map(Port.tcp(9000), Port.tcp(videoPort));274 }275 Container videoContainer = docker.create(containerConfig);276 videoContainer.start();277 String videoContainerIp = runningInDocker ? videoContainer.inspect().getIp() : "localhost";278 try {279 URL videoContainerUrl = new URL(String.format("http://%s:%s", videoContainerIp, videoPort));280 HttpClient videoClient = clientFactory.createClient(videoContainerUrl);281 LOG.fine(String.format("Waiting for video recording... (id: %s)", videoContainer.getId()));282 waitForServerToStart(videoClient, Duration.ofMinutes(1));283 } catch (Exception e) {284 videoContainer.stop(Duration.ofSeconds(10));285 String message = String.format(286 "Unable to verify video recording started (container id: %s), %s", videoContainer.getId(),287 e.getMessage());...

Full Screen

Full Screen

Source:SauceDockerSession.java Github

copy

Full Screen

1package com.saucelabs.grid;2import static com.google.common.net.HttpHeaders.CONTENT_TYPE;3import static com.saucelabs.grid.Common.JSON;4import static com.saucelabs.grid.Common.getSauceCapability;5import static java.time.Instant.ofEpochMilli;6import static org.openqa.selenium.docker.ContainerConfig.image;7import static org.openqa.selenium.json.Json.JSON_UTF_8;8import static org.openqa.selenium.remote.http.Contents.asJson;9import org.openqa.selenium.Capabilities;10import org.openqa.selenium.MutableCapabilities;11import org.openqa.selenium.UsernameAndPassword;12import org.openqa.selenium.docker.Container;13import org.openqa.selenium.docker.Docker;14import org.openqa.selenium.docker.Image;15import org.openqa.selenium.grid.node.ProtocolConvertingSession;16import org.openqa.selenium.grid.node.docker.DockerAssetsPath;17import org.openqa.selenium.internal.Require;18import org.openqa.selenium.remote.CapabilityType;19import org.openqa.selenium.remote.Dialect;20import org.openqa.selenium.remote.SessionId;21import org.openqa.selenium.remote.http.Contents;22import org.openqa.selenium.remote.http.HttpClient;23import org.openqa.selenium.remote.http.HttpMethod;24import org.openqa.selenium.remote.http.HttpRequest;25import org.openqa.selenium.remote.http.HttpResponse;26import org.openqa.selenium.remote.tracing.Tracer;27import java.net.URL;28import java.nio.file.Files;29import java.nio.file.Paths;30import java.time.Duration;31import java.time.Instant;32import java.util.ArrayList;33import java.util.Collections;34import java.util.HashMap;35import java.util.List;36import java.util.Map;37import java.util.concurrent.atomic.AtomicBoolean;38import java.util.concurrent.atomic.AtomicInteger;39import java.util.logging.Level;40import java.util.logging.Logger;41public class SauceDockerSession extends ProtocolConvertingSession {42 private static final Logger LOG = Logger.getLogger(SauceDockerSession.class.getName());43 private final Docker docker;44 private final Container container;45 private final Container videoContainer;46 private final AtomicInteger screenshotCount;47 private final AtomicBoolean screenshotsEnabled;48 private final DockerAssetsPath assetsPath;49 private final List<SauceCommandInfo> webDriverCommands;50 private final UsernameAndPassword usernameAndPassword;51 private final Image assetsUploaderImage;52 private final DataCenter dataCenter;53 private final AtomicBoolean tearDownTriggered;54 SauceDockerSession(55 Container container,56 Container videoContainer,57 Tracer tracer,58 HttpClient client,59 SessionId id,60 URL url,61 Capabilities stereotype,62 Capabilities capabilities,63 Dialect downstream,64 Dialect upstream,65 Instant startTime,66 DockerAssetsPath assetsPath,67 UsernameAndPassword usernameAndPassword,68 DataCenter dataCenter,69 Image assetsUploaderImage,70 SauceCommandInfo firstCommand,71 Docker docker) {72 super(tracer, client, id, url, downstream, upstream, stereotype, capabilities, startTime);73 this.container = Require.nonNull("Container", container);74 this.videoContainer = videoContainer;75 this.assetsPath = Require.nonNull("Assets path", assetsPath);76 this.screenshotCount = new AtomicInteger(0);77 this.screenshotsEnabled = new AtomicBoolean(false);78 this.usernameAndPassword = Require.nonNull("Sauce user & key", usernameAndPassword);79 this.webDriverCommands = new ArrayList<>();80 this.webDriverCommands.add(firstCommand);81 this.assetsUploaderImage = assetsUploaderImage;82 this.dataCenter = dataCenter;83 this.docker = Require.nonNull("Docker", docker);84 this.tearDownTriggered = new AtomicBoolean(false);85 }86 public int increaseScreenshotCount() {87 return screenshotCount.getAndIncrement();88 }89 public boolean canTakeScreenshot() {90 return screenshotsEnabled.get();91 }92 public void enableScreenshots() {93 screenshotsEnabled.set(true);94 }95 public void addSauceCommandInfo(SauceCommandInfo commandInfo) {96 if (!webDriverCommands.isEmpty()) {97 // Get when the last command ended to calculate times between commands98 SauceCommandInfo lastCommand = webDriverCommands.get(webDriverCommands.size() - 1);99 long betweenCommands = commandInfo.getStartTime() - lastCommand.getEndTime();100 commandInfo.setBetweenCommands(betweenCommands);101 commandInfo.setVideoStartTime(lastCommand.getVideoStartTime());102 }103 this.webDriverCommands.add(commandInfo);104 }105 public DockerAssetsPath getAssetsPath() {106 return assetsPath;107 }108 @Override109 public void stop() {110 new Thread(() -> {111 if (!tearDownTriggered.getAndSet(true)) {112 if (videoContainer != null) {113 videoContainer.stop(Duration.ofSeconds(10));114 }115 saveLogs();116 container.stop(Duration.ofMinutes(1));117 integrateWithSauce();118 }119 }).start();120 }121 private void saveLogs() {122 String sessionAssetsPath = assetsPath.getContainerPath(getId());123 String seleniumServerLog = String.format("%s/selenium-server.log", sessionAssetsPath);124 String logJson = String.format("%s/log.json", sessionAssetsPath);125 try {126 List<String> logs = container.getLogs().getLogLines();127 Files.write(Paths.get(logJson), getProcessedWebDriverCommands());128 Files.write(Paths.get(seleniumServerLog), logs);129 } catch (Exception e) {130 LOG.log(Level.WARNING, "Error saving logs", e);131 }132 }133 private void integrateWithSauce() {134 String sauceJobId = createSauceJob();135 Container assetUploaderContainer = createAssetUploaderContainer(sauceJobId);136 assetUploaderContainer.start();137 }138 private byte[] getProcessedWebDriverCommands() {139 String webDriverCommands = JSON.toJson(this.webDriverCommands);140 webDriverCommands = webDriverCommands.replaceAll("\"null\"", "null");141 return webDriverCommands.getBytes();142 }143 private String createSauceJob() {144 MutableCapabilities jobInfo = new MutableCapabilities();145 jobInfo.setCapability(CapabilityType.BROWSER_NAME, getCapabilities().getBrowserName());146 jobInfo.setCapability(CapabilityType.PLATFORM_NAME, getCapabilities().getPlatformName());147 jobInfo.setCapability(CapabilityType.BROWSER_VERSION, getCapabilities().getBrowserVersion());148 jobInfo.setCapability("framework", "webdriver");149 getSauceCapability(getCapabilities(), "build")150 .ifPresent(build -> jobInfo.setCapability("build", build.toString()));151 getSauceCapability(getCapabilities(), "name")152 .ifPresent(name -> jobInfo.setCapability("name", name.toString()));153 getSauceCapability(getCapabilities(), "tags")154 .ifPresent(tags -> jobInfo.setCapability("tags", tags));155 SauceCommandInfo firstCommand = webDriverCommands.get(0);156 String startTime = ofEpochMilli(firstCommand.getStartTime()).toString();157 jobInfo.setCapability("startTime", startTime);158 SauceCommandInfo lastCommand = webDriverCommands.get(webDriverCommands.size() - 1);159 String endTime = ofEpochMilli(lastCommand.getStartTime()).toString();160 jobInfo.setCapability("endTime", endTime);161 // TODO: We cannot always know if the test passed or not162 jobInfo.setCapability("passed", true);163 String apiUrl = String.format(164 dataCenter.apiUrl,165 usernameAndPassword.username(),166 usernameAndPassword.password());167 String responseContents = "";168 try {169 HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(apiUrl));170 HttpRequest request = new HttpRequest(HttpMethod.POST, "/v1/testcomposer/reports");171 request.setContent(asJson(jobInfo));172 request.setHeader(CONTENT_TYPE, JSON_UTF_8);173 HttpResponse response = client.execute(request);174 responseContents = Contents.string(response);175 Map<String, String> jobId = JSON.toType(responseContents, Map.class);176 return jobId.get("ID");177 } catch (Exception e) {178 LOG.log(Level.WARNING, String.format("Error creating job in Sauce Labs. %s", responseContents), e);179 }180 return null;181 }182 private Container createAssetUploaderContainer(String sauceJobId) {183 String hostSessionAssetsPath = assetsPath.getHostPath(getId());184 Map<String, String> assetUploaderContainerEnvVars = getAssetUploaderContainerEnvVars(sauceJobId);185 Map<String, String> assetsPath =186 Collections.singletonMap(hostSessionAssetsPath, "/opt/selenium/assets");187 return docker.create(188 image(assetsUploaderImage)189 .env(assetUploaderContainerEnvVars)190 .bind(assetsPath));191 }192 private Map<String, String> getAssetUploaderContainerEnvVars(String sauceJobId) {193 Map<String, String> envVars = new HashMap<>();194 envVars.put("SAUCE_JOB_ID", sauceJobId);195 envVars.put("SAUCE_API_HOST", dataCenter.apiHost);196 envVars.put("SAUCE_USERNAME", usernameAndPassword.username());197 envVars.put("SAUCE_ACCESS_KEY", usernameAndPassword.password());198 return envVars;199 }200}...

Full Screen

Full Screen

Source:ContainerConfig.java Github

copy

Full Screen

...14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.docker;18import com.google.common.collect.HashMultimap;19import com.google.common.collect.ImmutableMap;20import com.google.common.collect.Multimap;21import org.openqa.selenium.Beta;22import org.openqa.selenium.internal.Require;23import java.util.List;24import java.util.Map;25import java.util.stream.Collectors;26@Beta27public class ContainerConfig {28 private static final String DEFAULT_DOCKER_NETWORK = "bridge";29 private final Image image;30 // Port bindings, keyed on the container port, with values being host ports31 private final Multimap<String, Map<String, Object>> portBindings;32 private final Map<String, String> envVars;33 private final Map<String, String> volumeBinds;34 private final String networkName;35 private final boolean autoRemove;36 public ContainerConfig(Image image,37 Multimap<String, Map<String, Object>> portBindings,38 Map<String, String> envVars,39 Map<String, String> volumeBinds, String networkName) {40 this.image = image;41 this.portBindings = portBindings;42 this.envVars = envVars;43 this.volumeBinds = volumeBinds;44 this.networkName = networkName;45 this.autoRemove = true;46 }47 public static ContainerConfig image(Image image) {48 return new ContainerConfig(image, HashMultimap.create(), ImmutableMap.of(), ImmutableMap.of(),49 DEFAULT_DOCKER_NETWORK);50 }51 public ContainerConfig map(Port containerPort, Port hostPort) {52 Require.nonNull("Container port", containerPort);53 Require.nonNull("Host port", hostPort);54 if (!hostPort.getProtocol().equals(containerPort.getProtocol())) {55 throw new DockerException(56 String.format("Port protocols must match: %s -> %s", hostPort, containerPort));57 }58 Multimap<String, Map<String, Object>> updatedBindings = HashMultimap.create(portBindings);59 updatedBindings.put(60 containerPort.getPort() + "/" + containerPort.getProtocol(),61 ImmutableMap.of("HostPort", String.valueOf(hostPort.getPort()), "HostIp", ""));62 return new ContainerConfig(image, updatedBindings, envVars, volumeBinds, networkName);63 }64 public ContainerConfig env(Map<String, String> envVars) {65 Require.nonNull("Container env vars", envVars);66 return new ContainerConfig(image, portBindings, envVars, volumeBinds, networkName);67 }68 public ContainerConfig bind(Map<String, String> volumeBinds) {69 Require.nonNull("Container volume binds", volumeBinds);70 return new ContainerConfig(image, portBindings, envVars, volumeBinds, networkName);71 }72 public ContainerConfig network(String networkName) {73 Require.nonNull("Container network name", networkName);74 return new ContainerConfig(image, portBindings, envVars, volumeBinds, networkName);75 }76 @Override77 public String toString() {78 return "ContainerConfig{" +79 "image=" + image +80 ", portBindings=" + portBindings +81 ", envVars=" + envVars +82 ", volumeBinds=" + volumeBinds +83 ", networkName=" + networkName +84 ", autoRemove=" + autoRemove +85 '}';86 }87 private Map<String, Object> toJson() {88 List<String> envVars = this.envVars.keySet().stream()89 .map(key -> String.format("%s=%s", key, this.envVars.get(key)))90 .collect(Collectors.toList());91 List<String> volumeBinds = this.volumeBinds.keySet().stream()92 .map(key -> String.format("%s:%s", key, this.volumeBinds.get(key)))93 .collect(Collectors.toList());94 Map<String, Object> hostConfig = ImmutableMap.of(95 "PortBindings", portBindings.asMap(),96 "AutoRemove", autoRemove,97 "NetworkMode", networkName,98 "Binds", volumeBinds);99 return ImmutableMap.of(100 "Image", image.getId(),101 "Env", envVars,102 "HostConfig", hostConfig);103 }104}...

Full Screen

Full Screen

Source:CreateContainer.java Github

copy

Full Screen

...62 if (rawContainer.get("Warnings") instanceof Collection) {63 Collection<?> warnings = (Collection<?>) rawContainer.get("Warnings");64 if (warnings.size() > 0) {65 String allWarnings = warnings.stream()66 .map(String::valueOf)67 .collect(Collectors.joining("\n", " * ", ""));68 LOG.warning(69 String.format("Warnings while creating %s from %s: %s", id, info, allWarnings));70 }71 }72 return new Container(protocol, id);73 } catch (JsonException | NullPointerException e) {74 throw new DockerException("Unable to create container from " + info);75 }76 }77}...

Full Screen

Full Screen

Source:Docker.java Github

copy

Full Screen

...30 public boolean isSupported() {31 return getDocker().isPresent();32 }33 public String getVersion() {34 return getDocker().map(DockerProtocol::version).orElse("unsupported");35 }36 public Image getImage(String name) {37 Require.nonNull("Image name to get", name);38 LOG.info("Obtaining image: " + name);39 return getDocker()40 .map(protocol -> protocol.getImage(name))41 .orElseThrow(() -> new DockerException("Unable to get image " + name));42 }43 public Container create(ContainerConfig config) {44 Require.nonNull("Container config", config);45 LOG.fine("Creating image from " + config);46 return getDocker()47 .map(protocol -> protocol.create(config))48 .orElseThrow(() -> new DockerException("Unable to create container: " + config));49 }50 public Optional<ContainerInfo> inspect(ContainerId id) {51 Require.nonNull("Container id", id);52 LOG.fine("Inspecting container with id: " + id);53 if (!getDocker().map(protocol -> protocol.isContainerPresent(id)).orElse(false)) {54 return Optional.empty();55 }56 return Optional.of(getDocker()57 .map(protocol -> protocol.inspectContainer(id))58 .orElseThrow(() -> new DockerException("Unable to inspect container: " + id)));59 }60 private Optional<DockerProtocol> getDocker() {61 if (dockerClient.isPresent()) {62 return dockerClient;63 }64 synchronized (this) {65 if (!dockerClient.isPresent()) {66 dockerClient = new VersionCommand(client).getDockerProtocol();67 }68 }69 return dockerClient;70 }71}...

Full Screen

Full Screen

map

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.docker.ContainerConfig2import org.openqa.selenium.docker.Container3import org.openqa.selenium.docker.Docker4def config = new ContainerConfig()5config.portBindings.add('4444/tcp', '4444/tcp')6def container = new Docker().createContainer(config)7container.start()8def selenium = new RemoteWebDriver(9 DesiredCapabilities.chrome())10selenium.quit()11container.stop()12container.remove()

Full Screen

Full Screen

map

Using AI Code Generation

copy

Full Screen

1ContainerConfig containerConfig = new ContainerConfig();2containerConfig.setImage("selenium/standalone-chrome:3.141.59-20200525");3containerConfig.setPortBindings(new HashMap<String, List<PortBinding>>(){{4 put("4444/tcp", new ArrayList<PortBinding>(){{5 add(new PortBinding(null, "4444"));6 }});7}});8containerConfig.setNetwork("selenium");9containerConfig.setNetworkAliases(new ArrayList<String>(){{10 add("hub");11}});12containerConfig.setHostname("hub");13containerConfig.setLabels(new HashMap<String, String>(){{14 put("se:role", "hub");15}}});16Docker docker = new Docker();17Container container = docker.createContainer(containerConfig);18container.start();19{% endhighlight %}20Now, let’s create a container for the node. We will use the same method to create the container for the node. We will use the same image as the hub. We will set the port mapping for the node to 5555. We will set the network to selenium. We will set the network aliases to node. We will set the hostname to node. We will set the labels to se:role as node. We will set the environment variables to HUB_HOST as hub and HUB_PORT as 4444. We will set the links to hub. We will set the volumes to /dev/shm:/dev/shm. We will set the privileged to true. We will set the cap_add to SYS_ADMIN. We will set the shm_size to 2G. We will set the restart_policy to always. We will set the restart_policy to always. We will set the log_config to new LogConfig("json-file", new HashMap<String, String>(){{21 put("max-size", "10m");22 put("max-file", "3");23}}). We will set the extra_hosts to new HashMap<String, String>(){{24 put("host.testcontainers.internal", "

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in ContainerConfig

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful