3. Pytest Test Framework

Ali Pala
3 min readOct 26, 2019

--

It is the third story of “Building a Hybrid Test Automation Framework”. You can find the previous blogs here.

In this story, I will teach you how to use pytest in your test. If you are trying to create a Selenium test, I would highly recommend using a testing framework. This story helps you understand the following.

  1. What is pytest?
  2. Installation,
  3. Syntax,
  4. Writing test with pytest.

1. What is pytest exactly?

Although there is a quite simple definition in pytestwebsite, I’d like to make a more simple definition for you. pytest is a mature full-featured Python testing tool that helps you write better programs. The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries. Nowadays, pytest is mainly used for API testing but we will use pytest to write functional GUI test with Selenium.

2. Installation

To start the installation of pytest, execute the following command in your command line.

pip install -U pytest

Once the installation is done, confirm the installation of the correct version.

py.test -h

If you see the pytest help, that’s it! Your installation is done!

3. Syntax

  1. As a convention, the python file names should start with “test” liketest_login.py.
  2. The class names also should start with “Test”, asTestLogin. The class should not have an __init__ method.
  3. Test method names should start with “test_”, as well. For example,test_login_success(). If you do create a method without this rule, your method doesn’t match the convention and won’t be considered as a test. Of course, won’t be executed :)

4. Writing test with pytest

Now, we are ready to start writing a test. Create a directory that our pytest file is located in. And then, create a python file named test_sample.py.Don’t forget the installation of the pytest before using it. You can Let’s write a function sum_two() takes two arguments num1 and num2 and returns their sum. We can now write our first test to verify this function. Here is the final looks of test_sample.py.

To run this test, go to the directory which you created before and put the test_sample.py file and execute this command: pytest test_sample.py.After running this command, the output will be seen below.

pytest -v test_sample.py “-v” (verbose) option provides more info about the test run. As you can see, one test is passed, one test is failed because the sum of the 2 and 5 is not equal to 10.

Here is a code snippet that we used in our framework while trying to login to the system. We will take a look closer later on. Please be patient :)

That’s a summary to understand the writing simple test. You can also find very nice details in this link or pytest official site. Let’s continue with the next blog. See you there!

--

--

Ali Pala

Entrepreneur, Quality Coach, AI Enthusiast, Public Speaker, Trainer, Dad