Having The Discipline To Write Tests

April 15, 2024 • 3 minute read
PythonTestingTDDSeleniumPytest

I have a real apprehension with writing tests for my code. My feeling has always been something that doesn't add end user functionality or utility to the underlying logic ends up causing issues for me as I am not spending time fleshing out features or refactoring code. This ends up biting me in the ass, where bad code gets into an application breaking everything or parts of it. So this just causes issues for the end user and me while I am stressing to find a quick fix, which can also snowball as bad patches come out in that progression.

Finding a balance in that I start writing tests giving myself space to explore new features more effectively. Finding ways that make the bridging to full on testing is important here. Even though I have written tests for most applications now; I still find gaps in those methods and edge cases keep creeping in. Scope is a big issue here as my planning mostly comes in broad strokes, so my tests end up being broad, so for example I end up testing if the pages load and some other smaller unit test.

Basic response code test from this site.:

@pytest.mark.parametrize(
    "url",
    [
        "/",
        "/about/",
        "/projects/",
        "/blog/",
        "/robots.txt",
        "/sitemap.xml",
    ],
)
@pytest.mark.django_db()
@pytest.mark.usefixtures("_generate_db_content")
def test_page_loads(url, db):
    client = Client()
    response = client.get(url)
    assert response.status_code in VALID_STATUS_CODES

Even though I think myself as having pre-planned a lot, most things happen on the fly for me, so even though I might write some sort of unit tests I will tack them on, as long as they give me that positive indication. This might be indication of experience though as my vision for an end product might be skewed due too not knowing the full scope of a piece of software. As I build more and more though the experience does come in and I find it easier to plan beforehand and therefore pre-test these cases

Luckily writing this in 2024 there are a lot of solutions around especially in the Python ecosystem with the core Unittest module or Pytest originating from 2003, but these are aimed at testing core functionality mostly, so find ways to test UI/UX is a bit harder and more ominous. Selenium definitely helps there which can be combined with some effective integration tests in order to gather a decent amount of coverage.

This will come over time as I get used to the development flow in the future. Finding more ways of integrating procedures in order to keep my code in working order. While writing good tests I found that it gave me peace of mind, since it was another thing that I could worry about less.