brunogirin

brunogirin

Python Testing with pytest, Second Edition: explain the rationale behind the change in the fixture code (pages 143, 144)

In the “Testing at Multiple Layers to Avoid Mocking” section, the code for the cards_db fixture changes. In previous chapters, it was something like:

@pytest.fixture(scope="session")
def db(tmp_path_factory):
  """CardsDB object connected to a temporary database"""
  db_path = tmp_path_factory.mktemp('cards_db')
  db_ = cards.CardsDB(db_path)
  yield db_
  db_.close()

@pytest.fixture(scope="function")
def cards_db(db, request, faker):
  """CardsDB object that's empty"""
  db.delete_all()
  return db

When we reach this section, it changes to:

@pytest.fixture(scope="module")
def db_path(tmp_path_factory):
  db_path = tmp_path_factory.mktemp("cards_db")
  return db_path

@pytest.fixture()
def cards_db(db_path, monkeypatch):
  monkeypatch.setenv("CARDS_DB_DIR", str(db_path))
  db_ = cards.CardsDB(db_path)
  db_.delete_all()
  yield db_
  db_.close()

Explaning this code change could introduce some important testing concepts that junior developers may struggle with. By adding the monkeypatch.setenv line, you ensure that the high level API via the cards_db package will point to the same database as the one created manually via the cards.CardsDB class. This is necessary because your tests operate at two different levels at the same time. It might be useful to show it failing if you don’t set the environment variable and explain why.

This also introduces an important concept about how you design your tests. As mentioned elsewhere in the book, tests are meant to be independent and you need to ensure you know what they’re testing. One way this is often done is by designing tests such that the “When” part of the test is the only part that exercises the code under test (in this case, the cards_db package) while the “Given” and “Then” parts of the test are kept independent of the code under test. This way you know exactly what the “When” part is testing. However, when designing your tests that way, it means the “When” part is acting against a different layer from the “Given” and “Then” parts and you need to ensure those layers are configured the same.

This test design point introduces another point about making your app easily testable. In the case of the CardDB app, the fact that its main configuration option can be set via an environment variable is what makes this code possible.

Finally, this raises a point about test strategy. When I see code like this in my own projects, I immediately add a simple test suite to validate that the configuration options are properly handled. If those tests fail in the future, it is likely that a lot of other tests will fail in cascade. I typically set a special mark on those such as @pytest.mark.canary so if I suddently have a lot of tests failing, I check the canary ones first and make sure they are fixed as a priority on the basis that if those fail, a lot of others will fail too.

Apologies for such a complex and long-winded comment on this small change. When I started asking myself “why?” repeatedly when seeing that code change, I realised that there were a lot of logic behind that change that is natural to an experienced tester but not to a junior one. I don’t know if this would be better explained as an addition to this chapter, an aside, or any other form but I feel that it would be worthwhile to explain the rationale behind this code change.

First Post!

brianokken

brianokken

Author of Python Testing with pytest

Thanks for the feedback

Popular Pragmatic topics Top

jeffmcompsci
Title: Design and Build Great Web APIs - typo “https://company-atk.herokuapp.com/2258ie4t68jv” (page 19, third bullet in URL list) Typo:...
New
mikecargal
Title: Hands-On Rust (Chap 8 (Adding a Heads Up Display) It looks like ​.with_simple_console_no_bg​(SCREEN_WIDTH*2, SCREEN_HEIGHT*2...
New
herminiotorres
Hi @Margaret , On page VII the book tells us the example and snippets will be all using Elixir version 1.11 But on page 3 almost the en...
New
herminiotorres
Hi! I know not the intentions behind this narrative when called, on page XI: mount() |> handle_event() |> render() but the correc...
New
Charles
In general, the book isn’t yet updated for Phoenix version 1.6. On page 18 of the book, the authors indicate that an auto generated of ro...
New
akraut
The markup used to display the uploaded image results in a Phoenix.LiveView.HTMLTokenizer.ParseError error. lib/pento_web/live/product_l...
New
Henrai
Hi, I’m working on the Chapter 8 of the book. After I add add the point_offset, I’m still able to see acne: In the image above, I re...
New
EdBorn
Title: Agile Web Development with Rails 7: (page 70) I am running windows 11 pro with rails 7.0.3 and ruby 3.1.2p20 (2022-04-12 revision...
New
redconfetti
Docker-Machine became part of the Docker Toolbox, which was deprecated in 2020, long after Docker Desktop supported Docker Engine nativel...
New
dachristenson
@mfazio23 Android Studio will not accept anything I do when trying to use the Transformations class, as described on pp. 140-141. Googl...
New

Other popular topics Top

Devtalk
Hello Devtalk World! Please let us know a little about who you are and where you’re from :nerd_face:
New
AstonJ
You might be thinking we should just ask who’s not using VSCode :joy: however there are some new additions in the space that might give V...
New
foxtrottwist
Here’s our thread for the Keyboardio Atreus. It is a mechanical keyboard based on and a slight update of the original Atreus (Keyboardio ...
New
Margaret
Hello content creators! Happy new year. What tech topics do you think will be the focus of 2021? My vote for one topic is ethics in tech...
New
AstonJ
Saw this on TikTok of all places! :lol: Anyone heard of them before? Lite:
New
First poster: bot
The overengineered Solution to my Pigeon Problem. TL;DR: I built a wifi-equipped water gun to shoot the pigeons on my balcony, controlle...
New
First poster: bot
Large Language Models like ChatGPT say The Darnedest Things. The Errors They MakeWhy We Need to Document Them, and What We Have Decided ...
New
PragmaticBookshelf
A Ruby-Centric Chat with Noel Rappin @noelrappin Once you start noodling around with Ruby you quickly figure out, as Noel Rappi...
New
New
AstonJ
This is cool! DEEPSEEK-V3 ON M4 MAC: BLAZING FAST INFERENCE ON APPLE SILICON We just witnessed something incredible: the largest open-s...
New

Latest in PragProg

View all threads ❯