Python for Automation: An introduction to more effective test automation
If you’re someone who wants to venture into software testing or boost your career prospects if you’re a manual tester, you may have come across job descriptions stating that candidates should have scripting or programming knowledge in at least one of the following languages: Java, Python, C# etc. Today, regardless of whether you’re applying to be a manual tester or not, most companies will expect you to have some knowledge in automation. This makes it essential to learn a new language and grow your skill set.
Before beginning with automation testing, however, you must be well-versed with the concepts, methodologies, and terminologies used in manual testing and the testing tools available in the market. The second prerequisite is learning a programming or scripting language. Among a sea of programming languages available in the market, Java and Python are the two most common languages used for automation. Java or Python, that’s the next BIG question! In truth, the choice is completely yours. Both Java and Python have their own pros and cons. If you are the kind of person who dreads coding, what you actually dislike is the lengthy syntax, complexity, and the frustrating punctuations at the end of each line. In that case, I would recommend you to start with Python instead of Java.
To automate web testing, you need to understand the vocabulary of programming languages, how to work with Selenium, read HTML and CSS to extract Xpath, get familiar with Git and learn Continuous Integration (CI) tools. At the same time, memorizing definitions and syntaxes can be a bit overwhelming for a beginner. Since you need to understand what exactly each function does, Python is preferred because of its simplicity.
Python vs Java
Python codes are written in plain English with easy predefined structures
For example, the syntax for printing a statement in Java is
system.out.println(“My code”);
while in Python, you have to simply type “print”
print(“My code”)
Fewer lines of code
“Any fool can write code that a computer can understand. Good programmers write code that humans can understand” — Martin Fowler, a British engineer
Writing 300–400 lines of code isn’t impressive anymore. Short lines of code help you achieve high standards of readability, maintainability, and efficiency. And this comes naturally with Python.
For instance, to print a statement in Java, you need to create a class, a main method, and finally the print statement. That means you just wrote seven lines of code!
public class HelloWorld{ public static void main (String[] args) { System.out.println("My blog"); }}
To print a statement in Python, you only need one line of code.
print(“My blog”)
Python is a dynamically typed language
To understand this point better, let’s declare a variable in both Java and Python.
Declaring a variable in Java:
int num =5;
When a variable is declared in Java, an area of memory is set aside for holding the value (let’s assume that value is 5) allowed by the data type. The memory allocated will be interpreted by the data type. If it’s an integer variable then the memory allocated will be read as an integer and so on. During initialization, the value is stored at that memory location and at the time of compilation, this stored value will be checked. So, we cannot mix datatypes.
Declaring a variable in Python:
num = 5;
Comparatively, Python doesn’t know the type of variable until the code is run. It simply stores the value 5 at some memory location and then binds the variable name “num” to that memory location.
Python in software testing
The primary goal of test automation is to reduce human intervention as much as possible by automating anything and everything. This increases the speed of execution, helps you run tests unattended, broadens coverage, and makes the process error-free and efficient. Python is best-suited for such test automation. With Python automation, scripting is simpler, clearer, and easier to maintain. Moreover, Python has many open-source libraries with off-the-peg solutions.
Pytest
Pytest is one of the most famous and best frameworks for Selenium Python. It can drive any kind of functional tests, be it unit testing or end-to-end testing. Test cases are written just like functions and are invulnerable to any failure since global variables are avoided. The “assert” statement is yet another useful tool in Pytest that confirms (by assert statements) that the result conforms to expectations. This statement has an automatic introspection system so that the error messages are clear and give more context to the output.
For example:
# contents of source codedef vowels(): return set(‘aeiou’)# content of test_language.pydef test_vowels(): result = vowels() expected = set(‘aeyou’) assert result == expected
If we run this test file…
======= FAILURES ========_______ test_vowels ________def test_vowels():result = vowels()expected = set(‘aeyou’)> assert result == expectedE assert set([‘a’, ‘e’, ‘i’, ‘o’, ‘u’]) == set([‘a’, ‘e’, ‘o’, ‘u’, ‘y’])E Extra items in the left set:E ‘i’E Extra items in the right set:E ‘y’E Use -v to get the full difftest_language.py:5: AssertionError======= 1 failed in 0.12 seconds ========
Pypi packages
Python has a rich library of packages. The Python Package Index (PyPI) is a repository for these packages. Developers of the Python community use PyPI to distribute their softwares and they are just a “pip install” away. When tests need to be done quickly and easily, Python makes it possible! Why waste time when features are readily available at your fingertips and just need to be verified?
Test reports
Generating test reports is one major pain point in any test automation framework. The test results become more insightful when a reporting feature is combined with the test cases. Many such report generation packages are available in Python. All you need to do is install the package and import it to your Python file. ‘Pytest-html’ is one such plugin that generates a basic html report in a simple and readable format.
Allure is yet another report generation plugin. Allure Report is a flexible lightweight test report tool that allows you to maximize the extraction of useful information from everyday execution of tests. Allure Report provides you with a comprehensive picture of which features have been covered, where defects are clustered, how long execution takes, and more.
In a nutshell, Python is one of the most popular programming languages in the world for many good reasons. It has a large, active, and supportive community too. Python is also a highly sought after programming language and is learnt by web developers, data scientists, and non-programmers as well. Moreover, it has consistently ranked near the top on TIOBE, Stack Overflow, and GitHub (as well as GitHut).
Between Java and Python, both programming languages are suitable for test automation and have large developer communities supporting them. Learning one does not mean you can’t learn the other — many programmers venture into several languages, and learning multiple languages can actually strengthen the understanding of programming languages altogether. However, as discussed above, Python offers several benefits — from ease of understanding to better speed and productivity. It only makes sense, especially if you’re a beginner, to learn Python first and then Java and other languages, as required. Yes, you heard it right! It’s time to drop the coffee (Java) and catch the snake (Python)!
References:
1. https://www.careerist.com/insights/qa-automation-in-python-not-java
2. https://automationpanda.com/2018/07/26/why-python-is-great-for-test-automation/
3. https://www.bmc.com/blogs/python-vs-java/