Sunday, 12 August 2012

UNIT TESTING


  • In computer programming, unit testing is a method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine if they are fit for use.
  • The goal of unit testing is to isolate each part of the program and show that the individual parts are correct.
Advantages 

  Find problems early
  • Unit tests find problems early in the development cycle. Unit tests are created before the code itself is written. When the tests pass, that code is considered complete.
  • The unit tests alert the development team of the problem before handing the code off to testers or clients, it is still early in the development process.

   Facilitates change
  • Unit testing allows the programmer to write test cases for all functions and methods so that whenever a change causes a fault, it can be quickly identified and fixed.
  • Readily available unit tests make it easy for the programmer to check whether a piece of code is still working properly.

   Simplifies integration
  • By testing the parts of a program first and then testing the sum of its parts, integration testing becomes much easier.
   Documentation
  • Unit testing provides a sort of living documentation of the system.
  • Unit tests provides a basic understanding of what functionality is provided by a unit and how to use it.
   Design
  • The basic building blocks of unit testing are 'test cases' -- single scenarios that must be set up and checked for correctness.
  • The testing code of a Test Case instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases.
  • An example of unit testing :
       import unittest
 
        class SimpleWidgetTestCase(unittest.TestCase):
            def setUp(self):
                self.widget = Widget("The widget")

        class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
            def runTest(self):
                assert self.widget.size() == (50,50), 
                            'incorrect default size'

        class WidgetResizeTestCase(SimpleWidgetTestCase):
            def runTest(self):
                self.widget.resize(100,150)
                assert self.widget.size() == (100,150), \
                       'wrong size after resize'
    
  • In this, if the 'setUp' method raises an exception while the test is running, the framework will consider the test to have suffered an error, and the 'runTest' method will not be executed.
  • The TestCase class of the unittest compares its arguments and if not same, will raise an exception and the test will immediately be considered failed.
  • Place the following code at the bottom of your test module:
        if __name__ == "__main__":
            unittest.main()
    
    Then we could run the code in the command line.
    Eg: % python unittest.py widgettests.WidgetTestSuite
  • The design document (the unit-test itself) can be used to verify that the implementation adheres to the design.
  • With the unit-test design method, the tests will never pass if the developer does not implement the solution according to the design.
  • A detailed example of unit testing is given here

Limitations 
  • Testing cannot be expected to catch every error in the program: it is impossible to evaluate every execution path in all but the most trivial programs. 
  • Unit testing by definition only tests the functionality of the units themselves. Therefore, it will not catch integration errors or broader system-level errors.
  • Like all forms of software testing, unit tests can only show the presence of errors; they cannot show the absence of errors.
  • Another challenge related to writing the unit tests is the difficulty of setting up realistic and useful tests.
  •  If these initial conditions are not set correctly, the test will not be exercising the code in a realistic context, which diminishes the value and accuracy of unit test results. 
  • Use of a version control system is essential in unit testing.
  • It is also essential to implement a sustainable process for ensuring that test case failures are reviewed daily and addressed immediately.
 
  • These are some basic ideas regarding unit testing. You could refer here for more details.

Wednesday, 8 August 2012

GUIDELINES TO WRITE A PROGRAM IN PYTHON


