Menu

pytest fixtures: shared setup, fresh state and guaranteed cleanup
📰

pytest fixtures: shared setup, fresh state and guaranteed cleanup

DEV Community: python·Hasib Ahmed·1 day ago
#UCjIIcV9
#devtopython#devto#dev#cart#test
Reading 0:00
15s threshold

If your pytest files start with the same four lines of setup in every test, you are paying for it twice: once in reading, and again every time the setup changes. Fixtures fix both. This post walks through the core of them with one small shopping cart, including the part people skip: cleanup with yield .

The problem

Here is a small cart, shop.py :

DISCOUNTS = { }

def register_discount ( code , percent ) : DISCOUNTS [ code ] = percent

def remove_discount ( code ) : del DISCOUNTS [ code ]

class Cart : def __init__ ( self ) : self . lines = [ ]

def add ( self , name , price , quantity = 1 ) : if quantity < 1 : raise ValueError ( f "quantity must be at least 1: {quantity}" ) self . lines . append ( ( name , price , quantity ) )

def total ( self , code = None ) : amount = sum ( price * quantity for _ , price , quantity in self .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.