© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
A. PajankarPython Unit Test Automationhttps://doi.org/10.1007/978-1-4842-7854-3_1

1. Introduction to Python

Ashwin Pajankar1  
(1)
Nashik, Maharashtra, India
 

I hope you have glanced through the introduction section. If you have not, then I recommend reading it, as it will help you with the context and the philosophy of this book.

Let’s begin this adventurous journey by learning the history and background of Python.

I personally find Python amazing and have been enchanted by it. Python is a simple yet powerful programming language. When using Python, it’s easy to focus on the implementation of the solution to a given problem, as programmers do not have to worry about the syntax of the programming language.

The History of Python

Python was conceived in the late 1980s. Guido van Rossum began its implementation in late 1989 at the Centrum Wiskunde & Informatica (National Research Institute for Mathematics and Computer Science) in the Netherlands. Python is a successor to the ABC programming language, which itself was inspired by SETL. In February 1991, Van Rossum published Python code to the alt.sources newsgroup. The name Python was inspired by the television show “Monty Python’s Flying Circus,” as Van Rossum is a big fan of Monty Python.

Van Rossum is the principal author of Python. He played a central role in guiding the development and evolution of Python. He held the title of Benevolent Dictator for Life for Python. In 2018, he stepped down from that role. As of the writing of this edition, he works for Microsoft.

The central philosophy of Python, called the Zen of Python, is explained in PEP-20, which can be found at https://www.python.org/dev/peps/pep-0020.

It is a collection of 20 software principles, as follows:
  • Beautiful is better than ugly.

  • Explicit is better than implicit.

  • Simple is better than complex.

  • Complex is better than complicated.

  • Flat is better than nested.

  • Sparse is better than dense.

  • Readability counts.

  • Special cases aren’t special enough to break the rules.

  • Practicality beats purity.

  • Errors should never pass silently.

  • Unless explicitly silenced.

  • In the face of ambiguity, refuse the temptation to guess.

  • There should be one—and preferably only one—obvious way to do it.

  • Although that way may not be obvious at first unless you’re Dutch.

  • Now is better than never.

  • Although never is often better than right now.

  • If the implementation is hard to explain, it’s a bad idea.

  • If the implementation is easy to explain, it may be a good idea.

  • Namespaces are one honking great idea—let’s do more of those!

Features of Python

The following sections discuss the features of Python that have become popular and beloved in the programming community.

Simple

Python is a simple and minimalist language. Reading a well written and good Python program makes you feel as if you are reading English text.

Easy to Learn

Due to its simple and English-like syntax, Python is extremely easy for beginners to learn.

That is the prime reason that, nowadays, it is taught as the first programming language to high school and university students who take introduction to programming and programming 101 courses. An entire new generation of programmers is learning Python as their first programming language.

Easy to Read

Unlike other high-level programming languages, Python does not provide much provision for obfuscating code and making it unreadable. The English-like structure of Python code makes it easier to read, compared to code written in other programming languages. This makes it easier to understand and easier to learn, compared to other high-level languages like C and C++.

Easy to Maintain

As Python code is easy to read, easy to understand, and easy to learn, anyone maintaining the code becomes comfortable with its codebase in considerably less time. I can vouch for this from personal experiences of maintaining and enhancing large legacy codebases written in a combination of bash and Python 2.

Open Source

Python is an open-source project. That means its source code is freely available. You can make changes to it to suit your needs and use the original and changed code in your applications.

High-Level Language

While writing Python programs, you do not have to manage low-level details like memory management, CPU timings, and scheduling processes. All these tasks are managed by the Python interpreter. You can directly write the code in easy-to- understand, English-like syntax.

Portable

Python has been ported to many platforms. All Python programs work on any of these platforms without requiring any changes, if you are careful enough to avoid any system-dependent features. You can use Python on GNU/Linux, Windows, Android, FreeBSD, macOS, iOS, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn, RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE, and PocketPC.

Interpreted

Python is an interpreted language. Programs written in a high-level programming language like C, C++, and Java are first compiled. This means that they are first converted into an intermediate format. When you run the program, this intermediate format is loaded from secondary storage (i.e., a hard disk) to memory (RAM) by the linker/loader. So, C, C++, and Java have separate compilers and linkers/loaders. This is not the case with Python. Python runs its programs directly from the source code. You do not have to bother about compiling and linking to the proper libraries. This makes Python programs truly portable, as you can copy the program to one computer from another and the program runs fine as long as the necessary libraries are installed on the target computer.

