Introduction to Python Automation Testing with Pytest


Pytest is one of the most mind-blowing open-source, straightforward, versatile and Python-based Test Automation System accessible at the market today. Pytest powers you to test anything including Information bases, UI and is more famous among testers for API Testing. It can either be run as a singular apparatus for testing or it very well may be appended to Python web improvement structures like Django or Flask, upgrading their unit test abilities and dependability.


Introduction to Python Automation Testing with Pytest

Introduction to Python Automation Testing with Pytest

Also Read: ROS(Robot Operating System): The Infrastructure of Modern Robotics I

Tests in Pytest are essential python capabilities which we can run as entire, or explicitly based on labels or names. Additionally, parallel test running element is inbuilt to Pytest which you can get to that by just determining an additional contention to CLI pytest run.


Features Of Pytest

There are various testing frameworks and tools accessible presently. Using of such frameworks would depend upon data driven, keyword driven, hybrid, BDD, and so on. You can pick the one that accommodates your necessity best.

Having said that Python and pytest are taking a gigantic offer in this opposition. Python and its connected apparatus are profoundly utilized most likely in light of the fact that they are more reasonable for individuals with no or little programming mastery contrasted with different dialects. The pytest system makes it simple to compose little tests, yet scales to help complex functional testing for applications and libraries.

A portion of the significant highlights of Pytest:-

  • Programmed revelation of test modules and capabilities
  • Viable CLI for better control, what you need to run or skip
  • A develop full-included Python testing apparatus
  • Works with conventional unit test framework


Automatic and Configurable Test Disclosure

Pytest naturally hopes to find tests in python modules whose names start with test_ or end with . Additionally naturally it expects test capability names to begin with test_ prefix. Anyway this test revelation convention can be changed by adding your own arrangement in pytest's one of the design records. More on official website.


# content of pytest.ini
# Example: have pytest look for "check" instead of "test"
# can also be defined in tox.ini or setup.cfg file, although the section
# name in setup.cfg files should be "tool:pytest"
python_files = check_*.py
python_classes = Check
python_functions = *_check

We should take a look at the extremely fundamental test capability.

class CheckClass(object):
   def one_check(self):
       x = "hey"
       assert 'h' in x

   def two_check(self):
       x = "hii"
       assert hasattr(x, 'check')

No extravagant assertEqual or assertDictEqual and so forth, outright and straightforward declare . Don't bother bringing in these attesting capabilities for basic activity of looking at two items. Declare is something python as of now offers, so don't bother wasting time.

What is Boilerplate ?

In computer programming, boilerplate code or just boilerplate refers to sections of code that have to be included in many places with little or no alteration. When creating a new class, for example, a programmer often has to add boilerplate code to perform a number of tasks, such as dynamically allocating memory for the new object and initializing member variables. You can see that the "test" works. It basically test the fundamental tasks of account software.

from Account import Account
def test_default_initial_amount():
  Account = Account ()
  assert Account.balance == 0
  Account.close()def test_setting_initial_amount():
  Account = Account(initial_amount=100)
  assert Account.balance == 100
  Account.close()def test_ Account _add_cash():
  Account = Account (initial_amount=10)
  assert Account.balance == 100
  Account.close()def test_ Account _spend_cash():
  Account = Account (initial_amount=20)
  assert Account.balance == 10

Have you seen something - lot of boilerplate. Something else worth seeing is that test is doing a couple of different things separated from simply testing a piece of usefulness for example Launching Account and furthermore shutting it - Account.close(). Presently we should investigate how we can dispose of boilerplate with pytest apparatuses.

import pytest
from _pytest.fixtures import SubRequest
from Account import
def Account(request: SubRequest):
param = getattr(request, ‘param’, None)
if param:
prepared_ Account = Account (initial_amount=param[0])
prepared_ Account = Account ()
yield prepared_ Account
prepared_ Account.close()#==================== tests

