This file is indexed.

/usr/lib/python2.7/dist-packages/nss_cache/command_test.py is in nsscache 0.33-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
# Copyright 2007 Google Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

"""Unit tests for nss_cache/command.py."""

__author__ = ('jaq@google.com (Jamie Wilkinson)',
              'vasilios@google.com (Vasilios Hoffman)')

import grp
import os
import pwd
import shutil
import StringIO
import sys
import tempfile
import time
import unittest

import mox

from nss_cache import command
from nss_cache import config
from nss_cache import error
from nss_cache import lock
from nss_cache import nss

from nss_cache.caches import caches
from nss_cache.caches import cache_factory
from nss_cache.maps import automount
from nss_cache.maps import passwd
from nss_cache.sources import source
from nss_cache.sources import source_factory

from nss_cache.update import updater
from nss_cache.update import files_updater
from nss_cache.update import map_updater


class TestCommand(mox.MoxTestBase):
  """Unit tests for the Command class."""

  def testRunCommand(self):
    c = command.Command()
    self.assertRaises(NotImplementedError, c.Run, [], {})

  def testLock(self):
    self.mox.StubOutClassWithMocks(lock, 'PidFile')
    mock_lock = lock.PidFile(filename=None)
    mock_lock.Lock(force=False).AndReturn('LOCK')
    mock_lock.Lock(force=False).AndReturn('MORLOCK')
    mock_lock.Locked().AndReturn(True)
    mock_lock.Unlock()

    self.mox.ReplayAll()

    c = command.Command()

    # First test that we create a lock and lock it.
    self.assertEquals('LOCK', c._Lock())

    # Then we test that we lock the existing one a second time.
    self.assertEquals('MORLOCK', c._Lock())

  def testForceLock(self):
    self.mox.StubOutClassWithMocks(lock, 'PidFile')
    mock_lock = lock.PidFile(filename=None)
    mock_lock.Lock(force=True).AndReturn('LOCK')
    mock_lock.Locked().AndReturn(True)
    mock_lock.Unlock()

    self.mox.ReplayAll()
    c = command.Command()

    self.assertEquals('LOCK', c._Lock(force=True))


  def testUnlock(self):
    self.mox.StubOutClassWithMocks(lock, 'PidFile')
    mock_lock = lock.PidFile(filename=None)
    mock_lock.Lock(force=False).AndReturn(True)
    mock_lock.Locked().AndReturn(True)
    mock_lock.Unlock()
    mock_lock.Locked().AndReturn(False) # destructor

    self.mox.ReplayAll()
    c = command.Command()
    c._Lock()
    c._Unlock()


  def testCommandHelp(self):
    c = command.Command()
    self.assertNotEqual(None, c)
    self.assertEqual(None, c.Help())

  def testDummyCommand(self):

    class Dummy(command.Command):
      """Dummy docstring for dummy command."""

      def Run(self):
        return 0

    c = Dummy()
    self.assertTrue(isinstance(c, command.Command))
    self.failIfEqual(None, c.Help())