Object-Oriented

Python supports object-oriented programming paradigms. In object-oriented programming languages, the program is built around objects that combine data and related functionality. Python is a very simple but powerful object-oriented programming language.

Extensible

One of the features of Python is that you can call C and C++ routines from Python programs. If you want the core functionality of the application to run faster, you can code that part in C/C++ and call it in the Python program (C/C++ programs generally run faster than Python).

Extensive Libraries

Python has an extensive standard library, which comes pre-installed. The standard library has all the essential features of a modern day programming language. It has provision for databases, unit testing (we will explore this in this book), regular expressions, multi-threading, network programming, computer graphics, image processing, GUI, and other utilities. This is part of Python’s batteries-included philosophy.

Apart from standard library, Python has a large and ever-growing set of third-party libraries. The list of these libraries can be found in the Python Package Index (https://pypi.org/). We will explore a few libraries like unittest, nose, nose2, pytest, and selenium for test automation in this book. I also have worked with and extensively written on the libraries for scientific computing and computer vision such as numpy, scipy, matplotlib, pillow, scikit-image, and OpenCV.

Robust

Python provides robustness by means of its ability to handle errors. The full stack trace of the encountered errors is available and makes the programmer’s life more bearable. The runtime errors are known as exceptions. The feature that allows handling of these errors is known as the exception handling mechanism.

Rapid Prototyping

Python is used as a rapid prototyping tool . As you have read, Python has extensive libraries and is easy to learn, so many software architects are increasingly using it as a tool to rapidly prototype their ideas into working models in a very short period of time.

Memory Management

In assembly language and programming languages like C and C++, memory management is the responsibility of the programmer. And this is in addition to the task at hand. This creates an unnecessary burden on the programmer. In Python, the Python interpreter handles memory management. This helps programmers steer clear of memory issues and focus on the task at hand.

Powerful

Python has everything in it for a modern programming language. It is used for applications like computer vision, supercomputing, drug discovery, scientific computing, simulation, and bioinformatics. Millions of programmers around the world use Python. Many big organizations like NASA, Google, SpaceX, and Cisco use Python for their applications and infrastructure.

Community Support

I find this the most appealing feature of Python. As you have read, Python is open source and has a community of almost a million programmers (probably more, as today’s high school kids are learning Python) throughout the world. That means there are plenty of forums on the Internet supporting programmers who encounter roadblocks. None of my queries related to Python has ever gone unanswered.

Python 3

Python 3 was released in 2008. The Python development team decided to do away with some of the redundant features of the Python language, simplify some of its features, rectify some design flaws, and add some much-needed features.

It was decided that a major revision number was warranted and the resultant release would not be backward compatible. Python 2.x and 3.x were supposed to coexist in parallel for the programmer community to have enough time to migrate their code and the third-party libraries from 2.x to 3.x. Python 2.x code cannot run on Python 3 in many cases, as there are significant differences between 2.x and 3.x.

Differences Between Python 2 and Python 3

The following are the most notable differences between Python 2 and Python 3. Let’s look at them in brief:
  • The print() function

    This is perhaps the most notable difference between Python 2 and Python 3. The print statement of Python 2 is replaced with the print() function in Python 3.

  • Integer division

    The nature of integer division has been changed in Python 3 for the sake of mathematical correctness. In Python 2, the result of division of two integer operands is an integer. However, in Python 3, it is a float value.

  • Omission of xrange()

    In Python 2, for creating iterable objects, the xrange() function is used. In Python 3, range() is implemented much like xrange(). So, a separate xrange() is not needed anymore. Using xrange() in Python 3 raises a nameError.

  • Raising exceptions

    It is mandatory in Python 3 to enclose exception arguments, if any, in parentheses, whereas in Python 2 it is optional.

  • Handling exceptions

    In Python 3, while handling exceptions, the as keyword is needed before the parameter to handle an argument. In Python 2, it is not needed.

  • New style classes

    Python 2 supports old and new style classes, whereas Python 3 supports only new style classes. All classes created in Python 3 use new style classes by default.

  • New features of Python 3

    The following new features of Python 3 have not been backported to Python 2:
    1. a.

      Strings are Unicode by default

       
    2. b.

      Clean Unicode/byte separation

       
    3. c.

      Exception chaining

       
    4. d.

      Function annotations

       
    5. e.

      Syntax for keyword-only arguments

       
    6. f.

      Extended tuple unpacking

       
    7. g.

      Non-local variable declarations

       

From this list, you will be frequently using print(), new-style classes, and exceptions in the code examples in this book.

Why Use Python 3

From the previous list, you will be frequently using new-style classes and exceptions in the code examples in this book.

Python’s wiki page (https://wiki.python.org/moin/Python2orPython3) says the following:

Python 3 is strongly recommended for any new development.

New generation of programmers are introduced to Python 3 as their first programming language. When they are comfortable with the concept and philosophy of Python programming, they are gradually introduced to Python 2 so that they can also work with legacy codebases. Many organizations have already started migrating codebases from Python 2 to Python 3. All new projects in Python extensively use Python 3. Python 2 is almost dead as of writing of this edition of the book. Most organizations are migrating their legacy codebases from Python 2 to Python 3. Day by day, there is less and less code in Python 2 and it is either abandoned or converted to Python 3. It is a long and tedious process to convert Python 2 code to Python 3. Many organizations are doing it on as-needed basis. The general rule of thumb that most organizations follow is that if the code works then they do not touch it. However, as I have already said, all the new projects involving Python are kicked off with Python 3. Going forward, conversion of legacy Python 2 codebase to Python 3 will present technically challenging and financially lucrative opportunities for professionals.

I personally think that these are pretty good reasons to use Python 3.

Installing Python 3

This section discusses how to install Python 3 on various commonly used computer OSs.

Installation on Linux

Linux has many popular distributions. Python 3 is preinstalled on many popular distributions.

Installation on Debian, Ubuntu, and Derivatives

The Python 3 interpreter comes preinstalled on the latest releases of Debian, Ubuntu, and their derivatives.

Installation on Fedora and CentOS

The Python 3 interpreter comes preinstalled on the latest releases of Fedora and CentOS.

Note

On most of the latest Linux distributions, both versions of Python (Python 2 and Python 3) are installed by default. The interpreter for Python 2 is a binary executable file named python and the interpreter for Python 3 is another binary executable file named python3. You can use python3 --V or python3 --version to check the version of the Python 3 interpreter installed on your Linux computer. Also, you can use the which python3 command to determine the location of the interpreter on the disk.

Installation on macOS X

On macOS X, the Python 2 interpreter is installed by default and can be invoked from the terminal using the python command. If you want to use Python 3, you have to install it. Make sure that the computer is connected to the Internet and run the brew install python3 command in the terminal. This will install Python 3. It will also install other utilities, such as pip, setuptools, and wheel.

Once the installation finishes, go to the terminal and type python3 --V or python3 --version to check the version of the Python 3 interpreter installed.

Installation on Windows

In Windows OS , Python 3 installation requires a bit more effort. Python 2 or Python 3 is not preinstalled on a Windows computer. In order to install it, you have to visit the downloads section of the Python website at https://www.python.org/downloads, as shown in Figure 1-1.
../images/436414_2_En_1_Chapter/436414_2_En_1_Fig1_HTML.jpg
Figure 1-1

Python downloads section on the website

Select Python 3.5.2. (The numbers 5 and 2 might change if there is a new stable release of Python after the book is published.) This will download the setup file for Python 3. Open the setup file once it is downloaded. Click on the Run button in the dialog box shown in Figure 1-2.
../images/436414_2_En_1_Chapter/436414_2_En_1_Fig2_HTML.jpg
Figure 1-2

Open File - Security Warning dialog box

Note

Depending on the settings, you might require admin privileges to install Python 3 (or any other program, for that matter) on a Windows computer. If you are in an organizational setting, check with your system admin team for this information.

If you are using Windows 7, depending on the update status of your computer, you might encounter the message box shown in Figure 1-3.
../images/436414_2_En_1_Chapter/436414_2_En_1_Fig3_HTML.jpg
Figure 1-3

Setup Failed message for Windows 7

Update the OS by installing any Windows updates and then rerun the setup file. The window in Figure 1-4 will appear when you are successful.
../images/436414_2_En_1_Chapter/436414_2_En_1_Fig4_HTML.jpg
Figure 1-4

Python Installation window

Check the Add Python 3.x to PATH checkbox. This will ensure that Python is added to the PATH system variable and you will be able to access Python from the command prompt of Windows (cmd) after the installation. Click the Install Now button and continue the setup wizard. Once installation finishes, it will show a success message.

Running a Python Program and Python Modes

You have set up your environment for Python programming now. Now you can get started with a simple concept of Python. Python has two basic modes—normal and interactive. Let’s look at these modes in detail.

Interactive Mode

Python’s interactive mode is a command-line shell that provides immediate output for every executed statement. It also stores the output of previously executed statements in active memory. As new statements are executed by the Python interpreter, the entire sequence of previously executed statements is considered while evaluating the current output. You have to type python3 in the command prompt of Linux/macOS and python in the command prompt cmd of Windows to invoke the Python 3 interpreter into interactive mode, as follows:
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
You can execute Python statements directly in this interactive mode just like you run commands in the OS shell/console, as follows:
>>> print('Hello World!')
Hello World!
>>>
You will not be using interactive mode in the book. However, it’s the quickest way to check small snippets of code (5 to 10 lines). You can quit interactive mode with the exit() statement, as follows:
>>> exit()
$

Script Mode

Script mode is where the Python script files (.py) are executed by the Python interpreter.

Create a file called test.py and add the print ('Hello World!') statement to the file. Save the file and run it with the Python 3 interpreter as follows.
$ python3 test.py
Hello World!
$

In this example, python3 is the interpreter and test.py is the filename. If the Python test.py file is not in the same directory where you’re invoking the python3 interpreter, you have to provide the absolute path of the Python file.

Note

For all Linux and Mac computers, the command for the Python 3 interpreter is python3. For Windows, it is just python, assuming that only Python 3 is installed on the Windows computer and its location is added to the PATH variable during installation or manually after the installation. Throughout this book, I use a Linux command prompt (on my Raspberry Pi 4) to run the code examples. I will mention it explicitly wherever Windows is used for a couple of examples.

IDEs for Python

An Integrated Development Environment (IDE) is a software suite that has all the basic tools to write and test programs. A typical IDE has a compiler, a debugger, a code editor, and a build automation tool. Most programming languages have various IDEs to make programmers lives better. Python too has many IDEs. Let’s take a look at a few IDEs for Python.

IDLE

IDLE stands for Integrated Development Environment. It comes bundled with Python. IDLE3 is for Python 3. It’s popular with beginners of Python. Just type idle3 in the command prompt in a Linux computer where Python 3 is installed. Figure 1-5 is a screenshot of an IDLE3 code editor and an interactive prompt.
../images/436414_2_En_1_Chapter/436414_2_En_1_Fig5_HTML.jpg
Figure 1-5

IDLE3 running on a Raspberry Pi

If IDLE is not installed by default on your Linux distribution then you have to install it manually. For Debian and derivatives, the command for the installation is as follows:
sudo apt-get install idle

The PyDev Plugin for Eclipse

If you are a seasoned Java programmer, you probably have worked on Eclipse. Eclipse is a very popular IDE for Java and it can be used with other programming languages too. PyDev is a Python IDE for Eclipse, and it can be used in Python, Jython, and IronPython development (see Figure 1-6). You can install PyDev from the Eclipse marketplace at www.pydev.org.
../images/436414_2_En_1_Chapter/436414_2_En_1_Fig6_HTML.jpg
Figure 1-6

Eclipse with PyDev

Geany

Geany (see Figure 1-7) is a text editor that uses the GTK+ toolkit with basic features of an integrated development environment. It supports many file types and has some nice features. Check out https://www.geany.org for more details.
../images/436414_2_En_1_Chapter/436414_2_En_1_Fig7_HTML.jpg
Figure 1-7

Geany

PyCharm

PyCharm by JetBrains is another IDE for Python and it’s packed with powerful features like a debugger, a code inspection tool, version control, and an integrated unit test runner. It is a cross-platform IDE available for Windows, macOS, and Linux distributions. Its Community Edition is a free download. Visit its home page at https://www.jetbrains.com/pycharm/ for more information.

The code examples in this book are better suited for execution from the command prompt, due to the nature of the libraries involved. I personally prefer to write the logic and code on paper (Yes! Using a piece of paper!) first and then use a plain-text editor with syntax highlighting. For example, I recommend Notepad++ on Windows, or nano, Leafpad, and gedit on Linux. You can use IDLE3 or Geany for writing and compiling the code.

However, most of the code examples are meant to be executed from the command line.

Exercise 1-1

Complete this exercise to understand Python 3’s background better.

Conclusion

In this chapter, you learned the background, history, and features of Python. You also studied the important differences between Python 2 and Python 3. You learned how to install and use Python 3 in script and interactive modes. Finally, you looked at a few popular IDEs for Python. In the next chapter, you will get started with the concepts of test automation and look at a simple test automation library for Python, called doctest. You will also briefly look at pydoc.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.103.61