Feb 26, 2014

Django Tutorial - Part I

Reference: 
Django Project / Django Book

Django web framework / Python web development with Django

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.
The tage line for Django is "The web framework for perfectionists with deadlines"
Django makes it easier to build Web apps more quickly and with less code, mainly used for web development


Main components of The Django framework


Object-relational mapper
Define your data models entirely in Python. You get a rich, dynamic database-access API for free, but you can still write SQL if required.
If your web application is data extensive, better write your SQL instead of object-relational mapper

Automatic admin interface
It comes with Admin interface, you need to enable it in the web framework
There by saving extra effort in creating the admin interface from the scratch

Elegant URL design
Very Flexible URL design using loose coupling
URL definitions and the view functions they call are loosely coupled; that is, the decision of what the URL should be for a given function, and the implementation of the function itself, reside in two separate places. This lets you switch out one piece without affecting the other.
Map the URLs and view methods, if you want to change the URL pattern later, you can do it very easily by changing urls.py
It makes use of regular expression for mapping the URL patterns
It generates dynamic URLs as well

Template system
Use Django's powerful, extensible and designer-friendly template language to separate design, content and Python code.

Cache system
Hook into memcached or other cache frameworks for super performance — caching is as granular as you need.

Internationalization
Django has full support for multi-language applications, letting you specify translation strings and providing hooks for language-specific functionality.


How to Install Django

Download Django (https://www.djangoproject.com/download/) and unzip

django-admin.py should be on your system path if you installed Django via its setup.py utility.
on Windows, you need to update your PATH environment variable.

python setup.py install
python -c 'import sys, pprint; pprint.pprint(sys.path)' #this locate site-packages direcotry

How to check Django Installed

>>> import django
>>> django.VERSION
(1, 4, 2, 'final', 0)

How to create a project

django-admin.py startproject <proj_name>
E.g., django-admin.py startproject mysite

Django Project Structure

The startproject command creates a directory containing five files:
mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

How to access Django from shell

python manage.py shell

Django Development Server

Django comes with its own development server

Difference between Django Development Server Vs Web Development Server like Apache is as mentioned below :

Advantage:
Comes as part of Django itself
You can develop your site rapidly without having to deal with configuring your production server (e.g., Apache) until you are ready for production
Django Development server watches your code and automatically reloads it. making it easy for you to change code without restarting server

Disadvantage:
Not suitable for production environment
You have to deploy your code to Apache when moving to production

Django Development Server suitable in development environment
Apache web development server suitable in production environment

How to start Django Development Server

Django develeopment server works on default port 8000
python manage.py runserver 8000

How to test home page on Web Page

Using Django Development Server
http://127.0.0.1:8000/

Using Apache Server (If you configure Apache)
http://127.0.0.1/mysite/

How to configure Apache with Django

In Apache httpd.conf
WSGScriptAlias /mysite "C:/django_workspace/mysite/mysite/wsgi.py"


Thanks for reading this article. I will discuss more examples in the coming sessions, stay tuned :-)


Feb 24, 2014

UIAutomator Tutorial - Part II

In continuation to earlier post on UIAutomator Introduction / UIAutomator Basics lets discuss more UIAutomator Android with few examples

Reference: UIAutomator Documentation / Android Developer Docs

UIAutomator API in brief

It provides six different classes, these classes with interfaces and exceptions allows to capture and manipulate UI components on Android Device.

Following are the classes :
   UiDevice
   UiObject
   UiScrollable
   UiSelector
   UiCollection
   UiConfigurator

UiDevice
  Provides access to state information about the device. We can  also use this class to simulate user actions on the device, such  as pressing the d-pad hardware button or pressing the Home and Menu buttons.
UiObject
 Represents a user interface (UI) element.
UiScrollable
 Provides support for searching for items in a scrollable UI .
UiSelector
 Represents a query for one or more target UI elements on a device screen.
UiCollection
  Used to enumerate  screen elements for the purpose of counting, or targeting a sub elements by a child's text or description.
UiConfigurator
  Allows  to set key parameters for running uiautomator tests

We need to import following classes
import android.widget.LinearLayout;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
import com.android.uiautomator.core.UiDevice;

UiObject/UISelector

Click on Text
new UiObject(new UiSelector().text(text)).click();

Click on Button
We need to use Button Class name for this
new UiObject(new UiSelector().text(btnText).className("android.widget.Button")).click();

Long Click
new UiObject(new UiSelector().text(text)).longClick();

Press Back
getUiDevice().pressBack();

Go Back to Home
getUiDevice().pressHome();

Click and Wait
new UiObject(new UiSelector().description(text)).clickAndWaitForNewWindow();

Check if text exists
new UiObject(new UiSelector().text(value)).exists();

Wait until 
new UiObject(new UiSelector().className(android.widget.ProgressBar.class.getName())).waitUntilGone(1000);


UIDevice

Example : Swipe Down Notification

import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObjectNotFoundException;

