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

PyCon Russia 2018 — Unit Testing

PyCon Russia 2018 — Unit Testing

Vadim Pushtaev

July 23, 2018
Tweet

More Decks by Vadim Pushtaev

Other Decks in Programming

Transcript

  1. Гибкие параметры def create(dt=None): if dt is None: dt =

    datetime.now() def download(requests_lib=None): if requests_lib is None: requests_lib = requests class Downloader: def __init__(self, config, logger): self._config = config self._logger = logger 18/34
  2. 19/34 mock from unittest import mock requests_lib = mock.MagicMock() requests_lib.get.return_value.status_code

    = 404 @mock.patch('that.module.requests') def test_download(self, requests_lib): requests_lib.get.return_value.status_code = 404
  3. Данные в базе Копия реальной базы Слепок реальной базы Вручную

    подготовленные данные Пустая база Фабрики 28/34
  4. factory_boy import factory from . import models class UserFactory(factory.django.DjangoModelFactory): class

    Meta: model = models.User first_name = factory.Sequence( lambda n: 'User #{}'.format(n) ) group = factory.SubFactory(GroupFactory) 29/34 user = UserFactory()
  5. def setUp(self): super(BaseTestCase, self).setUp() self._patchers = { 'etcd': patch('common.utils.etcd.Etcd.write'), 'celery':

    patch('celery.current_app.send_task'), } self._patchers['etcd'].return_value = None self._patchers['celery'].return_value = True for patcher in self._patchers.values(): patcher.start() � Patchers 31/34
  6. @BaseTestCase.cases( ( 'dst', pytz.timezone('Europe/Moscow'), DT.utc(2011, 3, 27, 6, 12, 23),

    # 10:12:23 (MSD) datetime.date(2011, 3, 27), ), ( 'no_dst', pytz.timezone('Europe/Moscow'), DT.utc(2016, 2, 7, 23, 43, 12), # 02:43:12 (MSK) datetime.date(2016, 2, 8), ), ) def test_date_of_time(self, timezone, dt, date): self.assertEqual(DT.date_of_time(dt, timezone), date) 33/34 Таблицы результатов https://bit.ly/2NvZdUT
  7. def count_german_letters(self): return len([ x for x in self._string if

    self._is_german_letter(x) ]) def delete_german_letters(self): return ''.join( x for x in self._string if not self._is_german_letter(x) ) def _is_german_letter(self, c): return c in string.ascii_lowercase or c in 'ÄäÖöÜü ß'