def test_default_initial_amount(Account):
assert Account.balance == 0@pytest.mark.parametrize(‘Account’, [(100,)], indirect=True)
def test_setting_initial_amount(Account):
assert Account.balance == 100@pytest.mark.parametrize(‘Account’, [(10,)], indirect=True)
def test_ Account_add_cash(Account):
assert Account.balance == 100@pytest.mark.parametrize(‘Account’, [(20,)], indirect=True)
def test_ Account_spend_cash(Account):
assert Account.balance == 10

Test capabilities are really unobtrusive, and doing just what they expect to do. Putting up and destroying launching and shutting Account are being taken consideration by apparatus Account. Not just it is assisting with composing reusable piece of code, it likewise adds the substance of information detachment. On the off chance that you look cautiously, Account sum is a piece of test information provided from beyond the test rationale, and not hard-coded inside test capability.

Execute Test Cases against many different Data Set

Pytest has a cool element for parameterizing your installation. We should investigate it with a example. Suppose your item uncovered the CLI interface point to locally oversee it. Likewise your item has bunches of default boundaries getting set on startup, and you need to approve default upsides of every such boundary. One can imagine thinking of one experiment for every one of these settings, however with pytest its a lot more straightforward:-

@pytest.mark.parametrize(“setting_name, setting_value”, [(‘qdb_mem_usage’, ‘low’),
(‘report_crashes’, ‘yes’),
(‘stop_download_on_hang’, ‘no’),
(‘stop_download_on_disconnect’, ‘no’),
(‘reduce_connections_on_congestion’, ‘no’),
(‘global.max_web_users’, ‘1000’),
(‘global.max_downloads’, ‘10’),
(‘use_kernel_congestion_detection’, ‘no’),
(‘log_type’, ‘normal’),
(‘no_signature_check’, ‘no’),
(‘disable_xmlrpc’, ‘no’),
(‘disable_ntp’, ‘yes’),
(‘ssl_mode’, ‘tls_1_2’),])

def test_settings_defaults(self, setting_name, setting_value):
assert product_shell.run_command(setting_name) == \
self.”The current value for \’{0}\’ is     \’{1}\’.”.format(setting_name, setting_value), \
‘The {} default should be {}’.format(preference_name, preference_value)

You just composed 13 experiments (each for different setting_value), and in future on the off chance that you add another setting into your item, you should simply, add one more tuple on top.


Using GUI test along with Selenium and API tests

Your item can have numerous connection points like CLI which we examined previously. Then it could be GUI and API as well. Prior to conveying your product piece, testing every one of them is significant. In a venture software where numerous parts are reliant and coupled, change in one section might influence the rests.

Recall pytest is only a framework to work with "testing", not explicit sort of testing. So you can construct your GUI tests with selenium or API tests with Python's solicitations library for instance, and run it with pytest.

  • apiobjects: Great spot for making coverings for summoning API end-focuses. You can have a BaseAPIObject and a determined class to match your necessities
  • helpers: Compose your assistant techniques
  • lib: Library records, which can be utilized by various parts for example your apparatuses in conftest, pageobjects and so forth.
  • pageobjects: PageObjects configuration example can be utilized for making your classes of various GUI pages. We at valid use Webium, which is a Page Item design execution library for Python.
  • suites: You can compose your pylint code confirmation suites here, getting certainty on your code quality would be useful.
  • tests: You can have classified test catalogs in light of the kind of your tests. It makes it simple to oversee and investigate your tests.


Test cases, want to run them in parallel

You might have a lot of experiments in your test suite, and there might be times when you might want to run experiments in parallel and lessen by large test execution time.

Pytest offers a wonderful module to run tests in parallel named pytest-xdist, which expands pytest with with new test execution modes. Install this module utilizing pip as shown below.

pip install pytest-xdist


Pytest accompanies built-in support make result records which can be used by Jenkins, Bamboo or other Continuous Integration servers :-

pytest test/file/path — junitxml=path

This can produce incredible XML style yield, which can be deciphered by numerous CI frameworks parsers.



Pytest's fame is developing consistently. Likewise, it has a wide local area support, which allows you to get sufficiently close to a ton of expansions for example pytest-django, which assists you with composing tests for your Django web applications reconciliation. Keep in mind, pytest upholds running unittest experiments, so assuming that you are utilizing unittest , pytest merits considering for future.

Leave a Comment