Tuesday 3 March 2015

My Python Notes: Decorators

Python is a hybrid programming language it support both object oriented programming as well as functional programming.

Like everything else in python function are also objects.

Functions and nested functions
















In the above example dir() is used to display the objects.
                   
Lets Look at a simple function
                                                basicFunction1.py

Lets run it
Since function are object they can be assigned to variables.
  
                                       basicFunction2.py

In basicFunction2.py 
At step #1 we assign the variable fun with the function label funIn.

step #2 we call function funIn by adding () -- parentheses to the variable fun.

Now let  us consider a function within a function ie.. nested functions.


Moving on to a function which returns a function.

                                              nestedBasics1.py
The the above code has two function funOut()-- outer function & funIn() -- inner function.

At step #1 the funOut() return label of the inner function label

step #2 the variable funCall has the inner function label.

step #3 now the inner function can be called by just adding () -- parentheses to the funCall variable.

Lets us now consider a variation of  nestedBasics1.py 


                                     nestedBasics2.py[closures]


In the above code 

At step #1 we declare variable name.Function funIn() store this value.

 step #2 the funOut() return label of the inner function label


step #3 the variable funCall has the inner function label.

step #4 now the inner function can be called by just adding () -- parentheses to the funCall variable.
When the inner function is being called it is able to display the value of name, since funIn() was able to store name value at Runtime (as mentioned in step #1).


Now lets us make nestedBasics2.py more dynamic 


Advantage of Nested functions

Lets us examine nestedBasics2.py 
At step #1 we are creating a new object of the function funOut()

step #2 we are creating another object of the function funOut()

Now lets us consider the class version of nestedBasics2.py.

                                    funClass.py

In the above code funClass.py,
At step #1  we need define an initializer  method __init__() 
step #2 we need a regular  method to act on the class attribute name.
step #3 we are creating a object of class funOut
step #4 now in order to access regular method we are using .dot operator

If we are writing a class with one regular method, it better to used nested functions.

Function which takes another function


In the above code we have two functions avg() & cal()
cal() --takes a function as one of the input parameters.

*args , **kwargs

A function can have positional arguments which are also know as named and mandatory, the second type of arguments are default which are optional and are also know as keyword arguments.

Positional arguments

 
In the above code , the function man() take two argument name & age ie positional arguments..
At step #1 we interchange two argument but get the same results(named argument)
step #2 we pass one argument and we get an error message(mandatory argument)

Default(Keyword) arguments

In the above code the function we have has two default arguments
At step #3 when we don't pass any argument the function consider the default values

Output 

*args--takes an unlimited number of positional arguments.It prevent the program from crashing,and is used when we don't know the number of input arguments.


*kwargs-- takes an unlimited number of keyword arguments, and store the data in a dictionary.

*args and *kwargs


Decorators 

Function without arguments.

Till now we have seen that function are object and few example on nested functions.
Lets us now move on to decorators.

                                          decoratorsbasic1.py


In the above example decoratorsbasic1.py we have two function at runtime ie  wrapper() & name()

wrapper() does three things.
1) It take a function as parameter(myFunc)
2)wrapper has an inner function which calls the passed function(myFunc), and store it in variable(y).
3)Finally wrapper return the inner function label(innerFunc)

At step #1 in decoratorsbasic1.py 
The innerFunc label is assigned to name and this in turn when executed
 changes the return value of the function name().

A slight modification to decoratorsbasic1.py  would be done by adding decorator symbol(@)
with the wrapper function label just above the name function.



Lets us consider another example

Function with arguments


In the above code we have are applying a decorators which checks ,that both the input parameter are non-zero and +ve.

Now lets us consider a decorator which can handle any number of positional & keyword arguments.

Let us write a decorators which can only read data passed to the function,but not executed the decorated function itself.

There are two function at runtime ie wrapper() , man().

wrapper does two things
 At step #1 the inner function is designed to handle any function signature.
step #2 innerWrap is able to access the argument of the decorated function man()
but it does not executed the contents of man() function.


Now lets access the parameter passed to the function as well execute the function itself.



At step #1 we are able to access the contents of passed arguments.
step #2 two things happen one, is that we execute the function to be wrapped man()
and the other is that we modify the return value of wrapped function man().

CLASS-DECORATOR

Till Now we have seen decorators which are built using function ,lets try using CLASSES






























In the above code foo1() & foo2() are passed as object to class myDecorator.
Now in myDecorator we have defined a __call__() method which gets called each time,
the decorated function gets called.




















addOne class adds one to the return value of the decorated function foo()


Friday 23 January 2015

Handling Web Alerts

