Files @ 437ecfe6dd16
Branch filter:

Location: rattail-project/rattail/rattail/tests/importing/test_handlers.py

Lance Edgar
More tweaks for new importer framework

* Fix bug where some args weren't passed from command to handler
* Add new `ToRattailHandler` for convenience
* Add `ImportHandler.commit_partial_host` flag and logic
* Add `Importer.empty_local_data` flag and logic
* Fix bug where `Importer.delete` flag was ON by default
* tests for hopefully everything relevant..
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# -*- coding: utf-8 -*-

from __future__ import unicode_literals, absolute_import

import datetime
import unittest

import pytz
from sqlalchemy import orm
from mock import patch, Mock
from fixture import TempIO

from rattail.db import Session
from rattail.importing import handlers, Importer
from rattail.config import RattailConfig
from rattail.tests import RattailTestCase
from rattail.tests.importing import ImporterTester
from rattail.tests.importing.test_importers import MockImporter
from rattail.tests.importing.test_postgresql import MockBulkImporter


class TestImportHandler(unittest.TestCase):

    def test_init(self):

        # vanilla
        handler = handlers.ImportHandler()
        self.assertEqual(handler.importers, {})
        self.assertEqual(handler.get_importers(), {})
        self.assertEqual(handler.get_importer_keys(), [])
        self.assertEqual(handler.get_default_keys(), [])
        self.assertFalse(handler.commit_host_partial)

        # with config
        handler = handlers.ImportHandler()
        self.assertIsNone(handler.config)
        config = RattailConfig()
        handler = handlers.ImportHandler(config=config)
        self.assertIs(handler.config, config)

        # dry run
        handler = handlers.ImportHandler()
        self.assertFalse(handler.dry_run)
        handler = handlers.ImportHandler(dry_run=True)
        self.assertTrue(handler.dry_run)

        # extra kwarg
        handler = handlers.ImportHandler()
        self.assertRaises(AttributeError, getattr, handler, 'foo')
        handler = handlers.ImportHandler(foo='bar')
        self.assertEqual(handler.foo, 'bar')

    def test_get_importer(self):
        get_importers = Mock(return_value={'foo': Importer})

        # no importers
        handler = handlers.ImportHandler()
        self.assertIsNone(handler.get_importer('foo'))

        # no config
        with patch.object(handlers.ImportHandler, 'get_importers', get_importers):
            handler = handlers.ImportHandler()
        importer = handler.get_importer('foo')
        self.assertIs(type(importer), Importer)
        self.assertIsNone(importer.config)
        self.assertIs(importer.handler, handler)

        # with config
        config = RattailConfig()
        with patch.object(handlers.ImportHandler, 'get_importers', get_importers):
            handler = handlers.ImportHandler(config=config)
        importer = handler.get_importer('foo')
        self.assertIs(type(importer), Importer)
        self.assertIs(importer.config, config)
        self.assertIs(importer.handler, handler)

        # dry run
        with patch.object(handlers.ImportHandler, 'get_importers', get_importers):
            handler = handlers.ImportHandler()
        importer = handler.get_importer('foo')
        self.assertFalse(importer.dry_run)
        with patch.object(handlers.ImportHandler, 'get_importers', get_importers):
            handler = handlers.ImportHandler(dry_run=True)
        importer = handler.get_importer('foo')
        self.assertTrue(handler.dry_run)

        # host title
        with patch.object(handlers.ImportHandler, 'get_importers', get_importers):
            handler = handlers.ImportHandler()
        importer = handler.get_importer('foo')
        self.assertIsNone(importer.host_system_title)
        handler.host_title = "Foo"
        importer = handler.get_importer('foo')
        self.assertEqual(importer.host_system_title, "Foo")

        # extra kwarg
        with patch.object(handlers.ImportHandler, 'get_importers', get_importers):
            handler = handlers.ImportHandler()
        importer = handler.get_importer('foo')
        self.assertRaises(AttributeError, getattr, importer, 'bar')
        importer = handler.get_importer('foo', bar='baz')
        self.assertEqual(importer.bar, 'baz')

    def test_get_importer_kwargs(self):

        # empty by default
        handler = handlers.ImportHandler()
        self.assertEqual(handler.get_importer_kwargs('foo'), {})

        # extra kwargs are preserved
        handler = handlers.ImportHandler()
        self.assertEqual(handler.get_importer_kwargs('foo', bar='baz'), {'bar': 'baz'})

    def test_begin_transaction(self):
        handler = handlers.ImportHandler()
        with patch.object(handler, 'begin_host_transaction') as begin_host:
            with patch.object(handler, 'begin_local_transaction') as begin_local:
                handler.begin_transaction()
                begin_host.assert_called_once_with()
                begin_local.assert_called_once_with()

    def test_begin_host_transaction(self):
        handler = handlers.ImportHandler()
        handler.begin_host_transaction()

    def test_begin_local_transaction(self):
        handler = handlers.ImportHandler()
        handler.begin_local_transaction()

    def test_commit_transaction(self):
        handler = handlers.ImportHandler()
        with patch.object(handler, 'commit_host_transaction') as commit_host:
            with patch.object(handler, 'commit_local_transaction') as commit_local:
                handler.commit_transaction()
                commit_host.assert_called_once_with()
                commit_local.assert_called_once_with()

    def test_commit_host_transaction(self):
        handler = handlers.ImportHandler()
        handler.commit_host_transaction()

    def test_commit_local_transaction(self):
        handler = handlers.ImportHandler()
        handler.commit_local_transaction()

    def test_rollback_transaction(self):
        handler = handlers.ImportHandler()
        with patch.object(handler, 'rollback_host_transaction') as rollback_host:
            with patch.object(handler, 'rollback_local_transaction') as rollback_local:
                handler.rollback_transaction()
                rollback_host.assert_called_once_with()
                rollback_local.assert_called_once_with()

    def test_rollback_host_transaction(self):
        handler = handlers.ImportHandler()
        handler.rollback_host_transaction()

    def test_rollback_local_transaction(self):
        handler = handlers.ImportHandler()
        handler.rollback_local_transaction()

    def test_import_data(self):

        # normal
        handler = handlers.ImportHandler()
        result = handler.import_data()
        self.assertEqual(result, {})

    def test_import_data_dry_run(self):

        # as init kwarg
        handler = handlers.ImportHandler(dry_run=True)
        with patch.object(handler, 'commit_transaction') as commit:
            with patch.object(handler, 'rollback_transaction') as rollback:
                handler.import_data()
                self.assertFalse(commit.called)
                rollback.assert_called_once_with()
        self.assertTrue(handler.dry_run)

        # as import kwarg
        handler = handlers.ImportHandler()
        with patch.object(handler, 'commit_transaction') as commit:
            with patch.object(handler, 'rollback_transaction') as rollback:
                handler.import_data(dry_run=True)
                self.assertFalse(commit.called)
                rollback.assert_called_once_with()
        self.assertTrue(handler.dry_run)

    def test_import_data_invalid_model(self):
        importer = Mock()
        importer.import_data.return_value = [], [], []
        FooImporter = Mock(return_value=importer)

        handler = handlers.ImportHandler()
        handler.importers = {'Foo': FooImporter}

        handler.import_data('Foo')
        self.assertEqual(FooImporter.call_count, 1)
        importer.import_data.assert_called_once_with()

        FooImporter.reset_mock()
        importer.reset_mock()

        handler.import_data('Missing')
        self.assertFalse(FooImporter.called)
        self.assertFalse(importer.called)

    def test_import_data_with_changes(self):
        importer = Mock()
        FooImporter = Mock(return_value=importer)

        handler = handlers.ImportHandler()
        handler.importers = {'Foo': FooImporter}

        importer.import_data.return_value = [], [], []
        with patch.object(handler, 'process_changes') as process:
            handler.import_data('Foo')
            self.assertFalse(process.called)

        importer.import_data.return_value = [1], [2], [3]
        with patch.object(handler, 'process_changes') as process:
            handler.import_data('Foo')
            process.assert_called_once_with({'Foo': ([1], [2], [3])})

    def test_import_data_commit_host_partial(self):
        importer = Mock()
        importer.import_data.side_effect = ValueError
        FooImporter = Mock(return_value=importer)

        handler = handlers.ImportHandler()
        handler.importers = {'Foo': FooImporter}

        handler.commit_host_partial = False
        with patch.object(handler, 'commit_host_transaction') as commit:
            self.assertRaises(ValueError, handler.import_data, 'Foo')
            self.assertFalse(commit.called)

        handler.commit_host_partial = True
        with patch.object(handler, 'commit_host_transaction') as commit:
            self.assertRaises(ValueError, handler.import_data, 'Foo')
            commit.assert_called_once_with()

    @patch('rattail.importing.handlers.send_email')
    def test_process_changes_sends_email(self, send_email):
        handler = handlers.ImportHandler()
        handler.import_began = pytz.utc.localize(datetime.datetime.utcnow())
        changes = [], [], []

        # warnings disabled
        handler.warnings = False
        handler.process_changes(changes)
        self.assertFalse(send_email.called)

        # warnings enabled
        handler.warnings = True
        handler.process_changes(changes)
        self.assertEqual(send_email.call_count, 1)

        send_email.reset_mock()

        # warnings enabled, with command (just for coverage..)
        handler.warnings = True
        handler.command = Mock(name='import-testing', parent=Mock(name='rattail'))
        handler.process_changes(changes)
        self.assertEqual(send_email.call_count, 1)