class TestUpdateCommand(mox.MoxTestBase):
  """Unit tests for the Update command class."""

  def setUp(self):
    super(TestUpdateCommand, self).setUp()
    self.workdir = tempfile.mkdtemp()

    class DummyConfig(object):
      pass

    self.conf = DummyConfig()
    self.conf.options = {config.MAP_PASSWORD: config.MapOptions(),
                         config.MAP_AUTOMOUNT: config.MapOptions()}
    self.conf.options[config.MAP_PASSWORD].cache = {'name': 'dummy',
                                                    'dir': self.workdir}
    self.conf.options[config.MAP_PASSWORD].source = {'name': 'dummy'}
    self.conf.options[config.MAP_AUTOMOUNT].cache = {'name': 'dummy',
                                                     'dir': self.workdir}
    self.conf.options[config.MAP_AUTOMOUNT].source = {'name': 'dummy'}
    self.conf.timestamp_dir = self.workdir
    self.conf.lockfile = None

  def tearDown(self):
    super(TestUpdateCommand, self).tearDown()
    shutil.rmtree(self.workdir)

  def testConstructor(self):
    c = command.Update()
    self.failIfEqual(None, c)

  def testHelp(self):
    c = command.Update()
    self.failIfEqual(None, c.Help())

  def testRunWithNoParameters(self):
    c = command.Update()

    self.mox.StubOutWithMock(c, 'UpdateMaps')
    c.UpdateMaps(self.conf, incremental=True, force_lock=False, force_write=False).AndReturn(0)
    self.mox.ReplayAll()

    self.assertEquals(0, c.Run(self.conf, []))

  def testRunWithBadParameters(self):
    c = command.Update()
    # Trap stderr so the unit test runs clean,
    # since unit test status is printed on stderr.
    dev_null = StringIO.StringIO()
    stderr = sys.stderr
    sys.stderr = dev_null
    self.assertEquals(2, c.Run(None, ['--invalid']))
    sys.stderr = stderr

  def testRunWithFlags(self):
    c = command.Update()

    self.mox.StubOutWithMock(c, 'UpdateMaps')
    c.UpdateMaps(self.conf, incremental=False, force_lock=True, force_write=True).AndReturn(0)
    self.mox.ReplayAll()

    self.assertEquals(0, c.Run(self.conf,
                               ['-m', config.MAP_PASSWORD, '-f',
                                '--force-write', '--force-lock']))
    self.assertEqual(['passwd'], self.conf.maps)

  def testUpdateSingleMaps(self):
    self.mox.StubOutClassWithMocks(lock, 'PidFile')
    lock_mock = lock.PidFile(filename=None)
    lock_mock.Lock(force=False).AndReturn(True)
    lock_mock.Locked().AndReturn(True)
    lock_mock.Unlock()

    self.conf.maps = [config.MAP_PASSWORD]
    self.conf.cache = 'dummy'

    modify_stamp = 1
    map_entry = passwd.PasswdMapEntry({'name': 'foo', 'uid': 10, 'gid': 10})
    passwd_map = passwd.PasswdMap([map_entry])
    passwd_map.SetModifyTimestamp(modify_stamp)

    source_mock = self.mox.CreateMock(source.Source)
    source_mock.GetMap(config.MAP_PASSWORD, location=None).AndReturn(passwd_map)

    self.mox.StubOutWithMock(source_factory, 'Create')
    source_factory.Create(self.conf.options[config.MAP_PASSWORD].source).AndReturn(source_mock)

    cache_mock = self.mox.CreateMock(caches.Cache)
    cache_mock.WriteMap(map_data=passwd_map).AndReturn(0)

    self.mox.StubOutWithMock(cache_factory, 'Create')
    cache_factory.Create(self.conf.options[config.MAP_PASSWORD].cache, config.MAP_PASSWORD).AndReturn(cache_mock)

    self.mox.ReplayAll()
    c = command.Update()
    self.assertEquals(0, c.UpdateMaps(self.conf,
                                      incremental=True, force_write=False))

  def testUpdateAutomounts(self):
    self.mox.StubOutClassWithMocks(lock, 'PidFile')
    lock_mock = lock.PidFile(filename=None)
    lock_mock.Lock(force=False).AndReturn(True)
    lock_mock.Locked().AndReturn(True)
    lock_mock.Unlock()

    self.conf.maps = [config.MAP_AUTOMOUNT]
    self.conf.cache = 'dummy'

    modify_stamp = 1
    map_entry = automount.AutomountMapEntry()
    map_entry.key = '/home'
    map_entry.location = 'foo'
    automount_map = automount.AutomountMap([map_entry])
    automount_map.SetModifyTimestamp(modify_stamp)

    source_mock = self.mox.CreateMock(source.Source)
    source_mock.GetAutomountMasterMap().AndReturn(automount_map)
    source_mock.GetMap(config.MAP_AUTOMOUNT, location='foo').AndReturn(automount_map)

    self.mox.StubOutWithMock(source_factory, 'Create')
    source_factory.Create(self.conf.options[config.MAP_PASSWORD].source).AndReturn(source_mock)

    cache_mock = self.mox.CreateMock(caches.Cache)
    cache_mock.GetMapLocation().AndReturn('home')
    cache_mock.WriteMap(map_data=automount_map).AndReturn(0)
    cache_mock.WriteMap(map_data=automount_map).AndReturn(0)

    self.mox.StubOutWithMock(cache_factory, 'Create')
    cache_factory.Create(self.conf.options[config.MAP_AUTOMOUNT].cache, config.MAP_AUTOMOUNT, automount_mountpoint='/home').AndReturn(cache_mock)
    cache_factory.Create(self.conf.options[config.MAP_AUTOMOUNT].cache, config.MAP_AUTOMOUNT, automount_mountpoint=None).AndReturn(cache_mock)

    self.mox.ReplayAll()

    c = command.Update()
    self.assertEquals(0, c.UpdateMaps(self.conf,
                                      incremental=True, force_write=False))

  def testUpdateMapsTrapsPermissionDenied(self):
    self.mox.StubOutWithMock(map_updater.MapUpdater, 'UpdateFromSource')
    map_updater.MapUpdater.UpdateFromSource(mox.IgnoreArg(), incremental=True, force_write=False).AndRaise(error.PermissionDenied)

    self.mox.StubOutClassWithMocks(lock, 'PidFile')
    lock_mock = lock.PidFile(filename=None)
    lock_mock.Lock(force=False).AndReturn(True)
    lock_mock.Locked().AndReturn(True)
    lock_mock.Unlock()
    
    self.conf.maps = [config.MAP_PASSWORD]
    self.conf.cache = 'dummy'
    modify_stamp = 1
    map_entry = passwd.PasswdMapEntry({'name': 'foo', 'uid': 10, 'gid': 10})
    passwd_map = passwd.PasswdMap([map_entry])
    passwd_map.SetModifyTimestamp(modify_stamp)

    source_mock = self.mox.CreateMock(source.Source)

    self.mox.StubOutWithMock(source_factory, 'Create')
    source_factory.Create(self.conf.options[config.MAP_PASSWORD].source).AndReturn(source_mock)

    cache_mock = self.mox.CreateMock(caches.Cache)

    self.mox.StubOutWithMock(cache_factory, 'Create')

    self.mox.ReplayAll()

    c = command.Update()
    self.assertEquals(1, c.UpdateMaps(self.conf, incremental=True,
                                      force_write=False))

  def testUpdateMapsCanForceLock(self):
    self.mox.StubOutClassWithMocks(lock, 'PidFile')
    lock_mock = lock.PidFile(filename=None)
    lock_mock.Lock(force=True).AndReturn(False)
    lock_mock.Locked().AndReturn(True)
    lock_mock.Unlock()

    self.mox.ReplayAll()

    c = command.Update()
    self.assertEquals(c.UpdateMaps(self.conf, False, force_lock=True),
                      c.ERR_LOCK)

  def testSleep(self):
    self.mox.StubOutWithMock(time, 'sleep')
    time.sleep(1)

    c = command.Update()
    self.mox.StubOutWithMock(c, 'UpdateMaps')
    c.UpdateMaps(self.conf, incremental=True, force_lock=mox.IgnoreArg(), force_write=mox.IgnoreArg()).AndReturn(0)
    self.mox.ReplayAll()

    c.Run(self.conf, ['-s', '1'])

  def testForceWriteFlag(self):
    c = command.Update()
    (options, _) = c.parser.parse_args([])
    self.assertEqual(False, options.force_write)
    (options, _) = c.parser.parse_args(['--force-write'])
    self.assertEqual(True, options.force_write)

  def testForceLockFlag(self):
    c = command.Update()
    (options, _) = c.parser.parse_args([])
    self.assertEqual(False, options.force_lock)
    (options, _) = c.parser.parse_args(['--force-lock'])
    self.assertEqual(True, options.force_lock)

  def testForceWriteFlagCallsUpdateMapsWithForceWriteTrue(self):
    c = command.Update()

    self.mox.StubOutWithMock(c, 'UpdateMaps')
    c.UpdateMaps(self.conf, incremental=mox.IgnoreArg(), force_lock=mox.IgnoreArg(), force_write=True).AndReturn(0)
    self.mox.ReplayAll()

    self.assertEqual(0, c.Run(self.conf, ['--force-write']))

  def testForceLockFlagCallsUpdateMapsWithForceLockTrue(self):
    c = command.Update()

    self.mox.StubOutWithMock(c, 'UpdateMaps')
    c.UpdateMaps(self.conf, incremental=mox.IgnoreArg(), force_lock=True, force_write=mox.IgnoreArg()).AndReturn(0)
    self.mox.ReplayAll()

    self.assertEqual(0, c.Run(self.conf, ['--force-lock']))

  def testUpdateMapsWithBadMapName(self):
    c = command.Update()
    self.mox.StubOutWithMock(c, '_Lock')
    c._Lock(force=False, path=None).AndReturn(True)
    self.mox.ReplayAll()
    # Create an invalid map name.
    self.assertEqual(1, c.Run(self.conf, ['-m', config.MAP_PASSWORD + 'invalid']))