GUIDELINES TO WRITE A PROGRAM IN PYTHON.
  • The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code.
  • The guidelines is about consistency. Consistency with this style guide is important. Consistency within a project is more important.
  • Break the rules, if it hinders the readability of the code.
     CODE LAY OUT
     Indentation:
  • Use 4 spaces per indentation level.
  • Continuation lines should align wrapped elements either vertically or using a hanging indent.
  • Eg:
         def long_function_name(
                     var_one, var_two, var_three
                     var_four):
            print( var_one )
     Tabs or Spaces?:
  • Never mix tabs and spaces.
  • Either follow indenting Python with spaces only or tabs only.
     Maximum Line Length:
  • Limit all lines to a maximum of 79 characters.
  • Wrapping long lines is done by using Python's implied line continuation inside parentheses, brackets and braces.
  • The preferred place to break around a binary operator is after the operator, not before it.
  • Eg:
   class Rectangle(Blob):
       def __init__ (self, width, height,
                     color='black', emphasis=None highlight=0):
           if (width == 0 and height == 0 and
               color == 'red' and emphasis == 'strong' or
               highlight > 100);
               raise ValueError("sorry you lose")
           if width == 0 and height == 0 and (color == 'red' or
                                              emphasis is None):
               raise ValueError("I don't think so -- values are %s,
                                %s" (width,height))
           Blob.__init__(self, width, height,
                         color, emphasis,highlight)
  
     Blank Lines:
  • Separate top-level function and class definitions with two blank lines.
  • Method definitions inside a class are separated by a single blank line.
  • Extra blank lines may be used to separate groups of related functions.
  • Use blank lines in functions, sparingly, to indicate logical sections.
     Encodings:
  • Code in the core Python distribution should always use the ASCII or Latin-1 encoding.
  • For Python 3.0 and beyond, UTF-8 is preferred over Latin-1.
  • Files using ASCII should not have a coding cookie.
  • Latin-1 (or UTF-8) should only be used when a comment or docstring needs to mention an author name that requires Latin-1; otherwise, using \x, \u or \U escapes is the preferred way to include non-ASCII data in string literals.
  • All identifiers in the Python standard library MUST use ASCII-only identifiers, and SHOULD use English words wherever feasible.
  • The only exceptions are
    (a) test cases testing the non-ASCII features, and
    (b) names of authors.
      Imports:
  • Imports should usually be on separate lines.
  • Eg:
              import os
         import sys.
  • Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
  • Imports should be grouped in the following order:
          1. standard library imports
          2. related third party imports
          3. local application/library specific imports .
    You should put a blank line between each group of imports.
    Put any relevant __all__ specification after the imports.
  • Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports.
  • When importing a class from a class-containing module, it's usually okay to spell this:
                      from myclass import MyClass
                      from foo.bar.yourclass import YourClass.

      Whitespace in Expressions and Statements:
  • Avoid extraneous whitespace in the following situations:
  • Immediately inside parentheses, brackets or braces.
  • Immediately before a comma, semicolon, or colon.
  • Immediately before the open parenthesis that starts the argument list of a function call.
  • Immediately before the open parenthesis that starts an indexing or slicing.
  • More than one space around an assignment (or other) operator to align it with another.

      Other Recommendations:
  • Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
  • If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Never use more than one space, and always have the same amount of whitespace on both sides of a binary operator.
  • Eg:
    i = i + 1
    submitted += 1
    x = x * 2 - 1
    hypot2 = x * x + y *y
  • Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.
  • Eg:
        def complex(real, imag=0.0):
             return magic(r=real, i=imag).
  • Compound statements (multiple statements on the same line) are generally discouraged.
     Comments:
  • Comments should not be contradict. Always make a priority of keeping the comments up-to-date when the code changes!
  • Comments should be complete sentences. If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter .
  • If a comment is short, the period at the end can be omitted. Block comments generally consist of one or more paragraphs built out of complete sentences, and each sentence should end in a period.
  • You should use two spaces after a sentence-ending period.
  • When writing English, Strunk and White apply.

     Block Comments:
  • Block comments generally apply to code that follows them, and are indented to the same level as that code.
  • Each line of a block comment starts with a # and a single space.
  • Paragraphs inside a block comment are separated by a line containing a single #.

      Inline Comments:
  • Use inline comments sparingly.
  • Inline comments should be separated by at least two spaces from the statement.
  • They should start with a # and a single space.

     Documentation Strings:
  • Docstrings explain how to use code, and are for the users of your code.
  • Explain the purpose of the function, help full to someone else later on.
  • Describe the parameters expected, the return values, and any exceptions raised.
  • Docstrings are useful in interactive use (help()) and for auto-documentation systems.

     Naming Conventions:
  • joined_lower for functions, methods, attributes.
  • joined_lower or ALL_CAPS for constants.
  • StudlyCaps for classes.
  • camelCase only to conform to pre-existing conventions.

     Prescriptive: Naming Conventions:
     Names to Avoid:
  • Never use the characters 'l' , 'O' , or 'I' as single character variable names.

     Package and Module Names:
  • Modules should have short, all-lowercase names.
  • Underscores can be used in the module name if it improves readability.]
  • Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
  • It is important that module names be chosen to be fairly short .

     Class Names:
  • Almost without exception, class names use the CapWords convention.
  • Classes for internal use have a leading underscore in addition.

     Exception Names:
  • Because exceptions should be classes, the class naming convention applies here. You should use the suffix "Error" on your exception names.

     Functional Names:
  • Function names should be lowercase, with words separated by underscores as necessary to improve readability.
     Method Names and Instance Varibles:
  • Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
  • Use one leading underscore only for non-public methods and instance variables.
  • To avoid name clashes with subclasses, use two leading underscores to invoke Python's name mangling rules.
     Constants:
  • Constants are usually defined on a module level and written in all capital letters with underscores separating words.

      Designing for Inheritance:
  • Always decide whether a class's methods and instance variables should be public or non-public.
  • Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backward incompatible changes.
  • Non-public attributes are those that are not intended to be used by third parties.
  • Another category of attributes are those that are part of the "subclass API"