######################################################################
# fake import handler, tested mostly for basic coverage
######################################################################

class MockImportHandler(handlers.ImportHandler):

    def get_importers(self):
        return {'Product': MockImporter}

    def import_data(self, *keys, **kwargs):
        result = super(MockImportHandler, self).import_data(*keys, **kwargs)
        self._result = result
        return result


class TestImportHandlerImportData(ImporterTester, unittest.TestCase):

    sample_data = {
        '16oz': {'upc': '00074305001161', 'description': "Apple Cider Vinegar 16oz"},
        '32oz': {'upc': '00074305001321', 'description': "Apple Cider Vinegar 32oz"},
        '1gal': {'upc': '00074305011283', 'description': "Apple Cider Vinegar 1gal"},
    }

    def setUp(self):
        self.config = RattailConfig()
        self.handler = MockImportHandler(config=self.config)
        self.importer = MockImporter(config=self.config)

    def import_data(self, **kwargs):
        # must modify our importer in-place since we need the handler to return
        # that specific instance, below (because the host/local data context
        # managers reference that instance directly)
        self.importer._setup(**kwargs)
        with patch.object(self.handler, 'get_importer', Mock(return_value=self.importer)):
            result = self.handler.import_data('Product', **kwargs)
        if result:
            self.result = result['Product']
        else:
            self.result = [], [], []

    def test_invalid_importer_key_is_ignored(self):
        handler = handlers.ImportHandler()
        self.assertNotIn('InvalidKey', handler.importers)
        self.assertEqual(handler.import_data('InvalidKey'), {})

    def test_create(self):
        local = self.copy_data()
        del local['32oz']
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data()
        self.assert_import_created('32oz')
        self.assert_import_updated()
        self.assert_import_deleted()

    def test_update(self):
        local = self.copy_data()
        local['16oz']['description'] = "wrong description"
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data()
        self.assert_import_created()
        self.assert_import_updated('16oz')
        self.assert_import_deleted()

    def test_delete(self):
        local = self.copy_data()
        local['bogus'] = {'upc': '00000000000000', 'description': "Delete Me"}
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data(delete=True)
        self.assert_import_created()
        self.assert_import_updated()
        self.assert_import_deleted('bogus')

    def test_duplicate(self):
        host = self.copy_data()
        host['32oz-dupe'] = host['32oz']
        with self.host_data(host):
            with self.local_data(self.sample_data):
                self.import_data()
        self.assert_import_created()
        self.assert_import_updated()
        self.assert_import_deleted()

    def test_max_create(self):
        local = self.copy_data()
        del local['16oz']
        del local['1gal']
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data(max_create=1)
        self.assert_import_created('16oz')
        self.assert_import_updated()
        self.assert_import_deleted()

    def test_max_total_create(self):
        local = self.copy_data()
        del local['16oz']
        del local['1gal']
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data(max_total=1)
        self.assert_import_created('16oz')
        self.assert_import_updated()
        self.assert_import_deleted()

    def test_max_update(self):
        local = self.copy_data()
        local['16oz']['description'] = "wrong"
        local['1gal']['description'] = "wrong"
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data(max_update=1)
        self.assert_import_created()
        self.assert_import_updated('16oz')
        self.assert_import_deleted()

    def test_max_total_update(self):
        local = self.copy_data()
        local['16oz']['description'] = "wrong"
        local['1gal']['description'] = "wrong"
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data(max_total=1)
        self.assert_import_created()
        self.assert_import_updated('16oz')
        self.assert_import_deleted()

    def test_max_delete(self):
        local = self.copy_data()
        local['bogus1'] = {'upc': '00000000000001', 'description': "Delete Me"}
        local['bogus2'] = {'upc': '00000000000002', 'description': "Delete Me"}
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data(delete=True, max_delete=1)
        self.assert_import_created()
        self.assert_import_updated()
        self.assert_import_deleted('bogus1')

    def test_max_total_delete(self):
        local = self.copy_data()
        local['bogus1'] = {'upc': '00000000000001', 'description': "Delete Me"}
        local['bogus2'] = {'upc': '00000000000002', 'description': "Delete Me"}
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data(delete=True, max_total=1)
        self.assert_import_created()
        self.assert_import_updated()
        self.assert_import_deleted('bogus1')

    def test_dry_run(self):
        local = self.copy_data()
        del local['32oz']
        local['16oz']['description'] = "wrong description"
        local['bogus'] = {'upc': '00000000000000', 'description': "Delete Me"}
        with self.host_data(self.sample_data):
            with self.local_data(local):
                self.import_data(delete=True, dry_run=True)
        # TODO: maybe need a way to confirm no changes actually made due to dry
        # run; currently results still reflect "proposed" changes.  this rather
        # bogus test is here just for coverage sake
        self.assert_import_created('32oz')
        self.assert_import_updated('16oz')
        self.assert_import_deleted('bogus')

    def test_warnings_run(self):
        local = self.copy_data()
        del local['32oz']
        local['16oz']['description'] = "wrong description"
        local['bogus'] = {'upc': '00000000000000', 'description': "Delete Me"}
        with self.host_data(self.sample_data):
            with self.local_data(local):
                with patch('rattail.importing.handlers.send_email') as send_email:
                    self.assertEqual(send_email.call_count, 0)
                    self.import_data(delete=True, warnings=True, dry_run=True)
                    self.assertEqual(send_email.call_count, 1)
        # second time is just for more coverage...
        with self.host_data(self.sample_data):
            with self.local_data(local):
                with patch('rattail.importing.handlers.send_email') as send_email:
                    self.handler.command = Mock()
                    self.assertEqual(send_email.call_count, 0)
                    self.import_data(delete=True, warnings=True)
                    self.assertEqual(send_email.call_count, 1)
        # TODO: maybe need a way to confirm no changes actually made due to dry
        # run; currently results still reflect "proposed" changes.  this rather
        # bogus test is here just for coverage sake
        self.assert_import_created('32oz')
        self.assert_import_updated('16oz')
        self.assert_import_deleted('bogus')


