Sunday, March 4, 2018

Selenium IDe : All about Selenium IDe

All about Selenium IDe


Note : You can directly use xpaths in the IDE 
example :



About :
  1. Ide is best use to perform disposable fast and small repeataitve tasks .
  2. So basically we know Java Selenium does not come with record option like other automation tools so when you can use IDe to record steps and later export to Java / Python - TestNg/ Junit . And change the element locators value to required and use it in your code.
Note : You use below links to grab your  locator values :
http://catchbug.blogspot.in/2013/11/selenium-ide-tips-and-crash-refs.html
http://catchbug.blogspot.in/2016/03/selenium-how-to-create-xpath.html
http://catchbug.blogspot.in/2015/09/selenium-using-firefox-inbuilt.html




Common Commands

Command
Number of Parameters
Description
open
0 - 2
Opens a page using a URL.
click/clickAndWait
1
Clicks on a specified element.
type/typeKeys
2
Types a sequence of characters.
verifyTitle/assertTitle
1
Compares the actual page title with an expected value.
verifyTextPresent
1
Checks if a certain text is found within the page.
verifyElementPresent
1
Checks the presence of a certain element.
verifyTable
2
Compares the contents of a table with expected values.
waitForPageToLoad
1
Pauses execution until the page is loaded completely.
waitForElementPresent
1
Pauses execution until the specified element becomes present.

Find by text value
css=tag:contains("inner text")
css=button:contains("Create Product")

Syntax for Locator Usage
Method
Target Syntax
Example
By ID
id= id_of_the_element
id=email
By Name
name=name_of_the_element
name=userName
By Name Using Filters
name=name_of_the_element filter=value_of_filter
name=tripType value=oneway
By Link Text
link=link_text
link=REGISTER
Tag and ID
css=tag#id
css=input#email
Tag and Class
css=tag.class
css=input.inputtext
Tag and Attribute
css=tag[attribute=value]
css=input[name=lastName]
Tag, Class, and Attribute
css=tag.class[attribute=value]
css=input.inputtext[tabindex=1]
DOM
>getElementById
>getElementsByName
>dom:name
(applies only to elements within a named form)
>dom:index

document.forms[index of the form].elements[index of the element]

document.getElementsByName("name")[index]
document.forms[0].elements[”phone”]



Add loop in selenium IDE :
  1. Download this js file: https://github.com/darrenderidder/sideflow/blob/master/sideflow.js
  2. Launch Selenium IDE from Firefox and open the options menu.
  3. Upload the .js file to the "Selenium Core extensions (user-extensions.js)" field.
  4. Restart IDE 
  5. Make sure u modify and add below commands depending on your requirement
New Test
Command
Target
Value
open
http://docs.seleniumhq.org/

setSpeed
1000

store
1
MyVar
while
storedVars.MyVar <= 3

echo
${MyVar}

highlight
css=img[alt="Selenium Logo"]

store
javascript{storedVars.MyVar++;}

endWhile





 Ref :
https://www.guru99.com/introduction-selenuim-ide.html

https://stackoverflow.com/questions/11033321/how-to-loop-tests-in-selenium-ide
https://www.guru99.com/first-selenium-test-script.html 


Saturday, February 24, 2018

Linux : Access Linux machine using Android

To Connect linux (debian) with Android

1. Linux - sudo apt-get install openssh-client  (remember if u want to access a system then should run client server)
2. Linux - sudo service ssh start
3. Linux -sudo service ssh status
4. Find ip address of the using - sudo ifconfig
(find ip address - usually eth0 in 1st para , for rasp pi search for something like 192.168.1.34 or something like that)
5. Now in Linux
addnew user : sudo useradd -m deepak -G sudo
add password : sudo passwd fred

6. In Android install termux app
7. Open termux  run command - apt install openssh

8. optional(https://linuxconfig.org/ssh-into-linux-your-computer-from-android-with-termux
ssh-keygen -b 4096 -t rsa
ssh-copy-id -i ~/.ssh/id_rsa.pub username@192.168.1.1 )

9. ssh deepak@raspberry_ip
ex:ssh deepak"192.168.1.34

