aboutsummaryrefslogtreecommitdiff
blob: f61d4b629521ff6ef3bab5d779b38dcbce645d39 (plain)
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
# -*- coding: utf-8 -*-
#################################################################################
# EXTERNAL LAYMAN TESTS
#################################################################################
# File:       external.py
#
#             Runs external (non-doctest) test cases.
#
# Copyright:
#             (c) 2009        Sebastian Pipping
#             Distributed under the terms of the GNU General Public License v2
#
# Author(s):
#             Sebastian Pipping <sebastian@pipping.org>
#

from __future__ import print_function
from __future__ import unicode_literals

'''Runs external (non-doctest) test cases.'''

import os
import sys
import shutil
import tempfile
import unittest
import xml.etree.ElementTree as ET # Python 2.5
#Py3
try:
    import urllib.request as urllib
except ImportError:
    import urllib

from  layman.argsparser       import ArgsParser
from  layman.api              import LaymanAPI
from  layman.db               import DB
from  layman.dbbase           import DbBase
from  layman.compatibility    import fileopen
from  layman.config           import BareConfig, OptionConfig
from  layman.maker            import Interactive
from  layman.output           import Message
from  layman.overlays.overlay import Overlay
from  layman.remotedb         import RemoteDB
from  layman.repoconfmanager  import RepoConfManager
from  layman.utils            import path
from  warnings import filterwarnings, resetwarnings

encoding = sys.getdefaultencoding()

if encoding != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')

HERE = os.path.dirname(os.path.realpath(__file__))

class AddDeleteEnableDisableFromConf(unittest.TestCase):

    def test(self):
        tmpdir = tempfile.mkdtemp(prefix='laymantmp_')
        makeconf = os.path.join(tmpdir, 'make.conf')
        reposconf = os.path.join(tmpdir, 'repos.conf')

        make_txt =\
        'PORTDIR_OVERLAY="\n'\
        '$PORTDIR_OVERLAY"'

        # Create the .conf files so layman doesn't
        # complain.
        with fileopen(makeconf, 'w') as f:
            f.write(make_txt)

        with fileopen(reposconf, 'w') as f:
            f.write('')

        my_opts = {
                   'installed' :
                   HERE + '/testfiles/global-overlays.xml',
                   'make_conf' : makeconf,
                   'nocheck'    : 'yes',
                   'storage'   : tmpdir,
                   'repos_conf' : reposconf,
                   'conf_type' : ['make.conf', 'repos.conf'],
                   }

        config = OptionConfig(my_opts)
        config.set_option('quietness', 3)

        a = DB(config)
        config['output'].set_colorize(False)

        conf = RepoConfManager(config, a.overlays)

        # Set up our success tracker.
        success = []

        # Add all the overlays in global_overlays.xml.
        for overlay in a.overlays.keys():
            conf_success = conf.add(a.overlays[overlay])
            if conf_success == False:
                success.append(False)
            else:
                success.append(True)

        # Disable one overlay.
        self.assertTrue(conf.disable(a.overlays['wrobel']))

        # Enable disabled overlay.
        self.assertTrue(conf.enable(a.overlays['wrobel']))

        # Delete all the overlays in global_overlays.xml.
        for overlay in a.overlays.keys():
            self.assertTrue(conf.delete(a.overlays[overlay]))

        # Clean up.
        os.unlink(makeconf)
        os.unlink(reposconf)

        shutil.rmtree(tmpdir)


