van Heemstra Systems.GitHub.io

van Heemstra Systems - Github io

View on GitHub

Step 3 - Coding: calculator

Following Test-Driven Development (TDD) principles, we'll now code the software for the calculator software system.

For the purpose of demonstration, we use different programming languages to achieve the same goal.

Step 3.1 - Coding in C#: calculator

Link

Step 3.2 - Coding in Java: calculator

Link

Step 3.3 - Coding in JavaScript: calculator

Link

Step 3.4 - Coding in Python: calculator

Link

GitHub

As we created a repository called 'calculator' at the start of our use case, we will now create a branch for our code in Python, as follows.

cd calculator
git branch python

Next, change our current branch to the 'python' branch.

git checkout python

From here on we will add and edit code for python in this python branch, in a newly created directory called python.

mkdir python
cd python

To see if Python is installed, type the below on your command line.

py -v

To see if PyTest is installed, type the below on your command line.

pytest -v

If not already installed, install pytest as follows

pip3 install pytest

Create a file `calculator.py` with the following content:

# calculator.py

class Calculator(object):
    def __init__(self, message = 'Hello World!'):
        self.message = message

Add the new file to git:

git add calculator.py

Create a file `test_calculator.py` with the following content:

# test_calculator.py
    
import unittest

from calculator import Calculator

class CalculatorTestCase(unittest.TestCase):
    def setUp(self):
        self.calculator = Calculator()

    def test_message(self):
        self.assertEqual(self.calculator.message, 'Hello World!', msg='Message Invalid.')

Add the new file to git:

git add test_calculator.py

Create a file '.gitignore' with the following content:

__pycache__
*.py[cod]
.DS_Store

Add the new file to git:

git add .gitignore

Run

pytest test_calculator.py
and PyTest will print a message alike this:

============================= test session starts =============================
platform win32 -- Python 3.5.2, pytest-3.4.0, py-1.5.2, pluggy-0.6.0
rootdir: C:\Users\user\Source\Repos\vanHeemstraSystems\calculator\python, inifile:
collected 1 item

test_calculator.py .                                                     [100%]

========================== 1 passed in 0.48 seconds ===========================

Commit your changes:

git commit -m "first unit test"

And push your changes back to the 'python' branch

git push --set-upstream origin python

Check the status to verify that all has been committed:

git status

You just successfully wrote your first test using PyTest!

more to follow...