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

Testing Django applications with py.test (EuroP...

Testing Django applications with py.test (EuroPython 2013)

Andreas Pelme

July 05, 2013
Tweet

More Decks by Andreas Pelme

Other Decks in Programming

Transcript

  1. from  django.test  import  TestCase class  TestHelloWorld(TestCase):        def

     test_hello_world(self):                response  =  self.client.get('/hi/')                self.assertEqual(response.status_code,                                                  200)                self.assertEqual(response.content,                                                  'Hello  World!') fredag 5 juli 13
  2. def  test_hello_world(client):        response  =  client.get('/hi/')    

     assert  response.status_code  ==  200      assert  response.content  ==  'Hello  World!' fredag 5 juli 13
  3. def  test_hello_world(client):        response  =  client.get('/hi/')    

     assert  response.status_code  ==  200      assert  response.content  ==  'Hello  World!' fredag 5 juli 13
  4. $  py.test F ===================  FAILURES  ==================== _______________  test_hello_world  ________________ client

     =  <django.test.client.Client  object  at   0x1065f58d0>    def  test_hello_world(client):          response  =  client.get('/hi/')          assert  response.status_code  ==  200 >        assert  response.content  ==  'Hello  World!' E        assert  'Hello  EuroPython!'  ==  'Hello  World!' E            -­‐  Hello  EuroPython! E            +  Hello  World! test_hello_world.py:5:  AssertionError fredag 5 juli 13
  5. assertAlmostEqual assertAlmostEquals assertDictContainsSubset assertDictEqual assertEqual assertEquals assertFalse assertGreater assertGreaterEqual assertIn

    assertIs assertIsInstance assertIsNone assertIsNot assertIsNotNone assertItemsEqual assertLess assertLessEqual assertListEqual assertMultiLineEqual assertNotAlmostEqual assertNotAlmostEquals assertNotEqual assertNotEquals assertNotIn assertNotIsInstance assertNotRegexpMatches assertRaises assertRaisesRegexp assertRegexpMatches assertSequenceEqual assertSetEqual assertTrue assertTupleEqual fredag 5 juli 13
  6. from  datetime  import  datetime,  time from  django.http  import  HttpResponse def

     greet(request):        now  =  datetime.now().time()        if  time(5)  <  now  <  time(12):                greeting  =  'morning'        elif  time(18)  <  now  <  time(21):                greeting  =  'evening'        else:                greeting  =  'day'        return  HttpResponse('Good  %s!'  %  greeting) fredag 5 juli 13
  7. from  datetime  import  datetime,  time from  django.http  import  HttpResponse def

     greet(request):        now  =  datetime.now().time()        if  time(5)  <  now  <  time(12):                greeting  =  'morning'        elif  time(18)  <  now  <  time(21):                greeting  =  'evening'        else:                greeting  =  'day'        return  HttpResponse('Good  %s!'  %  greeting) fredag 5 juli 13
  8. #  greeter.py from  datetime  import  time def  greeting_at(time_of_day):    

       if  time(5)  <  time_of_day  <  time(12):                return  'morning'        elif  time(18)  <  time_of_day  <  time(21):                return  'evening'        else:                return  'day' fredag 5 juli 13
  9. #  views.py from  datetime  import  time from  django.http  import  HttpResponse

    from  .greeter  import  greeting_at def  greet(request):        now  =  datetime.now().time()        greeting  =  greeting_at(now)        return  HttpResponse('Good  %s!'  %                                                greeting) fredag 5 juli 13
  10. ___________  test_user_count  ____________ test_db_access.py:4:  in  test_user_count >      assert

     User.objects.count()  ==  0 ...  snip  ... E      Failed:  Database  access  not  allowed,        use  the  "django_db"  mark  to  enable fredag 5 juli 13
  11. %KBOHPpYUVSFT [{"model": "myapp.person", "pk": 1, "fields": {"first_name": "John", "last_name": "Lennon"}},

    {"model": "myapp.person", "pk": 2, "fields": {"first_name": "Paul", "last_name": "McCartney"}} ] Slow & hard to maintain.. avoid them! fredag 5 juli 13
  12. from  django.db  import  models class  Group(models.Model):        name

     =  models.TextField() class  Person(models.Model):        first_name  =  models.TextField()        last_name  =  models.TextField()        group  =  models.ForeignKey(Group)        def  group_letter(self):                return  self.group.name[0].upper() fredag 5 juli 13
  13. import  factory from  yourapp.models  import  Person,  Group class  GroupFactory(factory.Factory):  

         FACTORY_FOR  =  Group        name  =  'Developers' class  PersonFactory(factory.Factory):        FACTORY_FOR  =  Person        first_name  =  'John'        last_name  =  'Doe'        group  =  factory.SubFactory(GroupFactory) fredag 5 juli 13
  14. from  yourfactories  import  PersonFactory def  test_group_letter():        person

     =  PersonFactory.build(                group__name='admins')        assert  person.group_letter()  ==  'A' fredag 5 juli 13
  15. import  pytest @pytest.mark.django_db def  test_group_letter():        person  =

     PersonFactory.create(                group__name='admins')        assert  person.group_letter()  ==  'A' fredag 5 juli 13
  16. 3FRVFTU%KBOHPEBUBCBTFBDDFTT JOBpYUVSF import  pytest from  your_factories  import  UserFactory @pytest.fixture def

     person_in_db(db):        return  PersonFactory.create() fredag 5 juli 13
  17. (SFBUSFTPVSDFT w $BSM.FZFS 5FTUJOHBOE%KBOHP 1Z$PO w %KBOHPUFTUJOHCFTUQSBDUJDFTBOEJOTQJSBUJPOGPSUIJTUBML w IUUQXXXZPVUVCFDPNXBUDI WJDL/2D/9J4

    w )PMHFS,SFLFM QZUFTUSBQJEBOETJNQMFUFTUJOHXJUI1ZUIPO  &VSP1ZUIPO w IUUQXXXZPVUVCFDPNXBUDI WL;+)6N;9. w QZUFTUEPDVNFOUBUJPO w IUUQQZUFTUPSH w QZUFTUEKBOHPEPDVNFOUBUJPO w IUUQQZUFTUEKBOHPSFBEUIFEPDTPSH fredag 5 juli 13