class TestVerifyCommand(mox.MoxTestBase):

  def setUp(self):
    super(TestVerifyCommand, self).setUp()

    class DummyConfig(object):
      pass

    class DummySource(source.Source):
      name = 'dummy'

      def Verify(self):
        return 0

    # Instead of a DummyCache, we will override cache_factory.Create so
    # we can return a pmock cache object.
    self.original_caches_create = cache_factory.Create
    self.original_sources_create = source_factory.Create

    # Add dummy source to the set if implementations of sources.
    source_factory.RegisterImplementation(DummySource)

    # Create a config with a section for a passwd map.
    self.conf = DummyConfig()
    self.conf.options = {config.MAP_PASSWORD: config.MapOptions()}
    self.conf.options[config.MAP_PASSWORD].cache = {'name': 'dummy'}
    self.conf.options[config.MAP_PASSWORD].source = {'name': 'dummy'}

    self.original_verify_configuration = config.VerifyConfiguration
    self.original_getmap = nss.GetMap
    self.original_getpwall = pwd.getpwall
    self.original_getgrall = grp.getgrall

    # Setup maps used by VerifyMap testing.
    big_map = passwd.PasswdMap()
    map_entry1 = passwd.PasswdMapEntry()
    map_entry1.name = 'foo'
    map_entry1.uid = 10
    map_entry1.gid = 10
    big_map.Add(map_entry1)
    map_entry2 = passwd.PasswdMapEntry()
    map_entry2.name = 'bar'
    map_entry2.uid = 20
    map_entry2.gid = 20
    big_map.Add(map_entry2)

    small_map = passwd.PasswdMap()
    small_map.Add(map_entry1)

    self.big_map = big_map
    self.small_map = small_map

  def tearDown(self):
    super(TestVerifyCommand, self).tearDown()
    config.VerifyConfiguration = self.original_verify_configuration
    cache_factory.Create = self.original_caches_create
    nss.getmap = self.original_getmap
    source_factory.Create = self.original_sources_create
    pwd.getpwall = self.original_getpwall
    grp.getgrall = self.original_getgrall

  def testConstructor(self):
    c = command.Verify()
    self.assertTrue(isinstance(c, command.Verify))

  def testHelp(self):
    c = command.Verify()
    self.failIfEqual(None, c.Help())

  def testRunWithNoParameters(self):

    def FakeVerifyConfiguration(conf):
      """Assert that we call VerifyConfiguration correctly."""
      self.assertEquals(conf, self.conf)
      return (0, 0)

    def FakeVerifyMaps(conf):
      """Assert that VerifyMaps is called with a config object."""
      self.assertEquals(conf, self.conf)
      return 0

    config.VerifyConfiguration = FakeVerifyConfiguration

    c = command.Verify()
    c.VerifyMaps = FakeVerifyMaps

    self.conf.maps = []

    self.assertEquals(1, c.Run(self.conf, []))

  def testRunWithBadParameters(self):
    c = command.Verify()
    # Trap stderr so the unit test runs clean,
    # since unit test status is printed on stderr.
    dev_null = StringIO.StringIO()
    stderr = sys.stderr
    sys.stderr = dev_null
    self.assertEquals(2, c.Run(None, ['--invalid']))
    sys.stderr = stderr

  def testRunWithParameters(self):

    def FakeVerifyConfiguration(conf):
      """Assert that we call VerifyConfiguration correctly."""
      self.assertEquals(conf, self.conf)
      return (0, 0)

    def FakeVerifyMaps(conf):
      """Assert that VerifyMaps is called with a config object."""
      self.assertEquals(conf, self.conf)
      return 0

    config.VerifyConfiguration = FakeVerifyConfiguration

    c = command.Verify()
    c.VerifyMaps = FakeVerifyMaps

    self.assertEquals(0, c.Run(self.conf, ['-m',
                                           config.MAP_PASSWORD]))

  def testVerifyMapsSucceedsOnGoodMaps(self):
    cache_mock = self.mox.CreateMock(caches.Cache)
    cache_mock.GetMap().AndReturn(self.small_map)

    self.mox.StubOutWithMock(cache_factory, 'Create')
    cache_factory.Create(self.conf.options[config.MAP_PASSWORD].cache, config.MAP_PASSWORD).AndReturn(cache_mock)

    self.conf.maps = [config.MAP_PASSWORD]

    self.mox.StubOutWithMock(nss, 'GetMap')
    nss.GetMap(config.MAP_PASSWORD).AndReturn(self.big_map)

    self.mox.ReplayAll()

    c = command.Verify()

    self.assertEquals(0, c.VerifyMaps(self.conf))

  def testVerifyMapsBad(self):
    cache_mock = self.mox.CreateMock(caches.Cache)
    cache_mock.GetMap().AndReturn(self.big_map)

    self.mox.StubOutWithMock(cache_factory, 'Create')
    cache_factory.Create(self.conf.options[config.MAP_PASSWORD].cache, config.MAP_PASSWORD).AndReturn(cache_mock)

    self.conf.maps = [config.MAP_PASSWORD]

    self.mox.StubOutWithMock(nss, 'GetMap')
    nss.GetMap(config.MAP_PASSWORD).AndReturn(self.small_map)

    self.mox.ReplayAll()

    c = command.Verify()

    self.assertEquals(1, c.VerifyMaps(self.conf))

  def testVerifyMapsException(self):
    cache_mock = self.mox.CreateMock(caches.Cache)
    cache_mock.GetMap().AndRaise(error.CacheNotFound)

    self.mox.StubOutWithMock(cache_factory, 'Create')
    cache_factory.Create(self.conf.options[config.MAP_PASSWORD].cache, config.MAP_PASSWORD).AndReturn(cache_mock)

    self.conf.maps = [config.MAP_PASSWORD]

    self.mox.StubOutWithMock(nss, 'GetMap')
    nss.GetMap(config.MAP_PASSWORD).AndReturn(self.small_map)

    self.mox.ReplayAll()

    c = command.Verify()

    self.assertEquals(1, c.VerifyMaps(self.conf))

  def testVerifyMapsSkipsNetgroups(self):
    self.mox.StubOutWithMock(cache_factory, 'Create')

    self.conf.maps = [config.MAP_NETGROUP]

    self.mox.StubOutWithMock(nss, 'GetMap')

    self.mox.ReplayAll()

    c = command.Verify()

    self.assertEquals(0, c.VerifyMaps(self.conf))

  def testVerifySourcesGood(self):
    source_mock = self.mox.CreateMock(source.Source)
    source_mock.Verify().AndReturn(0)

    self.mox.StubOutWithMock(source_factory, 'Create')
    source_factory.Create(mox.IgnoreArg()).AndReturn(source_mock)
    self.conf.maps = [config.MAP_PASSWORD]

    self.mox.ReplayAll()
    self.assertEquals(0, command.Verify().VerifySources(self.conf))

  def testVerifySourcesBad(self):

    self.conf.maps = []
    self.assertEquals(1, command.Verify().VerifySources(self.conf))

    source_mock = self.mox.CreateMock(source.Source)
    source_mock.Verify().AndReturn(1)

    self.mox.StubOutWithMock(source_factory, 'Create')
    source_factory.Create(self.conf.options[config.MAP_PASSWORD].cache).AndReturn(source_mock)

    self.conf.maps = [config.MAP_PASSWORD]

    self.mox.ReplayAll()

    self.assertEquals(1, command.Verify().VerifySources(self.conf))

  def testVerifySourcesTrapsSourceUnavailable(self):
    self.conf.maps = []
    self.assertEquals(1, command.Verify().VerifySources(self.conf))

    def FakeCreate(conf):
      """Stub routine returning a pmock to test VerifySources."""
      self.assertEquals(conf,
                        self.conf.options[config.MAP_PASSWORD].source)
      raise error.SourceUnavailable

    old_source_base_create = source_factory.Create
    source_factory.Create = FakeCreate
    self.conf.maps = [config.MAP_PASSWORD]

    self.assertEquals(1, command.Verify().VerifySources(self.conf))

    source_factory.Create = old_source_base_create


