Debian Codegraph @

tests/test-verify-repo-operations.py

raw
1 """Fuzz testing for operations against a Mercurial repository
2
3 This uses Hypothesis's stateful testing to generate random repository
4 operations and test Mercurial using them, both to see if there are any
5 unexpected errors and to compare different versions of it."""
6
7 import os
8 import subprocess
9 import sys
10
11 # Only run if slow tests are allowed
12 if subprocess.call(
13 [os.environ['PYTHON'], '%s/hghave' % os.environ['TESTDIR'], 'slow']
14 ):
15 sys.exit(80)
16
17 # These tests require Hypothesis and pytz to be installed.
18 # Running 'pip install hypothesis pytz' will achieve that.
19 # Note: This won't work if you're running Python < 2.7.
20 try:
21 from hypothesis.extra.datetime import datetimes
22 except ImportError:
23 sys.stderr.write("skipped: hypothesis or pytz not installed" + os.linesep)
24 sys.exit(80)
25
26 # If you are running an old version of pip you may find that the enum34
27 # backport is not installed automatically. If so 'pip install enum34' will
28 # fix this problem.
29 try:
30 import enum
31
32 assert enum # Silence pyflakes
33 except ImportError:
34 sys.stderr.write("skipped: enum34 not installed" + os.linesep)
35 sys.exit(80)
36
37 import binascii
38 from contextlib import contextmanager
39 import shlex
40 import shutil
41 import silenttestrunner
42 import subprocess
43
44 from hypothesis.errors import HypothesisException
45 from hypothesis.stateful import (
46 rule,
47 RuleBasedStateMachine,
48 Bundle,
49 precondition,
50 )
51 from hypothesis import settings, note, strategies as st
52 from hypothesis.configuration import set_hypothesis_home_dir
53 from hypothesis.database import ExampleDatabase
54
55 testdir = os.path.abspath(os.environ["TESTDIR"])
56
57 # We store Hypothesis examples here rather in the temporary test directory
58 # so that when rerunning a failing test this always results in refinding the
59 # previous failure. This directory is in .hgignore and should not be checked in
60 # but is useful to have for development.
61 set_hypothesis_home_dir(os.path.join(testdir, ".hypothesis"))
62
63 runtests = os.path.join(os.environ["RUNTESTDIR"], "run-tests.py")
64 testtmp = os.environ["TESTTMP"]
65 assert os.path.isdir(testtmp)
66
67 generatedtests = os.path.join(testdir, "hypothesis-generated")
68
69 try:
70 os.makedirs(generatedtests)
71 except OSError:
72 pass
73
74 # We write out generated .t files to a file in order to ease debugging and to
75 # give a starting point for turning failures Hypothesis finds into normal
76 # tests. In order to ensure that multiple copies of this test can be run in
77 # parallel we use atomic file create to ensure that we always get a unique
78 # name.
79 file_index = 0
80 while True:
81 file_index += 1
82 savefile = os.path.join(
83 generatedtests, "test-generated-%d.t" % (file_index,)
84 )
85 try:
86 os.close(os.open(savefile, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
87 break
88 except FileExistsError:
89 pass
90 assert os.path.exists(savefile)
91
92 hgrc = os.path.join(".hg", "hgrc")
93
94 filecharacters = (
95 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
96 "[]^_`;=@{}~ !#$%&'()+,-"
97 )
98
99 files = (
100 st.text(filecharacters, min_size=1)
101 .map(lambda x: x.strip())
102 .filter(bool)
103 .map(lambda s: s.encode('ascii'))
104 )
105
106 safetext = st.text(
107 st.characters(
108 min_codepoint=1, max_codepoint=127, blacklist_categories=('Cc', 'Cs')
109 ),
110 min_size=1,
111 ).map(lambda s: s.encode('utf-8'))
112
113 extensions = st.sampled_from(
114 (
115 'shelve',
116 'mq',
117 'blackbox',
118 )
119 )
120
121
122 @contextmanager
123 def acceptableerrors(*args):
124 """Sometimes we know an operation we're about to perform might fail, and
125 we're OK with some of the failures. In those cases this may be used as a
126 context manager and will swallow expected failures, as identified by
127 substrings of the error message Mercurial emits."""
128 try:
129 yield
130 except subprocess.CalledProcessError as e:
131 if not any(a in e.output for a in args):
132 note(e.output)
133 raise
134
135
136 reponames = st.text("abcdefghijklmnopqrstuvwxyz01234556789", min_size=1).map(
137 lambda s: s.encode('ascii')
138 )
139
140
141 class verifyingstatemachine(RuleBasedStateMachine):
142 """This defines the set of acceptable operations on a Mercurial repository
143 using Hypothesis's RuleBasedStateMachine.
144
145 The general concept is that we manage multiple repositories inside a
146 repos/ directory in our temporary test location. Some of these are freshly
147 inited, some are clones of the others. Our current working directory is
148 always inside one of these repositories while the tests are running.
149
150 Hypothesis then performs a series of operations against these repositories,
151 including hg commands, generating contents and editing the .hgrc file.
152 If these operations fail in unexpected ways or behave differently in
153 different configurations of Mercurial, the test will fail and a minimized
154 .t test file will be written to the hypothesis-generated directory to
155 exhibit that failure.
156
157 Operations are defined as methods with @rule() decorators. See the
158 Hypothesis documentation at
159 http://hypothesis.readthedocs.org/en/release/stateful.html for more
160 details."""
161
162 # A bundle is a reusable collection of previously generated data which may
163 # be provided as arguments to future operations.
164 repos = Bundle('repos')
165 paths = Bundle('paths')
166 contents = Bundle('contents')
167 branches = Bundle('branches')
168 committimes = Bundle('committimes')
169
170 def __init__(self):
171 super().__init__()
172 self.repodir = os.path.join(testtmp, "repos")
173 if os.path.exists(self.repodir):
174 shutil.rmtree(self.repodir)
175 os.chdir(testtmp)
176 self.log = []
177 self.failed = False
178 self.configperrepo = {}
179 self.all_extensions = set()
180 self.non_skippable_extensions = set()
181
182 self.mkdirp("repos")
183 self.cd("repos")
184 self.mkdirp("repo1")
185 self.cd("repo1")
186 self.hg("init")
187
188 def teardown(self):
189 """On teardown we clean up after ourselves as usual, but we also
190 do some additional testing: We generate a .t file based on our test
191 run using run-test.py -i to get the correct output.
192
193 We then test it in a number of other configurations, verifying that
194 each passes the same test."""
195 super().teardown()
196 try:
197 shutil.rmtree(self.repodir)
198 except OSError:
199 pass
200 ttest = os.linesep.join(" " + l for l in self.log)
201 os.chdir(testtmp)
202 path = os.path.join(testtmp, "test-generated.t")
203 with open(path, 'w') as o:
204 o.write(ttest + os.linesep)
205 with open(os.devnull, "w") as devnull:
206 rewriter = subprocess.Popen(
207 [runtests, "--local", "-i", path],
208 stdin=subprocess.PIPE,
209 stdout=devnull,
210 stderr=devnull,
211 )
212 rewriter.communicate("yes")
213 with open(path) as i:
214 ttest = i.read()
215
216 e = None
217 if not self.failed:
218 try:
219 output = subprocess.check_output(
220 [runtests, path, "--local", "--pure"],
221 stderr=subprocess.STDOUT,
222 )
223 assert "Ran 1 test" in output, output
224 for ext in self.all_extensions - self.non_skippable_extensions:
225 tf = os.path.join(
226 testtmp, "test-generated-no-%s.t" % (ext,)
227 )
228 with open(tf, 'w') as o:
229 for l in ttest.splitlines():
230 if l.startswith(" $ hg"):
231 l = l.replace(
232 "--config %s=" % (extensionconfigkey(ext),),
233 "",
234 )
235 o.write(l + os.linesep)
236 with open(tf) as r:
237 t = r.read()
238 assert ext not in t, t
239 output = subprocess.check_output(
240 [
241 runtests,
242 tf,
243 "--local",
244 ],
245 stderr=subprocess.STDOUT,
246 )
247 assert "Ran 1 test" in output, output
248 except subprocess.CalledProcessError as e:
249 note(e.output)
250 if self.failed or e is not None:
251 with open(savefile, "wb") as o:
252 o.write(ttest)
253 if e is not None:
254 raise e
255
256 def execute_step(self, step):
257 try:
258 return super().execute_step(step)
259 except (HypothesisException, KeyboardInterrupt):
260 raise
261 except Exception:
262 self.failed = True
263 raise
264
265 # Section: Basic commands.
266 def mkdirp(self, path):
267 if os.path.exists(path):
268 return
269 self.log.append(
270 "$ mkdir -p -- %s" % (shlex.quote(os.path.relpath(path)),)
271 )
272 os.makedirs(path)
273
274 def cd(self, path):
275 path = os.path.relpath(path)
276 if path == ".":
277 return
278 os.chdir(path)
279 self.log.append("$ cd -- %s" % (shlex.quote(path),))
280
281 def hg(self, *args):
282 extra_flags = []
283 for key, value in self.config.items():
284 extra_flags.append("--config")
285 extra_flags.append("%s=%s" % (key, value))
286 self.command("hg", *(tuple(extra_flags) + args))
287
288 def command(self, *args):
289 self.log.append("$ " + ' '.join(map(shlex.quote, args)))
290 subprocess.check_output(args, stderr=subprocess.STDOUT)
291
292 # Section: Set up basic data
293 # This section has no side effects but generates data that we will want
294 # to use later.
295 @rule(
296 target=paths,
297 source=st.lists(files, min_size=1).map(lambda l: os.path.join(*l)),
298 )
299 def genpath(self, source):
300 return source
301
302 @rule(
303 target=committimes,
304 when=datetimes(min_year=1970, max_year=2038) | st.none(),
305 )
306 def gentime(self, when):
307 return when
308
309 @rule(
310 target=contents,
311 content=st.one_of(
312 st.binary(), st.text().map(lambda x: x.encode('utf-8'))
313 ),
314 )
315 def gencontent(self, content):
316 return content
317
318 @rule(
319 target=branches,
320 name=safetext,
321 )
322 def genbranch(self, name):
323 return name
324
325 @rule(target=paths, source=paths)
326 def lowerpath(self, source):
327 return source.lower()
328
329 @rule(target=paths, source=paths)
330 def upperpath(self, source):
331 return source.upper()
332
333 # Section: Basic path operations
334 @rule(path=paths, content=contents)
335 def writecontent(self, path, content):
336 self.unadded_changes = True
337 if os.path.isdir(path):
338 return
339 parent = os.path.dirname(path)
340 if parent:
341 try:
342 self.mkdirp(parent)
343 except OSError:
344 # It may be the case that there is a regular file that has
345 # previously been created that has the same name as an ancestor
346 # of the current path. This will cause mkdirp to fail with this
347 # error. We just turn this into a no-op in that case.
348 return
349 with open(path, 'wb') as o:
350 o.write(content)
351 self.log.append(
352 (
353 "$ \"$PYTHON\" -c 'import binascii; "
354 "print(binascii.unhexlify(\"%s\"))' > %s"
355 )
356 % (
357 binascii.hexlify(content),
358 shlex.quote(path),
359 )
360 )
361
362 @rule(path=paths)
363 def addpath(self, path):
364 if os.path.exists(path):
365 self.hg("add", "--", path)
366
367 @rule(path=paths)
368 def forgetpath(self, path):
369 if os.path.exists(path):
370 with acceptableerrors(
371 "file is already untracked",
372 ):
373 self.hg("forget", "--", path)
374
375 @rule(s=st.none() | st.integers(0, 100))
376 def addremove(self, s):
377 args = ["addremove"]
378 if s is not None:
379 args.extend(["-s", str(s)])
380 self.hg(*args)
381
382 @rule(path=paths)
383 def removepath(self, path):
384 if os.path.exists(path):
385 with acceptableerrors(
386 'file is untracked',
387 'file has been marked for add',
388 'file is modified',
389 ):
390 self.hg("remove", "--", path)
391
392 @rule(
393 message=safetext,
394 amend=st.booleans(),
395 when=committimes,
396 addremove=st.booleans(),
397 secret=st.booleans(),
398 close_branch=st.booleans(),
399 )
400 def maybecommit(
401 self, message, amend, when, addremove, secret, close_branch
402 ):
403 command = ["commit"]
404 errors = ["nothing changed"]
405 if amend:
406 errors.append("cannot amend public changesets")
407 command.append("--amend")
408 command.append("-m" + shlex.quote(message))
409 if secret:
410 command.append("--secret")
411 if close_branch:
412 command.append("--close-branch")
413 errors.append("can only close branch heads")
414 if addremove:
415 command.append("--addremove")
416 if when is not None:
417 if when.year == 1970:
418 errors.append('negative date value')
419 if when.year == 2038:
420 errors.append('exceeds 32 bits')
421 command.append(
422 "--date=%s" % (when.strftime('%Y-%m-%d %H:%M:%S %z'),)
423 )
424
425 with acceptableerrors(*errors):
426 self.hg(*command)
427
428 # Section: Repository management
429 @property
430 def currentrepo(self):
431 return os.path.basename(os.getcwd())
432
433 @property
434 def config(self):
435 return self.configperrepo.setdefault(self.currentrepo, {})
436
437 @rule(
438 target=repos,
439 source=repos,
440 name=reponames,
441 )
442 def clone(self, source, name):
443 if not os.path.exists(os.path.join("..", name)):
444 self.cd("..")
445 self.hg("clone", source, name)
446 self.cd(name)
447 return name
448
449 @rule(
450 target=repos,
451 name=reponames,
452 )
453 def fresh(self, name):
454 if not os.path.exists(os.path.join("..", name)):
455 self.cd("..")
456 self.mkdirp(name)
457 self.cd(name)
458 self.hg("init")
459 return name
460
461 @rule(name=repos)
462 def switch(self, name):
463 self.cd(os.path.join("..", name))
464 assert self.currentrepo == name
465 assert os.path.exists(".hg")
466
467 @rule(target=repos)
468 def origin(self):
469 return "repo1"
470
471 @rule()
472 def pull(self, repo=repos):
473 with acceptableerrors(
474 "repository default not found",
475 "repository is unrelated",
476 ):
477 self.hg("pull")
478
479 @rule(newbranch=st.booleans())
480 def push(self, newbranch):
481 with acceptableerrors(
482 "default repository not configured",
483 "no changes found",
484 ):
485 if newbranch:
486 self.hg("push", "--new-branch")
487 else:
488 with acceptableerrors("creates new branches"):
489 self.hg("push")
490
491 # Section: Simple side effect free "check" operations
492 @rule()
493 def log(self):
494 self.hg("log")
495
496 @rule()
497 def verify(self):
498 self.hg("verify")
499
500 @rule()
501 def diff(self):
502 self.hg("diff", "--nodates")
503
504 @rule()
505 def status(self):
506 self.hg("status")
507
508 @rule()
509 def export(self):
510 self.hg("export")
511
512 # Section: Branch management
513 @rule()
514 def checkbranch(self):
515 self.hg("branch")
516
517 @rule(branch=branches)
518 def switchbranch(self, branch):
519 with acceptableerrors(
520 'cannot use an integer as a name',
521 'cannot be used in a name',
522 'a branch of the same name already exists',
523 'is reserved',
524 ):
525 self.hg("branch", "--", branch)
526
527 @rule(branch=branches, clean=st.booleans())
528 def update(self, branch, clean):
529 with acceptableerrors(
530 'unknown revision',
531 'parse error',
532 ):
533 if clean:
534 self.hg("update", "-C", "--", branch)
535 else:
536 self.hg("update", "--", branch)
537
538 # Section: Extension management
539 def hasextension(self, extension):
540 return extensionconfigkey(extension) in self.config
541
542 def commandused(self, extension):
543 assert extension in self.all_extensions
544 self.non_skippable_extensions.add(extension)
545
546 @rule(extension=extensions)
547 def addextension(self, extension):
548 self.all_extensions.add(extension)
549 self.config[extensionconfigkey(extension)] = ""
550
551 @rule(extension=extensions)
552 def removeextension(self, extension):
553 self.config.pop(extensionconfigkey(extension), None)
554
555 # Section: Commands from the shelve extension
556 @rule()
557 @precondition(lambda self: self.hasextension("shelve"))
558 def shelve(self):
559 self.commandused("shelve")
560 with acceptableerrors("nothing changed"):
561 self.hg("shelve")
562
563 @rule()
564 @precondition(lambda self: self.hasextension("shelve"))
565 def unshelve(self):
566 self.commandused("shelve")
567 with acceptableerrors("no shelved changes to apply"):
568 self.hg("unshelve")
569
570
571 class writeonlydatabase(ExampleDatabase):
572 def __init__(self, underlying):
573 super(ExampleDatabase, self).__init__()
574 self.underlying = underlying
575
576 def fetch(self, key):
577 return ()
578
579 def save(self, key, value):
580 self.underlying.save(key, value)
581
582 def delete(self, key, value):
583 self.underlying.delete(key, value)
584
585 def close(self):
586 self.underlying.close()
587
588
589 def extensionconfigkey(extension):
590 return "extensions." + extension
591
592
593 settings.register_profile(
594 'default',
595 settings(
596 timeout=300,
597 stateful_step_count=50,
598 max_examples=10,
599 ),
600 )
601
602 settings.register_profile(
603 'fast',
604 settings(
605 timeout=10,
606 stateful_step_count=20,
607 max_examples=5,
608 min_satisfying_examples=1,
609 max_shrinks=0,
610 ),
611 )
612
613 settings.register_profile(
614 'continuous',
615 settings(
616 timeout=-1,
617 stateful_step_count=1000,
618 max_examples=10**8,
619 max_iterations=10**8,
620 database=writeonlydatabase(settings.default.database),
621 ),
622 )
623
624 settings.load_profile(os.getenv('HYPOTHESIS_PROFILE', 'default'))
625
626 verifyingtest = verifyingstatemachine.TestCase
627
628 verifyingtest.settings = settings.default
629
630 if __name__ == '__main__':
631 try:
632 silenttestrunner.main(__name__)
633 finally:
634 # So as to prevent proliferation of useless test files, if we never
635 # actually wrote a failing test we clean up after ourselves and delete
636 # the file for doing so that we owned.
637 if os.path.exists(savefile) and os.path.getsize(savefile) == 0:
638 os.unlink(savefile)