Session = orm.sessionmaker()


class MockFromSQLAlchemyHandler(handlers.FromSQLAlchemyHandler):

    def make_host_session(self):
        return Session()


class MockToSQLAlchemyHandler(handlers.ToSQLAlchemyHandler):

    def make_session(self):
        return Session()


class TestFromSQLAlchemyHandler(unittest.TestCase):

    def test_init(self):
        handler = handlers.FromSQLAlchemyHandler()
        self.assertRaises(NotImplementedError, handler.make_host_session)

    def test_get_importer_kwargs(self):
        session = object()
        handler = handlers.FromSQLAlchemyHandler(host_session=session)
        kwargs = handler.get_importer_kwargs(None)
        self.assertEqual(list(kwargs.iterkeys()), ['host_session'])
        self.assertIs(kwargs['host_session'], session)

    def test_begin_host_transaction(self):
        handler = MockFromSQLAlchemyHandler()
        self.assertIsNone(handler.host_session)
        handler.begin_host_transaction()
        self.assertIsInstance(handler.host_session, orm.Session)
        handler.host_session.close()

    def test_commit_host_transaction(self):
        # TODO: test actual commit for data changes
        session = Session()
        handler = handlers.FromSQLAlchemyHandler(host_session=session)
        self.assertIs(handler.host_session, session)
        handler.commit_host_transaction()
        self.assertIsNone(handler.host_session)

    def test_rollback_host_transaction(self):
        # TODO: test actual rollback for data changes
        session = Session()
        handler = handlers.FromSQLAlchemyHandler(host_session=session)
        self.assertIs(handler.host_session, session)
        handler.rollback_host_transaction()
        self.assertIsNone(handler.host_session)