Monday, 6 August 2012

Git Basics


Git Basics.
Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

Git is a powerful DVCS. Git has unworldly powers.
Some of the advantages of Git over other VCS are:
  • Since the entire history of the project right there on your local disk,
    most operations seem almost instantaneous.
  • If you want to see the changes introduced between the current version of
    a file and the file a month ago, Git can look up the file a month ago and do
    a local difference calculation, instead of;
     Either ask a remote server to do it.
    Or pull an older version of the file from the remote server to do it 
    locally.
  • You can do much of your work when you are travelling or when the VPN
    client is not working properly , you can then commit happily when you get
    to a network connection to upload.
  • Everything in Git is check-summed before it is stored and is then referred
    to by that checksum. This means it’s impossible to change the contents of
    any file or directory without Git knowing about it.
  • You can’t lose information in transit or get file corruption without Git
    being able to detect it.
  • The mechanism that Git uses for this checksumming is called a SHA–1 hash.
  • Git stores everything not by file name but in the Git database addressable
    by the hash value of its contents.
  • Git has three main states that your files can reside in: committed,
    modified, and staged.
               Committed: Committed means that the data is safely stored in your
                                  local database.
               Modified: Modified means that you have changed the file but have not
                                committed it to your database yet.
               Staged: Staged means that you have marked a modified file in its
                            current version to go into your next commit snapshot.
  • The basic Git workflow goes something like this:
        1. You modify files in your working directory.
        2. You stage the files, adding snapshots of them to your staging area.
        3. You do a commit, which takes the files as they are in the staging
             area and stores that snapshot permanently to your Git directory.
  • Hence, If a particular version of a file is in the git directory, it’s
    considered committed. If it’s Modified but has been added to the staging
    area, it is staged. And if it was changed since it was checked out but has
    not been staged, it is modified.
How to start with Git.
First thing is to install it. You can either install it from source or install an existing package for your platform.

 * If you’re on a Debian-based distribution like Ubuntu, try apt-get:
               '$ apt-get install git-core'
 * Next step is to 'First Time Git Setup' to personalize the git
 * For this you have to create a Repository in github.com/
 * Once you had created the Repository, then open the terminal,the folder where the code is saved, that         is to be pushed to github repository.
 * Then do the following steps:
  • 'git init'
               # To initialise.
  • 'git add filename'
               # To add a file (Eg: git add string.py).
  • 'git commit -m "first commit"
           # To commit the file with version number. if the edited second version    is pushing, then do "second commit".
               # To push the code directly to the repository from terminal. Master is the name of computer and the url is obtained when the repository is created in Github.com.
               #Then enter the username of github(Eg: 'kishorekdty').
               #Enter your password of github and press enter key.
  • Thats all to do..
             Then it will show something like;
             To https://github.com/kishorekdty/kishore.git
              25192b3..23ee338 master → master
              So your code has pushed to Github..