desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Assert if the intercepted log matches the regular expression,
or if "invert" is True and no match is found.'
| def _AssertLogMatches(self, expected_regexp, invert, format):
| if isinstance(expected_regexp, basestring):
expected_regexp = re.compile(expected_regexp, (re.MULTILINE | re.DOTALL))
handler = logging.getLogger().handlers[0]
if (not hasattr(handler, 'stream')):
raise unittest.SkipTest()
log_text = handler.stream.getvalue()
matches = (expected_rege... |
'Maps a url regex to a response.
Any request whose url matches the given regex will get the corresponding
response (if multiple regexes match, the most recently mapped one wins).
The response may be a string (used as the body), a
`tornado.httpclient.HTTPResponse` object, or a function that takes a
request and returns o... | def map(self, regex, response):
| self.url_map.insert(0, (re.compile(regex), response))
|
'Implementation of AsyncHTTPClient.fetch'
| def fetch(self, request, callback=None, **kwargs):
| if (not isinstance(request, httpclient.HTTPRequest)):
request = httpclient.HTTPRequest(url=request, **kwargs)
for (regex, response) in self.url_map:
if regex.match(request.url):
if callable(response):
response = response(request)
if isinstance(response, ba... |
'Hacky support for mock.patch.
We patch the AsyncHTTPClient class and replace it with this instance,
so "calling" the instance should act like instantiating the class.'
| def __call__(self, io_loop=None):
| if (io_loop is not None):
assert (io_loop is self.io_loop)
return self
|
'Test secrets manager without a domain dir.'
| def testNoDomainDir(self):
| mgr = secrets.SecretsManager('test', 'fake_domain', self._shared_dir)
mgr.Init()
self.assertEqual(len(mgr.ListSecrets()), 0)
self.assertRaises(IOError, mgr.PutSecret, 'foo', 'codeforfoo')
|
'Test secrets manager with plain-text secrets.'
| def testPlain(self):
| mgr = secrets.SecretsManager('test', self._domain, self._shared_dir)
mgr.Init()
self.assertEqual(len(mgr.ListSecrets()), 0)
self.assertRaises(KeyError, mgr.GetSecret, 'foo')
self.assertFalse(mgr.HasSecret('foo'))
mgr.PutSecret('foo', 'codeforfoo')
self.assertTrue(mgr.HasSecret('foo'))
se... |
'Test secrets manager with encrypted secrets.'
| def testEncrypted(self):
| passphrase = 'my voice is my passport!'
with mock.patch.object(secrets.getpass, 'getpass') as getpass:
getpass.return_value = passphrase
mgr = secrets.SecretsManager('test', self._domain, self._shared_dir)
mgr.Init(should_prompt=True)
mgr.PutSecret('foo', 'codeforfoo')
... |
'Test the secrets managers in their natural habitat: automatic selection of user vs shared based on flags.'
| def testMultipleManagers(self):
| secrets._user_secrets_manager = None
secrets._shared_secrets_manager = None
options.options.devbox = True
secrets.InitSecrets()
self.assertIsNotNone(secrets._user_secrets_manager)
self.assertIsNone(secrets._shared_secrets_manager)
secrets._user_secrets_manager.PutSecret('foo', 'codeforfoo')
... |
'Creates a web server which handles:
- GET /datastore?k=<key> - retrieve value for <key>; shard is hash of key
- POST /datastore?k=<key>&v=<value> - set datastore <key>:<value>; shard is hash of key'
| def get_app(self):
| return web.Application([('/datastore', _DatastoreHandler)])
|
'Test the webserver handles datastore key/value store and retrieval
by inserting a collection of random values and verifying their
retrieval, in parallel.'
| @async_test
def testDatastore(self):
| values = self._CreateRandomValues(num_values=100)
def _InsertDone():
self._RetrieveValues(values, self.stop)
self._InsertValues(values, _InsertDone)
|
'Creates num_values random integers between [0, 1<<20)'
| def _CreateRandomValues(self, num_values=100):
| return [int(random.uniform(0, (1 << 20))) for i in xrange(num_values)]
|
'Inserts values into datastore via the tornado web server and
invokes callback with the sequence of values when complete. The
values are randomly distributed over the available shards.
- The key of each value is computed as: \'k%d\' % value'
| def _InsertValues(self, values, callback):
| def _VerifyResponse(cb, resp):
self.assertEqual(resp.body, 'ok')
cb()
with util.Barrier(callback) as b:
for val in values:
self.http_client.fetch(httpclient.HTTPRequest(self.get_url('/datastore'), method='POST', body=('k=k%d&v=%d' % (val, val))), callback=partial(_VerifyRespo... |
'Retrieves and verifies the specified values from Datastore database
via the tornado web server.'
| def _RetrieveValues(self, values, callback):
| def _VerifyResponse(val, cb, resp):
self.assertEqual(resp.body, repr(val))
cb()
with util.Barrier(callback) as b:
for val in values:
self.http_client.fetch(httpclient.HTTPRequest(self.get_url(('/datastore?k=k%d' % val)), method='GET'), callback=partial(_VerifyResponse, val, b... |
'Basic tests of the Message class.'
| def testMessage(self):
| self._TestMessage(MessageTestCase.MSG_NO_VERSION, original_version=Message.INITIAL_VERSION)
self._TestMessage(MessageTestCase.MSG_WITH_VERSION, original_version=Message.ADD_HEADERS_VERSION)
self._TestMessage(MessageTestCase.MSG_NO_VERSION, default_version=Message.ADD_HEADERS_VERSION, original_version=Messag... |
'Test version migration functionality on the Message class.'
| def testMigrate(self):
| message = self._TestMessage(MessageTestCase.MSG_NO_VERSION, original_version=Message.INITIAL_VERSION, max_supported_version=Message.INITIAL_VERSION, schema=MessageTestCase.SCHEMA_WITH_VERSION, allow_extra_fields=True, migrate_version=Message.ADD_HEADERS_VERSION)
message = self._TestMessage(message.dict, sanitiz... |
'Requests not on the whitelist raise an error.'
| def test_unmapped(self):
| with self.assertRaises(ValueError):
self.http_client.fetch(kURL, self.stop)
|
'Map a url to a constant string.'
| def test_string(self):
| self.http_client.map(kURL, 'hello world')
self.http_client.fetch(kURL, self.stop)
response = self.wait()
self.assertEqual(response.body, 'hello world')
|
'Map a url to a function returning a string.'
| def test_callable(self):
| self.http_client.map(kURL, (lambda request: 'hello world'))
self.http_client.fetch(kURL, self.stop)
response = self.wait()
self.assertEqual(response.body, 'hello world')
|
'Map a url to a function returning an HTTPResponse.
HTTPResponse\'s constructor requires a request object, so there is no
fourth variant that returns a constant HTTPResponse.'
| def test_response(self):
| self.http_client.map(kURL, (lambda request: httpclient.HTTPResponse(request, 404, buffer=StringIO(''))))
self.http_client.fetch(kURL, self.stop)
response = self.wait()
self.assertEqual(response.code, 404)
|
'Replace the AsyncHTTPClient class using mock.patch.'
| def test_with_patch(self):
| self.http_client.map(kURL, 'hello world')
with mock.patch('tornado.httpclient.AsyncHTTPClient', self.http_client):
real_client = httpclient.AsyncHTTPClient()
self.assertIs(self.http_client, real_client)
real_client.fetch(kURL, self.stop)
response = self.wait()
self.assertE... |
'Test the nesting of a single ContextLocal subclass.'
| def testNestedContexts(self):
| with util.Barrier(self._OnSuccess, on_exception=self._OnException) as b:
with StackContext(ExampleContext(1)):
self.io_loop.add_callback(partial(self._VerifyExampleContext, 1, b.Callback()))
with StackContext(ExampleContext(2)):
self._VerifyExampleContext(2, util.NoCa... |
'Test the usage of multiple ContextLocal subclasses in tandem.'
| def testMultipleContextTypes(self):
| with util.Barrier(self._OnSuccess, on_exception=self._OnException) as b:
with StackContext(ExampleContext(1)):
with StackContext(ExampleContextTwoParams(2, 3)):
self._VerifyExampleContext(1, util.NoCallback)
self._VerifyExampleContextTwoParams(2, 3, util.NoCallbac... |
'Use a multiple of 6 for the length of the random string to ensure
no padding is used in the encoded result.'
| def _RandomString(self):
| length = (random.randint(1, 10) * 6)
return ''.join([chr(random.randint(0, 255)) for i in xrange(length)])
|
'Ensure Retry preserves StackContext.'
| def testWithStackContext1(self):
| self.__in_context = False
@contextlib.contextmanager
def _MyContext():
try:
self.__in_context = True
(yield)
finally:
self.__in_context = False
def _OnCompletedCheckContext(result, error):
self.assertTrue(self.__in_context)
self.stop()
... |
'Ensure Retry doesn\'t interfere with asynchronous function that throws immediately.'
| def testWithStackContext2(self):
| try:
with stack_context.ExceptionStackContext(self._OnError):
retry.CallWithRetryAsync(retry.RetryPolicy(), self._AsyncFuncRaisesError, callback=self._OnCompleted)
self.assert_(False, 'Expected exception to be raised')
except:
self.wait()
|
'Ensure Retry doesn\'t interfere with asynchronous callback that throws.'
| def testWithStackContext3(self):
| try:
with stack_context.ExceptionStackContext(self._OnError):
retry.CallWithRetryAsync(retry.RetryPolicy(check_exception=(lambda typ, val, tb: True)), self._AsyncFunc, callback=self._OnCompletedRaisesError)
self.wait()
self.assert_(False, 'Expected exception to be rai... |
'Ensure Retry doesn\'t interfere with barriers.'
| def testWithBarrier(self):
| retry_policy = retry.RetryPolicy(max_tries=2, check_result=(lambda res, err: err))
with util.MonoBarrier(self._OnCompleted) as b:
retry.CallWithRetryAsync(retry_policy, self._AsyncFuncFailOnce, callback=b.Callback())
self.wait()
|
'Test RetryPolicy __init__ API.'
| def testRetryPolicyApi(self):
| self.assertRaises(OverflowError, functools.partial(retry.RetryPolicy, timeout=1234123412341234))
retry.RetryPolicy(timeout=timedelta(milliseconds=500))
self.assertEqual(retry.RetryPolicy(timeout=10).timeout.total_seconds(), 10)
self.assertEqual(retry.RetryPolicy(timeout=(-1.5)).timeout.total_seconds(), ... |
'Test retry scenario in which the RetryPolicy max_tries is exceeded.'
| def testMaxTries(self):
| retry_policy = retry.RetryPolicy(max_tries=10, check_result=(lambda res, err: True))
retry.CallWithRetryAsync(retry_policy, self._AsyncFunc, callback=self._OnCompleted)
self.wait()
self.assertLogMatches('Retrying.*Retrying.*Retrying.*Retrying.*Retrying.*Retrying.*Retrying.*Retrying.*Retrying', 'Expected... |
'Test retry scenario in which the RetryPolicy timeout is exceeded.'
| def testTimeoutAndDelays(self):
| retry_policy = retry.RetryPolicy(timeout=0.6, min_delay=0.05, max_delay=0.2, check_result=(lambda res, err: True))
retry.CallWithRetryAsync(retry_policy, self._AsyncFunc, callback=self._OnCompleted)
self.wait()
self.assertLogMatches('Retrying.*Retrying.*Retrying', 'Expected at least 3 retrie... |
'Test CallWithRetry API.'
| def testCallWithRetryApi(self):
| self.assertRaises(AssertionError, retry.CallWithRetryAsync, None, None)
|
'Retry on exceptions raised immediately by async function.'
| def testRetryWithException(self):
| def CallWithRetry():
retry_policy = retry.RetryPolicy(max_tries=3, check_exception=(lambda typ, val, tb: True))
retry.CallWithRetryAsync(retry_policy, self._AsyncFuncRaisesErrorOnce, dict(), callback=self.stop)
self.io_loop.add_callback(CallWithRetry)
self.wait()
|
'Retry on exceptions raised by async function after stack transfer.'
| def testRetryWithException2(self):
| def CallAfterStackTransfer(dict, callback):
func = functools.partial(self._AsyncFuncRaisesErrorOnce, dict, callback)
self.io_loop.add_callback(func)
retry_policy = retry.RetryPolicy(max_tries=3, check_exception=(lambda typ, val, tb: True))
retry.CallWithRetryAsync(retry_policy, CallAfterStac... |
'List of random integers (0-20) and of random size (10-20).'
| def _RandomList(self):
| l = []
for i in range(random.randint(10, 20)):
l.append(random.randint(0, 20))
print ('list: %r' % l)
return l
|
'No indentation, no percentiles.'
| def testSimple(self):
| a = self._RandomList()
out_str = ('mean=%.2f\nmedian=%.2f\nstddev=%.2f' % (numpy.mean(a), numpy.median(a), numpy.std(a)))
self.assertEqual(statistics.FormatStats(a), out_str)
|
'With indentation, no percentiles.'
| def testIndent(self):
| a = self._RandomList()
out_str = (' mean=%.2f\n median=%.2f\n stddev=%.2f' % (numpy.mean(a), numpy.median(a), numpy.std(a)))
self.assertEqual(statistics.FormatStats(a, indent=3), out_str)
|
'With indentation and percentiles.'
| def testPercentile(self):
| a = self._RandomList()
p = [80, 90, 95, 99]
out_str = (' mean=%.2f\n median=%.2f\n stddev=%.2f\n' % (numpy.mean(a), numpy.median(a), numpy.std(a)))
out_str += (' 80/90/95/99 percentiles=%s' % numpy.percentile(a, p))
self.assertEqual(statistics.FormatSta... |
'Bucket limits can be floats, but we round everything for display.'
| def testRounding(self):
| a = [1, 1, 2, 4, 4]
out_str = ' [1-1) 2 40.00% ########\n'
out_str += ' [1-2) 1 20.00% ####\n'
out_str += ' [2-2) 0 0.00% \n'
out_str += ' [2-3) 0 0.00% \n'
out_str += ' [3-4] 2 40.00% ########'
self.asse... |
'Make the barrier callback and then raise exception.'
| def testCompletedBeforeException(self):
| val = [0]
def _Exception(type_, value_, traceback):
logging.info('Exception')
val[0] += 1
def _Completed():
logging.info('Completed')
val[0] += 1
def _RaiseException():
raise KeyError('key')
def _PropException(type_, value_, traceback):
self.io_loop.ad... |
'Raise exception and then make the barrier callback.'
| def testCompletedAfterException(self):
| val = [0]
def _Exception(type_, value_, traceback):
logging.info('Exception')
val[0] += 1
self.io_loop.add_callback(self.stop)
def _Completed():
logging.info('Completed')
val[0] += 1
self.io_loop.add_callback(self.stop)
def _RaiseException(completed_cb):
... |
'Test exception raised before barrier context is exited.'
| def testImmediateException(self):
| def _OnException(type, value, tb):
self.stop()
with util.ExceptionBarrier(_OnException):
raise Exception('an error')
self.wait()
|
'Test exception raised after initial barrier context has exited.'
| def testDelayedException(self):
| def _OnException(type, value, tb):
self.stop()
def _RaiseException():
raise Exception('an error')
with util.ExceptionBarrier(_OnException):
self.io_loop.add_callback(_RaiseException)
self.wait()
|
'ERROR: Try to use Callback() method on barrier.'
| def testCallback(self):
| def _OnException(type, value, tb):
self.assertEqual(type, AssertionError)
self.stop()
with util.ExceptionBarrier(_OnException) as b:
b.Callback()
self.wait()
|
'ERROR: Raise multiple exceptions within scope of exception barrier.'
| def testMultipleExceptions(self):
| def _OnException(type, value, tb):
self.stop()
def _RaiseException():
raise Exception('an error')
with util.ExceptionBarrier(_OnException) as b:
self.io_loop.add_callback(_RaiseException)
self.io_loop.add_callback(_RaiseException)
self.wait()
|
'Verify that without an exception handler, a thrown exception
in a barrier propagates.'
| def testUnhandledExeption(self):
| success = [False]
def _Op(cb):
raise ZeroDivisionError('exception')
def _OnSuccess():
success[0] = True
def _RunBarrier():
with util.Barrier(_OnSuccess) as b:
_Op(b.Callback())
self.assertRaises(ZeroDivisionError, _RunBarrier)
self.assertTrue((not success[0]))... |
'Verify that if an exception handler is specified, a thrown
exception doesn\'t propagate.'
| def testHandledException(self):
| exception = [False]
success = [False]
def _OnException(type, value, traceback):
exception[0] = True
self.io_loop.add_callback(self.stop)
def _OnSuccess():
success[0] = True
def _Op(cb):
raise Exception('exception')
with util.Barrier(_OnSuccess, on_exception=_OnExc... |
'Verify that a handled exception in a nested barrier doesn\'t prevent
outer barrier from completing.'
| def testNestedBarriers(self):
| exceptions = [False, False]
level1_reached = [False]
def _Level2Exception(type, value, traceback):
exceptions[1] = True
def _Level2(cb):
raise Exception('exception in level 2')
def _Level1Exception(type, value, traceback):
exceptions[0] = True
def _OnLevel1():
... |
'Test for the Total counter type.'
| def testTotal(self):
| total = counters._TotalCounter('mytotal', 'Description')
sampler = total.get_sampler()
sampler2 = total.get_sampler()
self.assertEqual(0, sampler())
total.increment()
self.assertEqual(1, sampler())
total.increment(4)
self.assertEqual(5, sampler())
total.decrement()
self.assertEqu... |
'Test for the delta counter type.'
| def testDelta(self):
| delta = counters._DeltaCounter('mydelta', 'Description')
sampler = delta.get_sampler()
sampler2 = delta.get_sampler()
self.assertEqual(0, sampler())
delta.increment()
self.assertEqual(1, sampler())
delta.increment(4)
self.assertEqual(4, sampler())
delta.decrement()
self.assertEqu... |
'Construct reader from either a JSON string or a Python dict.'
| def __init__(self, keydata):
| if isinstance(keydata, basestring):
keydata = json.loads(keydata)
assert isinstance(keydata, dict), keydata
self.dict = keydata
|
'Returns the "meta" attribute.'
| def GetMetadata(self):
| return self.dict['meta']
|
'Returns a key having "version_number" as its name.'
| def GetKey(self, version_number):
| return self.dict[str(version_number)]
|
'Does nothing, as there is nothing to close.'
| def Close(self):
| pass
|
'Construct reader from either a JSON string or a Python dict.'
| def __init__(self, keydata=None):
| if isinstance(keydata, basestring):
keydata = json.loads(keydata)
assert ((keydata is None) or isinstance(keydata, dict)), keydata
self.dict = (keydata if (keydata is not None) else {})
|
'Stores "metadata" in the "meta" attribute.'
| def WriteMetadata(self, metadata, overwrite=True):
| if ((not overwrite) and ('meta' in metadata)):
raise errors.KeyczarError('"meta" attribute already exists')
self.dict['meta'] = str(metadata)
|
'Stores "key" in an attribute having "version_number" as its name.'
| def WriteKey(self, key, version_number, encrypter=None):
| key = str(key)
if encrypter:
key = encrypter.Encrypt(key)
self.dict[str(version_number)] = key
|
'Removes the key for the given version.'
| def Remove(self, version_number):
| self.dict.pop(str(version_number))
|
'Does nothing, as there is nothing to close.'
| def Close(self):
| pass
|
'Initialize a TTornadoTransport with a Tornado IOStream.
@param host(str) The host to connect to.
@param port(int) The (TCP) port to connect to.'
| def __init__(self, host='localhost', port=9090):
| self.host = host
self.port = port
self._stream = None
self._io_loop = ioloop.IOLoop.current()
self._timeout_secs = None
|
'Sets a timeout for use with open/read/write operations.'
| def set_timeout(self, timeout_secs):
| self._timeout_secs = timeout_secs
|
'Creates a connection to host:port and spins up a tornado
IOStream object to write requests and read responses from the
thrift server. After making the asynchronous connect call to
_stream, the current greenlet yields control back to the parent
greenlet (presumably the "master" greenlet).'
| def open(self):
| assert (greenlet.getcurrent().parent is not None)
addrinfo = socket.getaddrinfo(self.host, self.port, socket.AF_INET, socket.SOCK_STREAM, 0, 0)
(af, socktype, proto, canonname, sockaddr) = addrinfo[0]
self._stream = IOStream(socket.socket(af, socktype, proto), io_loop=self._io_loop)
self._open_inter... |
'Construct a new message from the provided Python dictionary. Determine
the version of the message and store it in the version field. A number of
checks are made to make sure that the version is valid. The first
requirement is that the message version falls within the range (inclusive)
[min_supported_version, max_suppo... | def __init__(self, message_dict, min_supported_version=INITIAL_VERSION, max_supported_version=MAX_VERSION, default_version=INITIAL_VERSION):
| assert (type(message_dict) is dict), (type(message_dict), message_dict)
self.dict = message_dict
assert (min_supported_version >= MIN_SUPPORTED_MESSAGE_VERSION)
assert (max_supported_version <= MAX_MESSAGE_VERSION)
self.original_version = self._GetMessageVersion(max_supported_version, default_versio... |
'Validate that the message conforms to the specified schema.
If the "allow_extra_fields" argument is False, then fail the
validation if the message contains any extra fields that are
not specified explicitly in the schema. If validation fails,
then raise a BadMessageException. If the validation succeeds,
associate the ... | def Validate(self, schema, allow_extra_fields=False):
| assert schema, 'A schema must be provided in order to validate.'
try:
validictory.validate(self.dict, schema)
if (not allow_extra_fields):
self._FindExtraFields(self.dict, schema, True)
self.schema = schema
except Exception as e:
raise BadM... |
'Remove any fields from the message that are not explicitly
allowed by the schema. This is used to remove extraneous fields
from objects which may have been added during message processing.'
| def Sanitize(self):
| assert self.schema, 'No schema available. Sanitize may only be called after Validate has been called.'
self._FindExtraFields(self.dict, self.schema, False)
|
'Migrate this message\'s content to the format with version
"migrate_version". To do this, apply the "migrators" list in
sequence. Each migrator will mutate the content of the message to
conform to the next (or previous) version of the message format.
If migrators == None, the REQUIRED_MIGRATORS will be used by
default... | def Migrate(self, client, migrate_version, callback, migrators=None):
| def _OnMigrate(intermediate_version):
'Called each time a migrator has been applied; keep invoking Migrate\n until the final migrate version is reached.\n '
self.version = intermediate_version
if (i... |
'Recursively visit the fields of the message in a depth-first
order. Invoke the visitor for each field, passing the name of
the field and its value. If the handler returns None, then no
changes are made to the message. If the handler returns an
empty tuple (), then the field is removed from the message. If
the handler ... | def Visit(self, visitor):
| self._VisitHelper(self.dict, visitor)
|
'Helper visitor that traverses the message tree.'
| def _VisitHelper(self, node, handler):
| if isinstance(node, dict):
for (key, value) in node.items():
self._VisitHelper(value, handler)
result = handler(key, value)
if (result is None):
continue
del node[key]
if (len(result) == 2):
node[result[0]] = result[... |
'Recursively traverses the message, looking for extra fields that
are not explicitly allowed in the schema. If "raise_error" is True,
then raise a BadMessageException if such fields are found. Otherwise,
remove the fields from the message entirely.'
| def _FindExtraFields(self, message_dict, schema, raise_error):
| if (schema['type'] == 'object'):
assert isinstance(message_dict, dict)
for k in message_dict.keys():
if ('properties' in schema):
if (k not in schema['properties']):
if raise_error:
raise BadMessageException(('Message contain... |
'Extract the version from the message headers. Usually this is just
the value of the "version" field. However, if that version is not
supported by the server, the value of the "min_required_version"
field is consulted. If the value of this field is less than or equal
to the max supported version, then the server can "f... | def _GetMessageVersion(self, max_supported_version, default_version):
| headers = self.dict.get('headers', None)
if (headers is None):
if (default_version == Message.INITIAL_VERSION):
return Message.INITIAL_VERSION
self.dict['headers'] = dict(version=default_version)
elif (not headers.has_key('version')):
headers['version'] = default_version
... |
'Construct a migrator that will be activated as a message\'s version
is migrated to or from "migrate_version".'
| def __init__(self, migrate_version):
| self.migrate_version = migrate_version
|
'Called in order to migrate a message to the "migrate_version" format,
from the previous format version. "callback" is invoked with no parameters
when the migration is complete.'
| def MigrateForward(self, client, message, callback):
| raise NotImplementedError()
|
'Called in order to migrate a message from the "migrate_version"
format, to the previous format version. "callback" is invoked with no
parameters when the migration is complete.'
| def MigrateBackward(self, client, message, callback):
| raise NotImplementedError()
|
'Migrators are compared to one another by "migrate_version", which
imposes a total ordering of migrators.'
| def __cmp__(self, other):
| assert isinstance(other, MessageMigrator)
return cmp(self.migrate_version, other.migrate_version)
|
'Add the headers object to the message.'
| def MigrateForward(self, client, message, callback):
| message.dict['headers'] = dict(version=Message.ADD_HEADERS_VERSION)
callback()
|
'Remove the headers object from the message.'
| def MigrateBackward(self, client, message, callback):
| del message.dict['headers']
callback()
|
'Visit all fields in the message and replace event fields with episode fields.'
| def MigrateForward(self, client, message, callback):
| def _ReplaceEventWithEpisode(key, value):
if RenameEventMigrator._EPISODE_TO_EVENT.has_key(key):
raise BadMessageException('Episode fields should not appear in older messages.')
episode = RenameEventMigrator._EVENT_TO_EPISODE.get(key, None)
return ((episode, ... |
'Visit all fields in the message and replace episode fields with event fields.'
| def MigrateBackward(self, client, message, callback):
| def _ReplaceEpisodeWithEvent(key, value):
if RenameEventMigrator._EVENT_TO_EPISODE.has_key(key):
raise BadMessageException('Event fields should not appear in newer messages.')
event = RenameEventMigrator._EPISODE_TO_EVENT.get(key, None)
return ((event, value)... |
'Migration steps:
* add \'contact_user_id\' if first identities entry has user_id property.
* add \'identity\' from first identities entry.
* remove \'identities\'
* remove \'contact_source\'
* remove \'contact_id\'
* remove \'labels\' if present.
* remove any contacts that have only phone numbers.
* remove any contact... | def MigrateBackward(self, client, message, callback):
| from viewfinder.backend.db.contact import Contact
contacts_list = []
for contact in message.dict['contacts']:
if (('labels' in contact) and (Contact.REMOVED in contact['labels'])):
continue
if (len(contact['identities']) == 0):
continue
first_identity_properti... |
'Returns a regular dictionary with the same leaf items as this DotDict.
The resulting dict will have no nesting - items will have a dot-joined key
reflecting their nesting in the DotDict.
#Example...
d = DotDict()
d.a = 1
d.x = dict()
d.x.y = 2
d.x.z = 3
flat = d.flatten()
print d.keys() # [\'a\', \'x.y\', \'x.z\'... | def flatten(self):
| newdict = dict()
def recurse_flatten(prefix, dd):
for (k, v) in dd.iteritems():
newkey = (((prefix + '.') + k) if (len(prefix) > 0) else k)
if isinstance(v, DotDict):
recurse_flatten(newkey, v)
else:
newdict[newkey] = v
recurse_flat... |
'Ensure that the log is consistently encoded as UTF-8.'
| def format(self, record):
| msg = super(_LogFormatter, self).format(record)
if isinstance(msg, unicode):
msg = msg.encode('utf-8')
return msg
|
'Creates a new heapy object, sets it to begin profiling, and returns to caller.'
| def StartProfiling(self):
| hp = hpy()
hp.setrelheap()
return hp
|
'Returns the heap object for further examination.'
| def StopProfiling(self, hp):
| try:
return hp.heap()
finally:
del hp
|
'Called from a periodic timer to dump (hopefully) useful information
about the heap to the logs.'
| def _PeriodicDump(self, hp):
| logging.info('in periodic dump')
heap = self.StopProfiling(hp)
logging.info(('By class or dict owner:\n%s' % heap.byclodo))
logging.info(('By referrers:\n%s' % heap.byrcs))
logging.info(('By type:\n%s' % heap.bytype))
logging.info(('By via:\n%s' % heap.byvia))
del ... |
'Configures the secrets module to get and write secrets to a
subdirectory of --secrets_dir corresponding to \'domain\'.'
| def __init__(self, name, domain, secrets_dir):
| self._secrets = dict()
self._name = name
self.__secrets_subdir = os.path.join(secrets_dir, domain)
self.__passphrase = None
|
'If \'encrypted\' is True, a passphrase must be determined. The AMI
user-data is queried first for the secrets pass phrase. If
unavailable, the user is prompted via the console for the
pass-phrase before continuing. If \'encrypted\' is True, \'query_twice\'
determines whether to ask the user twice for the passphrase fo... | def Init(self, can_prompt=True, should_prompt=False, query_twice=False):
| passphrase_key = 'user-data/passphrase'
def _GetPassphraseFromKeyring():
"Retrieve the passphrase from keyring. Prompts whether to store it if not found.\n If a passphrase was retrieved or stored, save to self.__passph... |
'Reads the secrets with assumption they are not encrypted.'
| def InitForTest(self):
| self._need_passphrase = False
self._ReadSecrets()
|
'Returns a list of available secrets.'
| def ListSecrets(self):
| return self._secrets.keys()
|
'Returns true if the secret is in the secrets map.'
| def HasSecret(self, secret):
| return (secret in self._secrets)
|
'Returns the secret from the secrets map.'
| def GetSecret(self, secret):
| return self._secrets[secret].strip()
|
'Writes the secrets file and possibly encrypts the value.'
| def PutSecret(self, secret, secret_value):
| self._secrets[secret] = secret_value.strip()
fn = self._GetSecretFile(secret, verify=False)
with open(fn, 'w') as f:
os.chmod(fn, (stat.S_IRUSR | stat.S_IWUSR))
if self.__passphrase:
encrypted_secret = self._EncryptSecret(self._secrets[secret])
f.write(json.dumps(encr... |
'Assumes the secret is a Keyczar crypt keyset. Loads the secret
value and returns a Keyczar Crypter object already initialized with
the keyset value.'
| def GetCrypter(self, secret):
| return keyczar.Crypter(keyczar_dict.DictReader(self.GetSecret(secret)))
|
'Assumes the secret is a Keyczar signing keyset. Loads the secret
value and returns a Keyczar Signer object already initialized with
the keyset value.'
| def GetSigner(self, secret):
| return keyczar.Signer(keyczar_dict.DictReader(self.GetSecret(secret)))
|
'Concatenates the secret name with the --secrets_dir command
line flag.'
| def _GetSecretFile(self, secret, verify=True):
| path = os.path.join(self.__secrets_subdir, secret)
if (verify and (not os.access(path, os.R_OK))):
raise IOError('unable to access {0}'.format(path))
return path
|
'Reads the secrets file and possibly decrypts it.'
| def _ReadSecret(self, secret):
| with open(self._GetSecretFile(secret), 'r') as f:
contents = f.read()
try:
(cipher, ciphertext) = json.loads(contents)
if (cipher != 'AES'):
return contents
except:
return contents
return self._DecryptSecret(cipher, ciphertext)
|
'Reads all secrets from the secrets subdir.'
| def _ReadSecrets(self):
| try:
secrets = os.listdir(self.__secrets_subdir)
except Exception:
return
for secret in secrets:
self._secrets[secret] = self._ReadSecret(secret)
|
'Decrypts the ciphertext secret, splits it into the first
DIGEST_BYTES bytes (sha256 message digest), and verifies the digest
matches the secret. Returns the plaintext secret on success.'
| def _DecryptSecret(self, cipher, ciphertext):
| if (not self.__passphrase):
raise CannotReadEncryptedSecretError('no passphrase initialized')
assert (cipher == 'AES'), ('cipher %s not supported' % cipher)
aes_cipher = AES.new(self._PadText(self.__passphrase))
plaintext = aes_cipher.decrypt(base64.b64decode(ciphertext)).rstrip(S... |
'Computes a SHA256 message digest of the secret, prepends the
digest, pads to a multiple of BLOCK_SIZE, encrypts using an AES
cipher, and base64 encodes. Returns a tuple containing the cipher
used and the base64-encoded, encrypted value.'
| def _EncryptSecret(self, plaintext_secret):
| aes_cipher = AES.new(self._PadText(self.__passphrase))
sha256 = SHA256.new(plaintext_secret)
assert (len(sha256.digest()) == SecretsManager.DIGEST_BYTES), 'expected length of sha256 message digest not 256 bits'
plaintext = self._PadText((sha256.digest() + plaintext_secret))
c... |
'Pads the provided text so that it is a multiple of BLOCK_SIZE.
The padding character is specified by PADDING. Returns the padded
version of \'text\'.'
| def _PadText(self, text):
| if (len(text) in (16, 24, 32)):
return text
return (text + ((SecretsManager.BLOCK_SIZE - (len(text) % SecretsManager.BLOCK_SIZE)) * SecretsManager.PADDING))
|
'Entry point called by the operation framework.'
| @classmethod
@gen.coroutine
def Execute(cls, client, activity, viewpoint_id, episodes):
| (yield UnshareOperation(client, activity, viewpoint_id, episodes)._Unshare())
|
'"Orchestrates the unshare operation by executing each of the phases in turn.
As a side effect of traversal, Unshare will accumulate information about the unshare action
in "_unshares_dict" using the following format:
{\'vp_id0\': [{\'ep_id0\': [ph_id0, ph_id1, ...]},
{\'ep_id1\': [ph_id2]}],
\'vp_id1\': ...}
This info... | @gen.coroutine
def _Unshare(self):
| try:
(yield self._lock_tracker.AcquireViewpointLock(self._viewpoint_id))
(yield self._Check())
self._client.CheckDBNotModified()
(yield self._Update())
(yield self._Account())
(yield self._Notify())
finally:
(yield self._lock_tracker.ReleaseAllViewpointLoc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.