Correct way to install tar ball in Linux

Correct way to install tar ball in Linux :

Example : User installing rar application in Linux machine


method 1 :
sudo apt-get install rar
or
sudo yum install unrar

Method 2:
cd /tmp
wget https://www.rarlab.com/rar/rarlinux-5.5.0.tar.gz
tar -zxvf rarlinux-*.tar.gz
./unrar
sudo cp rar unrar /usr/local/bin

--------Clean UP-------
sudo apt-get autoclean
sudo apt-get clean
sudo apt-get autoremove
--------------------------

Wednesday, January 24, 2018

Python : Copy entire node along with subnodes in XML

Python : Copy entire node along with sub nodes in XML



from xml.etree import ElementTree 
from xml.etree.ElementTree import Element, SubElement, Comment, tostring 
import copy

xml = """<a>
           <b>
            <c>
                <d>India</d>
            </c>
             <c>
                <d>USA</d>
            </c>
              <c>
                <d>China</d>
            </c>
   </b>
 </a>"""

#---------------------
def xml_node_grabber(xml , node_name):
    result=[]
    xml_tree = ElementTree.fromstring(xml)

    for i in xml_tree.findall(".//"+node_name):
        dupe = copy.deepcopy(i) #copy <c> node
        result.append(dupe) #insert the new node
    
    iterator_res=iter(result)
    return (iterator_res)
#------------------------

res=xml_node_grabber(xml, "c")
for i in res:
    print(ElementTree.tostring(i))



Result:

b'<c>\n                <d>India</d>\n            </c>\n             '
b'<c>\n                <d>USA</d>\n            </c>\n              '
b'<c>\n                <d>China</d>\n            </c>\n  

Tuesday, January 16, 2018

Python : Call function using string (similar to Java Reflection API )

Python : Call function using string (similar to Java Reflection API )


# Calling
class animals:
    def dog(self):
        print("bark")
       
    def lion(self):
        print("roar")


obj=getattr(animals(),'dog')
obj()

result :
bark

Thursday, December 28, 2017

html / javascript : Make elements visible / hidden on drop down values

 Make elements visible / hidden on drop down values


<html>
Display Element
<select id="display" name="form_select" onchange="showDiv()">
   <option value="no">No</option>
   <option value="yes">Yes</option>
</select>
<div id="hidden_div" style="display:none;">Hello hidden content</div>

<script type="text/javascript">
    function showDiv()
    {
       if(document.getElementById('display').value=="yes")
        document.getElementById('hidden_div').style.display = "block";
        else
        document.getElementById('hidden_div').style.display = "none";
    }
</script>
</html>

Wednesday, December 27, 2017

Python : Flask accept data from user (POST)

Flask Accept data from user

Pre - Req :

1. Make sure u have installed Flask module , Requests module 
2. Currently using Liclipse as python IDE

Example 1 :
To accept data from user ( post request ) and display result in same page

----------------------Paste below code inside Your_Project/templates/vote.html------------------------------
<html>
   <body>
        <form action=""  method = "POST">
            <p>Enter Name : <input name="name" type="text" /></p>
            <p>Enter Age :<input name="age" type="text" />&nbsp;</p>
            <! note : button should always be type ="submit">
            <p><input name="OK" type="submit" value="submit" /></p>
        </form>

        {% if name %}
            <p><strong>{{name}} is {{eligible}} to vote</span></strong></p>
        {% endif %}

   </body>
</html>
--------------------------------------------------------------------------------------------------------

from flask import request,Flask,json,render_template
from flask.json import jsonify
app = Flask(__name__)

@app.route('/')
def vote():
    return render_template('vote.html')

@app.route('/',methods=['POST'])
def vote1():
    result1 = request.form
#input fields values are stored as dictionary  and key = input name given in html

    if (int(result1['age'])>=18):
        eligible="is eligible"
    else:
        eligible="is not eligible"
    return render_template("vote.html",name=result1['name'],eligible=eligible)

if __name__ == "__main__":

    app.run(host='0.0.0.0', port=1111 , debug=True)#http://localhost:1111/"