class AddDeleteDB(unittest.TestCase):
    def test(self):
        repo_name     = 'tar_test_overlay'
        temp_dir_path = tempfile.mkdtemp(prefix='laymantmp_')
        db_file       = os.path.join(temp_dir_path, 'installed.xml')
        make_conf     = os.path.join(temp_dir_path, 'make.conf')
        repo_conf     = os.path.join(temp_dir_path, 'repos.conf')

        tar_source_path = os.path.join(HERE, 'testfiles', 'layman-test.tar.bz2')

        (_, temp_tarball_path) = tempfile.mkstemp()
        shutil.copyfile(tar_source_path, temp_tarball_path)

        # Write overlay collection XML
        xml_text = '''\
<?xml version="1.0" encoding="UTF-8"?>
<repositories xmlns="" version="1.0">
  <repo quality="experimental" status="unofficial">
    <name>%(repo_name)s</name>
    <description>XXXXXXXXXXX</description>
    <owner>
      <email>foo@example.org</email>
    </owner>
    <source type="tar">file://%(temp_tarball_url)s</source>
  </repo>
</repositories>
        '''\
        % {
            'temp_tarball_url': urllib.pathname2url(temp_tarball_path),
            'repo_name': repo_name
          }

        (fd, temp_xml_path) = tempfile.mkstemp()

        my_opts = {'installed'     : temp_xml_path,
                   'conf_type'     : ['make.conf', 'repos.conf'],
                   'db_type'       : 'xml',
                   'nocheck'       : 'yes',
                   'make_conf'     : make_conf,
                   'repos_conf'    : repo_conf,
                   'storage'       : temp_dir_path,
                   'check_official': False}

        with os.fdopen(fd, 'w') as f:
            f.write(xml_text)

        with fileopen(make_conf, 'w') as f:
            f.write('PORTDIR_OVERLAY="$PORTDIR_OVERLAY"\n')

        with fileopen(repo_conf, 'w') as f:
            f.write('')

        config = OptionConfig(options=my_opts)
        config.set_option('quietness', 3)

        a = DB(config)
        config.set_option('installed', db_file)

        # Add an overlay to a fresh DB file.
        b = DB(config)
        b.add(a.select(repo_name))

        # Make sure it's actually installed.
        specific_overlay_path = os.path.join(temp_dir_path, repo_name)
        self.assertTrue(os.path.exists(specific_overlay_path))

        # Check the DbBase to ensure that it's reading the installed.xml.
        c = DbBase(config, paths=[db_file,])
        self.assertEqual(list(c.overlays), ['tar_test_overlay'])

        # Make sure the configs have been written to correctly.
        conf = RepoConfManager(config, b.overlays)
        self.assertEqual(list(conf.overlays), ['tar_test_overlay'])

        # Delete the overlay from the second DB.
        b.delete(b.select(repo_name))
        self.assertEqual(b.overlays, {})

        # Ensure the installed.xml has been cleaned properly.
        c = DbBase(config, paths=[db_file,])
        self.assertEqual(c.overlays, {})

        conf = RepoConfManager(config, b.overlays)
        self.assertEqual(conf.overlays, {})

        # Clean up.
        os.unlink(temp_xml_path)
        os.unlink(temp_tarball_path)
        shutil.rmtree(temp_dir_path)


