Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Writing Faster Django Tests

Writing Faster Django Tests

Vaibhav Mishra

May 17, 2014
Tweet

More Decks by Vaibhav Mishra

Other Decks in Programming

Transcript

  1. "Tests are slow so I am disabling it for a

    while" - Every Developer everywhere # python manage.py test
  2. HOW TO WRITE FASTER TESTS non-trivial code bases have test

    that normally runs in units of seconds ideally your tests should take less then 30 seconds to run, the less the better Developers disable them or not run them because we are not java guys.
  3. HOW 1. Eliminate bottlenecks 2. When can't eliminate - minimize

    it 3. When can't minimize - mock it (not literally)
  4. HOW TO MINIMIZE / ELIMINATE IO Don't test on real

    database when developing. in your settings.py add i f ' t e s t ' i n s y s . a r g v o r ' t e s t _ c o v e r a g e ' i n s y s . a r g v : # C o v e r s r e g u l a r t e s t i n g a n d d j a n g o - D A T A B A S E S [ ' d e f a u l t ' ] = { ' E N G I N E ' : ' d j a n g o . d b . b a c k e n d s . s q l i t e 3 ' } D A T A B A S E S [ ' t a p 2 ' ] = { ' E N G I N E ' : ' d j a n g o . d b . b a c k e n d s . s q l i t e 3 ' } D A T A B A S E S [ ' u s e r s d b ' ] = { ' E N G I N E ' : ' d j a n g o . d b . b a c k e n d s . s q l i t e 3 ' }
  5. USING FASTER DB FOR TESTING SQLITE runs in memory, in

    last slide we instructed django to use sqlite whenever test are run or use your database's in-memory mode.
  6. DISABLE CRYPTOGRAPHY Change order of password hashers it results in

    a huge(upto 4-5x YMMV) test speed bump. i f ' t e s t ' i n s y s . a r g v : P A S S W O R D _ H A S H E R S = ( ' d j a n g o . c o n t r i b . a u t h . h a s h e r s . S H A 1 P a s s w o r d H a s h e r ' , ' d j a n g o . c o n t r i b . a u t h . h a s h e r s . P B K D F 2 P a s s w o r d H a s h e r ' , ' d j a n g o . c o n t r i b . a u t h . h a s h e r s . P B K D F 2 S H A 1 P a s s w o r d H a s h e r ' , ' d j a n g o . c o n t r i b . a u t h . h a s h e r s . B C r y p t P a s s w o r d H a s h e r ' , ' d j a n g o . c o n t r i b . a u t h . h a s h e r s . M D 5 P a s s w o r d H a s h e r ' , ' d j a n g o . c o n t r i b . a u t h . h a s h e r s . C r y p t P a s s w o r d H a s h e r ' , )
  7. MOCKING DB CALLS Use something like python's own mock library

    pip install mock part of standard library in python 3 book = Mock(spec=Book)
  8. A PRIMER ON MOCKING A simple tutorial for mocking <this

    is a placeholder slide to be replaced by actual content later>
  9. TIPS FOR MOCKING IN DJANGO using partials to modify function

    calls patching objects <this is a placeholder slide to be replaced by actual content later>
  10. MAKE IT VISIBLE coverage run python manage.py test Make coverage

    report accessible to your build tools use django-jenkins (for django > 1.6) to generate various reports