I'am experimenting with selenium IDE and i came across a problem with asserting an approximate value. I need to check a value inside an element with an id. It is numeric value with comma (",") as a separator.
Problem is that i need to check if the numeric value is valid with a tolerance of 0.01.
For example:
<div id="uniqueId">2,54</div>
assertText - value = 2.53
I need above example to pass the test, and also pass if the value in div si 2,52 or 2,53. I understand that i can use assertEval to insert javascript, but i'm not very good in javascript and also from what i've read the javascript capabilities of selenium are limited.
Any help would be greatly appreciated!
Using assertEval is a good idea. The javascript you will need will be something like
var numberStr = "${actualText}".replace(",", ".");
var number = parseFloat(numberStr);
var difference = Math.abs(eval(number-${expectedValue}));
(difference <= 0.01)?true:false;
I don't know much javascript but according to this thread we need to first replace decimal mark from ',' to '.' (1st line) so we can later convert the string found on page to number (2nd line).
${actualText} is a variable in which we store the actual value taken from page while the ${expectedValue} is a value you need to define on your own. Note that tolerance (0.01) is "hardcoded", you may want to replace it with variable too.
Now to make it shorter (and less readable):
(Math.abs(eval(parseFloat("${actualText}".replace(",", "."))-${expectedValue}))<=0.01)?true:false
Having the javascript we can prepare Selenium script:
storeText | id=uniqueId | actualText
store | 2.53 | expectedValue
assertEval | JS LINE FORM ABOVE GOES HERE | true
Related
I cant use send_Keys() method to input values in the current website im working on.
So im trying to use javascript to input values.
i tried click() and clear() together with send_keys() before i decided to use javascript but to my disappointment, it didnt work.
i use the javascript code to input value below
driver.execute_script("document.getElementById('CustCd').setAttribute('value', 'J590')")
and it worked.
But currently my code is inside a loop and the value changes, how can i replace J590 with a variable that gets the value?
Here is the code that i tried
ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
driver.execute_script("document.getElementById('CCRNo').value=ccr_No")
I know its wrong, any help would be appreciated. My Javascript is weak.
Just some side note if anybody would be able to solve my send_keys() error.
The function only takes in the first character that i send. For example, send_keys("J590") gives J, send_keys("J590-TE21") gives J-
First, the correct way to set the current value of an input is to assign to the value property. There is no attribute for the inputs current value (the value attribute is the input's default value, more here).
The rest is a special case of a general-purpose question: "How do I output a Python variable's value into JavaScript code?"
If the string you're outputting doesn't contain quotes or backslashes, you may get away with using a format string and outputting the value in quotes as Guy shows. (JavaScript has two kinds of quotes, ' and "; you only need to escape the kind you use around the value.) Those kinds of assumptions tend to break down, though; as soon as the string is Hi, I'm Joe that approach breaks.
In the general case, to ensure proper escaping and that all values are written correctly, you can use JSON:
import json
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').value = {json.dumps(value)};")
That outputs:
document.getElementById('CustCd').value = "J590";
Live Example
That way, you don't have to worry about quoting and escaping, it's all handled for you since valid JSON is valid JavaScript (thanks to a recent JavaScript specification fix; prior to that there was an edge case incompatibility that people almost never ran into).
It's also useful for numbers, or more complex things you might want to pass to hte JavaScript code. For instance:
import json
class Example:
foo = ""
bar = 0
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
value = Example("I'm a string with \"quotes\" in it.", 42)
print(f"const obj = {json.dumps(value.__dict__)};")
num = 42
print(f"const num = {json.dumps(num)};")
That outputs:
const obj = {"foo": "I'm a string with \"quotes\" in it.", "bar": 42};
const num = 42;
obj ends up being an object, because the initializer is a valid JavaScript object literal containing the data from the Example object. Similarly, num is a valid JavaScript number.
Live Example
You need to insert the variable as variable, not literal
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').setAttribute('value', '{value}')")
Using Javascript to input the values of a variable you can use the following solution:
ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
# ccr_No = J590
driver.execute_script("document.getElementById('CCRNo').value='" + ccr_No + "';")
An example, to input the values of a variable within Search Box of Google Home Page:
Code Block:
driver.get("https://www.google.com/")
value = 'J590'
driver.execute_script("document.getElementsByName('q')[0].value='" + value + "';")
Browser Snapshot:
You can find a relevant discussion in Selenium : How to send variable character strings through executeScript()
Ho to evaluate a scientifc expression (x+3x-4+sin x) by passing different values x to find the output
Please let me know the inbuilt function that can be used in java
Well I am not going give the whole code to you, but here are some hints:
The best way to eval an expression without any external API would be using running the expression as a javascript code and get the result.
Since you just can't do sin(0) + 6 in javascript, you will have to use RegEx to replace all function name to Math.(function name here) without affecting other function name. Such as sin(0) + asin(0)will be replaced to Math.sin(0) + Math.asin(0).
The changing value of x is very simple, just use RegEx to replace the x to a value without affecting other stuff, like x + exp(1) will be turned to 0 + Math.exp(1)
User can run javascript code with your calculator if using javascript, please be careful not to allow users to do so.
Similar question have been asked before, you might want to take a look about it: Evaluating a math expression given in string form
You’re looking for the sin method present in the Math library.
An example:
Math.sin(25); // Returns ‘sin’ of the value ‘25’
When doing this:
casperjs somescript.js --number=736280854938322517687376855643288785
and in the code:
var casper = require('casper').create();
var value = casper.cli.get("number");
console.log(value); // yields: 7.3628085493832246e+35
// want: 736280854938322517687376855643288785
I've looked and looked, pondered and hacked, but I'm not having much luck. The easy solution seems to be simply converting the number into a string. Or passing the number in as a string. But the syntax for this eludes me.
See Raw parameter values:
By default, the cli object will process every passed argument & cast them to the appropriate detected type[...]
You need to use casper.cli.raw.get("number") to get a non-parsed value. Since integer values that are bigger than 253 cannot be represented as an integer without losing precision, you would need to work with them as a string or use some big integer library (such as JSBN).
I am trying to do a simple thing but for some reason it is not working. I am using Knockout and I have a model which I update after user enter some data and use the same to communicate back to C# code on server side. For some reason, when I try to assign decimal value to one of the member of model it isn't working. Though, in this case I am using knockout, I believe it has nothing to do with KO. See the screenshot where I have the value 22.78 and I am trying to do parseFloat but it ends up as just 22. I tried other things such as removing he parseFloat just to see if it accepts the string value as it is but even that is not working. Can someone help?
Your doing Bitwise OR while assigning the value.
this.AMOUNT_RECEIVED = parseFloat(data.AMOUNT_RECEIVED) | 0;
so only it returns 22. Because 22.78 | 0 is 22.
Please check this code.
console.log(22.78 | 0);
Please try this code while assigning value. You can get decimal values without loss.
this.AMOUNT_RECEIVED = parseFloat(data.AMOUNT_RECEIVED);
Pelase Check below link for more details.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR
try this (please notice the double || )
this.AMOUNT_RECEIVED = parseFloat(data.AMOUNT_RECEIVED) || 0;
I have an equation/formula stored in database and I want it to be triggered based on key up input event in a webpage.
Example formula: [55-57]
This is a simple minus operation, where the number actually represents the id of a row in database
I have looked at this solution which replaces numbers found in a string to new value. But I need the new value to be replaced with incremented letters such as a, b and so on. Also the leading and ending brackets [] need to be removed so that I can perform an eval later using JavaScript.
Later the equation will be convert to a-b. Variable a and b represent other HTML elements that holds a value. So whenever I key in something into text field, changes will reflect on other part of webpage. It's like auto computation.
Thank you for those helping this. Hope this question will help somebody.
Try something like this. If you need more help, you seriously need to re-word your question or post a jsfiddle, or something.
var eqn = '55-57'; // brackets removed. Remove them with a regex of /\[|\]/g if you need to
var result = eval( eqn.replace( /\w+/g, function( res ){
return +document.getElementById( res[1] );
} );
Basically this replaces 55 and 57 with the numerical values of #55 and #57. It would also work for #b, etc.
It then eval's the result, basically doing whatever math is in your equation.