# Tests archive overlay types (squashfs, tar)
# http://bugs.gentoo.org/show_bug.cgi?id=304547
class ArchiveAddRemoveSync(unittest.TestCase):

    def _create_squashfs_overlay(self):
        repo_name = 'squashfs-test-overlay'
        squashfs_source_path = os.path.join(HERE, 'testfiles', 'layman-test.squashfs')

        # Duplicate test squashfs (so we can delete it after testing)
        (_, temp_squashfs_path) = tempfile.mkstemp()
        shutil.copyfile(squashfs_source_path, temp_squashfs_path)

        # Write overlay collection XML
        xml_text = '''\
<?xml version="1.0" encoding="UTF-8"?>
<repositories xmlns="" version="1.0">
  <repo quality="experimental" status="unofficial">
    <name>%(repo_name)s</name>
    <description>XXXXXXXXXXX</description>
    <owner>
      <email>foo@example.org</email>
    </owner>
    <source type="squashfs">file://%(temp_squashfs_url)s</source>
  </repo>
</repositories>
        '''\
        % {
            'temp_squashfs_url': urllib.pathname2url(temp_squashfs_path),
            'repo_name': repo_name
          }
        print(xml_text)
        return xml_text, repo_name, temp_squashfs_path


    def _create_tar_overlay(self):
        repo_name = 'tar-test-overlay'
        tar_source_path = os.path.join(HERE, 'testfiles', 'layman-test.tar.bz2')

        # Duplicate test tarball (so we can delete it after testing)
        (_, temp_tarball_path) = tempfile.mkstemp()
        shutil.copyfile(tar_source_path, temp_tarball_path)

        # Write overlay collection XML
        xml_text = '''\
<?xml version="1.0" encoding="UTF-8"?>
<repositories xmlns="" version="1.0">
  <repo quality="experimental" status="unofficial">
    <name>%(repo_name)s</name>
    <description>XXXXXXXXXXX</description>
    <owner>
      <email>foo@example.org</email>
    </owner>
    <source type="tar">file://%(temp_tarball_url)s</source>
  </repo>
</repositories>
        '''\
        % {
            'temp_tarball_url': urllib.pathname2url(temp_tarball_path),
            'repo_name': repo_name
          }
        print(xml_text)
        return xml_text, repo_name, temp_tarball_path


    def test(self):
        archives = []
        try:
            from layman.overlays.modules.tar.tar import TarOverlay
            archives.append('tar')
            from layman.overlays.modules.squashfs.squashfs import SquashfsOverlay
            archives.append('squashfs')
        except ImportError:
            pass

        for archive in archives:
            xml_text, repo_name, temp_archive_path = getattr(self,
                                            "_create_%(archive)s_overlay" %
                                            {'archive': archive})()

            (fd, temp_collection_path) = tempfile.mkstemp()
            with os.fdopen(fd, 'w') as f:
                f.write(xml_text)

            # Make playground directory
            temp_dir_path = tempfile.mkdtemp()

            # Make DB from it
            config = BareConfig()
            # Necessary for all mountable overlay types
            layman_inst = LaymanAPI(config=config)
            db = DbBase(config, [temp_collection_path])

            specific_overlay_path = os.path.join(temp_dir_path, repo_name)
            o = db.select(repo_name)

            # Actual testcase
            o.add(temp_dir_path)
            self.assertTrue(os.path.exists(specific_overlay_path))
            # (1/2) Sync with source available
            o.sync(temp_dir_path)
            self.assertTrue(os.path.exists(specific_overlay_path))
            os.unlink(temp_archive_path)
            try:
                # (2/2) Sync with source _not_ available
                o.sync(temp_dir_path)
            except:
                pass
            self.assertTrue(os.path.exists(specific_overlay_path))
            o.delete(temp_dir_path)
            self.assertFalse(os.path.exists(specific_overlay_path))

            # Cleanup
            os.unlink(temp_collection_path)
            os.rmdir(temp_dir_path)


class CLIArgs(unittest.TestCase):

    def test(self):
        # Append cli args to sys.argv with correspoding options:
        sys.argv.append('--config')
        sys.argv.append(HERE + '/../../etc/layman.cfg')

        sys.argv.append('--overlay_defs')
        sys.argv.append('')

        # Test the passed in cli opts on the ArgsParser class:
        a = ArgsParser()
        test_url = 'https://api.gentoo.org/overlays/repositories.xml'
        self.assertTrue(test_url in a['overlays'].split('\n'))

        test_keys = ['auto_sync', 'bzr_addopts', 'bzr_command', 'bzr_postsync',
                     'bzr_syncopts', 'cache', 'check_official', 'clean_archive',
                     'conf_module', 'conf_type', 'config', 'configdir',
                     'custom_news_pkg', 'cvs_addopts', 'cvs_command',
                     'cvs_postsync', 'cvs_syncopts', 'darcs_addopts',
                     'darcs_command', 'darcs_postsync', 'darcs_syncopts',
                     'db_type', 'g-common_command', 'g-common_generateopts',
                     'g-common_postsync', 'g-common_syncopts',
                     'g-sorcery_command', 'g-sorcery_generateopts',
                     'g-sorcery_postsync', 'g-sorcery_syncopts', 'git_addopts',
                     'git_command', 'git_email', 'git_postsync', 'git_syncopts',
                     'git_user', 'gpg_detached_lists', 'gpg_signed_lists',
                     'http_proxy', 'https_proxy', 'installed', 'local_list',
                     'make_conf', 'mercurial_addopts', 'mercurial_command',
                     'mercurial_postsync', 'mercurial_syncopts',
                     'news_reporter', 'nocheck', 'overlay_defs', 'overlays',
                     'protocol_filter', 'quietness', 'repos_conf',
                     'require_repoconfig', 'rsync_command', 'rsync_postsync',
                     'rsync_syncopts', 'squashfs_addopts', 'squashfs_command',
                     'squashfs_postsync', 'squashfs_syncopts', 'storage',
                     'support_url_updates', 'svn_addopts', 'svn_command',
                     'svn_postsync', 'svn_syncopts', 't/f_options',
                     'tar_command', 'tar_postsync', 'umask', 'width']
        # Due to this not being a dict object, the keys() invocation is needed.
        self.assertEqual(sorted(a.keys()), test_keys)


