Best Selenium code snippet using org.openqa.selenium.internal.Require.stateCondition
Source:FirefoxOptions.java
...78 } else {79 Object rawOptions = source.getCapability(FIREFOX_OPTIONS);80 if (rawOptions != null) {81 // If `source` contains the keys we care about, then make sure they're good.82 Require.stateCondition(rawOptions instanceof Map, "Expected options to be a map: %s", rawOptions);83 Map<String, Object> sourceOptions = (Map<String, Object>) rawOptions;84 Map<String, Object> options = new TreeMap<>();85 for (Keys key : Keys.values()) {86 key.amend(sourceOptions, options);87 }88 this.firefoxOptions = Collections.unmodifiableMap(options);89 }90 if (source.getCapability(MARIONETTE) == Boolean.FALSE) {91 this.legacy = true;92 }93 }94 }95 private void mirror(FirefoxOptions that) {96 Map<String, Object> newOptions = new TreeMap<>(firefoxOptions);97 for (Keys key : Keys.values()) {98 Object value = key.mirror(firefoxOptions, that.firefoxOptions);99 if (value != null) {100 newOptions.put(key.key(), value);101 }102 }103 this.firefoxOptions = Collections.unmodifiableMap(newOptions);104 this.legacy = that.legacy;105 }106 public FirefoxOptions configureFromEnv() {107 // Read system properties and use those if they are set, allowing users to override them later108 // should they want to.109 String binary = System.getProperty(FirefoxDriver.SystemProperty.BROWSER_BINARY);110 if (binary != null) {111 setBinary(binary);112 }113 String profileName = System.getProperty(FirefoxDriver.SystemProperty.BROWSER_PROFILE);114 if (profileName != null) {115 FirefoxProfile profile = new ProfilesIni().getProfile(profileName);116 if (profile == null) {117 throw new WebDriverException(String.format(118 "Firefox profile '%s' named in system property '%s' not found",119 profileName, FirefoxDriver.SystemProperty.BROWSER_PROFILE));120 }121 setProfile(profile);122 }123 String forceMarionette = System.getProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE);124 if (forceMarionette != null && !Boolean.getBoolean(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE)) {125 setLegacy(true);126 }127 return this;128 }129 /**130 * @deprecated This method will be deleted and will not be replaced.131 */132 @Deprecated133 public FirefoxOptions setLegacy(boolean legacy) {134 setCapability(MARIONETTE, !legacy);135 return this;136 }137 /**138 * @deprecated This method will be deleted and will not be replaced.139 */140 @Deprecated141 public boolean isLegacy() {142 return legacy;143 }144 public FirefoxOptions setBinary(FirefoxBinary binary) {145 Require.nonNull("Binary", binary);146 addArguments(binary.getExtraOptions());147 return setFirefoxOption(Keys.BINARY, binary.getPath());148 }149 public FirefoxOptions setBinary(Path path) {150 Require.nonNull("Binary", path);151 return setFirefoxOption(Keys.BINARY, path.toString());152 }153 public FirefoxOptions setBinary(String path) {154 Require.nonNull("Binary", path);155 return setFirefoxOption(Keys.BINARY, path);156 }157 /**158 * Constructs a {@link FirefoxBinary} and returns that to be used, and because of this is only159 * useful when actually starting firefox.160 */161 public FirefoxBinary getBinary() {162 return getBinaryOrNull().orElseGet(FirefoxBinary::new);163 }164 public Optional<FirefoxBinary> getBinaryOrNull() {165 Object binary = firefoxOptions.get(Keys.BINARY.key());166 if (!(binary instanceof String)) {167 return Optional.empty();168 }169 FirefoxBinary toReturn = new FirefoxBinary(new File((String) binary));170 Object rawArgs = firefoxOptions.getOrDefault(Keys.ARGS.key(), new ArrayList<>());171 Require.stateCondition(rawArgs instanceof List, "Arguments are not a list: %s", rawArgs);172 ((List<?>) rawArgs).stream()173 .filter(Objects::nonNull)174 .map(String::valueOf)175 .forEach(toReturn::addCommandLineOptions);176 return Optional.of(toReturn);177 }178 public FirefoxOptions setProfile(FirefoxProfile profile) {179 Require.nonNull("Profile", profile);180 try {181 return setFirefoxOption(Keys.PROFILE, profile.toJson());182 } catch (IOException e) {183 throw new UncheckedIOException(e);184 }185 }186 public FirefoxProfile getProfile() {187 Object rawProfile = firefoxOptions.get(Keys.PROFILE.key());188 if (rawProfile == null) {189 return new FirefoxProfile();190 }191 if (rawProfile instanceof FirefoxProfile) {192 return (FirefoxProfile) rawProfile;193 }194 try {195 return FirefoxProfile.fromJson((String) rawProfile);196 } catch (IOException e) {197 throw new UncheckedIOException(e);198 }199 }200 public FirefoxOptions addArguments(String... arguments) {201 addArguments(Arrays.asList(arguments));202 return this;203 }204 public FirefoxOptions addArguments(List<String> arguments) {205 Require.nonNull("Arguments", arguments);206 Object rawList = firefoxOptions.getOrDefault(Keys.ARGS.key(), new ArrayList<>());207 Require.stateCondition(rawList instanceof List, "Arg list of unexpected type: %s", rawList);208 List<String> newArgs = new ArrayList<>();209 ((List<?>) rawList).stream()210 .map(String::valueOf)211 .forEach(newArgs::add);212 newArgs.addAll(arguments);213 return setFirefoxOption(Keys.ARGS, Collections.unmodifiableList(newArgs));214 }215 public FirefoxOptions addPreference(String key, Object value) {216 Require.nonNull("Key", key);217 Require.nonNull("Value", value);218 Object rawPrefs = firefoxOptions.getOrDefault(Keys.PREFS.key(), new HashMap<>());219 Require.stateCondition(rawPrefs instanceof Map, "Prefs are of unexpected type: %s", rawPrefs);220 Map<String, Object> newPrefs = new TreeMap<>();221 @SuppressWarnings("unchecked") Map<String, Object> prefs = (Map<String, Object>) rawPrefs;222 newPrefs.putAll(prefs);223 newPrefs.put(key, value);224 return setFirefoxOption(Keys.PREFS, Collections.unmodifiableMap(newPrefs));225 }226 public FirefoxOptions setLogLevel(FirefoxDriverLogLevel logLevel) {227 Require.nonNull("Log level", logLevel);228 return setFirefoxOption(Keys.LOG, logLevel.toJson());229 }230 public FirefoxOptions setHeadless(boolean headless) {231 Object rawArgs = firefoxOptions.getOrDefault(Keys.ARGS.key(), new ArrayList<>());232 Require.stateCondition(rawArgs instanceof List, "Arg list of unexpected type: %s", rawArgs);233 List<String> newArgs = new ArrayList<>();234 ((List<?>) rawArgs).stream()235 .map(String::valueOf)236 .filter(arg -> !"-headless".equals(arg))237 .forEach(newArgs::add);238 if (headless) {239 newArgs.add("-headless");240 }241 return setFirefoxOption(Keys.ARGS, Collections.unmodifiableList(newArgs));242 }243 @Override244 public void setCapability(String key, Object value) {245 Require.nonNull("Capability name", key);246 Require.nonNull("Value", value);247 switch (key) {248 case BINARY:249 if (value instanceof FirefoxBinary) {250 setBinary((FirefoxBinary) value);251 } else if (value instanceof Path) {252 setBinary((Path) value);253 } else if (value instanceof String) {254 setBinary((String) value);255 } else {256 throw new IllegalArgumentException("Unable to set binary from " + value);257 }258 break;259 case MARIONETTE:260 if (value instanceof Boolean) {261 legacy = !(Boolean) value;262 }263 break;264 case PROFILE:265 if (value instanceof FirefoxProfile) {266 setProfile((FirefoxProfile) value);267 } else if (value instanceof String) {268 try {269 FirefoxProfile profile = FirefoxProfile.fromJson((String) value);270 setProfile(profile);271 } catch (IOException e) {272 throw new WebDriverException(e);273 }274 } else {275 throw new WebDriverException("Unexpected value for profile: " + value);276 }277 break;278 default:279 // Do nothing280 }281 super.setCapability(key, value);282 }283 private FirefoxOptions setFirefoxOption(Keys key, Object value) {284 Map<String, Object> newOptions = new TreeMap<>(firefoxOptions);285 newOptions.put(key.key(), value);286 firefoxOptions = Collections.unmodifiableMap(newOptions);287 return this;288 }289 @Override290 protected Set<String> getExtraCapabilityNames() {291 Set<String> names = new TreeSet<>();292 names.add(FIREFOX_OPTIONS);293 if (legacy) {294 names.add(MARIONETTE);295 }296 return Collections.unmodifiableSet(names);297 }298 @Override299 protected Object getExtraCapability(String capabilityName) {300 Require.nonNull("Capability name", capabilityName);301 switch (capabilityName) {302 case FIREFOX_OPTIONS:303 return Collections.unmodifiableMap(firefoxOptions);304 case MARIONETTE:305 return !legacy;306 default:307 return null;308 }309 }310 @Override311 public FirefoxOptions merge(Capabilities capabilities) {312 Require.nonNull("Capabilities to merge", capabilities);313 FirefoxOptions newInstance = new FirefoxOptions();314 getCapabilityNames().forEach(name -> newInstance.setCapability(name, getCapability(name)));315 capabilities.getCapabilityNames().forEach(name -> newInstance.setCapability(name, capabilities.getCapability(name)));316 newInstance.mirror(this);317 if (capabilities instanceof FirefoxOptions) {318 newInstance.mirror((FirefoxOptions) capabilities);319 }320 return newInstance;321 }322 private enum Keys {323 ARGS("args") {324 @Override325 public void amend(Map<String, Object> sourceOptions, Map<String, Object> toAmend) {326 Object o = sourceOptions.get(key());327 if (!(o instanceof List)) {328 return;329 }330 Object rawArgs = toAmend.getOrDefault(key(), new ArrayList<>());331 @SuppressWarnings("unchecked") List<String> existingArgs = (List<String>) rawArgs;332 @SuppressWarnings("unchecked") List<String> sourceArgs = (List<String>) o;333 List<String> newArgs = new ArrayList<>(existingArgs);334 newArgs.addAll(sourceArgs);335 toAmend.put(key(), Collections.unmodifiableList(new ArrayList<>(newArgs)));336 }337 @Override338 public Object mirror(Map<String, Object> first, Map<String, Object> second) {339 Object rawFirst = first.getOrDefault(key(), new ArrayList<>());340 Require.stateCondition(rawFirst instanceof List, "Args are of unexpected type: %s", rawFirst);341 @SuppressWarnings("unchecked") List<String> firstList = (List<String>) rawFirst;342 Object rawSecond = second.getOrDefault(key(), new ArrayList<>());343 Require.stateCondition(rawSecond instanceof List, "Args are of unexpected type: %s", rawSecond);344 @SuppressWarnings("unchecked") List<String> secondList = (List<String>) rawSecond;345 List<String> args = new ArrayList<>(firstList);346 args.addAll(secondList);347 return args.isEmpty() ? null : args;348 }349 },350 BINARY("binary") {351 @Override352 public void amend(Map<String, Object> sourceOptions, Map<String, Object> toAmend) {353 Object o = sourceOptions.get(key());354 if (o instanceof FirefoxBinary) {355 FirefoxBinary binary = (FirefoxBinary) o;356 toAmend.put(key(), binary.getFile().toString());357 ARGS.amend(Collections.singletonMap(ARGS.key(), binary.getExtraOptions()), toAmend);358 } else if (o instanceof String) {359 toAmend.put(key(), o);360 }361 }362 @Override363 public Object mirror(Map<String, Object> first, Map<String, Object> second) {364 Object value = second.get(key());365 if (value == null) {366 value = first.get(key());367 }368 if (value == null) {369 return null;370 }371 Require.stateCondition(value instanceof String, "Unexpected type for binary: %s", value);372 return value;373 }374 },375 ENV("env") {376 @Override377 public void amend(Map<String, Object> sourceOptions, Map<String, Object> toAmend) {378 Object o = sourceOptions.get(key());379 if (o == null) {380 return;381 }382 Require.stateCondition(o instanceof Map, "Unexpected type for env: %s", o);383 Map<String, Object> collected = ((Map<?, ?>) o).entrySet().stream()384 .collect(toMap(entry -> String.valueOf(entry.getKey()), Map.Entry::getValue));385 toAmend.put(key(), Collections.unmodifiableMap(collected));386 }387 @Override388 public Object mirror(Map<String, Object> first, Map<String, Object> second) {389 Object rawFirst = first.getOrDefault(key(), new TreeMap<>());390 Require.stateCondition(rawFirst instanceof Map, "Env vars are of unexpected type: %s", rawFirst);391 @SuppressWarnings("unchecked") Map<String, String> firstPrefs = (Map<String, String>) rawFirst;392 Object rawSecond = second.getOrDefault(key(), new TreeMap<>());393 Require.stateCondition(rawSecond instanceof Map, "Env vars are of unexpected type: %s", rawSecond);394 @SuppressWarnings("unchecked") Map<String, String> secondPrefs = (Map<String, String>) rawSecond;395 Map<String, String> value = new TreeMap<>(firstPrefs);396 value.putAll(secondPrefs);397 return value.isEmpty() ? null : value;398 }399 },400 LOG("log") {401 @Override402 public void amend(Map<String, Object> sourceOptions, Map<String, Object> toAmend) {403 Object o = toAmend.get(key());404 if (o == null) {405 return;406 }407 Require.stateCondition(o instanceof Map, "Unexpected type for log: %s", o);408 toAmend.put(key(), o);409 }410 @Override411 public Object mirror(Map<String, Object> first, Map<String, Object> second) {412 Object value = second.get(key());413 if (value == null) {414 value = first.get(key());415 }416 if (value == null) {417 return null;418 }419 Require.stateCondition(value instanceof Map, "Log level is of unexpected type: %s", value);420 return value;421 }422 },423 PREFS("prefs") {424 @Override425 public void amend(Map<String, Object> sourceOptions, Map<String, Object> toAmend) {426 Object o = sourceOptions.get(key());427 if (o == null) {428 return;429 }430 Require.stateCondition(o instanceof Map, "Unexpected type for preferences: %s", o);431 Map<String, Object> collected = ((Map<?, ?>) o).entrySet().stream()432 .collect(toMap(entry -> String.valueOf(entry.getKey()), Map.Entry::getValue));433 toAmend.put(key(), Collections.unmodifiableMap(collected));434 }435 @Override436 public Object mirror(Map<String, Object> first, Map<String, Object> second) {437 Object rawFirst = first.getOrDefault(key(), new TreeMap<>());438 Require.stateCondition(rawFirst instanceof Map, "Prefs are of unexpected type: " + rawFirst);439 @SuppressWarnings("unchecked") Map<String, Object> firstPrefs = (Map<String, Object>) rawFirst;440 Object rawSecond = second.getOrDefault(key(), new TreeMap<>());441 Require.stateCondition(rawSecond instanceof Map, "Prefs are of unexpected type: " + rawSecond);442 @SuppressWarnings("unchecked") Map<String, Object> secondPrefs = (Map<String, Object>) rawSecond;443 Map<String, Object> value = new TreeMap<>(firstPrefs);444 value.putAll(secondPrefs);445 return value.isEmpty() ? null : value;446 }447 },448 PROFILE("profile") {449 @Override450 public void amend(Map<String, Object> sourceOptions, Map<String, Object> toAmend) {451 Object o = sourceOptions.get(key());452 if (o == null) {453 return;454 }455 if (o instanceof FirefoxProfile) {456 toAmend.put(key(), o);457 return;458 }459 Require.stateCondition(o instanceof String, "Unexpected type for profile: %s", o);460 toAmend.put(key(), o);461 }462 @Override463 public Object mirror(Map<String, Object> first, Map<String, Object> second) {464 Object value = second.get(key());465 if (value == null) {466 value = first.get(key());467 }468 if (value == null) {469 return null;470 }471 Require.stateCondition(value instanceof String, "Profile is of unexpected type: %s", value);472 return value;473 }474 },475 ;476 private final String key;477 Keys(String key) {478 this.key = key;479 }480 public String key() {481 return key;482 }483 public abstract void amend(Map<String, Object> sourceOptions, Map<String, Object> toAmend);484 public abstract Object mirror(Map<String, Object> first, Map<String, Object> second);485 }...
Source:RequireTest.java
...175 }176 @Test177 public void shouldCheckBooleanState() {178 assertThatExceptionOfType(IllegalStateException.class)179 .isThrownBy(() -> Require.stateCondition(2 * 2 == 5, "this is %s!", "math"))180 .withMessage("this is math!");181 assertThatCode(() -> Require.stateCondition(2 * 2 == 4, "this is %s!", "math"))182 .doesNotThrowAnyException();183 }184 @Test185 public void canCheckStateForNull() {186 assertThatExceptionOfType(IllegalStateException.class)187 .isThrownBy(() -> Require.state("x", (Object) null).nonNull())188 .withMessage("x must not be null");189 assertThatExceptionOfType(IllegalStateException.class)190 .isThrownBy(() -> Require.state("x", (Object) null).nonNull("must not be %s", "null"))191 .withMessage("x must not be null");192 String arg = "this";193 assertThat(Require.state("x", arg).nonNull()).isSameAs(arg);194 assertThat(Require.state("x", arg).nonNull("test")).isSameAs(arg);195 }...
Source:Preferences.java
...165 }166 private void checkPreference(String key, Object value) {167 Require.nonNull("Key", key);168 Require.nonNull("Value", value);169 Require.stateCondition(!immutablePrefs.containsKey(key) ||170 (immutablePrefs.containsKey(key) && value.equals(immutablePrefs.get(key))),171 "Preference %s may not be overridden: frozen value=%s, requested value=%s",172 key, immutablePrefs.get(key), value);173 if (MAX_SCRIPT_RUN_TIME_KEY.equals(key)) {174 int n;175 if (value instanceof String) {176 n = Integer.parseInt((String) value);177 } else if (value instanceof Integer) {178 n = (Integer) value;179 } else {180 throw new IllegalStateException(String.format(181 "%s value must be a number: %s", MAX_SCRIPT_RUN_TIME_KEY, value.getClass().getName()));182 }183 Require.stateCondition(n == 0 || n >= DEFAULT_MAX_SCRIPT_RUN_TIME,184 "%s must be == 0 || >= %s",185 MAX_SCRIPT_RUN_TIME_KEY,186 DEFAULT_MAX_SCRIPT_RUN_TIME);187 }188 }189}...
Source:RemoteSession.java
...72 this.codec = Require.nonNull("Codec", codec);73 this.id = Require.nonNull("Session id", id);74 this.capabilities = Require.nonNull("Capabilities", capabilities);75 File tempRoot = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), id.toString());76 Require.stateCondition(tempRoot.mkdirs(), "Could not create directory %s", tempRoot);77 this.filesystem = TemporaryFilesystem.getTmpFsBasedOn(tempRoot);78 CommandExecutor executor = new ActiveSessionCommandExecutor(this);79 this.driver = new Augmenter().augment(new RemoteWebDriver(80 executor,81 new ImmutableCapabilities(getCapabilities())));82 }83 @Override84 public SessionId getId() {85 return id;86 }87 @Override88 public Dialect getUpstreamDialect() {89 return upstream;90 }...
stateCondition
Using AI Code Generation
1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.internal.Require;6import org.openqa.selenium.support.ui.ExpectedConditions;7import org.openqa.selenium.support.ui.WebDriverWait;8public class StateCondition {9public static void main(String[] args) {10 System.setProperty("webdriver.chrome.driver", "chromedriver.exe");11 WebDriver driver = new ChromeDriver();12 Require stateCondition = new Require();13 WebDriverWait wait = new WebDriverWait(driver, 10);14 WebElement searchBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("q")));15 stateCondition.stateCondition(searchBox, true);16 driver.close();17}18}19How to check if element is displayed or not using isDisplayed() method of WebElement class?20How to check if element is displayed or not using isDisplayed() method of WebElement interface?21How to check if element is displayed or not using isDisplayed() method of WebElement interface in Selenium?22How to check if element is displayed or not using isDisplayed() method of WebElement class in Selenium?23How to check if element is displayed or not using isDisplayed() method of WebElement interface in Selenium Webdriver?24How to check if element is displayed or not using isDisplayed() method of WebElement class in Selenium Webdriver?
stateCondition
Using AI Code Generation
1requireVisible(element);2requireNotVisible(element);3requireEnabled(element);4requireNotEnabled(element);5requireSelected(element);6requireNotSelected(element);7requirePresent(element);8requireNotPresent(element);9requireClickable(element);
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.
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.
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.
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.
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.
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.
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.
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.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!