How to find checkbox is checked or unchecked using XPath in Selenium? - selenium

Not able to find whether checkbox is check or not? throwing exception.
I am using this XPath for checkbox:
.//*#id='row_SelectedProductURLIds0']//input[#id='actualcheckbox_SelectedProductURLIds' and #type='checkbox']
Image:
Code:
public bool VerifyCheckbox(By by, String expected)
{
bool isPresence = false;
WaitUntilElementIsPresent(by);
//string value = GetText(by);
//bool actual = Convert.ToBoolean(value);
bool expect = Convert.ToBoolean(expected);
// actual = expect ? isPresence = true : isPresence = false;
isPresence = Driver.FindElement(by).Selected;
Assert.AreEqual(expect, isPresence);
if (isPresence != expect)
{
isPresence = false;
}
else
{
isPresence = true;
}
return isPresence;
}

I'm not sure what all you are trying to accomplish but I've simplified it.
public bool VerifyCheckbox(By by, bool expected)
{
bool actual = Driver.FindElement(by).Selected;
Assert.AreEqual(expected, actual);
return (expected == actual);
}
I don't guess I understand why you need to Assert if they are equal AND return if they are equal. It seems redundant. It would be better to get rid of this whole function and just do the below.
Assert.AreEqual(expected, Driver.FindElement(By.Id("actualcheckbox_SelectedProductURLIds")).Selected);

Related

Is there any method in ByteBuddy to convert a TypeDescription.Generic into an appropriate java.lang.reflect.Type?