class CreateConfig(unittest.TestCase):

    def make_BareConfig(self):
        a = BareConfig()

        # Test components of the BareConfig class:
        self.test_url = 'https://api.gentoo.org/overlays/repositories.xml'
        assertEqual(a['overlay'], self.test_url)
        self.test_keys =  ['bzr_addopts', 'bzr_command', 'bzr_postsync',
                      'bzr_syncopts', 'cache', 'config', 'configdir',
                      'custom_news_func', 'custom_news_pkg', 'cvs_addopts',
                      'cvs_command', 'cvs_postsync', 'cvs_syncopts',
                      'darcs_addopts', 'darcs_command', 'darcs_postsync',
                      'darcs_syncopts', 'g-common_command',
                      'g-common_generateopts', 'g-common_postsync',
                      'g-common_syncopts', 'git_addopts', 'git_command',
                      'git_email', 'git_postsync', 'git_syncopts', 'git_user',
                      'installed', 'local_list', 'make_conf',
                      'mercurial_addopts', 'mercurial_command',
                      'mercurial_postsync', 'mercurial_syncopts',
                      'news_reporter', 'nocheck', 'nocolor', 'output',
                      'overlay_defs', 'overlays', 'proxy', 'quiet',
                      'quietness', 'rsync_command', 'rsync_postsync',
                      'rsync_syncopts', 'stderr', 'stdin', 'stdout', 'storage',
                      'svn_addopts', 'svn_command', 'svn_postsync',
                      'svn_syncopts', 't/f_options', 'tar_command',
                      'tar_postsync', 'umask', 'verbose', 'width']
        assertEqual(sorted(a), self.test_keys)
        assertEqual(a.get_option('nocheck'), True)


    def make_OptionConfig(self):
        my_opts = {
                   'overlays':
                   ["http://www.gentoo-overlays.org/repositories.xml"]
                  }
        new_defaults = {'configdir': '/etc/test-dir'}

        a = OptionConfig(options=my_opts, defaults=new_defaults)

        # Test components of the OptionConfig class:
        assertEqual(a['overlays'], self.test_url)
        assertEqual(a['configdir'], my_opts['configdir'])
        assertEqual(sorted(a), self.test_keys)


    def test(self):
        for i in ['BareConfig', 'OptionConfig']:
            getattr(self, 'make_%s' % i)


class FetchRemoteList(unittest.TestCase):

    def test(self):
        tmpdir = tempfile.mkdtemp(prefix='laymantmp_')
        cache = os.path.join(tmpdir, 'cache')

        my_opts = {
                   'overlays': ['file://'\
                                + HERE + '/testfiles/global-overlays.xml'],
                   'cache': cache,
                   'nocheck': 'yes',
                   'proxy': None,
                   'quietness': 3
                  }

        config = OptionConfig(my_opts)

        api = LaymanAPI(config)
        self.assertTrue(api.fetch_remote_list())

        filename = api._get_remote_db().filepath(config['overlays']) + '.xml'

        with fileopen(filename, 'r') as b:
            self.assertEqual(b.readlines()[19], '      A collection of ebuilds from Gunnar Wrobel [wrobel@gentoo.org].\n')
            for line in b.readlines():
                print(line, end='')

        # Check if we get available overlays.
        available = api.get_available()
        self.assertEqual(available, ['wrobel', 'wrobel-stable'])

        # Test the info of an overlay.
        all_info = api.get_all_info('wrobel')

        test_info = {'status': 'official', 'owner_name': None,
                     'description': ['Test'], 'src_uris':
                     ['https://overlays.gentoo.org/svn/dev/wrobel'],
                     'owner_email': 'nobody@gentoo.org', 'sources':
                     [('https://overlays.gentoo.org/svn/dev/wrobel',
                     'Subversion', None)], 'quality': 'experimental', 'name':
                     'wrobel', 'supported': True, 'src_types': ['Subversion'],
                     'official': True, 'priority': 10, 'feeds': [],
                     'irc': None, 'homepage': None}
        info = all_info['wrobel']
        info['src_uris'] = [e for e in info['src_uris']]
        info['src_types'] = [e for e in info['src_types']]
        
        self.assertEqual(info, test_info)

        self.assertEqual(info['status'], 'official')
        self.assertEqual(info['description'], ['Test'])
        sources = [('https://overlays.gentoo.org/svn/dev/wrobel', 'Subversion',
                    None)]
        self.assertEqual(info['sources'], sources)

        os.unlink(filename)
        shutil.rmtree(tmpdir)