class TestRepairCommand(unittest.TestCase):

  def setUp(self):

    class DummyConfig(object):
      pass

    class DummySource(source.Source):
      name = 'dummy'

      def Verify(self):
        return 0

    # Add dummy source to the set if implementations of sources
    source_factory.RegisterImplementation(DummySource)

    self.conf = DummyConfig()
    self.conf.options = {config.MAP_PASSWORD: config.MapOptions()}
    self.conf.options[config.MAP_PASSWORD].cache = {'name': 'dummy'}
    self.conf.options[config.MAP_PASSWORD].source = {'name': 'dummy'}

    self.original_verify_configuration = config.VerifyConfiguration

  def tearDown(self):
    config.VerifyConfiguration = self.original_verify_configuration

  def testCreate(self):
    c = command.Repair()
    self.assertTrue(isinstance(c, command.Repair))

  def testHelp(self):
    c = command.Repair()
    self.failIfEqual(None, c.Help())

  def testRunWithNoParameters(self):
    c = command.Repair()

    def FakeVerifyConfiguration(conf):
      """Assert that we call VerifyConfiguration correctly."""
      self.assertEquals(conf, self.conf)
      return (0, 1)

    config.VerifyConfiguration = FakeVerifyConfiguration

    self.conf.maps = []

    self.assertEquals(1, c.Run(self.conf, []))

  def testRunWithBadParameters(self):
    c = command.Repair()
    # Trap stderr so the unit test runs clean,
    # since unit test status is printed on stderr.
    dev_null = StringIO.StringIO()
    stderr = sys.stderr
    sys.stderr = dev_null
    self.assertEquals(2, c.Run(None, ['--invalid']))
    sys.stderr = stderr

  def testRunWithParameters(self):

    def FakeVerifyConfiguration(conf):
      """Assert that we call VerifyConfiguration correctly."""
      self.assertEquals(conf, self.conf)
      return (0, 1)

    config.VerifyConfiguration = FakeVerifyConfiguration

    c = command.Repair()

    self.assertEquals(1, c.Run(self.conf, ['-m',
                                           config.MAP_PASSWORD]))


