from __future__ import print_function import os from random import randrange from six.moves import StringIO from twisted.internet import reactor, defer from twisted.python import failure from twisted.trial import unittest from ..util.assertutil import precondition from allmydata.util.encodingutil import get_io_encoding from future.utils import PY2 if PY2: # XXX this is a hack that makes some tests pass on Python3, remove # in the future from ..scripts import runner # Imported for backwards compatibility: from .common_py3 import ( SignalMixin, skip_if_cannot_represent_filename, ReallyEqualMixin, # noqa: F401 ) def skip_if_cannot_represent_argv(u): precondition(isinstance(u, unicode)) try: u.encode(get_io_encoding()) except UnicodeEncodeError: raise unittest.SkipTest("A non-ASCII argv could not be encoded on this platform.") def run_cli(verb, *args, **kwargs): precondition(not [True for arg in args if not isinstance(arg, str)], "arguments to do_cli must be strs -- convert using unicode_to_argv", args=args) nodeargs = kwargs.get("nodeargs", []) argv = nodeargs + [verb] + list(args) stdin = kwargs.get("stdin", "") stdout = StringIO() stderr = StringIO() d = defer.succeed(argv) d.addCallback(runner.parse_or_exit_with_explanation, stdout=stdout) d.addCallback(runner.dispatch, stdin=StringIO(stdin), stdout=stdout, stderr=stderr) def _done(rc): return 0, stdout.getvalue(), stderr.getvalue() def _err(f): f.trap(SystemExit) return f.value.code, stdout.getvalue(), stderr.getvalue() d.addCallbacks(_done, _err) return d def parse_cli(*argv): # This parses the CLI options (synchronously), and returns the Options # argument, or throws usage.UsageError if something went wrong. return runner.parse_options(argv) class DevNullDictionary(dict): def __setitem__(self, key, value): return def insecurerandstr(n): return ''.join(map(chr, map(randrange, [0]*n, [256]*n))) def flip_bit(good, which): # flip the low-order bit of good[which] if which == -1: pieces = good[:which], good[-1:], "" else: pieces = good[:which], good[which:which+1], good[which+1:] return pieces[0] + chr(ord(pieces[1]) ^ 0x01) + pieces[2] def flip_one_bit(s, offset=0, size=None): """ flip one random bit of the string s, in a byte greater than or equal to offset and less than offset+size. """ if size is None: size=len(s)-offset i = randrange(offset, offset+size) result = s[:i] + chr(ord(s[i])^(0x01<