Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(492)

Side by Side Diff: infra/services/gnumbd/test/gnumbd_test.py

Issue 413983003: Refactor infra git libs and testing. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: Address comments Created 6 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 # Copyright 2014 The Chromium Authors. All rights reserved. 1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be 2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file. 3 # found in the LICENSE file.
4 4
5 import collections 5 import collections
6 import json 6 import json
7 import logging 7 import logging
8 import os 8 import os
9 import sys 9 import sys
10 import tempfile 10 import tempfile
11 11
12 from cStringIO import StringIO 12 from cStringIO import StringIO
13 13
14 from infra.services.gnumbd import inner_loop as gnumbd 14 import expect_tests
15 15
16 from infra.services.gnumbd.support import config_ref, data, git 16 from infra.libs import git2
17 from infra.libs.git2 import data
18 from infra.services.gnumbd import gnumbd
19 from infra.services.gnumbd.test import gnumbd_test_definitions
17 20
18 from infra.services.gnumbd.test import gnumbd_smoketests
19
20 # should already be on path
21 import expect_tests # pylint: disable=F0401
22 21
23 BASE_PATH = os.path.dirname(os.path.abspath(__file__)) 22 BASE_PATH = os.path.dirname(os.path.abspath(__file__))
24 23
25 24
26 # TODO(iannucci): Make these first class data library objects 25 # TODO(iannucci): Make these first class data library objects
27 class GitEntry(object): 26 class GitEntry(object):
28 typ = None 27 typ = None
29 mode = None 28 mode = None
30 29
31 def intern(self, repo): 30 def intern(self, repo):
(...skipping 26 matching lines...) Expand all
58 self.entries = entries 57 self.entries = entries
59 58
60 def intern(self, repo): 59 def intern(self, repo):
61 with tempfile.TemporaryFile() as tf: 60 with tempfile.TemporaryFile() as tf:
62 for path, entry in self.entries.iteritems(): 61 for path, entry in self.entries.iteritems():
63 tf.write('%s %s %s\t%s' % 62 tf.write('%s %s %s\t%s' %
64 (entry.mode, entry.typ, entry.intern(repo), path)) 63 (entry.mode, entry.typ, entry.intern(repo), path))
65 tf.seek(0) 64 tf.seek(0)
66 return repo.run('mktree', '-z', stdin=tf).strip() 65 return repo.run('mktree', '-z', stdin=tf).strip()
67 66
68 class TestRef(git.Ref): 67 class TestRef(git2.Ref):
69 def synthesize_commit(self, message, number=None, tree=None, svn=False, 68 def synthesize_commit(self, message, number=None, tree=None, svn=False,
70 footers=None): 69 footers=None):
71 footers = footers or collections.OrderedDict() 70 footers = footers or collections.OrderedDict()
72 if number is not None: 71 if number is not None:
73 if svn: 72 if svn:
74 footers[gnumbd.GIT_SVN_ID] = [ 73 footers[gnumbd.GIT_SVN_ID] = [
75 'svn://repo/path@%s 0039d316-1c4b-4281-b951-d872f2087c98' % number] 74 'svn://repo/path@%s 0039d316-1c4b-4281-b951-d872f2087c98' % number]
76 else: 75 else:
77 footers[gnumbd.COMMIT_POSITION] = [ 76 footers[gnumbd.COMMIT_POSITION] = [
78 gnumbd.FMT_COMMIT_POSITION(self, number)] 77 gnumbd.FMT_COMMIT_POSITION(self, number)]
79 78
80 commit = self.repo.synthesize_commit(self.commit, message, footers=footers, 79 commit = self.repo.synthesize_commit(self.commit, message, footers=footers,
81 tree=tree) 80 tree=tree)
82 self.update_to(commit) 81 self.update_to(commit)
83 return commit 82 return commit
84 83
85 84
86 class TestClock(object): 85 class TestClock(object):
87 def __init__(self): 86 def __init__(self):
88 self._time = 1402589336 87 self._time = 1402589336
89 88
90 def time(self): 89 def time(self):
91 self._time += 10 90 self._time += 10
92 return self._time 91 return self._time
93 92
94 93
95 class TestConfigRef(config_ref.ConfigRef): 94 class TestConfigRef(gnumbd.GnumbdConfigRef):
96 def update(self, **values): 95 def update(self, **values):
97 new_config = self.current 96 new_config = self.current
98 new_config.update(values) 97 new_config.update(values)
99 self.ref.synthesize_commit( 98 self.ref.synthesize_commit(
100 'update(%r)' % values.keys(), 99 'update(%r)' % values.keys(),
101 tree=GitTree({'config.json': GitFile(json.dumps(new_config))})) 100 tree=GitTree({'config.json': GitFile(json.dumps(new_config))}))
102 101
103 102
104 class TestRepo(git.Repo): 103 class TestRepo(git2.Repo):
105 def __init__(self, short_name, tmpdir, clock, mirror_of=None): 104 def __init__(self, short_name, clock, mirror_of=None):
106 super(TestRepo, self).__init__(mirror_of or 'local test repo') 105 super(TestRepo, self).__init__(mirror_of or 'local test repo')
107 self._short_name = short_name 106 self._short_name = short_name
108 self.repos_dir = tmpdir 107 self.repos_dir = tempfile.tempdir
109 108
110 if mirror_of is None: 109 if mirror_of is None:
111 self._repo_path = tempfile.mkdtemp(dir=self.repos_dir, suffix='.git') 110 self._repo_path = tempfile.mkdtemp(suffix='.git')
112 self.run('init', '--bare') 111 self.run('init', '--bare')
113 112
114 self._clock = clock 113 self._clock = clock
115 114
116 # pylint: disable=W0212 115 # pylint: disable=W0212
117 repo_path = property(lambda self: self._repo_path) 116 repo_path = property(lambda self: self._repo_path)
118 117
119 def __getitem__(self, refstr): 118 def __getitem__(self, refstr):
120 return TestRef(self, refstr) 119 return TestRef(self, refstr)
121 120
122 def synthesize_commit(self, parent, message, tree=None, footers=None): 121 def synthesize_commit(self, parent, message, tree=None, footers=None):
123 tree = tree or GitTree({'file': GitFile('contents')}) 122 tree = tree or GitTree({'file': GitFile('contents')})
124 tree = tree.intern(self) if isinstance(tree, GitTree) else tree 123 tree = tree.intern(self) if isinstance(tree, GitTree) else tree
125 assert isinstance(tree, str) 124 assert isinstance(tree, str)
126 125
127 parents = [parent.hsh] if parent is not git.INVALID else [] 126 parents = [parent.hsh] if parent is not git2.INVALID else []
128 127
129 timestamp = data.CommitTimestamp(self._clock.time(), '+', 8, 0) 128 timestamp = data.CommitTimestamp(self._clock.time(), '+', 8, 0)
130 user = data.CommitUser('Test User', 'test_user@example.com', timestamp) 129 user = data.CommitUser('Test User', 'test_user@example.com', timestamp)
131 130
132 return self.get_commit(self.intern(data.CommitData( 131 return self.get_commit(self.intern(data.CommitData(
133 tree, parents, user, user, (), message.splitlines(), 132 tree, parents, user, user, (), message.splitlines(),
134 data.CommitData.merge_lines([], footers or {}) 133 data.CommitData.merge_lines([], footers or {})
135 ), 'commit')) 134 ), 'commit'))
136 135
137 def snap(self, include_committer=False, include_config=False): 136 def snap(self, include_committer=False, include_config=False):
138 ret = {} 137 ret = {}
139 if include_committer: 138 if include_committer:
140 fmt = '%H%x00committer %cn <%ce> %ci%n%n%B%x00%x00' 139 fmt = '%H%x00committer %cn <%ce> %ci%n%n%B%x00%x00'
141 else: 140 else:
142 fmt = '%H%x00%B%x00%x00' 141 fmt = '%H%x00%B%x00%x00'
143 for ref in (r.ref for r in self.refglob('*')): 142 for ref in (r.ref for r in self.refglob('*')):
144 if ref == gnumbd.DEFAULT_CONFIG_REF and not include_config: 143 if ref == gnumbd.GnumbdConfigRef.REF and not include_config:
145 continue 144 continue
146 log = self.run('log', ref, '--format=%s' % fmt) 145 log = self.run('log', ref, '--format=%s' % fmt)
147 ret[ref] = collections.OrderedDict( 146 ret[ref] = collections.OrderedDict(
148 (commit, message.splitlines()) 147 (commit, message.splitlines())
149 for commit, message in ( 148 for commit, message in (
150 r.split('\0') for r in log.split('\0\0\n') if r) 149 r.split('\0') for r in log.split('\0\0\n') if r)
151 ) 150 )
152 return ret 151 return ret
153 152
154 def __repr__(self): 153 def __repr__(self):
155 return 'TestRepo(%r)' % self._short_name 154 return 'TestRepo(%r)' % self._short_name
156 155
157 156
158 def RunTest(tmpdir, test_name): 157 def RunTest(test_name):
159 ret = [] 158 ret = []
160 clock = TestClock() 159 clock = TestClock()
161 origin = TestRepo('origin', tmpdir, clock) 160 origin = TestRepo('origin', clock)
162 local = TestRepo('local', tmpdir, clock, origin.repo_path) 161 local = TestRepo('local', clock, origin.repo_path)
163 162
164 cref = TestConfigRef(origin[gnumbd.DEFAULT_CONFIG_REF]) 163 cref = TestConfigRef(origin)
165 cref.update(enabled_refglobs=['refs/heads/*'], interval=0) 164 cref.update(enabled_refglobs=['refs/heads/*'], interval=0)
166 165
167 def checkpoint(message, include_committer=False, include_config=False): 166 def checkpoint(message, include_committer=False, include_config=False):
168 ret.append([message, {'origin': origin.snap(include_committer, 167 ret.append([message, {'origin': origin.snap(include_committer,
169 include_config)}]) 168 include_config)}])
170 169
171 def run(include_log=True): 170 def run(include_log=True):
172 stdout = sys.stdout 171 stdout = sys.stdout
173 stderr = sys.stderr 172 stderr = sys.stderr
174 173
(...skipping 16 matching lines...) Expand all
191 ret.append(traceback.format_exc().splitlines()) 190 ret.append(traceback.format_exc().splitlines())
192 finally: 191 finally:
193 sys.stdout = stdout 192 sys.stdout = stdout
194 sys.stderr = stderr 193 sys.stderr = stderr
195 194
196 if include_log: 195 if include_log:
197 root_logger.removeHandler(shandler) 196 root_logger.removeHandler(shandler)
198 root_logger.setLevel(log_level) 197 root_logger.setLevel(log_level)
199 ret.append({'log output': logout.getvalue().splitlines()}) 198 ret.append({'log output': logout.getvalue().splitlines()})
200 199
201 gnumbd_smoketests.GNUMBD_TESTS[test_name]( 200 gnumbd_test_definitions.GNUMBD_TESTS[test_name](
202 origin, local, cref, run, checkpoint) 201 origin, local, cref, run, checkpoint)
203 202
204 return expect_tests.Result(ret) 203 return expect_tests.Result(ret)
205 204
206 205
207 def GenTests(tmpdir): 206 @expect_tests.test_generator
208 for test_name, test in gnumbd_smoketests.GNUMBD_TESTS.iteritems(): 207 def GenTests():
208 for test_name, test in gnumbd_test_definitions.GNUMBD_TESTS.iteritems():
209 yield expect_tests.Test( 209 yield expect_tests.Test(
210 __package__ + '.' + test_name, 210 __package__ + '.' + test_name,
211 expect_tests.FuncCall(RunTest, tmpdir, test_name), 211 expect_tests.FuncCall(RunTest, test_name),
212 os.path.join(BASE_PATH, 'gnumbd_smoketests.expected'), 212 expect_base=test_name, ext='yaml', break_funcs=[test],
213 test_name, 'yaml', break_funcs=[test]) 213 covers=(
214 expect_tests.Test.covers_obj(RunTest) +
215 expect_tests.Test.covers_obj(gnumbd_test_definitions)
216 ))
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698