class TestToSQLAlchemyHandler(unittest.TestCase):

    def test_init(self):
        handler = handlers.ToSQLAlchemyHandler()
        self.assertRaises(NotImplementedError, handler.make_session)

    def test_get_importer_kwargs(self):
        session = object()
        handler = handlers.ToSQLAlchemyHandler(session=session)
        kwargs = handler.get_importer_kwargs(None)
        self.assertEqual(list(kwargs.iterkeys()), ['session'])
        self.assertIs(kwargs['session'], session)

    def test_begin_local_transaction(self):
        handler = MockToSQLAlchemyHandler()
        self.assertIsNone(handler.session)
        handler.begin_local_transaction()
        self.assertIsInstance(handler.session, orm.Session)
        handler.session.close()

    def test_commit_local_transaction(self):
        # TODO: test actual commit for data changes
        session = Session()
        handler = handlers.ToSQLAlchemyHandler(session=session)
        self.assertIs(handler.session, session)
        with patch.object(handler, 'session') as session:
            handler.commit_local_transaction()
            session.commit.assert_called_once_with()
            self.assertFalse(session.rollback.called)
        # self.assertIsNone(handler.session)

    def test_rollback_local_transaction(self):
        # TODO: test actual rollback for data changes
        session = Session()
        handler = handlers.ToSQLAlchemyHandler(session=session)
        self.assertIs(handler.session, session)
        with patch.object(handler, 'session') as session:
            handler.rollback_local_transaction()
            session.rollback.assert_called_once_with()
            self.assertFalse(session.commit.called)
        # self.assertIsNone(handler.session)