Steps :
1. Run the above code
2. Open browser
3. Open http://localhost:1111/  or http://your_sytem_name:1111

Example 2 :
To accept data from user ( post request ) and display result in different page

----------------------Paste below code inside Your_Project/templates/vote2.html-----------------------------
<html>
   <body>
        <form action="http://den01bro.us.oracle.com:1111/result"  method = "POST">
            <p>Enter Name : <input name="name" type="text" /></p>
            <p>Enter Age :<input name="age" type="text" />&nbsp;</p>
            <! note : button should always be type ="submit">
            <p><input name="OK" type="submit" value="submit" /></p>
        </form>
   </body>
</html>
-------------------------------------------------------------------------------------------------------------------------
from flask import request,Flask,json,render_template
from flask.json import jsonify
app = Flask(__name__)

@app.route('/<string:name>')
def temp(name):
    return render_template('vote2.html')

@app.route('/result' ,methods=['POST'])
def temp2():
    result1 = request.form
    if (int(result1['age'])>=18):
        eligible="is eligible"
    else:
        eligible="is not eligible"
    return (result1['name']+" "+eligible)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=1111 , debug=True)#http://localhost:8000/"

Steps :
1. Run the above code

2. Open browser
3. Open http://localhost:1111/any_string  or http://your_sytem_name:1111/any_string_here


Example 3:
Adding example 1 + example 2 , ie., 

scenario 1 : If user opens http://localhost:1111/  , User will get result in the same page.
scenario 2 : If user opens http://localehost:1111/any_string , User will get result in different page .

----------------------Paste below code inside Your_Project/templates/vote.html------------------------------
<html>
   <body>
        <form action=""  method = "POST">
            <p>Enter Name : <input name="name" type="text" /></p>
            <p>Enter Age :<input name="age" type="text" />&nbsp;</p>
            <! note : button should always be type ="submit">
            <p><input name="OK" type="submit" value="submit" /></p>
        </form>

        {% if name %}
            <p><strong>{{name}} is {{eligible}} to vote</span></strong></p>
        {% endif %}

   </body>
</html>
----------------------Paste below code inside Your_Project/templates/vote2.html-----------------------------
<html>
   <body>
        <form action="http://den01bro.us.oracle.com:1111/result"  method = "POST">
            <p>Enter Name : <input name="name" type="text" /></p>
            <p>Enter Age :<input name="age" type="text" />&nbsp;</p>
            <! note : button should always be type ="submit">
            <p><input name="OK" type="submit" value="submit" /></p>
        </form>
   </body>
</html>
-------------------------------------------------------------------------------------------------------------------------
from flask import request,Flask,json,render_template
from flask.json import jsonify
app = Flask(__name__)

@app.route('/')
def vote():
    return render_template('vote.html')

@app.route('/',methods=['POST'])
def vote1():
    result1 = request.form
    if (int(result1['age'])>=18):
        eligible="is eligible"
    else:
        eligible="is not eligible"
    return render_template("vote.html",name=result1['name'],eligible=eligible)

@app.route('/<string:name>')
def temp(name):
    return render_template('vote2.html')

@app.route('/result' ,methods=['POST'])
def temp2():
    result1 = request.form
    if (int(result1['age'])>=18):
        eligible="is eligible"
    else:
        eligible="is not eligible"
    return (result1['name']+" "+eligible)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=1111 , debug=True)


Example 4:
Accept 2 input from a html file and display same value into another html .

----------------------Paste below code inside Your_Project/templates/input_data.html--------------------
<form action="{{ url_for('submit') }}" method="post">
    <textarea name="text"></textarea>
<textarea name="text2"></textarea>
    <input type="submit">
</form>
----------------------Paste code in Your_Project/templates/output_2data.html--------------------
<p>text1&nbsp;<input name="text1" type="text" value={{text1}}/></p>
<p>text2&nbsp;<input name="text2" type="text" value={{text2}}/></p>
----------------------input_data2.py----------------------
from flask import Flask, request, render_template

app = Flask(__name__)
@app.route('/')
def index():
    return render_template('input_data.html')