Web Alert are used to confirm the action taken by the user.
It take the focus away from the current window , and force the user to read the alert message.

Generally Web alerts consist of  message and  an OK, CANCEL button.

How does Selenium WebDriver handle Web Alert ??

In selenium WebDriver when an alert appears in the web-page ,
the control is still in the web-page hence we have to switch the control from
the web-page to alert window.

For accessing the Web Alert , we first have to create an alert object.

alert = browser.switch_to_alert()

Now we have control over the alert.
To perform action on the alert we need to know about alert class.

What is a Alert Class??

With the help of  Alert Class we can interact with alerts.
With this class we can
                              accept the alert using accept()----method
                              reject the alert using dismiss()-----method
     enter value in the alert box using send_keys()-----method
       receive the text found in the alert using ".text"


Simple Alert  Button

Lets handle a simple alert.In order to generate alert please copy the below html code,
and save it in ex1.html .



Navigate to folder where the file is saved and double click it.


The browser open with



Now before we write test scripts lets write test cases.

                                      test_ex1.html

Output in window's command prompt


Alert with OK & CANCEL Buttons

Save the below code in ex2.html


When we open ex2.html in a browser we get



The Test Cases for ex2.html are


test_ex2_v1.py



Lets us run test_ex2_v1.py in command line.


Structure of test_ex2_v1.py ,it has  two class namely  ConfirmationTestCase & ConfirmationTest




Now let us put the ConfirmationTestCase class in a file called ex2Base.py



Let us retain  ConfirmationTest and save the file as ex2Test.py



lets us run ex2Test.py from window command line.










Dialogue Box




















Please copy the below code for generating a dialogue box as show above.



Now lets write the test cases












test_ex3.py



Now lets execute test_ex3.html from window command line,










Thursday 15 January 2015

My Python Notes:class ToolKit & unittest Framework

What is a class ?

Class is way to represent Object found in the Real World.
The way we define a function using the keyword def ,class can be created using the keyword class.
So Lets create a class which describes the behavior of a human being using a Human class. 

Syntax   
class Human(object):


Class allow us to logical group data & functions and the data is know as attributes,functions is referred to as  methods.

As humans  we  have a name & age these are attributes.

Now let create a class Human with name & age.To represent the behavior of the Human we have defined two method eat() & my_stomach().
       
human.py
                      

With human.py we have create a human class ie... we have a blueprint for Humans


Function within a class are known as methods
Now lets create a who Human whose name is Jude Augustine,age 24 from the Human class ie... we are creating an object whose name is Jude Augustine & age 24

                                              object.py


lets run object.py


What have we done we have create a new object from the Human class

Note:
__init__()--- is used to assign value to the object ie..initialize the attributes.
The INIT method doesn't have a return statement, but it return the object that was created.

__str__()--- it return information about the object.

Lets us talk  to Jude why is he so sad.


Let write code it and save it in conversation1.py

Lets make Jude Happy....


Lets write the code for the above and save in conversation2.py





Creating Multiple Objects from Human Class

 Create James & John whose ages are 21 &22 have a sister whose name is Lisa who is 18 year Old,lets
create them using the Human Class.

                                              family.py
                                       
                                 save the above code in family.py & run it
#1 in family.py we are importing the Human class from the file human.py

#2 we create a brother_james with name james & age 21.

#3 we create a brother_john which is an object of class Human with name John & is 22 years old.

Creating multiple objects using List-Comprehension

                                       

from the above code we notice that humans[0] ----> James,24
                                                         humans[1] ----> John,22
                                                         humans[2] ----> Lisa,18

Now lets test  human.py using Unittest module



Lets now write the code for the above test cases.
 
                                    testHuman.py

 Now lets run  it testHuman.py




Now lets write some negative test cases


lets write the code & save it in negative.py

TookKIT
                  Human Class with few TookkIT elements.



 

1)Instance Variables are defined within the __init__ ()--method.

Information about Instance variable may vary as we can see from the multiple objects code.
Eg for Human class , name & age are instance variables.

2)Regular methods----function within a class are know are methods
Eg---- __init__(), __str__() ,eat() , my_stomach() are all methods

all the above method use self ,ie method using self are a parameter are known as Regular Methods.

3)Class Variables--- as human being we all have a heart & every being has One Heart.
   Eg-- heart = 1

4)Static Methods-- method that dont need self as a paramter, because they dont modify the Instance variables.They are helper function which can be used by other Regular Method.
They are added to class using decorators.

Eg   @staticmethod
        def heart_sound():
               print("lup--dup--lup---dup")

How does you heartBeat

the code for the above scenario 
heart.py


Run it