DRY vs DAMP in unit tests

Looping through endpoints isn’t bad thing …. or is it?

Tl:Dr — DRY for production code, sometimes ok in test code, but DAMP is preferrable.

(Disclaimer: Since I use Python 3 & Django on a daily basis i’ll be using snippets from them as examples.)

Nope.

Well, theoretically (i thought) yes. We just don’t want to repeat whatever bad smell we can find. But as it turns out, this is not always the case and it depends on use cases. One day i ran into a failing test that spat out the below error message:

Which view is failing & passing? Dunno because the message is ambiguous..
Loops through a list of endpoints. Can be 3, 9 or even 20 for all we know ..
A long list of dictionarys contaning our endpoints & expected status codes..
A test that loops through a list of views via GET request.

Solution

I asked my boss during a 1:1 meeting about my struggle with this. He suggested the DAMP approach. In a nutshell, use DRY for production code but DAMP is actually ok in unit tests. Because it doesn’t affect your code base at all and you really just want to test something like our views while also making it readable and easier to debug.

Separated test case for all views using DAMP approach.

So when is DRY acceptable in unit tests?

I’m going to take this example from here because it perfectly demonstrates (in my opinion) when DRY is good.

Loops through all 4xx status codes and checks errors return true
Line 2 perfectly tells you which status code had failed.

Questions? disagree?

Lemmi know. I’m actively learning new ways to improve the quality of my code for the convenience of my peers also and anytime I can be proven wrong is a big win for me too.

References:

What does “DAMP not DRY” mean when talking about unit tests?

Full-Stack Engineer, at one time also officially labelled “Professional Badass”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store