@app.route('/submit', methods=['POST'])
def submit():
    data=request.form
    data1=data['text']
    data2=data['text2']
    return render_template("output_2data.html",text1=data1,text2=data2)
    #return 'You entered: {}'.format(request.form['text'])

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8003)
-------------------------------------------------------------------------------------------------------------------------

Monday, December 11, 2017

python : Flask Basic

Flask (Python WebFramework )

Pre Req :
1. make sure python is installed in your system
2. pip install flask in terminal or cmd line.(python package installer)
Note:
1.         Default method =GET (if not mentioned)
2.         Use ARC , Postman etc., to make post statements
3.         “submit” button in html triggers post.

Use host="0.0.0.0" and port forward when using with docker
Example #app.run(host='0.0.0.0', port="5432",debug=True)
https://medium.com/@umerfarooq_26378/web-services-in-python-ef81a9067aaf


Html Template :

from flask import request,Flask,json,render_template

app = Flask(__name__)


@app.route(“/resource”)

Def xxx(resource)

                        ….

                        …..

if __name__ == "__main__":

    app.run(host='0.0.0.0', port=1234 , Debug=true)

Passing Args

#http://localhost:1234/hello?name=Luis

@app.route('/hello')

def api_hello():

    if 'name' in request.args:

        return 'data: ' + request.args['name']

    else:

        return 'Data: no data'

Any Resource

'''http://localhost:1234/any_string

@app.route("/<string:name>/")

def string_var(name):

    return "string_variable: "+name


Any Resource displaying html

#http://localhost:1234/random_string

#make sure “templates” folder is created insede project with image.html

@app.route("/<string:name>/") #<int:value>

def hello(name):

    return render_template('image2.html', name=name)

All Methods

''' GET/POST/PATCH/PUT/DELETE

   http://localhost:1234/verb ‘’’

@app.route('/verb', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])

def api_echo():

    if request.method == 'GET':

        return "verb: GET\n"

    elif request.method == 'POST':

        return "verb: POST\n"

    elif request.method == 'PATCH':

        return "verb: PACTH\n"

    elif request.method == 'PUT':

        return "verb: PUT\n"

    elif request.method == 'DELETE':

        return "verb: DELETE"


POST with body in REST

'''example

POST   http://localhost:1234/messages

H "Content-type: application/json"

-body '{"message":"Hello Data"}'

'''

@app.route('/messages', methods = ['POST'])

def api_message():

    if request.headers['Content-Type'] == 'text/plain':

        return "Text Message: " + str(request.data)

    elif request.headers['Content-Type'] == 'application/json':

        return "JSON Message: " + json.dumps(request.json)

    else:

        return "returns raw data:"+request.get_data()


POST accept from Html and send to html

Note:

1.         submit button in html to trigger POST

2.         Save html code in Project/templates/name.html

3.         Use Javascript inside html to manipulate data.

4.         Data is received to flask as dictionary

5.         Python data accessed in html as “{{}}”

6.         “url_for” used instead of “http://localhost:8003/submit”

input_data.html

<form action="{{ url_for('submit') }}" method="post">

    <textarea name="text"></textarea>

 <textarea name="text2"></textarea>

    <input type="submit">

</form>

output_2data.html

<p>text1&nbsp;<input name="text1" type="text" value={{text1}}/></p>

<p>text2&nbsp;<input name="text2" type="text" value={{text2}}/></p>

input_data2.py

from flask import Flask, request, render_template


app = Flask(__name__)

@app.route('/')

def index():

    return render_template('input_data.html')


@app.route('/submit', methods=['POST'])

def submit():

    data=request.form

    data1=data['text']

    data2=data['text2']

    return render_template("output_2data.html",text1=data1,text2=data2)

    #return 'You entered: {}'.format(request.form['text'])


if __name__ == "__main__":

    app.run(host='0.0.0.0', port=8003)


 Error handle

@app.errorhandler(404)

def not_found(error=None):

    message = {  'status': 404,  'message': 'Not Found: ' + request.url}

    resp = jsonify(message)

    resp.status_code = 404

    return resp