######################################################################
# fake bulk import handler, tested mostly for basic coverage
######################################################################

class MockBulkImportHandler(handlers.BulkToPostgreSQLHandler):

    def get_importers(self):
        return {'Department': MockBulkImporter}

    def make_session(self):
        return Session()


class TestBulkImportHandler(RattailTestCase, ImporterTester):

    importer_class = MockBulkImporter

    sample_data = {
        'grocery': {'number': 1, 'name': "Grocery", 'uuid': 'decd909a194011e688093ca9f40bc550'},
        'bulk': {'number': 2, 'name': "Bulk", 'uuid': 'e633d54c194011e687e33ca9f40bc550'},
        'hba': {'number': 3, 'name': "HBA", 'uuid': 'e2bad79e194011e6a4783ca9f40bc550'},
    }

    def setUp(self):
        self.setup_rattail()
        self.tempio = TempIO()
        self.config.set('rattail', 'workdir', self.tempio.realpath())
        self.handler = MockBulkImportHandler(config=self.config)

    def tearDown(self):
        self.teardown_rattail()
        self.tempio = None

    def import_data(self, host_data=None, **kwargs):
        if host_data is None:
            host_data = list(self.copy_data().itervalues())
        with patch.object(self.importer_class, 'normalize_host_data', Mock(return_value=host_data)):
            with patch.object(self.handler, 'make_session', Mock(return_value=self.session)):
                return self.handler.import_data('Department', **kwargs)

    def test_invalid_importer_key_is_ignored(self):
        handler = MockBulkImportHandler()
        self.assertNotIn('InvalidKey', handler.importers)
        self.assertEqual(handler.import_data('InvalidKey'), {})

    def assert_import_created(self, *keys):
        pass

    def assert_import_updated(self, *keys):
        pass

    def assert_import_deleted(self, *keys):
        pass

    def test_normal_run(self):
        if self.postgresql():
            self.import_data()

    def test_dry_run(self):
        if self.postgresql():
            self.import_data(dry_run=True)