class FormatBranchCategory(unittest.TestCase):
    def _run(self, number):
        #config = {'output': Message()}
        config = BareConfig()

        # Discuss renaming files to "branch-%d.xml"
        filename1 = os.path.join(HERE, 'testfiles',
                'subpath-%d.xml' % number)

        # Read, write, re-read, compare
        os1 = DbBase(config, [filename1])
        filename2 = tempfile.mkstemp()[1]
        os1.write(filename2)
        os2 = DbBase(config, [filename2])
        os.unlink(filename2)
        self.assertTrue(os1 == os2)

        # Pass original overlays
        return os1

    def test(self):
        os1 = self._run(1)
        os2 = self._run(2)

        # Same content from old/layman-global.txt
        #   and new/repositories.xml format?
        self.assertTrue(os1 == os2)


class MakeOverlayXML(unittest.TestCase):

    def test(self):
        temp_dir_path = tempfile.mkdtemp()
        my_opts = {
                   'overlays': ['file://'\
                        + HERE + '/testfiles/global-overlays.xml'],
                   'nocheck': 'yes',
                   'proxy': None,
                   'quietness': 3,
                  }

        config = OptionConfig(my_opts)

        ovl_dict = {
                    'name': 'wrobel',
                    'description': ['Test'],
                    'owner_name': 'nobody',
                    'owner_email': 'nobody@gentoo.org',
                    'status': 'official',
                    'source': [['https://overlays.gentoo.org/svn/dev/wrobel',
                                 'svn', '']],
                    'priority': '10',
                   }

        a = Overlay(config=config, ovl_dict=ovl_dict, ignore=config['ignore'])
        ovl = (ovl_dict['name'], a)
        path = temp_dir_path + '/overlay.xml'
        create_overlay_xml = Interactive(config=config)

        create_overlay_xml(overlay_package=ovl, path=path)
        self.assertTrue(os.path.exists(path))

        with fileopen(path, 'r') as xml:
            test_line = '    <source type="svn">'\
                        'https://overlays.gentoo.org/svn/dev/wrobel</source>\n'
            self.assertTrue(test_line in xml.readlines())
            for line in xml.readlines():
                print(line, end='')

        shutil.rmtree(temp_dir_path)