public static void swipeDownNotificationBar() throws UiObjectNotFoundException {
UiDevice deviceInstance = UiDevice.getInstance();
int dHeight = deviceInstance.getDisplayHeight();
int dWidth = deviceInstance.getDisplayWidth();
int xScrollPosition = dWidth / 2;
int yScrollStop = dHeight / 2;
UiDevice.getInstance().swipe(xScrollPosition, 0, xScrollPosition, yScrollStop, 100);
}

UiScrollable

Example: 
1) Scroll and Click event

import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiScrollable;

new UiScrollable(new UiSelector().scrollable(false))
.scrollIntoView(new UiSelector().text(text));
new UiObject(new UiSelector().text(text)).click();

2) Scroll Back
new UiScrollable(new UiSelector().scrollable(true)).scrollBackward();

How to create a project in Eclipse

Create a Java project in Eclipse
After Creating Java Project, add external jar files which are android.jar and uiautomator.jar
android.and uiautomator.jar are present in
“D:\adt-bundle-windows-x86\adt-bundle-windows\sdk\platforms\android-4.2”

Create Java File

Create Test.java in project / eclipse work space, say it is in D:\UIAutomator

public void clickText(String text) throws UiObjectNotFoundException {
    new UiObject(new UiSelector().text(text)).click();
}

How to build UIAutomator project

You need Apache Ant software for building Java project

Syntax:
android create uitest-project -n "project-name" -t 1 -p "project-location"

"-t" referes to Android target (in case of different versions of Android are present, you can define which target to build this JAR)

E.g.,
cd D:\UIAutomator
D:
android create uitest-project -n UIAutomatorTest -t 1 -p D:\UIAutomator
ant build
cd bin
adb push UIAutomatorTest.jar /data/local/tmp
cd ..

The above commands create a JAR file in the bin folder
Then push the JAR file to /data/local/tmp folder of Android phone

How to call UIAutomator methods from Adb Shell

Go to command line and execute the below command

adb shell uiautomator runtest UIAutomatorTest.jar -c com.test.uiautomator.Test#clickText -e text "Phone"

Here Test refers to Test.java class
ClickText refers to the method inside Test.java
-e <Name> <Value> pairs for passing to test classes

If you haven't go through earlier post, Please go through


Feb 22, 2014

UIAutomator Tutorial - Part I


Reference: http://developer.android.com/tools/help/uiautomator


What is UIAutomator / UIAutomator Introduction


  • UIAutomator  is Introduced  by Google and it is available from Jellybean Versions of Android.
  • The UIAutomator is a testing framework provided by Google's Android 

Use of UIAutomator


  • To test Android Applications efficiently by creating automated functional UI test cases that can be run against applications on one or more devices.
  • Works on all the Android applications, including Google’s installed apps such as Settings, Contacts, Phone, etc.

Skills Required for working on UIAutomator


Core Java
Software: ANT, Android SDK, Eclipse

How UIAutomator works

  • Java project is created using android.jar and uiautomator.jar. 
  • uiautomator.jar provided by Android,  has in built methods which are used to perform UI actions  on Android device.
  • Create the Android test project based on your requirement; build a Jar file for the Java project is created and push the JAR file to /data/local/tmp location of Android device. 
  • Using adb shell, one can access the methods inside the Jar

How to build UIAutomator Project


cd D:\UIAutomator
D:
android create uitest-project -n UIAutomatorTest -t 1 -p D:\UIAutomator
ant build
cd bin
adb push UIAutomatorTest.jar /data/local/tmp


The above commands create a JAR file in the bin folder
Then push the JAR file to /data/local/tmp folder of Android phone


How to invoke a method in the JAR file

   adb shell uiautomator runtest UIAutomatorTest.jar -c com.test.uiautomator.Bluetooth#btPair


Debug UIAutomator


  • Using android DDMS tool (present in Eclipse), we can analyze properties of Android screen (Activity)
  • Using android DDMS tool, we can get the screenshot of the android screen and access the layout of the android screen, there implement the logic of what action we want to achieve

Advantages / Pros


  • Free ware, developed by Google, trust-able
  • Simple, uses class object OOPS methodology, less time to implement
  • Handling asynchronous events like Toasts,dialog and alerts occurring  during tests is easy. (JAR approach)

Disadvantages / Cons


  • Works only from Android version 4.1. 



UIAutomator API


  • It provides six different classes, these classes with interfaces and exceptions allows to capture and manipulate UI components on Android Device.

Following are the classes : 
   UiDevice 
   UiObject 
   UiScrollable 
   UiSelector 
   UiCollection 
   UiConfigurator 

UiDevice 

  Provides access to state information about the device. We can  also use this class to simulate user actions on the device, such  as pressing the d-pad hardware button or pressing the Home and Menu buttons. 

UiObject 

 Represents a user interface (UI) element. 

UiScrollable 

 Provides support for searching for items in a scrollable UI . 

UiSelector 

 Represents a query for one or more target UI elements on a device screen. 

UiCollection 

  Used to enumerate  screen elements for the purpose of counting, or targeting a sub elements by a child's text or description. 

UiConfigurator 

  Allows  to set key parameters for running uiautomator tests  



Thanks for reading. I will discuss more samples/examples on UIAutomator in detail in the next post

Feb 20, 2014

python serial

The following example illustrates python serial communication / python read serial port 

