Organizing your Django test codebase * 5 key ingredients for making testing a solution instead of a problem * Achieving fluency * How mocking works * Good tests require good code
or make the least possible •Hard to write if you are testing existing code that is coupled, macaroni •Reasonably easy to write if you are testing existing code that is already decoupled •Easy to write if you writing code from scratch with TDD •Here is were you might use mocks most part of the time
are not allowed to write any production code unless it is to make a failing unit test pass. •You are not allowed to write any more of a unit test than is sufficient to fail; and runtime errors are failures. •You are not allowed to write any more production code than is sufficient to pass the one failing unit test. Uncle Bob Martin, 2005 Easy to write if you writing code from scratch with TDD
not to outreach 3rd party resources •Slow •Still shouldn’t depend on 3rd party resources •Most part of the time you don’t need mocks •Unless you need to isolate 3rd party resources •Intense database usage
provide ” “a much better feedback”) assert True, “:)” Any module-level classes that begin with “Test” is instantiated by nose, then all the methods containing with “test” will be found and run
try: get_deal_by_id(5) raise AssertionError(“calling get_deal_by_id(5) “ ”should have raised but didn’t”) except Deal.DoesNotExist, e: assert unicode(e) == “Deal with id 5 does not exist”, ... Old school:
assert that(get_deal_by_id, with_args=(5,)).raises(Deal.DoesNotExist) Sure: get_deal_by_id.when.called_with(5).should.throw( Deal.DoesNotExist, "Deal with id 5 does not exist", ) or
mocks and your test becomes hard to undersdand: isolate your code •If it's too hard to setup your test, your production code is doing too much, isolate it! •In the end of the day, if still can't mock your code you have to do refactoring!
mocks and your test becomes hard to undersdand: isolate your code •If it's too hard to setup your test, your production code is doing too much, isolate it! •In the end of the day, if still can't mock your code you have to do refactoring!
PyQuery You call urls with: import sure from django.test.client import Client from lxml import html http = Client() dom = html.fromstring(http.get(“/deals/ny.html”).content) dom.cssselect(“section.deal”).should.have.length_of(100)
= Browser() # Visit URL url = "http://www.google.com" browser.visit(url) browser.fill('q', 'splinter - python acceptance testing for web applications') # Find and click the 'search' button button = browser.find_by_name('btnG') # Interact with elements button.click() if browser.is_text_present('splinter.cobrateam.info'): print "Yes, the official website was found!" else: print "No, it wasn't found... We need to improve our SEO techniques"