class OverlayObjTest(unittest.TestCase):

    def objattribs(self):
        document = ET.parse(HERE + '/testfiles/global-overlays.xml')
        overlays = document.findall('overlay') + document.findall('repo')
        output = Message()

        ovl_a = Overlay({'output': output, 'db_type': 'xml'}, xml=overlays[0])
        self.assertEqual(ovl_a.name, 'wrobel')
        self.assertEqual(ovl_a.is_official(), True)
        url = ['https://overlays.gentoo.org/svn/dev/wrobel']
        self.assertEqual(list(ovl_a.source_uris()), url)
        self.assertEqual(ovl_a.owner_email, 'nobody@gentoo.org')
        self.assertEqual(ovl_a.descriptions, ['Test'])
        self.assertEqual(ovl_a.priority, 10)

        ovl_b = Overlay({'output': output, 'db_type': 'xml'}, xml=overlays[1])
        self.assertEqual(ovl_b.is_official(), False)


    def getinfostr(self):
        document = ET.parse(HERE + '/testfiles/global-overlays.xml')
        overlays = document.findall('overlay') + document.findall('repo')
        output = Message()

        ovl = Overlay({'output': output, 'db_type': 'xml'}, xml=overlays[0])
        test_infostr = 'wrobel\n~~~~~~\nSource  : '\
                       'https://overlays.gentoo.org/svn/dev/wrobel\nContact '\
                       ': nobody@gentoo.org\nType    : Subversion; Priority: '\
                       '10\nQuality : experimental\n\nDescription:\n  Test\n'
        self.assertEqual(ovl.get_infostr().decode('utf-8'), test_infostr)
        print(ovl.get_infostr().decode('utf-8'))


    def getshortlist(self):
        document = ET.parse(HERE + '/testfiles/global-overlays.xml')
        overlays = document.findall('overlay') + document.findall('repo')
        output = Message()

        ovl = Overlay({'output': output, 'db_type': 'xml'}, xml=overlays[0])
        test_short_list = 'wrobel                    [Subversion] '\
                          '(https://o.g.o/svn/dev/wrobel         )'
        self.assertEqual(ovl.short_list(80).decode('utf-8'), test_short_list)
        print(ovl.short_list(80).decode('utf-8'))


    def test(self):
        self.objattribs()
        self.getinfostr()
        self.getshortlist()


class PathUtil(unittest.TestCase):

    def test(self):
        self.assertEqual(path([]), '')
        self.assertEqual(path(['a']), 'a')
        self.assertEqual(path(['a', 'b']), 'a/b')
        self.assertEqual(path(['a/', 'b']), 'a/b')
        self.assertEqual(path(['/a/', 'b']), '/a/b')
        self.assertEqual(path(['/a', '/b/']), '/a/b')
        self.assertEqual(path(['/a/', 'b/']), '/a/b')
        self.assertEqual(path(['/a/','/b/']), '/a/b')
        self.assertEqual(path(['/a/','/b','c/']), '/a/b/c')


class Unicode(unittest.TestCase):
    def _overlays_bug(self, number):
        config = BareConfig()
        filename = os.path.join(HERE, 'testfiles', 'overlays_bug_%d.xml'\
                                                    % number)
        o = DbBase(config, [filename])
        for verbose in (True, False):
            for t in o.list(verbose=verbose):
                print(t[0].decode('utf-8'))
                print()

    def test_184449(self):
        self._overlays_bug(184449)

    def test_286290(self):
        self._overlays_bug(286290)


