summaryrefslogtreecommitdiff
path: root/tests/unit/test_model.py
blob: 98f971948b4c78beefcc05600e8f4c8b6eda62ad (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
785
# Copyright 2015 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.


import configparser
import collections
import os
import random
import types
from unittest import mock

import fixtures
import testtools

from zuul import model
from zuul import configloader
from zuul.lib import encryption
from zuul.lib import yamlutil as yaml
import zuul.lib.connections

from tests.base import BaseTestCase, FIXTURE_DIR
from zuul.lib.ansible import AnsibleManager
from zuul.lib import tracing
from zuul.model_api import MODEL_API
from zuul.zk.zkobject import LocalZKContext
from zuul.zk.components import COMPONENT_REGISTRY
from zuul import change_matcher


class Dummy(object):
    def __init__(self, **kw):
        for k, v in kw.items():
            setattr(self, k, v)


class TestJob(BaseTestCase):
    def setUp(self):
        COMPONENT_REGISTRY.registry = Dummy()
        COMPONENT_REGISTRY.registry.model_api = MODEL_API
        self._env_fixture = self.useFixture(
            fixtures.EnvironmentVariable('HISTTIMEFORMAT', '%Y-%m-%dT%T%z '))
        super(TestJob, self).setUp()
        # Toss in % in env vars to trigger the configparser issue
        self.connections = zuul.lib.connections.ConnectionRegistry()
        self.addCleanup(self.connections.stop)
        self.connection = Dummy(connection_name='dummy_connection')
        self.source = Dummy(canonical_hostname='git.example.com',
                            connection=self.connection)
        self.abide = model.Abide()
        self.tenant = model.Tenant('tenant')
        self.tenant.default_ansible_version = AnsibleManager().default_version
        self.tenant.semaphore_handler = Dummy(abide=self.abide)
        self.layout = model.Layout(self.tenant)
        self.tenant.layout = self.layout
        self.project = model.Project('project', self.source)
        self.context = model.SourceContext(
            self.project.canonical_name, self.project.name,
            self.project.connection_name, 'master', 'test', True)
        self.untrusted_context = model.SourceContext(
            self.project.canonical_name, self.project.name,
            self.project.connection_name, 'master', 'test', False)
        self.tpc = model.TenantProjectConfig(self.project)
        self.tenant.addUntrustedProject(self.tpc)
        self.pipeline = model.Pipeline('gate', self.tenant)
        self.pipeline.source_context = self.context
        self.pipeline.manager = mock.Mock()
        self.pipeline.tenant = self.tenant
        self.zk_context = LocalZKContext(self.log)
        self.pipeline.manager.current_context = self.zk_context
        self.pipeline.state = model.PipelineState()
        self.pipeline.state._set(pipeline=self.pipeline)
        self.layout.addPipeline(self.pipeline)
        with self.zk_context as ctx:
            self.queue = model.ChangeQueue.new(
                ctx, pipeline=self.pipeline)
        self.pcontext = configloader.ParseContext(
            self.connections, None, self.tenant, AnsibleManager())

        private_key_file = os.path.join(FIXTURE_DIR, 'private.pem')
        with open(private_key_file, "rb") as f:
            priv, pub = encryption.deserialize_rsa_keypair(f.read())
            self.project.private_secrets_key = priv
            self.project.public_secrets_key = pub
        m = yaml.Mark('name', 0, 0, 0, '', 0)
        self.start_mark = model.ZuulMark(m, m, '')
        config = configparser.ConfigParser()
        self.tracing = tracing.Tracing(config)

    @property
    def job(self):
        job = self.pcontext.job_parser.fromYaml({
            '_source_context': self.context,
            '_start_mark': self.start_mark,
            'name': 'job',
            'parent': None,
            'irrelevant-files': [
                '^docs/.*$'
            ]})
        return job

    def test_change_matches_returns_false_for_matched_skip_if(self):
        change = model.Change('project')
        change.files = ['/COMMIT_MSG', 'docs/foo']
        self.assertFalse(self.job.changeMatchesFiles(change))

    def test_change_matches_returns_false_for_single_matched_skip_if(self):
        change = model.Change('project')
        change.files = ['docs/foo']
        self.assertFalse(self.job.changeMatchesFiles(change))

    def test_change_matches_returns_true_for_unmatched_skip_if(self):
        change = model.Change('project')
        change.files = ['/COMMIT_MSG', 'foo']
        self.assertTrue(self.job.changeMatchesFiles(change))

    def test_change_matches_returns_true_for_single_unmatched_skip_if(self):
        change = model.Change('project')
        change.files = ['foo']
        self.assertTrue(self.job.changeMatchesFiles(change))

    def test_job_sets_defaults_for_boolean_attributes(self):
        self.assertIsNotNone(self.job.voting)

    def test_job_variants(self):
        # This simulates freezing a job.

        secrets = ['foo']
        py27_pre = model.PlaybookContext(
            self.context, 'py27-pre', [], secrets, [])
        py27_run = model.PlaybookContext(
            self.context, 'py27-run', [], secrets, [])
        py27_post = model.PlaybookContext(
            self.context, 'py27-post', [], secrets, [])

        py27 = model.Job('py27')
        py27.timeout = 30
        py27.pre_run = (py27_pre,)
        py27.run = (py27_run,)
        py27.post_run = (py27_post,)

        job = py27.copy()
        self.assertEqual(30, job.timeout)

        # Apply the diablo variant
        diablo = model.Job('py27')
        diablo.timeout = 40
        job.applyVariant(diablo, self.layout, None)

        self.assertEqual(40, job.timeout)
        self.assertEqual(['py27-pre'],
                         [x.path for x in job.pre_run])
        self.assertEqual(['py27-run'],
                         [x.path for x in job.run])
        self.assertEqual(['py27-post'],
                         [x.path for x in job.post_run])
        self.assertEqual(secrets, job.pre_run[0].secrets)
        self.assertEqual(secrets, job.run[0].secrets)
        self.assertEqual(secrets, job.post_run[0].secrets)

        # Set the job to final for the following checks
        job.final = True
        self.assertTrue(job.voting)

        good_final = model.Job('py27')
        good_final.voting = False
        job.applyVariant(good_final, self.layout, None)
        self.assertFalse(job.voting)

        bad_final = model.Job('py27')
        bad_final.timeout = 600
        with testtools.ExpectedException(
                Exception,
                "Unable to modify final job"):
            job.applyVariant(bad_final, self.layout, None)

    @mock.patch("zuul.model.zkobject.ZKObject._save")
    def test_job_inheritance_job_tree(self, save_mock):
        base = self.pcontext.job_parser.fromYaml({
            '_source_context': self.context,
            '_start_mark': self.start_mark,
            'name': 'base',
            'parent': None,
            'timeout': 30,
        })
        self.layout.addJob(base)
        python27 = self.pcontext.job_parser.fromYaml({
            '_source_context': self.context,
            '_start_mark': self.start_mark,
            'name': 'python27',
            'parent': 'base',
            'timeout': 40,
        })
        self.layout.addJob(python27)
        python27diablo = self.pcontext.job_parser.fromYaml({
            '_source_context': self.context,
            '_start_mark': self.start_mark,
            'name': 'python27',
            'branches': [
                'stable/diablo'
            ],
            'timeout': 50,
        })
        self.layout.addJob(python27diablo)

        project_config = self.pcontext.project_parser.fromYaml({
            '_source_context': self.context,
            '_start_mark': self.start_mark,
            'name': 'project',
            'gate': {
                'jobs': [
                    {'python27': {'timeout': 70,
                                  'run': 'playbooks/python27.yaml'}}
                ]
            }
        })
        self.layout.addProjectConfig(project_config)

        change = model.Change(self.project)
        change.branch = 'master'
        item = self.queue.enqueueChange(change, None)

        self.assertTrue(base.changeMatchesBranch(change))
        self.assertTrue(python27.changeMatchesBranch(change))
        self.assertFalse(python27diablo.changeMatchesBranch(change))

        with self.zk_context as ctx:
            item.freezeJobGraph(self.layout, ctx,
                                skip_file_matcher=False,
                                redact_secrets_and_keys=False)
        self.assertEqual(len(item.getJobs()), 1)
        job = item.getJobs()[0]
        self.assertEqual(job.name, 'python27')
        self.assertEqual(job.timeout, 70)

        change.branch = 'stable/diablo'
        item = self.queue.enqueueChange(change, None)

        self.assertTrue(base.changeMatchesBranch(change))
        self.assertTrue(python27.changeMatchesBranch(change))
        self.assertTrue(python27diablo.changeMatchesBranch(change))

        with self.zk_context as ctx:
            item.freezeJobGraph(self.layout, ctx,
                                skip_file_matcher=False,
                                redact_secrets_and_keys=False)
        self.assertEqual(len(item.getJobs()), 1)
        job = item.getJobs()[0]
        self.assertEqual(job.name, 'python27')
        self.assertEqual(job.timeout, 70)

    @mock.patch("zuul.model.zkobject.ZKObject._save")
    def test_inheritance_keeps_matchers(self, save_mock):
        base = self.pcontext.job_parser.fromYaml({
            '_source_context': self.context,
            '_start_mark': self.start_mark,
            'name': 'base',
            'parent': None,
            'timeout': 30,
        })
        self.layout.addJob(base)
        python27 = self.pcontext.job_parser.fromYaml({
            '_source_context': self.context,
            '_start_mark': self.start_mark,
            'name': 'python27',
            'parent': 'base',
            'timeout': 40,
            'irrelevant-files': ['^ignored-file$'],
        })
        self.layout.addJob(python27)

        project_config = self.pcontext.project_parser.fromYaml({
            '_source_context': self.context,
            '_start_mark': self.start_mark,
            'name': 'project',
            'gate': {
                'jobs': [
                    'python27',
                ]
            }
        })
        self.layout.addProjectConfig(project_config)

        change = model.Change(self.project)
        change.branch = 'master'
        change.files = ['/COMMIT_MSG', 'ignored-file']
        item = self.queue.enqueueChange(change, None)

        self.assertTrue(base.changeMatchesFiles(change))
        self.assertFalse(python27.changeMatchesFiles(change))

        self.pipeline.manager.getFallbackLayout = mock.Mock(return_value=None)
        with self.zk_context as ctx:
            item.freezeJobGraph(self.layout, ctx,
                                skip_file_matcher=False,
                                redact_secrets_and_keys=False)
        self.assertEqual([], item.getJobs())

    def test_job_source_project(self):
        base_project = model.Project('base_project', self.source)
        base_context = model.SourceContext(
            base_project.canonical_name, base_project.name,
            base_project.connection_name, 'master', 'test', True)
        tpc = model.TenantProjectConfig(base_project)
        self.tenant.addUntrustedProject(tpc)

        base = self.pcontext.job_parser.fromYaml({
            '_source_context': base_context,
            '_start_mark': self.start_mark,
            'parent': None,
            'name': 'base',
        })
        self.layout.addJob(base)

        other_project = model.Project('other_project', self.source)
        other_context = model.SourceContext(
            other_project.canonical_name, other_project.name,
            other_project.connection_name, 'master', 'test', True)
        tpc = model.TenantProjectConfig(other_project)
        self.tenant.addUntrustedProject(tpc)
        base2 = self.pcontext.job_parser.fromYaml({
            '_source_context': other_context,
            '_start_mark': self.start_mark,
            'name': 'base',
        })
        with testtools.ExpectedException(
                Exception,
                "Job base in other_project is not permitted "
                "to shadow job base in base_project"):
            self.layout.addJob(base2)

    @mock.patch("zuul.model.zkobject.ZKObject._save")
    def test_job_pipeline_allow_untrusted_secrets(self, save_mock):
        self.pipeline.post_review = False
        job = self.pcontext.job_parser.fromYaml({
            '_source_context': self.context,
            '_start_mark': self.start_mark,
            'name': 'job',
            'parent': None,
            'post-review': True
        })

        self.layout.addJob(job)

        project_config = self.pcontext.project_parser.fromYaml(
            {
                '_source_context': self.context,
                '_start_mark': self.start_mark,
                'name': 'project',
                'gate': {
                    'jobs': [
                        'job'
                    ]
                }
            }
        )
        self.layout.addProjectConfig(project_config)

        change = model.Change(self.project)
        # Test master
        change.branch = 'master'
        item = self.queue.enqueueChange(change, None)
        with testtools.ExpectedException(
                Exception,
                "Pre-review pipeline gate does not allow post-review job"):
            with self.zk_context as ctx:
                item.freezeJobGraph(self.layout, ctx,
                                    skip_file_matcher=False,
                                    redact_secrets_and_keys=False)


class TestGraph(BaseTestCase):
    def test_job_graph_disallows_multiple_jobs_with_same_name(self):
        graph = model.JobGraph({})
        job1 = model.Job('job')
        job2 = model.Job('job')
        graph.addJob(job1)
        with testtools.ExpectedException(Exception,
                                         "Job job already added"):
            graph.addJob(job2)

    def test_job_graph_disallows_circular_dependencies(self):
        graph = model.JobGraph({})
        jobs = [model.Job('job%d' % i) for i in range(0, 10)]
        prevjob = None
        for j in jobs[:3]:
            if prevjob:
                j.dependencies = frozenset([
                    model.JobDependency(prevjob.name)])
            graph.addJob(j)
            prevjob = j
        # 0 triggers 1 triggers 2 triggers 3...

        # Cannot depend on itself
        with testtools.ExpectedException(
                Exception,
                "Dependency cycle detected in job jobX"):
            j = model.Job('jobX')
            j.dependencies = frozenset([model.JobDependency(j.name)])
            graph.addJob(j)

        # Disallow circular dependencies
        with testtools.ExpectedException(
                Exception,
                "Dependency cycle detected in job job3"):
            jobs[4].dependencies = frozenset([
                model.JobDependency(jobs[3].name)])
            graph.addJob(jobs[4])
            jobs[3].dependencies = frozenset([
                model.JobDependency(jobs[4].name)])
            graph.addJob(jobs[3])

        jobs[5].dependencies = frozenset([model.JobDependency(jobs[4].name)])
        graph.addJob(jobs[5])

        with testtools.ExpectedException(
                Exception,
                "Dependency cycle detected in job job3"):
            jobs[3].dependencies = frozenset([
                model.JobDependency(jobs[5].name)])
            graph.addJob(jobs[3])

        jobs[3].dependencies = frozenset([
            model.JobDependency(jobs[2].name)])
        graph.addJob(jobs[3])
        jobs[6].dependencies = frozenset([
            model.JobDependency(jobs[2].name)])
        graph.addJob(jobs[6])

    def test_job_graph_allows_soft_dependencies(self):
        parent = model.Job('parent')
        child = model.Job('child')
        child.dependencies = frozenset([
            model.JobDependency(parent.name, True)])

        # With the parent
        graph = model.JobGraph({})
        graph.addJob(parent)
        graph.addJob(child)
        self.assertEqual(graph.getParentJobsRecursively(child.name),
                         [parent])

        # Skip the parent
        graph = model.JobGraph({})
        graph.addJob(child)
        self.assertEqual(graph.getParentJobsRecursively(child.name), [])

    def test_job_graph_allows_soft_dependencies4(self):
        # A more complex scenario with multiple parents at each level
        parents = [model.Job('parent%i' % i) for i in range(6)]
        child = model.Job('child')
        child.dependencies = frozenset([
            model.JobDependency(parents[0].name, True),
            model.JobDependency(parents[1].name)])
        parents[0].dependencies = frozenset([
            model.JobDependency(parents[2].name),
            model.JobDependency(parents[3].name, True)])
        parents[1].dependencies = frozenset([
            model.JobDependency(parents[4].name),
            model.JobDependency(parents[5].name)])
        # Run them all
        graph = model.JobGraph({})
        for j in parents:
            graph.addJob(j)
        graph.addJob(child)
        self.assertEqual(set(graph.getParentJobsRecursively(child.name)),
                         set(parents))

        # Skip first parent, therefore its recursive dependencies don't appear
        graph = model.JobGraph({})
        for j in parents:
            if j is not parents[0]:
                graph.addJob(j)
        graph.addJob(child)
        self.assertEqual(set(graph.getParentJobsRecursively(child.name)),
                         set(parents) -
                         set([parents[0], parents[2], parents[3]]))

        # Skip a leaf node
        graph = model.JobGraph({})
        for j in parents:
            if j is not parents[3]:
                graph.addJob(j)
        graph.addJob(child)
        self.assertEqual(set(graph.getParentJobsRecursively(child.name)),
                         set(parents) - set([parents[3]]))


class TestTenant(BaseTestCase):
    def test_add_project(self):
        tenant = model.Tenant('tenant')
        connection1 = Dummy(connection_name='dummy_connection1')
        source1 = Dummy(canonical_hostname='git1.example.com',
                        name='dummy',  # TODOv3(jeblair): remove
                        connection=connection1)

        source1_project1 = model.Project('project1', source1)
        source1_project1_tpc = model.TenantProjectConfig(source1_project1)
        tenant.addConfigProject(source1_project1_tpc)
        d = {'project1':
             {'git1.example.com': source1_project1}}
        self.assertEqual(d, tenant.projects)
        self.assertEqual((True, source1_project1),
                         tenant.getProject('project1'))
        self.assertEqual((True, source1_project1),
                         tenant.getProject('git1.example.com/project1'))

        source1_project2 = model.Project('project2', source1)
        tpc = model.TenantProjectConfig(source1_project2)
        tenant.addUntrustedProject(tpc)
        d = {'project1':
             {'git1.example.com': source1_project1},
             'project2':
             {'git1.example.com': source1_project2}}
        self.assertEqual(d, tenant.projects)
        self.assertEqual((False, source1_project2),
                         tenant.getProject('project2'))
        self.assertEqual((False, source1_project2),
                         tenant.getProject('git1.example.com/project2'))

        connection2 = Dummy(connection_name='dummy_connection2')
        source2 = Dummy(canonical_hostname='git2.example.com',
                        name='dummy',  # TODOv3(jeblair): remove
                        connection=connection2)

        source2_project1 = model.Project('project1', source2)
        tpc = model.TenantProjectConfig(source2_project1)
        tenant.addUntrustedProject(tpc)
        d = {'project1':
             {'git1.example.com': source1_project1,
              'git2.example.com': source2_project1},
             'project2':
             {'git1.example.com': source1_project2}}
        self.assertEqual(d, tenant.projects)
        with testtools.ExpectedException(
                Exception,
                "Project name 'project1' is ambiguous"):
            tenant.getProject('project1')
        self.assertEqual((False, source1_project2),
                         tenant.getProject('project2'))
        self.assertEqual((True, source1_project1),
                         tenant.getProject('git1.example.com/project1'))
        self.assertEqual((False, source2_project1),
                         tenant.getProject('git2.example.com/project1'))

        source2_project2 = model.Project('project2', source2)
        tpc = model.TenantProjectConfig(source2_project2)
        tenant.addConfigProject(tpc)
        d = {'project1':
             {'git1.example.com': source1_project1,
              'git2.example.com': source2_project1},
             'project2':
             {'git1.example.com': source1_project2,
              'git2.example.com': source2_project2}}
        self.assertEqual(d, tenant.projects)
        with testtools.ExpectedException(
                Exception,
                "Project name 'project1' is ambiguous"):
            tenant.getProject('project1')
        with testtools.ExpectedException(
                Exception,
                "Project name 'project2' is ambiguous"):
            tenant.getProject('project2')
        self.assertEqual((True, source1_project1),
                         tenant.getProject('git1.example.com/project1'))
        self.assertEqual((False, source2_project1),
                         tenant.getProject('git2.example.com/project1'))
        self.assertEqual((False, source1_project2),
                         tenant.getProject('git1.example.com/project2'))
        self.assertEqual((True, source2_project2),
                         tenant.getProject('git2.example.com/project2'))

        source1_project2b = model.Project('subpath/project2', source1)
        tpc = model.TenantProjectConfig(source1_project2b)
        tenant.addConfigProject(tpc)
        d = {'project1':
             {'git1.example.com': source1_project1,
              'git2.example.com': source2_project1},
             'project2':
             {'git1.example.com': source1_project2,
              'git2.example.com': source2_project2},
             'subpath/project2':
             {'git1.example.com': source1_project2b}}
        self.assertEqual(d, tenant.projects)
        self.assertEqual((False, source1_project2),
                         tenant.getProject('git1.example.com/project2'))
        self.assertEqual((True, source2_project2),
                         tenant.getProject('git2.example.com/project2'))
        self.assertEqual((True, source1_project2b),
                         tenant.getProject('subpath/project2'))
        self.assertEqual(
            (True, source1_project2b),
            tenant.getProject('git1.example.com/subpath/project2'))

        source2_project2b = model.Project('subpath/project2', source2)
        tpc = model.TenantProjectConfig(source2_project2b)
        tenant.addConfigProject(tpc)
        d = {'project1':
             {'git1.example.com': source1_project1,
              'git2.example.com': source2_project1},
             'project2':
             {'git1.example.com': source1_project2,
              'git2.example.com': source2_project2},
             'subpath/project2':
             {'git1.example.com': source1_project2b,
              'git2.example.com': source2_project2b}}
        self.assertEqual(d, tenant.projects)
        self.assertEqual((False, source1_project2),
                         tenant.getProject('git1.example.com/project2'))
        self.assertEqual((True, source2_project2),
                         tenant.getProject('git2.example.com/project2'))
        with testtools.ExpectedException(
                Exception,
                "Project name 'subpath/project2' is ambiguous"):
            tenant.getProject('subpath/project2')
        self.assertEqual(
            (True, source1_project2b),
            tenant.getProject('git1.example.com/subpath/project2'))
        self.assertEqual(
            (True, source2_project2b),
            tenant.getProject('git2.example.com/subpath/project2'))

        with testtools.ExpectedException(
                Exception,
                "Project project1 is already in project index"):
            tenant._addProject(source1_project1_tpc)


class TestFreezable(BaseTestCase):
    def test_freezable_object(self):

        o = model.Freezable()
        o.foo = 1
        o.list = []
        o.dict = {}
        o.odict = collections.OrderedDict()
        o.odict2 = collections.OrderedDict()

        o1 = model.Freezable()
        o1.foo = 1
        l1 = [1]
        d1 = {'foo': 1}
        od1 = {'foo': 1}
        o.list.append(o1)
        o.list.append(l1)
        o.list.append(d1)
        o.list.append(od1)

        o2 = model.Freezable()
        o2.foo = 1
        l2 = [1]
        d2 = {'foo': 1}
        od2 = {'foo': 1}
        o.dict['o'] = o2
        o.dict['l'] = l2
        o.dict['d'] = d2
        o.dict['od'] = od2

        o3 = model.Freezable()
        o3.foo = 1
        l3 = [1]
        d3 = {'foo': 1}
        od3 = {'foo': 1}
        o.odict['o'] = o3
        o.odict['l'] = l3
        o.odict['d'] = d3
        o.odict['od'] = od3

        seq = list(range(1000))
        random.shuffle(seq)
        for x in seq:
            o.odict2[x] = x

        o.freeze()

        with testtools.ExpectedException(Exception, "Unable to modify frozen"):
            o.bar = 2
        with testtools.ExpectedException(AttributeError, "'tuple' object"):
            o.list.append(2)
        with testtools.ExpectedException(TypeError, "'mappingproxy' object"):
            o.dict['bar'] = 2
        with testtools.ExpectedException(TypeError, "'mappingproxy' object"):
            o.odict['bar'] = 2

        with testtools.ExpectedException(Exception, "Unable to modify frozen"):
            o1.bar = 2
        with testtools.ExpectedException(Exception, "Unable to modify frozen"):
            o.list[0].bar = 2
        with testtools.ExpectedException(AttributeError, "'tuple' object"):
            o.list[1].append(2)
        with testtools.ExpectedException(TypeError, "'mappingproxy' object"):
            o.list[2]['bar'] = 2
        with testtools.ExpectedException(TypeError, "'mappingproxy' object"):
            o.list[3]['bar'] = 2

        with testtools.ExpectedException(Exception, "Unable to modify frozen"):
            o2.bar = 2
        with testtools.ExpectedException(Exception, "Unable to modify frozen"):
            o.dict['o'].bar = 2
        with testtools.ExpectedException(AttributeError, "'tuple' object"):
            o.dict['l'].append(2)
        with testtools.ExpectedException(TypeError, "'mappingproxy' object"):
            o.dict['d']['bar'] = 2
        with testtools.ExpectedException(TypeError, "'mappingproxy' object"):
            o.dict['od']['bar'] = 2

        with testtools.ExpectedException(Exception, "Unable to modify frozen"):
            o3.bar = 2
        with testtools.ExpectedException(Exception, "Unable to modify frozen"):
            o.odict['o'].bar = 2
        with testtools.ExpectedException(AttributeError, "'tuple' object"):
            o.odict['l'].append(2)
        with testtools.ExpectedException(TypeError, "'mappingproxy' object"):
            o.odict['d']['bar'] = 2
        with testtools.ExpectedException(TypeError, "'mappingproxy' object"):
            o.odict['od']['bar'] = 2

        # Make sure that mapping proxy applied to an ordered dict
        # still shows the ordered behavior.
        self.assertTrue(isinstance(o.odict2, types.MappingProxyType))
        self.assertEqual(list(o.odict2.keys()), seq)


class TestRef(BaseTestCase):
    def test_ref_equality(self):
        change1 = model.Change('project1')
        change1.ref = '/change1'
        change1b = model.Change('project1')
        change1b.ref = '/change1'
        change2 = model.Change('project2')
        change2.ref = '/change2'
        self.assertFalse(change1.equals(change2))
        self.assertTrue(change1.equals(change1b))

        tag1 = model.Tag('project1')
        tag1.ref = '/tag1'
        tag1b = model.Tag('project1')
        tag1b.ref = '/tag1'
        tag2 = model.Tag('project2')
        tag2.ref = '/tag2'
        self.assertFalse(tag1.equals(tag2))
        self.assertTrue(tag1.equals(tag1b))

        self.assertFalse(tag1.equals(change1))

        branch1 = model.Branch('project1')
        branch1.ref = '/branch1'
        branch1b = model.Branch('project1')
        branch1b.ref = '/branch1'
        branch2 = model.Branch('project2')
        branch2.ref = '/branch2'
        self.assertFalse(branch1.equals(branch2))
        self.assertTrue(branch1.equals(branch1b))

        self.assertFalse(branch1.equals(change1))
        self.assertFalse(branch1.equals(tag1))


class TestSourceContext(BaseTestCase):
    def setUp(self):
        super().setUp()
        self.connection = Dummy(connection_name='dummy_connection')
        self.source = Dummy(canonical_hostname='git.example.com',
                            connection=self.connection)
        self.project = model.Project('project', self.source)
        self.context = model.SourceContext(
            self.project.canonical_name, self.project.name,
            self.project.connection_name, 'master', 'test', True)
        self.context.implied_branches = [
            change_matcher.BranchMatcher('foo'),
            change_matcher.ImpliedBranchMatcher('foo'),
        ]

    def test_serialize(self):
        self.context.deserialize(self.context.serialize())