This doth be a machine-wrought text which may contain errors!
The Art of Proving Truths by Means of Tests
Now that we have forged our Classes and labored with Validation, a firm foundation is laid to commence upon the Trial. This proving is but an essential part of the craft’s progression, aiding us to ensure that our Code performs as it ought.
For how may one possess certainty that the Code serves its purpose, if ‘tis never subjected unto test?
What is Unit Testing?
Unit Testing ‘tis a method to assay and probe our code’s small parts with automation and order. In Python we employ a module named pytest to pen and execute these trials. A “unit” is that which may be tested of least measure within an application, oftentimes but a single function or method it shall be. When one useth pytest, ‘twas most importunate that we do observe the proper nomenclature, lest the tests remain unfound by pytest; such as to prefix thy files with test_, and likewise thine functions with test_.
An example of a unit test:
def test_add():
assert 0.3 + 0.3 + 0.3 == 0.9
Executed by typing pytest into the terminal.
A curious truth
The cipher above shall fail, for in Python, .3 + .3 + .3 becomes nought point eight nine nine nine nine nine nine nine nine naught!
Task I - Install pytest
Install thou pytest within thy virtual environment. This is to be done by executing the following command in the terminal:
pip install pytest
Task Two - Forge a Trial
Create anew a file within thy project’s domain, naming it test_data.py. Within this scroll thou shalt devise a trial for the Person class which thou didst craft in the prior module. This trial shall verify that a Person may be conjured with values of good repute.
An exemplar of how such a trial might appear:
from main import Person
def test_person_working():
bob_kaare = Person(name="Bob Kåre",
eye_color=EyeColor.BLUE,
phone_number=PhoneNumber("12345678"),
email=Email("bob_kaare@example.com"))
assert bob_kaare.name == "Bob Kåre"
assert bob_kaare.eye_color == EyeColor.BLUE
This manner of proving is named “happy path” proving, for we doth test that all things work as they ought when valid values are given, yet it serveth but little purpose.
Task III - Trial of Validation
Forge manifold trials within test_person.py which shall verify that the validation in Email and PhoneNumber performeth their duty aright. Thou shalt test both lawful and unlawful values herein. Herein thou must employ a function in pytest named raises, which checketh if a certain error is cast forth.
import pytest
def test_exception():
with pytest.raises(KeyError):
my_dict = {"a": 1, "b": 2}
value = my_dict["c"] # This shall 'raise' a KeyError
Tip
Thou mayst forge as many functions as thy heart desires, so long as their name doth commence with test_.
Solution: An example of a trial for an invalid mail address
from main import Email
import pytest
def test_invalid_email():
with pytest.raises(ValueError):
email = Email("not-an-email")
For What Purpose to Perform This Deed?
By possessing sound trials upon our craft, we may rest assured that it performeth its duty with fidelity, and we shall swiftly discern if aught hath gone amiss when alterations are wrought within the code. This is of paramount import in grander undertakings, wherein many artisans toil in concert, and ‘tis but too easy for error to creep into the work.
Video: For What Cause Do Tests Guard Thy Code Against Fresh Errantry
This moving image doth expound upon why trial is of great import, and how automated assays may unmask blemishes after alterations within the code.
By employing such instruments as Jest or Selenium, one may put webpages to assay without manual toil, thereby ensuring that all things function as they ought following each change in the code. Surely we desire to know that “user registration,” “payment,” and “login” work as intended, have ye not?
Ponder these scenarios most carefully
What befalls (or shall befall) if..:
- A user doth attempt to register with an email already in use?
- A user hath a date of birth yet to come?
- A user who inscribeth the name “jOHN dOE”?
Task IV - Automated Trial (CI)
When we publish our code upon GitHub, then mayst thou set up a thing named GitHub Actions which can runne our tests of its own accord each time ye make alteration to the code. This is called Continuous Integration (CI), and it aideth us to assure that our code doth ever function as it ought.
Make a file within thy project folder bearing the name .github/workflows/pytest.yml. Within this file, thou shalt add the following code:
name: Pytest
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pytest
# Doth thou procure such sundries as thy venture requireth?
pip install -r requirements.txt
- name: Run tests with pytest
run: pytest
If thou hast set it forth in due manner, lo! a new tab shall appear within thy GitHub repository, bearing the name “Actions.” Therein shalt thou behold thine tests being run automatically each time thou makest an alteration to the code, and tidings shall come unto thee should any of the tests fail (a red cross and by means of electronic post).
A Remark upon File Structure
Thy file structure shall determine if GitHub Actions doth function or naught thereof. Ensure that the .github folder resteth in the root of thy project, and likewise a tests folder wherein thine test files abide.
Thou mayest alter the pytest.yml file to point unto the right folder.
Suche Actions files may also serve to trial thy code upon sundry versions of Python or operating systems; they can likewise be employed to build and publish thy software with ease, for instance, to release a website unto the world, or to refresh an application in the App Store or Google Play.
Code Coverage
There existeth likewise that which is named “Code Coverage,” wherewith thou mayest discern how much of thy code is in truth tested. ‘Twould be of great use to know if thou hast sufficent tests, or if there be portions of thine art untested altogether.
Certain masters do require that a certain proportion of thy code be covered by trials ere it be deployed, to ensure the same is stout and performeth as it ought.