class TestHelpCommand(unittest.TestCase):

  def setUp(self):
    self.stdout = sys.stdout
    sys.stdout = StringIO.StringIO()

  def tearDown(self):
    sys.stdout = self.stdout

  def testHelp(self):
    c = command.Help()
    self.failIfEqual(None, c.Help())

  def testRunWithNoParameters(self):
    c = command.Help()
    self.assertEquals(0, c.Run(None, []))

  def testRunHelpHelp(self):
    c = command.Help()
    self.assertEquals(0, c.Run(None, ['help']))


class TestStatusCommand(mox.MoxTestBase):

  def setUp(self):
    super(TestStatusCommand, self).setUp()

    class DummyConfig(object):
      pass

    class DummySource(source.Source):
      name = 'dummy'

      def Verify(self):
        return 0

    # stub out parts of update.MapUpdater
    class DummyUpdater(map_updater.MapUpdater):
      def GetModifyTimestamp(self):
        return 1

      def GetUpdateTimestamp(self):
        return 2

    # Add dummy source to the set if implementations of sources
    source_factory.RegisterImplementation(DummySource)

    self.conf = DummyConfig()
    self.conf.timestamp_dir = 'TEST_DIR'
    self.conf.options = {config.MAP_PASSWORD: config.MapOptions(),
                         config.MAP_AUTOMOUNT: config.MapOptions()}
    self.conf.options[config.MAP_PASSWORD].cache = {'name': 'dummy'}
    self.conf.options[config.MAP_PASSWORD].source = {'name': 'dummy'}
    self.conf.options[config.MAP_AUTOMOUNT].cache = {'name': 'dummy'}
    self.conf.options[config.MAP_AUTOMOUNT].source = {'name': 'dummy'}

    self.original_verify_configuration = config.VerifyConfiguration
    self.original_create = cache_factory.Create
    self.original_updater = map_updater.MapUpdater

    # stub this out for all tests
    map_updater.MapUpdater = DummyUpdater

  def tearDown(self):
    super(TestStatusCommand, self).tearDown()
    config.VerifyConfiguration = self.original_verify_configuration
    cache_factory.Create = self.original_create
    map_updater.MapUpdater = self.original_updater

  def testHelp(self):
    c = command.Status()
    self.failIfEqual(None, c.Help())

  def testRunWithNoParameters(self):
    c = command.Status()
    self.conf.maps = []
    self.assertEquals(0, c.Run(self.conf, []))

  def testRunWithBadParameters(self):
    c = command.Status()
    # Trap stderr so the unit test runs clean,
    # since unit test status is printed on stderr.
    dev_null = StringIO.StringIO()
    stderr = sys.stderr
    sys.stderr = dev_null
    self.assertEquals(2, c.Run(None, ['--invalid']))
    sys.stderr = stderr

  def testEpochFormatParameter(self):
    c = command.Status()
    (options, args) = c.parser.parse_args([])
    self.assertEqual(False, options.epoch)
    self.assertEqual([], args)

  def testObeysMapsFlag(self):
    stdout_buffer = StringIO.StringIO()

    old_stdout = sys.stdout
    sys.stdout = stdout_buffer

    c = command.Status()
    self.assertEqual(0, c.Run(self.conf, ['-m', 'passwd']))
    sys.stdout = old_stdout

    self.failIfEqual(0, len(stdout_buffer.getvalue()))
    self.failIf(stdout_buffer.getvalue().find('group') >= 0)

  def testGetSingleMapMetadata(self):
    # test both automount and non-automount maps.

    # cache mock is returned by FakeCreate() for automount maps
    cache_mock = self.mox.CreateMock(caches.Cache)
    cache_mock.GetMapLocation().AndReturn('/etc/auto.master')

    self.mox.StubOutWithMock(cache_factory, 'Create')
    cache_factory.Create(self.conf.options[config.MAP_AUTOMOUNT].cache, config.MAP_AUTOMOUNT, automount_mountpoint='automount_mountpoint').AndReturn(cache_mock)

    self.mox.ReplayAll()

    c = command.Status()

    values = c.GetSingleMapMetadata(config.MAP_PASSWORD, self.conf)
    self.failUnless('map' in values[0])
    self.failUnless('key' in values[0])
    self.failUnless('value' in values[0])

    values = c.GetSingleMapMetadata(
        config.MAP_AUTOMOUNT, self.conf,
        automount_mountpoint='automount_mountpoint')

    self.failUnless('map' in values[0])
    self.failUnless('key' in values[0])
    self.failUnless('value' in values[0])
    self.failUnless('automount' in values[0])

  def testGetSingleMapMetadataTimestampEpoch(self):
    c = command.Status()
    values = c.GetSingleMapMetadata(config.MAP_PASSWORD, self.conf,
                                    epoch=True)
    self.failUnless('map' in values[0])
    self.failUnless('key' in values[0])
    self.failUnless('value' in values[0])
    # values below are returned by dummyupdater
    self.assertEqual(1, values[0]['value'])
    self.assertEqual(2, values[1]['value'])

  def testGetSingleMapMetadataTimestampEpochFalse(self):
    # set the timezone so we get a consistent return value
    os.environ['TZ'] = 'US/Pacific'
    time.tzset()

    c = command.Status()
    values = c.GetSingleMapMetadata(config.MAP_PASSWORD, self.conf,
                                    epoch=False)
    self.failUnlessEqual('Wed Dec 31 16:00:02 1969',
                         values[1]['value'])

  def testGetAutomountMapMetadata(self):
    # need to stub out GetSingleMapMetadata (tested above) and then
    # stub out cache_factory.Create to return a cache mock that spits
    # out an iterable map for the function to use.

    # stub out GetSingleMapMetadata
    class DummyStatus(command.Status):
      def GetSingleMapMetadata(self, unused_map_name, unused_conf,
                               automount_mountpoint=None, epoch=False):
        return {'map': 'map_name', 'last-modify-timestamp': 'foo',
                'last-update-timestamp': 'bar'}

    # the master map to loop over
    master_map = automount.AutomountMap()
    master_map.Add(automount.AutomountMapEntry({'key': '/home',
                                           'location': '/etc/auto.home'}))
    master_map.Add(automount.AutomountMapEntry({'key': '/auto',
                                           'location': '/etc/auto.auto'}))

    # mock out a cache to return the master map
    cache_mock = self.mox.CreateMock(caches.Cache)
    cache_mock.GetMap().AndReturn(master_map)

    self.mox.StubOutWithMock(cache_factory, 'Create')
    cache_factory.Create(self.conf.options[config.MAP_AUTOMOUNT].cache, config.MAP_AUTOMOUNT, automount_mountpoint=None).AndReturn(cache_mock)

    self.mox.ReplayAll()

    c = DummyStatus()
    value_list = c.GetAutomountMapMetadata(self.conf)

    self.assertEqual(9, len(value_list))


if __name__ == '__main__':
  unittest.main()