What you need to have
Connect the device you want to read the SERIAL logs to the system
To know the port is working, cross check by opening the port and check the logs in TeraTerm
If TeraTerm already using the port, you cannot read the logs from SERIAL port, so make sure before executing the script, stop the TeraTerm

What the script will do
We use python module 'serial'
Create a serial object by passing port, baudrate, bytesize, parity etc.,
To continuously read the logs, use Python Thread concept

from serial import *
from threading import Thread

text_received = ''

def receiveSerialDataFromPort(ser):
    global text_received
    read_buffer = ''

    while True:
        read_buffer += ser.read(ser.inWaiting())
        if '\n' in read_buffer:
            text_received, read_buffer = read_buffer.split('\n')[-2:]
            print text_received

if __name__ ==  '__main__':
    ser = Serial(
        port='COM23',
        baudrate=230400,
        bytesize=EIGHTBITS,
        parity=PARITY_NONE,
        stopbits=STOPBITS_ONE,
        interCharTimeout=None
    )
    
    Thread(target=receiveSerialDataFromPort, args=(ser,)).start()
  

python find

Python find helps us to find a search pattern in a given text
Python method find() determines if a sub-string presents in a given string

Syntax:
str.find(str, beg=0 end=len(string))

For Example:
stra = "python find substring"
strb = "substring"

stra.find(strb)
stra.find(strb, 10) #This will search the required sub-string from index 10
stra.find(strb, 20) #This will search the required sub-string from index 20

print stra.find(strb)             #12
print stra.find(strb, 10)       #12
print stra.find(strb, 16, 30)  #-1
print stra.find(strb, 20, 30)  #-1

Return Value
find() returns -1 if there is no match, else it will return the index of the match

Example:
def getText():
    return "Python find Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices";

input_text = getText()

print input_text.find("Defaults for start")
print "\n"

if (input_text and input_text.find("Defaults for start") != -1):
    print "\n Found"
else:
    print "\n Not Found"
  

python check process running

We make use of python subprocess module
  • To write/execute the command in the command line
  • To write to stdin and read the output of stdout

Methods Used
1) checkProcessRunning
        To check whether process in running or not

2) writeToCMD
        To execute the command in the command line and read the output of it

Pass the required arguments
checkProcessRunning(cmd = "adb shell ps", processName = "com.android.phone")

cmd -> Command to execute
processName -> Text to search from the command line output

How to Run
python python_check_process_running.py
import subprocess

def checkProcessRunning(cmd, processName):
    print "\n Process to check : " + cmd
    result = writeToCMD(cmd)
    if (result[0].rstrip().find(processName) != -1):
        print processName + " is present/running"
        return True
    else:
        print processName + " is not present/running"
        return False
          
def writeToCMD(cmd):
    proc = None       
    proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell="True")
    stdout_value = proc.communicate()
    if stdout_value:
        return stdout_value

checkProcessRunning(cmd = "adb shell ps", processName = "com.android.phone")
  


Feb 14, 2014

Python Delete old files

Many a times, we come across deleting old files like logs, deprecated files from file system


We come across scenarios like 

To delete logs older than x days
To delete txt files older than x days

Let us discuss how we can achieve deleting old files using python script

What does the script do?
It will take the path from where you need to delete the txt files
The below program checks the time stamp of the files and deletes the txt files older than 7 days.
You can change the file extension, folder path and use it.
folder_path = "C:\Files_To_Read"
file_ends_with = ".txt"
how_many_days_old_logs_to_remove = 7

How to call the script?
python delete_old_logs.py

delete_old_logs.py

import os, time, sys

folder_path = "C:\Files_To_Read"
file_ends_with = ".txt"
how_many_days_old_logs_to_remove = 7

now = time.time()
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path,file)
    if os.path.isfile(file_full_path) and file.endswith(file_ends_with):
        #Delete files older than x days
        if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400: 
             os.remove(file_full_path)
             print "\n File Removed : " , file_full_path
 

perl extract urls from file

As a developer, we need to extract URLs from an input file quite often in our day to day work.
Let us discuss how to extract URLs from an input Text or HTML file using a perl snippet.
Let us automate extracting URLs

What does the script do?
The following script will take input file as command line argument.
It will read the file line by line, extract the HTTP urls and push the results into an array.
Finally prints the array object.

How to call the script?
perl get_urls_from_input_file.pl "C:\Files_To_Read\blog_html.txt"


get_urls_from_input_file.pl

use strict;
use warnings;
use warnings;
use Data::Dumper;

my %substitute = ( '%20' => '', '%3A' => '' , '%24' => '');
my @result_urls;

#perl get_urls_from_input_file.pl 'C:\Files_To_Read\blog_html.txt'

my $infile  = $ARGV[0];

open(my $fh, '<', $infile) or die "Could not open logfile: $!";
while ( my $each_line = <$fh> ) {
    chomp $each_line;

 if ($each_line =~ /['"](http:\/\/.*?)['"]/) {
  my $grep_url = $1;
  push(@result_urls, $1);
 }
}
close $fh;

print "\n" . Dumper(\@result_urls);

1;