(The surface area of the ByteBuddy API is overwhelmingly enormous, which is why I'm asking the question.)
I'm aware that I can take a TypeDescription.Generic and determine its "sort" and proceed rather laboriously "by hand" from there, but often times I've found there is a method buried somewhere that will do this sort of tedious work for me.
EDIT: a commenter asked for the "tedious" recipe. Here it is (stand back; please note the various implementations of various Types are more or less what you'd expect them to be):
public static final Type toType(final TypeDefinition type) throws ReflectiveOperationException {
final Type returnValue;
if (type == null) {
returnValue = null;
} else {
final TypeDescription.Generic genericType = type.asGenericType();
switch (type.getSort()) {
case GENERIC_ARRAY:
returnValue = new DefaultGenericArrayType(toType(type.getComponentType()));
break;
case NON_GENERIC:
returnValue = Class.forName(type.getTypeName(), false, Thread.currentThread().getContextClassLoader());
break;
case PARAMETERIZED:
final TypeDefinition ownerType = genericType.getOwnerType();
final TypeDefinition rawType = type.asErasure();
final List<? extends TypeDefinition> actualTypeArguments = genericType.getTypeArguments();
if (actualTypeArguments == null || actualTypeArguments.isEmpty()) {
returnValue = new DefaultParameterizedType(toType(ownerType), toType(rawType));
} else {
final Type[] actualJavaTypeArguments = new Type[actualTypeArguments.size()];
for (int i = 0; i < actualTypeArguments.size(); i++) {
actualJavaTypeArguments[i] = toType(actualTypeArguments.get(i));
}
returnValue = new DefaultParameterizedType(toType(ownerType), toType(rawType), actualJavaTypeArguments);
}
break;
case VARIABLE:
final TypeVariableSource typeVariableSource = genericType.getTypeVariableSource();
final GenericDeclaration gd;
if (typeVariableSource instanceof TypeDefinition typeDefinition) {
gd = Class.forName(typeDefinition.asErasure().getTypeName(), false, Thread.currentThread().getContextClassLoader());
} else if (typeVariableSource instanceof MethodDescription.InDefinedShape methodDescription) {
// Reflection time
final String name = methodDescription.getName();
final Class<?> cls = Class.forName(methodDescription.getDeclaringType().asErasure().getTypeName(), false, Thread.currentThread().getContextClassLoader());
final List<? extends TypeDefinition> parameterTypes = methodDescription.getParameters().asTypeList();
final Class<?>[] parameterClasses = new Class<?>[parameterTypes.size()];
for (int i = 0; i < parameterTypes.size(); i++) {
parameterClasses[i] = Class.forName(parameterTypes.get(i).asErasure().getName(), false, Thread.currentThread().getContextClassLoader());
}
if (MethodDescription.CONSTRUCTOR_INTERNAL_NAME.equals(name)) {
assert TypeDescription.VOID.equals(methodDescription.getReturnType());
gd = cls.getDeclaredConstructor(parameterClasses);
} else {
assert !MethodDescription.TYPE_INITIALIZER_INTERNAL_NAME.equals(name);
gd = cls.getDeclaredMethod(name, parameterClasses);
}
} else {
throw new IllegalArgumentException("Unexpected type variable source: " + typeVariableSource);
}
final TypeVariable<?>[] typeVariables = gd.getTypeParameters();
TypeVariable<?> temp = null;
for (final TypeVariable<?> typeVariable : typeVariables) {
if (typeVariable.getName().equals(genericType.getSymbol())) {
temp = typeVariable;
break;
}
}
assert temp != null;
returnValue = temp;
break;
case VARIABLE_SYMBOLIC:
throw new IllegalArgumentException("Unexpected type: " + type);
case WILDCARD:
final List<? extends TypeDefinition> upperBounds = genericType.getUpperBounds();
final List<? extends TypeDefinition> lowerBounds = genericType.getLowerBounds();
if (lowerBounds == null || lowerBounds.isEmpty()) {
if (upperBounds == null || upperBounds.isEmpty() || (upperBounds.size() == 1 && TypeDescription.Generic.OBJECT.equals(upperBounds.get(0)))) {
returnValue = UnboundedWildcardType.INSTANCE;
} else {
// Upper bounded.
final Type[] upperJavaBounds = new Type[upperBounds.size()];
for (int i = 0; i < upperBounds.size(); i++) {
upperJavaBounds[i] = toType(upperBounds.get(i)); // XXX recursive
}
returnValue = new UpperBoundedWildcardType(upperJavaBounds);
}
} else {
assert upperBounds == null || upperBounds.isEmpty() || (upperBounds.size() == 1 && TypeDescription.Generic.OBJECT.equals(upperBounds.get(0))) : "Unexpected upper bounds: " + upperBounds + "; lower bounds: " + lowerBounds;
// Lower bounded.
assert lowerBounds.size() == 1 : "Unexpected size in lower bounds: " + lowerBounds;
returnValue = new LowerBoundedWildcardType(toType(lowerBounds.get(0))); // XXX recursive
}
break;
default:
throw new IllegalArgumentException("Unexpected type: " + type);
}
}
return returnValue;
}
No, you can only convert a Type to a TypeDescription.Generic but there is no option to do it the other way. The easiest option to emulate this would probably be to define a class that defines a field of the given Type, to load this class and to read the field type using Java reflection.
The reason Byte Buddy cannot convert a description to a Type is that Byte Buddy abstracts out class loaders and that type variables might be detached from their declaring source.

Laravel: Find exact match, case sensitive

This code works but it is not sensitive to case/capitalization.
public function search(){
if ($search = \Request::get('q')) {
$patrons = Patron::where(function($query) use ($search){
$query->where('barcode','=',"$search")
})->paginate(20);
}else{
$patrons = Patron::latest()->paginate(5);
}
return $patrons;
}
Example
Searching for 'banana123' should NOT be equal to 'BaNaNa123' and should return 0.
How can we make the search exact match? Thank you.
You have to use BINARY
use DB;
...
public function search(){
if ($search = \Request::get('q')) {
$patrons = Patron::where(function($query) use ($search){
$query->whereRaw("BINARY `barcode` = '$search'");
// or
// $query->where(DB::raw("BINARY `barcode`), $search);
})->paginate(20);
}else{
$patrons = Patron::latest()->paginate(5);
}
return $patrons;
}
Also if you are using one where and not chaining it to other conditions you don't need to use function inside where. you can simply write:
use DB;
...
public function search(){
if ($search = \Request::get('q')) {
$patrons = Patron::where(DB::raw("BINARY `barcode`"), $search)->paginate(20);
}else{
$patrons = Patron::latest()->paginate(5);
}
return $patrons;
}

ActionScript 2.0 Random Boolean Function not working

I have the below code which show be randomly true and randomly false. But in my case its always being false. Any help is appreciated. Thanks.
In the below code tail and heads are the tow buttons.
on(release)
{
var guess:Boolean = Boolean(Math.round(Math.random()));
var input:Boolean;
if (event.target.name == "tail"){
input = true;
}
else if (event.target.name == "heads"){
input = false;
}
if (guess == input){
var newresult = Number(income.text) + Number(amount.text);
income.text = Number(newresult);
}
else{
var newresult = Number(income.text) - Number(amount.text);
income.text = Number(newresult);
}
}
This will also work:
on(release)
{
var guess:Boolean = Boolean(Math.floor(Math.random()*2));
if (guess){
result.text = "Your Guess is corrent";
var newresult = Number(income.text) + Number(amount.text);
income.text = Number(newresult);
}
else{
result.text = "Your Guess is wrong";
var newresult = Number(income.text) - Number(amount.text);
income.text = Number(newresult);
}
}
You dont need the event.target.name because the function is within the event handler of each button. So you can just use a random boolean. Event.target.name also doesnt work in AS2.0

Assingn TRUE value to a funcion in VB

The VB code below assigns True value assign to the function. But when I convert to C#, I am getting an error like we can not assign True to a method. How can I assign true to the method in C#. This is my VB code:
Private Function KeyOK(ByVal sKey As String) As Boolea
KeyOK = True
sKey = Trim(sKey)
If Len(sKey) <> KEY_LENGTH Then
KeyOK = False
Exit Function
The equivalent in C# is the return keyword. So, instead of KeyOK = false, you'd just write:
return false;
Here's an equivalent C# function:
private bool KeyOK(string sKey)
{
bool result = true;
sKey = (sKey ?? "").Trim();
if (sKey.Length != KEY_LENGTH)
result = false;
return result;
}
It is a matter of style/taste, but I would leave out the intermediates
private bool KeyOK(string key) {
return (key ?? "").Trim().Length == KEY_LENGTH;
}
or simply
private bool KeyOK(string key) {
return key.Trim().Length == KEY_LENGTH;
}
if you are happy that key will never be null.
(sticking my nose in un-necessarily)
Alan.

How to write a custom FindElement routine in Selenium?

I'm trying to figure out how to write a custom FindElement routine in Selenium 2.0 WebDriver. The idea would be something like this:
driver.FindElement(By.Method( (ISearchContext) => {
/* examine search context logic here... */ }));
The anonymous method would examine the ISearchContext and return True if it matches; False otherwise.
I'm digging through the Selenium code, and getting a bit lost. It looks like the actual By.* logic is carried out server-side, not client side. That seems to be complicating matters.
Any suggestions?
I do a multi-staged search. I have a method that performs a try catch and then a method that gets the element. In theory you could do a try catch until instead of this way but I like this way better because of my setup.
public bool CheckUntil(IWebDriver driver, string selectorType, string selectorInfo)
{
int Timer = 160;
bool itemFound = false;
for (int i = 0; i < Timer; i++)
if(itemFound)
{
i = 0
}
else
{
Thread.Sleep(500);
if(selectorType.ToLower() == "id" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.Id(selectorInfo).Displayed)
{
itemFound = true;
}
}
else if(selectorType.ToLower() == "tagname" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.TagName(selectorInfo).Displayed)
{
itemFound = true;
}
}
}
return itemFound;
}
Here's my try catch method you can add as many different types as you want id, cssselector, xpath, tagname, classname, etc.
public bool TryCatch(IWebDriver driver, string selectorType, string selectorInfo)
{
bool ElementFound = false;
try
{
switch(selectorType)
{
case "id":
driver.FindElement(By.Id(selectorInfo);
break;
case "tagname":
driver.FindElement(By.TagName(selectorInfo);
break;
}
ElementFound = truel
}
catch
{
ElementFound = false;
}
return ElementFound;
}
Ok, I figured out how to do this. I'm leveraging driver.ExecuteScript() to run custom js on the webdriver. It looks a bit like this:
function elementFound(elem) {
var nodeType = navigator.appName == ""Microsoft Internet
Explorer"" ? document.ELEMENT_NODE : Node.ELEMENT_NODE;
if(elem.nodeType == nodeType)
{
/* Element identification logic here */
}
else { return false; }
}
function traverseElement(elem) {
if (elementFound(elem) == true) {
return elem;
}
else {
for (var i = 0; i < elem.childNodes.length; i++) {
var ret = traverseElement(elem.childNodes[i]);
if(ret != null) { return ret; }
}
}
}
return traverseElement(document);