desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Spawns a thread that calls ``compute fn`` (along with additional arguments
``*compute_args`` and ``**compute_kwargs``), then applies the returned value to
:meth:`.Bot.answerInlineQuery` to answer the inline query.
If a preceding thread is already working for a user, that thread is cancelled,
thus ensuring at most one ... | def answer(outerself, inline_query, compute_fn, *compute_args, **compute_kwargs):
| from_id = inline_query['from']['id']
class Worker(threading.Thread, ):
def __init__(innerself):
super(Worker, innerself).__init__()
innerself._cancelled = False
def cancel(innerself):
innerself._cancelled = True
def run(innerself):
try:
... |
':param origin_set:
Callback query whose origin belongs to this set will be captured
:param enable_chat:
- ``False``: Do not intercept *chat-originated* callback query
- ``True``: Do intercept
- Notifier function: Do intercept and call the notifier function
on adding or removing an origin
:param enable_inline:
Same mea... | def __init__(self, id, origin_set, enable_chat, enable_inline):
| self._id = id
self._origin_set = origin_set
def dissolve(enable):
if (not enable):
return (False, None)
elif (enable is True):
return (True, None)
elif callable(enable):
return (True, enable)
else:
raise ValueError()
(self._... |
'Configure a :class:`.Listener` to capture callback query'
| def configure(self, listener):
| listener.capture([(lambda msg: (flavor(msg) == 'callback_query')), {'message': self._chat_origin_included}])
listener.capture([(lambda msg: (flavor(msg) == 'callback_query')), {'inline_message_id': self._inline_origin_included}])
|
':param send_func:
a function that sends messages, such as :meth:`.Bot.send\*`
:return:
a function that wraps around ``send_func`` and examines whether the
sent message contains an inline keyboard with callback data. If so,
future callback query originating from the sent message will be captured.'
| def augment_send(self, send_func):
| def augmented(*aa, **kw):
sent = send_func(*aa, **kw)
if (self._enable_chat and self._contains_callback_data(kw)):
self.capture_origin(message_identifier(sent))
return sent
return augmented
|
':param edit_func:
a function that edits messages, such as :meth:`.Bot.edit*`
:return:
a function that wraps around ``edit_func`` and examines whether the
edited message contains an inline keyboard with callback data. If so,
future callback query originating from the edited message will be captured.
If not, such captur... | def augment_edit(self, edit_func):
| def augmented(msg_identifier, *aa, **kw):
edited = edit_func(msg_identifier, *aa, **kw)
if (((edited is True) and self._enable_inline) or (isinstance(edited, dict) and self._enable_chat)):
if self._contains_callback_data(kw):
self.capture_origin(msg_identifier)
... |
':param delete_func:
a function that deletes messages, such as :meth:`.Bot.deleteMessage`
:return:
a function that wraps around ``delete_func`` and stops capturing
callback query originating from that deleted message.'
| def augment_delete(self, delete_func):
| def augmented(msg_identifier, *aa, **kw):
deleted = delete_func(msg_identifier, *aa, **kw)
if (deleted is True):
self.uncapture_origin(msg_identifier)
return deleted
return augmented
|
':param handler:
an ``on_message()`` handler function
:return:
a function that wraps around ``handler`` and examines whether the
incoming message is a chosen inline result with an ``inline_message_id``
field. If so, future callback query originating from this chosen
inline result will be captured.'
| def augment_on_message(self, handler):
| def augmented(msg):
if (self._enable_inline and (flavor(msg) == 'chosen_inline_result') and ('inline_message_id' in msg)):
inline_message_id = msg['inline_message_id']
self.capture_origin(inline_message_id)
return handler(msg)
return augmented
|
':return:
a proxy to ``bot`` with these modifications:
- all ``send*`` methods augmented by :meth:`augment_send`
- all ``edit*`` methods augmented by :meth:`augment_edit`
- ``deleteMessage()`` augmented by :meth:`augment_delete`
- all other public methods, including properties, copied unchanged'
| def augment_bot(self, bot):
| class BotProxy(object, ):
pass
proxy = BotProxy()
send_methods = ['sendMessage', 'forwardMessage', 'sendPhoto', 'sendAudio', 'sendDocument', 'sendSticker', 'sendVideo', 'sendVoice', 'sendVideoNote', 'sendLocation', 'sendVenue', 'sendContact', 'sendGame', 'sendInvoice', 'sendChatAction']
for meth... |
':param intercept_callback_query:
a 2-tuple (enable_chat, enable_inline) to pass to
:class:`.CallbackQueryCoordinator`'
| def __init__(self, intercept_callback_query, *args, **kwargs):
| global _cqc_origins
if (self.id in _cqc_origins):
origin_set = _cqc_origins[self.id]
else:
origin_set = set()
_cqc_origins[self.id] = origin_set
if isinstance(intercept_callback_query, tuple):
cqc_enable = intercept_callback_query
else:
cqc_enable = ((intercep... |
'Refresh timeout timer'
| def refresh(self):
| try:
if self._timeout_event:
self._scheduler.cancel(self._timeout_event)
except exception.EventNotFound:
pass
finally:
self._timeout_event = self._scheduler.event_later(self._timeout_seconds, ('_idle', {'seconds': self._timeout_seconds}))
|
':return:
a function wrapping ``handler`` to refresh timer for every
non-event message'
| def augment_on_message(self, handler):
| def augmented(msg):
(is_event(msg) or self.refresh())
if ((flavor(msg) == '_idle') and (msg is not self._timeout_event.data)):
return
return handler(msg)
return augmented
|
':return:
a function wrapping ``handler`` to cancel timeout event'
| def augment_on_close(self, handler):
| def augmented(ex):
try:
if self._timeout_event:
self._scheduler.cancel(self._timeout_event)
self._timeout_event = None
except exception.EventNotFound:
self._timeout_event = None
return handler(ex)
return augmented
|
'Raise an :class:`.IdleTerminate` to close the delegate.'
| def on__idle(self, event):
| raise exception.IdleTerminate(event['_idle']['seconds'])
|
'Configure a :class:`.Listener` to capture events with this object\'s
event space and source id.'
| def configure(self, listener):
| listener.capture([{re.compile('^_.+'): {'source': {'space': self._event_space, 'id': self._source_id}}}])
|
'Marshall ``flavor`` and ``data`` into a standard event.'
| def make_event_data(self, flavor, data):
| if (not flavor.startswith('_')):
raise ValueError('Event flavor must start with _underscore')
d = {'source': {'space': self._event_space, 'id': self._source_id}}
d.update(data)
return {flavor: d}
|
'Schedule an event to be emitted at a certain time.
:param when: an absolute timestamp
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.'
| def event_at(self, when, data_tuple):
| return self._base.event_at(when, self.make_event_data(*data_tuple))
|
'Schedule an event to be emitted after a delay.
:param delay: number of seconds
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.'
| def event_later(self, delay, data_tuple):
| return self._base.event_later(delay, self.make_event_data(*data_tuple))
|
'Schedule an event to be emitted now.
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.'
| def event_now(self, data_tuple):
| return self._base.event_now(self.make_event_data(*data_tuple))
|
'Cancel an event.'
| def cancel(self, event):
| return self._base.cancel(event)
|
'The underlying :class:`.Bot` or an augmented version thereof'
| @property
def bot(self):
| return self._bot
|
'See :class:`.Listener`'
| @property
def listener(self):
| return self._listener
|
'A :class:`.Sender` for this chat'
| @property
def sender(self):
| return self._sender
|
'An :class:`.Administrator` for this chat'
| @property
def administrator(self):
| return self._administrator
|
'A :class:`.Sender` for this user'
| @property
def sender(self):
| return self._sender
|
'Mesasge identifier of callback query\'s origin'
| @property
def origin(self):
| return self._origin
|
'An :class:`.Editor` to the originating message'
| @property
def editor(self):
| return self._editor
|
':param key_function:
A function that takes one argument (the message) and returns
one of the following:
- a key to the routing table
- a 1-tuple (key,)
- a 2-tuple (key, (positional, arguments, ...))
- a 3-tuple (key, (positional, arguments, ...), {keyword: arguments, ...})
Extra arguments, if returned, will be applie... | def __init__(self, key_function, routing_table):
| super(Router, self).__init__()
self.key_function = key_function
self.routing_table = routing_table
|
'Apply key function to ``msg`` to obtain a key. Return the routing table entry.'
| def map(self, msg):
| k = self.key_function(msg)
key = (k[0] if isinstance(k, (tuple, list)) else k)
return self.routing_table[key]
|
'Apply key function to ``msg`` to obtain a key, look up routing table
to obtain a handler function, then call the handler function with
positional and keyword arguments, if any is returned by the key function.
``*aa`` and ``**kw`` are dummy placeholders for easy chaining.
Regardless of any number of arguments returned ... | def route(self, msg, *aa, **kw):
| k = self.key_function(msg)
if isinstance(k, (tuple, list)):
(key, args, kwargs) = {1: (tuple(k) + ((), {})), 2: (tuple(k) + ({},)), 3: tuple(k)}[len(k)]
else:
(key, args, kwargs) = (k, (), {})
try:
fn = self.routing_table[key]
except KeyError as e:
if (None in self.ro... |
'Call :meth:`.Router.route` to handle the message.'
| def on_message(self, msg):
| self._router.route(msg)
|
'A delegate that never times-out, probably doing some kind of background monitoring
in the application. Most naturally paired with :func:`.per_application`.
:param capture: a list of patterns for :class:`.Listener` to capture'
| def __init__(self, seed_tuple, capture, **kwargs):
| (bot, initial_msg, seed) = seed_tuple
super(Monitor, self).__init__(bot, seed, **kwargs)
for pattern in capture:
self.listener.capture(pattern)
|
'A delegate to handle a chat.'
| def __init__(self, seed_tuple, include_callback_query=False, **kwargs):
| (bot, initial_msg, seed) = seed_tuple
super(ChatHandler, self).__init__(bot, seed, **kwargs)
self.listener.capture([{'chat': {'id': self.chat_id}}])
if include_callback_query:
self.listener.capture([{'message': {'chat': {'id': self.chat_id}}}])
|
'A delegate to handle a user\'s actions.
:param flavors:
A list of flavors to capture. ``all`` covers all flavors.'
| def __init__(self, seed_tuple, include_callback_query=False, flavors=(chat_flavors + inline_flavors), **kwargs):
| (bot, initial_msg, seed) = seed_tuple
super(UserHandler, self).__init__(bot, seed, **kwargs)
if (flavors == 'all'):
self.listener.capture([{'from': {'id': self.user_id}}])
else:
self.listener.capture([(lambda msg: (flavor(msg) in flavors)), {'from': {'id': self.user_id}}])
if include... |
'A delegate to handle a user\'s inline-related actions.'
| def __init__(self, seed_tuple, **kwargs):
| super(InlineUserHandler, self).__init__(seed_tuple, flavors=inline_flavors, **kwargs)
|
'A delegate to handle callback query from one origin.'
| def __init__(self, seed_tuple, **kwargs):
| (bot, initial_msg, seed) = seed_tuple
super(CallbackQueryOriginHandler, self).__init__(bot, seed, **kwargs)
self.listener.capture([(lambda msg: ((flavor(msg) == 'callback_query') and (origin_identifier(msg) == self.origin)))])
|
'A delegate to handle messages related to an invoice.'
| def __init__(self, seed_tuple, **kwargs):
| (bot, initial_msg, seed) = seed_tuple
super(InvoiceHandler, self).__init__(bot, seed, **kwargs)
self.listener.capture([{'invoice_payload': self.payload}])
self.listener.capture([{'successful_payment': {'invoice_payload': self.payload}}])
|
'__recvall(bytes) -> data
Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.'
| def __recvall(self, bytes):
| data = ''
while (len(data) < bytes):
data = (data + self.recv((bytes - len(data))))
return data
|
'setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxytype - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - T... | def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
| self.__proxy = (proxytype, addr, port, rdns, username, password)
|
'__negotiatesocks5(self,destaddr,destport)
Negotiates a connection through a SOCKS5 server.'
| def __negotiatesocks5(self, destaddr, destport):
| if ((self.__proxy[4] != None) and (self.__proxy[5] != None)):
self.sendall('\x05\x02\x00\x02')
else:
self.sendall('\x05\x01\x00')
chosenauth = self.__recvall(2)
if (chosenauth[0] != '\x05'):
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if (chosenauth[1... |
'getsockname() -> address info
Returns the bound IP address and port number at the proxy.'
| def getproxysockname(self):
| return self.__proxysockname
|
'getproxypeername() -> address info
Returns the IP and port number of the proxy.'
| def getproxypeername(self):
| return _orgsocket.getpeername(self)
|
'getpeername() -> address info
Returns the IP address and port number of the destination
machine (note: getproxypeername returns the proxy)'
| def getpeername(self):
| return self.__proxypeername
|
'__negotiatesocks4(self,destaddr,destport)
Negotiates a connection through a SOCKS4 server.'
| def __negotiatesocks4(self, destaddr, destport):
| rmtrslv = False
try:
ipaddr = socket.inet_aton(destaddr)
except socket.error:
if (self.__proxy[3] == True):
ipaddr = '\x00\x00\x00\x01'
rmtrslv = True
else:
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
req = (('\x04\x01' + struct.p... |
'__negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.'
| def __negotiatehttp(self, destaddr, destport):
| if (self.__proxy[3] == False):
addr = socket.gethostbyname(destaddr)
else:
addr = destaddr
self.sendall(((((((('CONNECT ' + addr) + ':') + str(destport)) + ' HTTP/1.1\r\n') + 'Host: ') + destaddr) + '\r\n\r\n'))
resp = self.recv(1)
while (resp.find('\r\n\r\n') == (-1)):
... |
'connect(self,despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket\'s connect).
To select the proxy server use setproxy().'
| def connect(self, destpair):
| if ((type(destpair) in (list, tuple) == False) or (len(destpair) < 2) or (type(destpair[0]) != str) or (type(destpair[1]) != int)):
raise GeneralProxyError((5, _generalerrors[5]))
if (self.__proxy[0] == PROXY_TYPE_SOCKS5):
if (self.__proxy[2] != None):
portnum = self.__proxy[2]
... |
'Verify generated presigned URL matches expected dict.
This method compares an actual URL against a dict of expected
values. The reason that the "expected_match" is a dict instead
of the expected presigned URL is because the query params
are unordered so we can\'t guarantee an expected query param
ordering.'
| def assert_presigned_url_matches(self, actual_url, expected_match):
| parts = urlsplit(actual_url)
self.assertEqual(parts.netloc, expected_match['hostname'])
self.assertEqual(parts.path, expected_match['path'])
query_params = self.parse_query_string(parts.query)
self.assertEqual(query_params, expected_match['query_params'])
|
'Override the default request patching because we need to
raise a ClientError exception.'
| def patch_make_request(self):
| self.make_request_is_patched = True
make_request_patch = self.make_request_patch.start()
make_request_patch.side_effect = ClientError({'Error': {'Code': 'NoSuchKey', 'Message': 'foo'}}, 'GetObject')
|
'This tests to ensure that streaming files for both uploads and
downloads do not use too much memory. Note that streaming uploads
will use slightly more memory than usual but should not put the
entire file into memory.'
| @attr('slow')
@unittest.skipIf(_running_on_rhel(), 'Streaming memory tests no supported on RHEL.')
def test_stream_large_file(self):
| bucket_name = _SHARED_BUCKET
num_mb = 200
foo_txt = self.files.create_file('foo.txt', '')
with open(foo_txt, 'wb') as f:
for i in range(num_mb):
f.write((('a' * 1024) * 1024))
max_mem_allowed = (self.max_mem_allowed + (2 * self.chunk_size))
full_command = ('s3 cp - s... |
'This tests uploading a small stream from stdin.'
| def test_upload(self):
| bucket_name = _SHARED_BUCKET
p = aws(('s3 cp - s3://%s/stream' % bucket_name), input_data='This is a test')
self.assert_no_errors(p)
self.assertTrue(self.key_exists(bucket_name, 'stream'))
self.assertEqual(self.get_key_contents(bucket_name, 'stream'), 'This is a test')
|
'This tests being able to upload unicode from stdin.'
| def test_unicode_upload(self):
| unicode_str = u'\xe9 This is a test'
byte_str = unicode_str.encode('utf-8')
bucket_name = _SHARED_BUCKET
p = aws(('s3 cp - s3://%s/stream' % bucket_name), input_data=byte_str)
self.assert_no_errors(p)
self.assertTrue(self.key_exists(bucket_name, 'stream'))
self.assertEqu... |
'This tests the ability to multipart upload streams from stdin.
The data has some unicode in it to avoid having to do a seperate
multipart upload test just for unicode.'
| @attr('slow')
def test_multipart_upload(self):
| bucket_name = _SHARED_BUCKET
data = (u'\xe9bcd' * ((1024 * 1024) * 10))
data_encoded = data.encode('utf-8')
p = aws(('s3 cp - s3://%s/stream' % bucket_name), input_data=data_encoded)
self.assert_no_errors(p)
self.assertTrue(self.key_exists(bucket_name, 'stream'))
self.assert_key_con... |
'This tests downloading a small stream from stdout.'
| def test_download(self):
| bucket_name = _SHARED_BUCKET
p = aws(('s3 cp - s3://%s/stream' % bucket_name), input_data='This is a test')
self.assert_no_errors(p)
p = aws(('s3 cp s3://%s/stream -' % bucket_name))
self.assert_no_errors(p)
self.assertEqual(p.stdout, 'This is a test')
|
'This tests downloading a small unicode stream from stdout.'
| def test_unicode_download(self):
| bucket_name = _SHARED_BUCKET
data = u'\xe9 This is a test'
data_encoded = data.encode('utf-8')
p = aws(('s3 cp - s3://%s/stream' % bucket_name), input_data=data_encoded)
self.assert_no_errors(p)
p = aws(('s3 cp s3://%s/stream -' % bucket_name))
self.assert_no_er... |
'This tests the ability to multipart download streams to stdout.
The data has some unicode in it to avoid having to do a seperate
multipart download test just for unicode.'
| @attr('slow')
def test_multipart_download(self):
| bucket_name = _SHARED_BUCKET
data = (u'\xe9bcd' * ((1024 * 1024) * 10))
data_encoded = data.encode('utf-8')
p = aws(('s3 cp - s3://%s/stream' % bucket_name), input_data=data_encoded)
p = aws(('s3 cp s3://%s/stream -' % bucket_name))
self.assert_no_errors(p)
self.assertEqual... |
'Confirm the appropriate action is taken when the soruce compare key
is equal to the destination compare key.'
| def test_compare_key_equal_should_not_sync(self):
| self.sync_strategy.determine_should_sync.return_value = False
src_files = []
dest_files = []
ref_list = []
result_list = []
time = datetime.datetime.now()
src_file = FileStat(src='', dest='', compare_key='comparator_test.py', size=10, last_update=time, src_type='local', dest_type='s3', opera... |
'Confirm the appropriate action is taken when the soruce compare key
is less than the destination compare key.'
| def test_compare_key_less(self):
| self.not_at_src_sync_strategy.determine_should_sync.return_value = False
self.not_at_dest_sync_strategy.determine_should_sync.return_value = True
src_files = []
dest_files = []
ref_list = []
result_list = []
time = datetime.datetime.now()
src_file = FileStat(src='', dest='', compare_key=... |
'Confirm the appropriate action is taken when the soruce compare key
is greater than the destination compare key.'
| def test_compare_key_greater(self):
| self.not_at_dest_sync_strategy.determine_should_sync.return_value = False
self.not_at_src_sync_strategy.determine_should_sync.return_value = True
src_files = []
dest_files = []
ref_list = []
result_list = []
time = datetime.datetime.now()
src_file = FileStat(src='', dest='', compare_key=... |
'Confirm the appropriate action is taken when there are no more source
files to take.'
| def test_empty_src(self):
| self.not_at_src_sync_strategy.determine_should_sync.return_value = True
src_files = []
dest_files = []
ref_list = []
result_list = []
time = datetime.datetime.now()
dest_file = FileStat(src='', dest='', compare_key='comparator_test.py', size=10, last_update=time, src_type='s3', dest_type='lo... |
'Confirm the appropriate action is taken when there are no more dest
files to take.'
| def test_empty_dest(self):
| self.not_at_dest_sync_strategy.determine_should_sync.return_value = True
src_files = []
dest_files = []
ref_list = []
result_list = []
time = datetime.datetime.now()
src_file = FileStat(src='', dest='', compare_key='domparator_test.py', size=10, last_update=time, src_type='local', dest_type=... |
'Confirm the appropriate action is taken when there are no more
files to take for both source and destination.'
| def test_empty_src_dest(self):
| src_files = []
dest_files = []
ref_list = []
result_list = []
files = self.comparator.call(iter(src_files), iter(dest_files))
for filename in files:
result_list.append(filename)
self.assertEqual(result_list, ref_list)
|
'Ensure that registering a single strategy class works as expected
when ``sync_type`` is specified.'
| def test_register_sync_strategy(self):
| register_sync_strategy(self.session, self.strategy_cls, 'sync_type')
self.strategy_cls.assert_called_with('sync_type')
self.strategy_object.register_strategy.assert_called_with(self.session)
|
'Ensure that registering a single strategy class works as expected
when the ``sync_type`` is not specified.'
| def test_register_sync_strategy_default_sync_type(self):
| register_sync_strategy(self.session, self.strategy_cls)
self.strategy_cls.assert_called_with('file_at_src_and_dest')
self.strategy_object.register_strategy.assert_called_with(self.session)
|
'Ensures that the class registers all of the necessary handlers'
| def test_register_strategy(self):
| session = Mock()
self.sync_strategy.register_strategy(session)
register_args = session.register.call_args_list
self.assertEqual(register_args[0][0][0], 'building-arg-table.sync')
self.assertEqual(register_args[0][0][1], self.sync_strategy.add_sync_argument)
self.assertEqual(register_args[1][0][0... |
'Ensure that this class cannot be directly used as the sync strategy.'
| def test_determine_should_sync(self):
| with self.assertRaises(NotImplementedError):
self.sync_strategy.determine_should_sync(None, None)
|
'Ensure that the ``arg_name`` property works as expected.'
| def test_arg_name(self):
| self.assertEqual(self.sync_strategy.arg_name, None)
self.sync_strategy.ARGUMENT = {'name': 'my-sync-strategy'}
self.assertEqual(self.sync_strategy.arg_name, 'my-sync-strategy')
|
'Ensure that the ``arg_dest`` property works as expected.'
| def test_arg_dest(self):
| self.assertEqual(self.sync_strategy.arg_dest, None)
self.sync_strategy.ARGUMENT = {'dest': 'my-dest'}
self.assertEqual(self.sync_strategy.arg_dest, 'my-dest')
|
'Ensures the sync argument is properly added to the
the command\'s ``arg_table``.'
| def test_add_sync_argument(self):
| arg_table = [{'name': 'original_argument'}]
self.sync_strategy.ARGUMENT = {'name': 'sync_argument'}
self.sync_strategy.add_sync_argument(arg_table)
self.assertEqual(arg_table, [{'name': 'original_argument'}, {'name': 'sync_argument'}])
|
'Ensures nothing is added to the command\'s ``arg_table`` if no
``ARGUMENT`` table is specified.'
| def test_no_add_sync_argument_for_no_argument_specified(self):
| arg_table = [{'name': 'original_argument'}]
self.sync_strategy.add_sync_argument(arg_table)
self.assertEqual(arg_table, [{'name': 'original_argument'}])
|
'Test if that the sync strategy is not returned if it has no argument.'
| def test_no_use_sync_strategy_for_no_argument_specified(self):
| params = {'my_sync_strategy': True}
self.assertEqual(self.sync_strategy.use_sync_strategy(params), None)
|
'Test if sync strategy argument has ``name`` but no ``dest`` and the
strategy was called in ``params``.'
| def test_use_sync_strategy_for_name_and_no_dest(self):
| self.sync_strategy.ARGUMENT = {'name': 'my-sync-strategy'}
params = {'my_sync_strategy': True}
self.assertEqual(self.sync_strategy.use_sync_strategy(params), self.sync_strategy)
|
'Test if sync strategy argument has ``name`` but no ``dest`` but
the strategy was not called in ``params``.'
| def test_no_use_sync_strategy_for_name_and_no_dest(self):
| self.sync_strategy.ARGUMENT = {'name': 'my-sync-strategy'}
params = {'my_sync_strategy': False}
self.assertEqual(self.sync_strategy.use_sync_strategy(params), None)
|
'Test if sync strategy argument has a ``name`` but for whatever reason
the strategy is not in ``params``.'
| def test_no_use_sync_strategy_for_not_in_params(self):
| self.sync_strategy.ARGUMENT = {'name': 'my-sync-strategy'}
self.assertEqual(self.sync_strategy.use_sync_strategy({}), None)
|
'Test if sync strategy argument has ``name`` and ``dest`` and the
strategy was called in ``params``.'
| def test_use_sync_strategy_for_name_and_dest(self):
| self.sync_strategy.ARGUMENT = {'name': 'my-sync-strategy', 'dest': 'my-dest'}
params = {'my-dest': True}
self.assertEqual(self.sync_strategy.use_sync_strategy(params), self.sync_strategy)
|
'Test if sync strategy argument has ``name`` and ``dest`` but the
the strategy was not called in ``params``.'
| def test_no_use_sync_strategy_for_name_and_dest(self):
| self.sync_strategy.ARGUMENT = {'name': 'my-sync-strategy', 'dest': 'my-dest'}
params = {'my-dest': False}
self.assertEqual(self.sync_strategy.use_sync_strategy(params), None)
|
'Test if sync strategy argument has ``name`` and ``dest`` but the
the strategy was not called in ``params`` even though the ``name`` was
called in ``params``.'
| def test_no_use_sync_strategy_for_dest_but_only_name_in_params(self):
| self.sync_strategy.ARGUMENT = {'name': 'my-sync-strategy', 'dest': 'my-dest'}
params = {'my-sync-strategy': True}
self.assertEqual(self.sync_strategy.use_sync_strategy(params), None)
|
'Confirms compare size works.'
| def test_compare_size(self):
| time = datetime.datetime.now()
src_file = FileStat(src='', dest='', compare_key='comparator_test.py', size=11, last_update=time, src_type='local', dest_type='s3', operation_name='upload')
dest_file = FileStat(src='', dest='', compare_key='comparator_test.py', size=10, last_update=time, src_type='s3', dest_t... |
'Confirms compare time works for uploads.'
| def test_compare_lastmod_upload(self):
| time = datetime.datetime.now()
future_time = (time + datetime.timedelta(0, 3))
src_file = FileStat(src='', dest='', compare_key='comparator_test.py', size=10, last_update=future_time, src_type='local', dest_type='s3', operation_name='upload')
dest_file = FileStat(src='', dest='', compare_key='comparator... |
'Confirms compare time works for copies.'
| def test_compare_lastmod_copy(self):
| time = datetime.datetime.now()
future_time = (time + datetime.timedelta(0, 3))
src_file = FileStat(src='', dest='', compare_key='comparator_test.py', size=10, last_update=future_time, src_type='s3', dest_type='s3', operation_name='copy')
dest_file = FileStat(src='', dest='', compare_key='comparator_test... |
'Confirms compare time works for downloads.'
| def test_compare_lastmod_download(self):
| time = datetime.datetime.now()
future_time = (time + datetime.timedelta(0, 3))
src_file = FileStat(src='', dest='', compare_key='comparator_test.py', size=10, last_update=time, src_type='s3', dest_type='local', operation_name='download')
dest_file = FileStat(src='', dest='', compare_key='comparator_test... |
'Confirm that same-sized files are synced when
the destination is older than the source and
`exact_timestamps` is set.'
| def test_compare_exact_timestamps_dest_older(self):
| time_src = datetime.datetime.now()
time_dst = (time_src - datetime.timedelta(days=1))
src_file = FileStat(src='', dest='', compare_key='test.py', size=10, last_update=time_src, src_type='s3', dest_type='local', operation_name='download')
dst_file = FileStat(src='', dest='', compare_key='test.py', size=1... |
'Confirm that same-sized files are synced when
the source is older than the destination and
`exact_timestamps` is set.'
| def test_compare_exact_timestamps_src_older(self):
| time_src = (datetime.datetime.now() - datetime.timedelta(days=1))
time_dst = datetime.datetime.now()
src_file = FileStat(src='', dest='', compare_key='test.py', size=10, last_update=time_src, src_type='s3', dest_type='local', operation_name='download')
dst_file = FileStat(src='', dest='', compare_key='t... |
'Confirm that same-sized files are not synced when
the source and destination are the same age and
`exact_timestamps` is set.'
| def test_compare_exact_timestamps_same_age_same_size(self):
| time_both = datetime.datetime.now()
src_file = FileStat(src='', dest='', compare_key='test.py', size=10, last_update=time_both, src_type='s3', dest_type='local', operation_name='download')
dst_file = FileStat(src='', dest='', compare_key='test.py', size=10, last_update=time_both, src_type='local', dest_type... |
'Confirm that files of differing sizes are synced when
the source and destination are the same age and
`exact_timestamps` is set.'
| def test_compare_exact_timestamps_same_age_diff_size(self):
| time_both = datetime.datetime.now()
src_file = FileStat(src='', dest='', compare_key='test.py', size=20, last_update=time_both, src_type='s3', dest_type='local', operation_name='download')
dst_file = FileStat(src='', dest='', compare_key='test.py', size=10, last_update=time_both, src_type='local', dest_type... |
'Confirm that same sized files are synced when the timestamps differ,
the type of operation is not a download, and ``exact_timestamps``
is set.'
| def test_compare_exact_timestamps_diff_age_not_download(self):
| time_src = datetime.datetime.now()
time_dst = (time_src - datetime.timedelta(days=1))
src_file = FileStat(src='', dest='', compare_key='test.py', size=10, last_update=time_src, src_type='s3', dest_type='local', operation_name='upload')
dst_file = FileStat(src='', dest='', compare_key='test.py', size=10,... |
'Confirm that files are synced when size differs.'
| def test_compare_size_only(self):
| time_src = datetime.datetime.now()
time_dst = (time_src + datetime.timedelta(days=1))
src_file = FileStat(src='', dest='', compare_key='test.py', size=11, last_update=time_src, src_type='local', dest_type='s3', operation_name='upload')
dst_file = FileStat(src='', dest='', compare_key='test.py', size=10,... |
'Confirm that files with the same size but different update times
are not synced.'
| def test_compare_size_only_different_update_times(self):
| time_src = datetime.datetime.now()
time_dst = (time_src + datetime.timedelta(days=1))
src_file = FileStat(src='', dest='', compare_key='test.py', size=10, last_update=time_src, src_type='local', dest_type='s3', operation_name='upload')
dst_file = FileStat(src='', dest='', compare_key='test.py', size=10,... |
'This tests to make sure the instructions for any command is generated
properly.'
| def test_create_instructions(self):
| cmds = ['cp', 'mv', 'rm', 'sync']
instructions = {'cp': ['file_generator', 'file_info_builder', 's3_handler'], 'mv': ['file_generator', 'file_info_builder', 's3_handler'], 'rm': ['file_generator', 'file_info_builder', 's3_handler'], 'sync': ['file_generator', 'comparator', 'file_info_builder', 's3_handler']}
... |
'Generate a single local file.'
| def test_local_file(self):
| input_local_file = {'src': {'path': self.local_file, 'type': 'local'}, 'dest': {'path': 'bucket/text1.txt', 'type': 's3'}, 'dir_op': False, 'use_src_name': False}
params = {'region': 'us-east-1'}
files = FileGenerator(self.client, '').call(input_local_file)
result_list = []
for filename in files:
... |
'Generate an entire local directory.'
| def test_local_directory(self):
| input_local_dir = {'src': {'path': self.local_dir, 'type': 'local'}, 'dest': {'path': 'bucket/', 'type': 's3'}, 'dir_op': True, 'use_src_name': True}
params = {'region': 'us-east-1'}
files = FileGenerator(self.client, '').call(input_local_dir)
result_list = []
for filename in files:
result_l... |
'This tests to make sure it fails when following bad symlinks.'
| def test_warn_bad_symlink(self):
| abs_root = six.text_type((os.path.abspath(self.root) + os.sep))
input_local_dir = {'src': {'path': abs_root, 'type': 'local'}, 'dest': {'path': self.bucket, 'type': 's3'}, 'dir_op': True, 'use_src_name': True}
file_stats = FileGenerator(self.client, '', True).call(input_local_dir)
file_gen = FileGenerat... |
'Generate a single s3 file
Note: Size and last update are not tested because s3 generates them.'
| def test_s3_file(self):
| input_s3_file = {'src': {'path': self.file1, 'type': 's3'}, 'dest': {'path': 'text1.txt', 'type': 'local'}, 'dir_op': False, 'use_src_name': False}
params = {'region': 'us-east-1'}
self.parsed_responses = [{'ETag': 'abcd', 'ContentLength': 100, 'LastModified': '2014-01-09T20:45:49.000Z'}]
self.patch_mak... |
'Test the error message for a 404 ClientError for a single file listing'
| def test_s3_single_file_404(self):
| input_s3_file = {'src': {'path': self.file1, 'type': 's3'}, 'dest': {'path': 'text1.txt', 'type': 'local'}, 'dir_op': False, 'use_src_name': False}
params = {'region': 'us-east-1'}
self.client = mock.Mock()
self.client.head_object.side_effect = ClientError({'Error': {'Code': '404', 'Message': 'Not Fo... |
'Generates s3 files under a common prefix. Also it ensures that
zero size files are ignored.
Note: Size and last update are not tested because s3 generates them.'
| def test_s3_directory(self):
| input_s3_file = {'src': {'path': (self.bucket + '/'), 'type': 's3'}, 'dest': {'path': '', 'type': 'local'}, 'dir_op': True, 'use_src_name': True}
params = {'region': 'us-east-1'}
files = FileGenerator(self.client, '').call(input_s3_file)
self.parsed_responses = [{'CommonPrefixes': [], 'Contents': [{'Key... |
'Generates s3 files under a common prefix. Also it ensures that
the directory itself is included because it is a delete command
Note: Size and last update are not tested because s3 generates them.'
| def test_s3_delete_directory(self):
| input_s3_file = {'src': {'path': (self.bucket + '/'), 'type': 's3'}, 'dest': {'path': '', 'type': 'local'}, 'dir_op': True, 'use_src_name': True}
self.parsed_responses = [{'CommonPrefixes': [], 'Contents': [{'Key': 'another_directory/', 'Size': 0, 'LastModified': '2012-01-09T20:45:49.000Z'}, {'Key': 'another_di... |
'Format a paths for directory operation. There are slashes at the
end of the paths.'
| def test_op_dir(self):
| src = ('.' + os.sep)
dest = 's3://kyknapp/golfVid/'
parameters = {'dir_op': True}
files = self.file_format.format(src, dest, parameters)
ref_files = {'src': {'path': (os.path.abspath(src) + os.sep), 'type': 'local'}, 'dest': {'path': 'kyknapp/golfVid/', 'type': 's3'}, 'dir_op': True, 'use_src_name':... |
'Format a paths for directory operation. There are no slashes at the
end of the paths.'
| def test_op_dir_noslash(self):
| src = '.'
dest = 's3://kyknapp/golfVid'
parameters = {'dir_op': True}
files = self.file_format.format(src, dest, parameters)
ref_files = {'src': {'path': (os.path.abspath(src) + os.sep), 'type': 'local'}, 'dest': {'path': 'kyknapp/golfVid/', 'type': 's3'}, 'dir_op': True, 'use_src_name': True}
s... |
'No directory operation. S3 source name given. Existing local
destination directory given.'
| def test_local_use_src_name(self):
| src = 's3://kyknapp/golfVid/hello.txt'
dest = '.'
parameters = {'dir_op': False}
files = self.file_format.format(src, dest, parameters)
ref_files = {'src': {'path': 'kyknapp/golfVid/hello.txt', 'type': 's3'}, 'dest': {'path': (os.path.abspath(dest) + os.sep), 'type': 'local'}, 'dir_op': False, 'use_... |
'No directory operation. S3 source name given. Nonexisting local
destination directory given.'
| def test_local_noexist_file(self):
| src = 's3://kyknapp/golfVid/hello.txt'
dest = ('someFile' + os.sep)
parameters = {'dir_op': False}
files = self.file_format.format(src, dest, parameters)
ref_files = {'src': {'path': 'kyknapp/golfVid/hello.txt', 'type': 's3'}, 'dest': {'path': (os.path.abspath(dest) + os.sep), 'type': 'local'}, 'dir... |
'No directory operation. S3 source name given. Local
destination filename given.'
| def test_local_keep_dest_name(self):
| src = 's3://kyknapp/golfVid/hello.txt'
dest = 'hello.txt'
parameters = {'dir_op': False}
files = self.file_format.format(src, dest, parameters)
ref_files = {'src': {'path': 'kyknapp/golfVid/hello.txt', 'type': 's3'}, 'dest': {'path': os.path.abspath(dest), 'type': 'local'}, 'dir_op': False, 'use_src... |
'No directory operation. Local source name given. S3
common prefix given.'
| def test_s3_use_src_name(self):
| src = 'fileformat_test.py'
dest = 's3://kyknapp/golfVid/'
parameters = {'dir_op': False}
files = self.file_format.format(src, dest, parameters)
ref_files = {'src': {'path': os.path.abspath(src), 'type': 'local'}, 'dest': {'path': 'kyknapp/golfVid/', 'type': 's3'}, 'dir_op': False, 'use_src_name': Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.