Best SeLion code snippet using com.paypal.selion.utils.SauceLabsRestApi
Source:SauceServlet.java
...22import javax.servlet.http.HttpServletResponse;23import com.paypal.selion.logging.SeLionGridLogger;24import com.paypal.selion.pojos.SeLionGridConstants;25import com.paypal.selion.proxy.SeLionSauceProxy;26import com.paypal.selion.utils.SauceLabsRestApi;27import org.apache.commons.lang.StringUtils;28import org.apache.http.HttpHost;29import org.apache.http.HttpResponse;30import org.apache.http.client.HttpClient;31import org.apache.http.entity.StringEntity;32import org.apache.http.message.BasicHttpEntityEnclosingRequest;33import org.openqa.grid.common.RegistrationRequest;34import org.openqa.grid.common.exception.GridConfigurationException;35import org.openqa.grid.internal.GridRegistry;36import org.openqa.grid.internal.utils.configuration.GridNodeConfiguration;37import org.openqa.grid.web.servlet.RegistryBasedServlet;38import org.openqa.selenium.MutableCapabilities;39import org.openqa.selenium.remote.internal.HttpClientFactory;40import com.paypal.selion.utils.ServletHelper;41/**42 * This {@link RegistryBasedServlet} based servlet takes care of spinning up or tearing down a virtual sauce node.<br>43 * <br>44 * This servlet requires the hub to also have {@link LoginServlet} available.45 */46public class SauceServlet extends RegistryBasedServlet {47 private static final SeLionGridLogger LOGGER = SeLionGridLogger.getLogger(SauceServlet.class);48 private static final long serialVersionUID = 9187677490975386050L;49 private static final String MAX_INSTANCES_CONFIG_PROPERTY = "maxInstances";50 private static final String SAUCELABS_BROWSER_NAME = "saucelabs";51 private static final String PROXY_HOST = "ondemand.saucelabs.com";52 private static final int PROXY_PORT = 80;53 /**54 * The proxy id that will be used to register to the hub55 */56 public static final String PROXY_ID = "http://" + PROXY_HOST + ":" + PROXY_PORT;57 /**58 * Request parameter that trigger a proxy shutdown action59 */60 public static final String SHUTDOWN_PARAM = "shutdown";61 private boolean registered;62 public SauceServlet(GridRegistry registry) {63 super(registry);64 }65 public SauceServlet() {66 this(null);67 }68 private String formatForHtmlTemplate(String message) {69 return String.format("<p align='center'><b>%s</b></p>", message);70 }71 @Override72 protected GridRegistry getRegistry() {73 // ensure the Registry returned reflects the hub state.74 final GridRegistry localRegistry = super.getRegistry();75 final GridRegistry hubRegistry = localRegistry.getHub().getRegistry();76 // yes, we only care if they are the same object reference.77 return (localRegistry.equals(hubRegistry)) ? localRegistry : hubRegistry;78 }79 /*80 * Disconnects the virtual node from the hub81 */82 private synchronized void disconnectVirtualSauceNodeFromGrid(HttpServletRequest req, HttpServletResponse resp)83 throws IOException {84 // Redirecting to login page if session is not found85 if (req.getSession(false) == null) {86 resp.sendRedirect(LoginServlet.class.getSimpleName());87 return;88 }89 String msg = "There is no sauce node running.";90 final SeLionSauceProxy proxy = (SeLionSauceProxy) getRegistry().getProxyById(PROXY_ID);91 if (proxy != null) {92 proxy.teardown();93 getRegistry().removeIfPresent(proxy);94 msg = "Sauce node shutdown successfully.";95 }96 registered = false;97 LOGGER.info(msg);98 ServletHelper.respondAsHtmlWithMessage(resp, formatForHtmlTemplate(msg));99 }100 /*101 * A helper method that takes care of registering a virtual node to the hub.102 */103 private synchronized void registerVirtualSauceNodeToGrid(HttpServletRequest req, HttpServletResponse resp)104 throws ServletException, IOException {105 // Redirecting to login page if session is not found106 if (req.getSession(false) == null) {107 resp.sendRedirect(LoginServlet.class.getSimpleName());108 return;109 }110 String respMsg = "Sauce node already registered.";111 if (registered) {112 ServletHelper.respondAsHtmlWithMessage(resp, formatForHtmlTemplate(respMsg));113 LOGGER.info(respMsg);114 return;115 }116 HttpClientFactory httpClientFactory = new HttpClientFactory();117 respMsg = "Sauce node registration failed. Please refer to the log file for failure details.";118 try {119 final int port = getRegistry().getHub().getConfiguration().port;120 final URL registration = new URL("http://localhost:" + port + "/grid/register");121 BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",122 registration.toExternalForm());123 request.setEntity(new StringEntity(getRegistrationRequestEntity()));124 HttpHost host = new HttpHost(registration.getHost(), registration.getPort());125 HttpClient client = httpClientFactory.getHttpClient();126 HttpResponse response = client.execute(host, request);127 if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {128 respMsg = "Sauce node registered successfully.";129 registered = true;130 }131 } catch (IOException | GridConfigurationException e) { // We catch the GridConfigurationException here to fail132 // gracefully133 // TODO Consider retrying on failure134 LOGGER.log(Level.WARNING, "Unable to register sauce node: ", e);135 } finally {136 httpClientFactory.close();137 }138 LOGGER.info(respMsg);139 ServletHelper.respondAsHtmlWithMessage(resp, formatForHtmlTemplate(respMsg));140 }141 /*142 * Update the registration request entity143 */144 private String getRegistrationRequestEntity() throws FileNotFoundException {145 // update the registration request with the max concurrent sessions/vms146 final GridNodeConfiguration gnc =147 GridNodeConfiguration.loadFromJSON(SeLionGridConstants.NODE_SAUCE_CONFIG_FILE);148 // get the max concurrent vm's allowed for the account from sauce labs149 final SauceLabsRestApi restApi;150 try {151 restApi = new SauceLabsRestApi();152 } catch (GridConfigurationException e) {153 throw e;154 }155 final int maxConcurrent = restApi.getMaxConcurrency();156 if (maxConcurrent != -1) {157 // update max sessions158 gnc.maxSession = maxConcurrent;159 // update browser max instances for all saucelabs "browser" types160 for (MutableCapabilities caps : gnc.capabilities) {161 if (caps.getBrowserName().equals(SAUCELABS_BROWSER_NAME)) {162 caps.setCapability(MAX_INSTANCES_CONFIG_PROPERTY, maxConcurrent);163 }164 }165 }...
Source:SauceLabsRestApiTest.java
...18import org.powermock.core.classloader.annotations.PrepareForTest;19import org.powermock.modules.testng.PowerMockTestCase;20import org.powermock.reflect.Whitebox;21import org.testng.annotations.Test;22import com.paypal.selion.utils.SauceLabsRestApi.SauceLabsHttpResponse;23import java.util.HashMap;24import static org.powermock.api.mockito.PowerMockito.*;25import static org.testng.Assert.assertEquals;26import static org.testng.Assert.assertTrue;27@PrepareForTest({ SauceLabsRestApi.class, SauceLabsHttpResponse.class })28public class SauceLabsRestApiTest extends PowerMockTestCase {29 private static final String mockApiResult = 30 "{\"subaccounts\": {\"foobar\": {\"all\": 1}},\"totals\": {\"all\": 2},\"concurrency\": 5}";31 @Test32 public void getMaxConcurrency() throws Exception {33 SauceLabsHttpResponse mockHttpResponse = mock(SauceLabsHttpResponse.class);34 doReturn(mockApiResult).when(mockHttpResponse, "getEntity");35 when(mockHttpResponse.getEntityAsJsonObject()).thenCallRealMethod();36 SauceLabsRestApi apiMock = mock(SauceLabsRestApi.class);37 Whitebox.setInternalState(apiMock, "maxTestCase", -1);38 doReturn(mockHttpResponse).when(apiMock, "doSauceRequest", Mockito.anyString());39 when(apiMock.getMaxConcurrency()).thenCallRealMethod();40 assertEquals(apiMock.getMaxConcurrency(), 5);41 }42 @Test43 public void getNumberOfTCRunningForSubAccount() throws Exception {44 SauceLabsHttpResponse mockHttpResponse = mock(SauceLabsHttpResponse.class);45 doReturn(mockApiResult).when(mockHttpResponse, "getEntity");46 when(mockHttpResponse.getEntityAsJsonObject()).thenCallRealMethod();47 SauceLabsRestApi apiMock = mock(SauceLabsRestApi.class);48 doReturn(mockHttpResponse).when(apiMock, "doSauceRequest", Mockito.anyString());49 when(apiMock.getNumberOfTCRunningForSubAccount(Mockito.anyString())).thenCallRealMethod();50 assertEquals(apiMock.getNumberOfTCRunningForSubAccount("foobar"), 1);51 }52 @Test53 public void getNumberOfTCRunning() throws Exception {54 SauceLabsHttpResponse mockHttpResponse = mock(SauceLabsHttpResponse.class);55 doReturn(mockApiResult).when(mockHttpResponse, "getEntity");56 when(mockHttpResponse.getEntityAsJsonObject()).thenCallRealMethod();57 SauceLabsRestApi apiMock = mock(SauceLabsRestApi.class);58 doReturn(mockHttpResponse).when(apiMock, "doSauceRequest", Mockito.anyString());59 when(apiMock.getNumberOfTCRunning()).thenCallRealMethod();60 assertEquals(apiMock.getNumberOfTCRunning(), 2);61 }62 @Test63 public void isAuthenticated() throws Exception {64 SauceLabsHttpResponse mockHttpResponse = mock(SauceLabsHttpResponse.class);65 doReturn(HttpStatus.SC_OK).when(mockHttpResponse, "getStatus");66 SauceLabsRestApi apiMock = mock(SauceLabsRestApi.class);67 Whitebox.setInternalState(apiMock, "accountCache", new HashMap<String, Boolean>());68 doReturn(mockHttpResponse).when(apiMock, "doSauceRequest", Mockito.any(), Mockito.anyString(),69 Mockito.anyInt(), Mockito.anyInt());70 when(apiMock.isAuthenticated(Mockito.anyString(), Mockito.anyString())).thenCallRealMethod();71 assertTrue(apiMock.isAuthenticated("foo", "bar"));72 }73}...
SauceLabsRestApi
Using AI Code Generation
1import com.paypal.selion.platform.grid.Grid;2import com.paypal.selion.platform.grid.browsercapabilities.DefaultCapabilitiesBuilder;3import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder;4import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsRestApi;5import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsAuthentication;6import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsAuthenticationBuilder;7import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsCapability;8import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsCapabilityBuilder;9import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsCapabilityBuilder.SauceLabsCapabilityBuilderForBrowser;10import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsCapabilityBuilder.SauceLabsCapabilityBuilderForPlatform;11import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsCapabilityBuilder.SauceLabsCapabilityBuilderForPlatform.SauceLabsCapabilityBuilderForPlatformVersion;12import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsCapabilityBuilder.SauceLabsCapabilityBuilderForPlatform.SauceLabsCapabilityBuilderForPlatformVersion.SauceLabsCapabilityBuilderForBrowserVersion;13import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsCapabilityBuilder.SauceLabsCapabilityBuilderForPlatform.SauceLabsCapabilityBuilderForPlatformVersion.SauceLabsCapabilityBuilderForBrowserVersion.SauceLabsCapabilityBuilderForDeviceName;14import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsCapabilityBuilder.SauceLabsCapabilityBuilderForPlatform.SauceLabsCapabilityBuilderForPlatformVersion.SauceLabsCapabilityBuilderForBrowserVersion.SauceLabsCapabilityBuilderForDeviceName.SauceLabsCapabilityBuilderForDeviceOrientation;15import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsCapabilitiesBuilder.SauceLabsCapabilityBuilder.SauceLabsCapabilityBuilderForPlatform.SauceLabsCapabilityBuilderForPlatformVersion.SauceLabsCapabilityBuilderForBrowserVersion.SauceLabsCapabilityBuilderForDeviceName.SauceLabsCapabilityBuilderForDeviceOrientation.SauceLabsCapabilityBuilderForDevice
SauceLabsRestApi
Using AI Code Generation
1import com.paypal.selion.utils.SauceLabsRestApi;2import org.json.JSONException;3import org.json.JSONObject;4import java.io.IOException;5import java.util.Map;6public class SauceLabsRestApiTest {7 public static void main(String[] args) throws IOException, JSONException {8 JSONObject jobStatus = SauceLabsRestApi.getJobStatus("job-id");9 System.out.println("Job Status: " + jobStatus.toString());10 Map<String, Object> jobStatusMap = SauceLabsRestApi.getJobStatusAsMap("job-id");11 System.out.println("Job Status: " + jobStatusMap.toString());12 String jobStatusString = SauceLabsRestApi.getJobStatusAsString("job-id");13 System.out.println("Job Status: " + jobStatusString);14 JSONObject jobStatus1 = SauceLabsRestApi.getJobStatus("job-id");15 System.out.println("Job Status: " + jobStatus1.toString());16 Map<String, Object> jobStatusMap1 = SauceLabsRestApi.getJobStatusAsMap("job-id");17 System.out.println("Job Status: " + jobStatusMap1.toString());18 String jobStatusString1 = SauceLabsRestApi.getJobStatusAsString("job-id");19 System.out.println("Job Status: " + jobStatusString1);20 JSONObject jobStatus2 = SauceLabsRestApi.getJobStatus("job-id");21 System.out.println("Job Status: " + jobStatus2.toString());22 Map<String, Object> jobStatusMap2 = SauceLabsRestApi.getJobStatusAsMap("job-id");23 System.out.println("Job Status: " + jobStatusMap2.toString());24 String jobStatusString2 = SauceLabsRestApi.getJobStatusAsString("job-id");25 System.out.println("Job Status: " + jobStatusString2);26 JSONObject jobStatus3 = SauceLabsRestApi.getJobStatus("job-id");27 System.out.println("Job Status: " + jobStatus
SauceLabsRestApi
Using AI Code Generation
1package com.paypal.selion.testcomponents;2import com.paypal.selion.platform.grid.Grid;3import com.paypal.selion.platform.grid.browsercapabilities.DefaultCapabilitiesBuilder;4import com.paypal.selion.platform.grid.browsercapabilities.SauceCapabilitiesBuilder;5import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsRestApi;6import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsSessionIdProvider;7import com.paypal.selion.platform.grid.Grid;8import com.paypal.selion.platform.grid.browsercapabilities.DefaultCapabilitiesBuilder;9import com.paypal.selion.platform.grid.browsercapabilities.SauceCapabilitiesBuilder;10import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsRestApi;11import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsSessionIdProvider;12import com.paypal.selion.platform.grid.Grid;13import com.paypal.selion.platform.grid.browsercapabilities.DefaultCapabilitiesBuilder;14import com.paypal.selion.platform.grid.browsercapabilities.SauceCapabilitiesBuilder;15import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsRestApi;16import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsSessionIdProvider;17import com.paypal.selion.platform.grid.Grid;18import com.paypal.selion.platform.grid.browsercapabilities.DefaultCapabilitiesBuilder;19import com.paypal.selion.platform.grid.browsercapabilities.SauceCapabilitiesBuilder;20import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsRestApi;21import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsSessionIdProvider;22import com.paypal.selion.platform.grid.Grid;23import com.paypal.selion.platform.grid.browsercapabilities.DefaultCapabilitiesBuilder;24import com.paypal.selion.platform.grid.browsercapabilities.SauceCapabilitiesBuilder;25import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsRestApi;26import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsSessionIdProvider;27import com.paypal.selion.platform.grid.Grid;28import com.paypal.selion.platform.grid.browsercapabilities.DefaultCapabilitiesBuilder;29import com.paypal.selion.platform.grid.browsercapabilities.SauceCapabilitiesBuilder;30import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsRestApi;31import com.paypal.selion.platform.grid.browsercapabilities.SauceLabsSessionIdProvider;32import com.paypal.selion.platform.grid.Grid;33import com.paypal.selion.platform.grid.browsercapabilities.DefaultCapabilitiesBuilder;34import com.paypal.selion.platform.grid.browsercapabilities.Sauce
SauceLabsRestApi
Using AI Code Generation
1import com.paypal.selion.utils.SauceLabsRestApi;2import org.json.JSONArray;3import org.json.JSONObject;4import org.testng.annotations.Test;5public class SauceLabsRestApiTest {6 public void testSauceLabsRestApi() throws Exception {7 SauceLabsRestApi sauceLabsRestApi = new SauceLabsRestApi();8 JSONArray jobIds = sauceLabsRestApi.getJobIds();9 JSONArray jobIdsForDay = sauceLabsRestApi.getJobIdsForDay("2014-12-11");10 JSONArray jobIdsForDayAndTime = sauceLabsRestApi.getJobIdsForDayAndTime("2014-12-11", "13:00");11 JSONArray jobIdsForTime = sauceLabsRestApi.getJobIdsForTime("13:00");12 JSONArray jobIdsForTimeRange = sauceLabsRestApi.getJobIdsForTimeRange("13:00", "14:00");13 JSONArray jobIdsForTimeRangeAndDay = sauceLabsRestApi.getJobIdsForTimeRangeAndDay("13:00", "14:00", "2014-12-11");14 JSONObject jobIdForJobName = sauceLabsRestApi.getJobIdForJobName("SauceLabsRestApiTest");15 JSONObject jobDetails = sauceLabsRestApi.getJobDetails("d9c9a8f8e3b44a3f8a2e1e3d7c2b1a0d");16 JSONObject jobDetailsForJobName = sauceLabsRestApi.getJobDetailsForJobName("SauceLabsRestApiTest");
SauceLabsRestApi
Using AI Code Generation
1import com.paypal.selion.utils.SauceLabsRestApi;2import java.io.*;3import java.util.*;4public class 3 {5public static void main(String[] args) {6SauceLabsRestApi api = new SauceLabsRestApi();7try {8List<String> jobs = api.getAllJobs();9File file = new File("jobList.txt");10file.createNewFile();11FileWriter writer = new FileWriter(file);12for (String job : jobs) {13writer.write(job + "14");15}16writer.flush();17writer.close();18} catch (IOException e) {19e.printStackTrace();20}21}22}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!