class ReadWriteSelectListDbBase(unittest.TestCase):

    def list_db(self):
        output = Message()
        config = {
                  'output': output,
                  'db_type': 'xml',
                  'svn_command': '/usr/bin/svn',
                  'rsync_command':'/usr/bin/rsync'
                 }
        db = DbBase(config, [HERE + '/testfiles/global-overlays.xml', ])

        test_info = ('wrobel\n~~~~~~\nSource  : '\
                     'https://overlays.gentoo.org/svn/dev/wrobel\nContact : '\
                     'nobody@gentoo.org\nType    : Subversion; Priority: 10\n'\
                     'Quality : experimental\n\nDescription:\n  Test\n',
                     'wrobel-stable\n~~~~~~~~~~~~~\nSource  : '\
                     'rsync://gunnarwrobel.de/wrobel-stable\nContact : '\
                     'nobody@gentoo.org\nType    : Rsync; Priority: 50\n'\
                     'Quality : experimental\n\nDescription:\n  A collection '\
                     'of ebuilds from Gunnar Wrobel [wrobel@gentoo.org].\n')

        info = db.list(verbose=True)

        for i in range(0, len(info)):
            self.assertEqual(info[i][0].decode('utf-8'), test_info[i])
            print(info[i][0].decode('utf-8'))

        test_info = ('wrobel                    [Subversion] '\
                     '(https://o.g.o/svn/dev/wrobel         )',
                     'wrobel-stable             [Rsync     ] '\
                     '(rsync://gunnarwrobel.de/wrobel-stable)')

        info = db.list(verbose=False, width=80)
        for i in range(0, len(info)):
            self.assertEqual(info[i][0].decode('utf-8'), test_info[i])
            print(info[i][0].decode('utf-8'))

    def read_db(self):
        output = Message()
        # First test if XML databasing works.
        config = {'output': output,
                  'db_type': 'xml',}
        db = DbBase(config, [HERE + '/testfiles/global-overlays.xml', ])
        keys = sorted(db.overlays)
        self.assertEqual(keys, ['wrobel', 'wrobel-stable'])

        url = ['rsync://gunnarwrobel.de/wrobel-stable']
        self.assertEqual(list(db.overlays['wrobel-stable'].source_uris()), url)

        # Test JSON databasing after.
        config['db_type'] = 'json'
        db = DbBase(config, [HERE + '/testfiles/global-overlays.json', ])
        keys = sorted(db.overlays)
        self.assertEqual(keys, ['twitch153', 'wrobel-stable'])

        url = ['git://github.com/twitch153/ebuilds.git']
        self.assertEqual(list(db.overlays['twitch153'].source_uris()), url)


    def select_db(self):
        output = Message()
        config = {'output': output,
                  'db_type': 'xml',}
        db = DbBase(config, [HERE + '/testfiles/global-overlays.xml', ])
        url = ['rsync://gunnarwrobel.de/wrobel-stable']
        self.assertEqual(list(db.select('wrobel-stable').source_uris()), url)

        config['db_type'] = 'json'
        db = DbBase(config, [HERE + '/testfiles/global-overlays.json', ])
        url = ['git://github.com/twitch153/ebuilds.git']
        self.assertEqual(list(db.select('twitch153').source_uris()), url)


    def write_db(self):
        tmpdir = tempfile.mkdtemp(prefix='laymantmp_')
        test_xml = os.path.join(tmpdir, 'test.xml')
        test_json = os.path.join(tmpdir, 'test.json')
        config = BareConfig()

        a = DbBase(config, [HERE + '/testfiles/global-overlays.xml', ])
        b = DbBase({'output': Message(), 'db_type': 'xml'}, [test_xml,])

        b.overlays['wrobel-stable'] = a.overlays['wrobel-stable']
        b.write(test_xml)

        c = DbBase({'output': Message(), 'db_type': 'xml'}, [test_xml,])
        keys = sorted(c.overlays)
        self.assertEqual(keys, ['wrobel-stable'])

        config.set_option('db_type', 'json')
        a = DbBase(config, [HERE + '/testfiles/global-overlays.json', ])
        b = DbBase({'output': Message(), 'db_type': 'json'}, [test_json,])

        b.overlays['twitch153'] = a.overlays['twitch153']
        b.write(test_json)

        c = DbBase({'output': Message(), 'db_type': 'json'}, [test_json,])
        keys = sorted(c.overlays)
        self.assertEqual(keys, ['twitch153'])

        # Clean up:
        os.unlink(test_xml)
        os.unlink(test_json)
        shutil.rmtree(tmpdir)


    def test(self):
        self.list_db()
        self.read_db()
        self.select_db()
        self.write_db()


class RemoteDBCache(unittest.TestCase):
    def test(self):
        tmpdir = tempfile.mkdtemp(prefix='laymantmp_')
        cache = os.path.join(tmpdir, 'cache')
        my_opts = {
                   'overlays' :
                   ['file://' + HERE + '/testfiles/global-overlays.xml'],
                   'cache' : cache,
                   'nocheck'    : 'yes',
                   'proxy' : None
                  }
        config = OptionConfig(my_opts)
        db = RemoteDB(config)
        self.assertEqual(db.cache(), (True, True))

        db_xml = fileopen(db.filepath(config['overlays']) + '.xml')

        test_line = '      A collection of ebuilds from Gunnar Wrobel '\
                    '[wrobel@gentoo.org].\n'
        self.assertEqual(db_xml.readlines()[19], test_line)

        for line in db_xml.readlines():
            print(line, end='')

        db_xml.close()
        keys = sorted(db.overlays)
        self.assertEqual(keys, ['wrobel', 'wrobel-stable'])

        shutil.rmtree(tmpdir)


if __name__ == '__main__':
    filterwarnings('ignore')
    unittest.main()
    resetwarnings()