Test-Driven Development with PyTest - Part 1
Tags: python, startup, career, beginners
Published: 2019-09-29 13:39:45

# Introduction
This will be a 3 part series for anyone who is looking to get up to speed and integrate TDD testing practices using Pytest. 

When I first started to learn about TDD, it was one of my software engineering classes at University. 

The professor was introducing TDD through the use of **JUnit** which back then I find it was a pain to set up and configure. 

Plus not seeing the value of having it as a developer practice. I just chuck it away as a good to have skill but not necessarily used during software development.

# Change in Perception
It was my frustration to debug my code whenever I encounter an error in my code which leads me to TDD. 

I would need to constantly understand what was wrong with the code which could take a few hours for me to look for bugs in my program.

Then manually testing it before committing it to **git** to fix the bug in my code. 

Thus I sought a better way to make my debugging live easier by incorporating TDD.

Slowly but surely I started to learn about TDD through reading books like [Clean Code][1] and [Test-driven development with Python][2], [Python Testing with PyTest][3].

My knowledge has grown and was further reinforced through working with other developers on code kata through JuniorDev SG's Developer Gym.

# What is PyTest?
[Pytest][4] is a testing framework. 

It reduces the amount of boilerplate code needed to create test cases.

Compared to the default testing framework that is bundled with Python, it is much easy to learn. 

Which was called [Unittest][5] that is designed based upon **JUnit** testing framework in Java.

# Setup and Configuration
Ok before we start creating test cases we need to set up the **virtual environment** & installing **pytest** to get started.

## Setup Virtual Environment 
First, we need to install the **pip** package called `virtualenv`. 

I assume you are using a Linux based system or an online cloud IDE  from websites like [REPL][6].

You are encouraged to proceed if you had installed the `virtualenv` and created a virtual environment called `venv` in your terminal:

```bash
pip install virtualenv
```

Now, once you had installed the `virtualenv` package through `pip`. You need to create a folder called `tutorial` and create a virtual environment called `venv` in your terminal:

```bash
mkdir tutorial
cd tutorial/
virtualenv venv
```

Once you had created the virtual environment, you need to **enable** the newly created virtual environment by entering the following command for Linux using your terminal:

```bash
source venv/bin/activate
```

## Installing PyTest
Now let's install the **PyTest** testing framework in your virtual environment within your folder called `tutorial` in the terminal:

```bash
pip install pytest
```

Great, once you had installed pytest, you can type the following to test if your pytest is working in the terminal:

```bash
pytest
```

You should see something similar to this once PyTest is successfully installed. 

![pytest 1][7]

Congrats in installing `Pytest` into your project. Take a chill pill and let's continue to write your first test case.

# Writing Your First Test Case
Alright, welcome back!!!  I will start you off by having you to create your first test case in pytest.

But first, we should create a file called `test_tutorial.py`:

```bash
touch test_tutorial.py
```

By default, pytest recognises test files when it starts with `test_something.py`.

Now we shall create a test case called `test_return_sum` to test the `return_sum` function:

```python
def test_return_sum():
    c = return_sum(1, 4)

    assert c == 5

``` 

Now let's run the following command in your terminal.

```bash
pytest
```

You will notice that the output will have a **F** beside `test_tutorial.py`. 

![pytest 2][8]

The `F` means that a test case has failed, which is the test case called `test_return_sum`.

A great thing about PyTest is that it provides helpful output on how to refactor the code.

Which for this case, it is the error by just defining a `return_sum` function. Let us make it pass by defining `return_sum` function:

```python
def return_sum(a, b):
    return a+b

```

Now run the `pytest` command again in your terminal to see if the test case passes.

![pytest 3][9]

You will notice that in the output it will show a `.` instead of the previous `F` beside the `test_tutorial.py`.

The `.` means that the test case has passed since you had fulfilled the test requirement for it to pass. 

Congrats you had first written your first test case in pytest!!!!

![Congrats](https://media.giphy.com/media/xT0xezQGU5xCDJuCPe/giphy.gif)

# Conclusion
I hope the article has been useful in getting you started to use Pytest. 

The Pytest framework is actually quite extensive and we had barely scratched the surface of it. 

I will start drill down on the various ways or tricks to use pytest and incorporating the use of TDD in my part 2 and 3 of this series.

If you like my article, please **sign up** for Max [Adventurer's Newsletter](http://eepurl.com/dOUoUb) for awesome content I stumble across weekly in **Python**, **Startup** and **Web Development**.

You can also **follow** me to get the **latest** update of my article on **Dev**


This post was originally posted on Max's blog at [Test Driven Development with PyTest - Part 1](https://www.maxongzb.com/test-driven-development-with-pytest-part-1-read-time-4-mins/) and [Photo by Hans-Peter Gauster on Unsplash](https://unsplash.com/photos/3y1zF4hIPCg)

# Reference
* [Clean Code][1]
* [Test-driven development with Python][2]
* [Python Testing with PyTest][3]
* [Pytest][4]
* [Unittest][5]
* [REPL][6]
* [Test Driven Development with Pytest][10]
* [Python Virtual Enviroments][11]


[1]: https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882
[2]: https://www.amazon.com/Test-Driven-Development-Python-Selenium-JavaScript/dp/1491958707/ref=sr_1_1?keywords=test+driven+development+with+python&qid=1569738168&s=books&sr=1-1
[3]: https://www.amazon.com/Python-Testing-pytest-Effective-Scalable/dp/1680502409/ref=sr_1_2?keywords=test+driven+development+with+python&qid=1569738187&s=books&sr=1-2
[4]: https://docs.pytest.org/en/latest/
[5]: https://docs.python.org/3.6/library/unittest.html
[6]: https://repl.it/
[7]: //images.ctfassets.net/ly2f59p4unnn/7heWRz6eFlRvWNrA48wg0U/878caaac150f04219996442e08ef53ed/pytest_1.png
[8]: //images.ctfassets.net/ly2f59p4unnn/79SiWOsinyS837Ffj4usuF/6815d6c590a34d8d298fa535ef6abe1f/pytest_2.png
[9]: //images.ctfassets.net/ly2f59p4unnn/6ogFgYfOLTA4TDoKGenK3D/d4151a1cbb93840a2c42f5299f41a065/pytest_3.png
[10]: https://stackabuse.com/test-driven-development-with-pytest/
[11]: https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/