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.

Popular Prag Prog topics Top

Razor54672
The answer to 3rd Problem of Chapter 5 (Making Choices) of “Practical Programming, Third Edition” seems incorrect in the given answer ke...
New
jamis
The following is cross-posted from the original Ray Tracer Challenge forum, from a post by garfieldnate. I’m cross-posting it so that the...
New
alanq
This isn’t directly about the book contents so maybe not the right forum…but in some of the code apps (e.g. turbo/06) it sends a TURBO_ST...
New
rmurray10127
Title: Intuitive Python: docker run… denied error (page 2) Attempted to run the docker command in both CLI and Powershell PS C:\Users\r...
New
jeremyhuiskamp
Title: Web Development with Clojure, Third Edition, vB17.0 (p9) The create table guestbook syntax suggested doesn’t seem to be accepted ...
New
Chrichton
Dear Sophie. I tried to do the “Authorization” exercise and have two questions: When trying to plug in an email-service, I found the ...
New
brian-m-ops
#book-python-testing-with-pytest-second-edition Hi. Thanks for writing the book. I am just learning so this might just of been an issue ...
New
creminology
Skimming ahead, much of the following is explained in Chapter 3, but new readers (like me!) will hit a roadblock in Chapter 2 with their ...
New
dtonhofer
@parrt In the context of Chapter 4.3, the grammar Java.g4, meant to parse Java 6 compilation units, no longer passes ANTLR (currently 4....
New
gorkaio
root_layout: {PentoWeb.LayoutView, :root}, This results in the following following error: no “root” html template defined for PentoWeb...
New

Other popular topics Top

AstonJ
If it’s a mechanical keyboard, which switches do you have? Would you recommend it? Why? What will your next keyboard be? Pics always w...
New
dasdom
No chair. I have a standing desk. This post was split into a dedicated thread from our thread about chairs :slight_smile:
New
brentjanderson
Bought the Moonlander mechanical keyboard. Cherry Brown MX switches. Arms and wrists have been hurting enough that it’s time I did someth...
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
Exadra37
I am a Linux user since 2012, more or less, and I always use Ubuntu on my computers, and my last 2 laptops have been used Thinkpads, wher...
New
Exadra37
I am asking for any distro that only has the bare-bones to be able to get a shell in the server and then just install the packages as we ...
New
PragmaticBookshelf
“A Mystical Experience” Hero’s Journey with Paolo Perrotta @nusco Ever wonder how authoring books compares to writing articles?...
New
New
PragmaticBookshelf
Author Spotlight: Peter Ullrich @PJUllrich Data is at the core of every business, but it is useless if nobody can access and analyze ...
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 ❯