2013-08-01 00:34:37 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
'''
|
2018-05-28 21:13:12 +00:00
|
|
|
:codeauthor: Pedro Algarvio (pedro@algarvio.me)
|
2013-09-16 16:24:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
tests.unit.payload_test
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~
|
2013-08-01 00:34:37 +00:00
|
|
|
'''
|
|
|
|
|
2018-02-28 16:23:57 +00:00
|
|
|
# Import python libs
|
2017-12-15 18:14:18 +00:00
|
|
|
from __future__ import absolute_import, print_function, unicode_literals
|
2014-11-22 11:30:30 +00:00
|
|
|
import time
|
|
|
|
import errno
|
|
|
|
import threading
|
2018-02-28 16:23:57 +00:00
|
|
|
import datetime
|
2014-11-21 19:05:13 +00:00
|
|
|
|
2013-08-01 00:34:37 +00:00
|
|
|
# Import Salt Testing libs
|
2017-02-27 13:58:07 +00:00
|
|
|
from tests.support.unit import skipIf, TestCase
|
2018-02-28 23:16:31 +00:00
|
|
|
from tests.support.mock import NO_MOCK, NO_MOCK_REASON
|
2013-08-01 00:34:37 +00:00
|
|
|
|
2018-02-28 16:23:57 +00:00
|
|
|
# Import Salt libs
|
2018-02-28 23:16:31 +00:00
|
|
|
from salt.utils import immutabletypes
|
2013-08-01 00:34:37 +00:00
|
|
|
from salt.utils.odict import OrderedDict
|
2014-11-10 16:29:58 +00:00
|
|
|
import salt.exceptions
|
2018-02-28 23:16:31 +00:00
|
|
|
import salt.payload
|
2013-08-01 00:34:37 +00:00
|
|
|
|
|
|
|
# Import 3rd-party libs
|
2014-11-10 16:29:58 +00:00
|
|
|
import zmq
|
Use explicit unicode strings + break up salt.utils
This PR is part of what will be an ongoing effort to use explicit
unicode strings in Salt. Because Python 3 does not suport Python 2's raw
unicode string syntax (i.e. `ur'\d+'`), we must use
`salt.utils.locales.sdecode()` to ensure that the raw string is unicode.
However, because of how `salt/utils/__init__.py` has evolved into the
hulking monstrosity it is today, this means importing a large module in
places where it is not needed, which could negatively impact
performance. For this reason, this PR also breaks out some of the
functions from `salt/utils/__init__.py` into new/existing modules under
`salt/utils/`. The long term goal will be that the modules within this
directory do not depend on importing `salt.utils`.
A summary of the changes in this PR is as follows:
* Moves the following functions from `salt.utils` to new locations
(including a deprecation warning if invoked from `salt.utils`):
`to_bytes`, `to_str`, `to_unicode`, `str_to_num`, `is_quoted`,
`dequote`, `is_hex`, `is_bin_str`, `rand_string`,
`contains_whitespace`, `clean_kwargs`, `invalid_kwargs`, `which`,
`which_bin`, `path_join`, `shlex_split`, `rand_str`, `is_windows`,
`is_proxy`, `is_linux`, `is_darwin`, `is_sunos`, `is_smartos`,
`is_smartos_globalzone`, `is_smartos_zone`, `is_freebsd`, `is_netbsd`,
`is_openbsd`, `is_aix`
* Moves the functions already deprecated by @rallytime to the bottom of
`salt/utils/__init__.py` for better organization, so we can keep the
deprecated ones separate from the ones yet to be deprecated as we
continue to break up `salt.utils`
* Updates `salt/*.py` and all files under `salt/client/` to use explicit
unicode string literals.
* Gets rid of implicit imports of `salt.utils` (e.g. `from salt.utils
import foo` becomes `import salt.utils.foo as foo`).
* Renames the `test.rand_str` function to `test.random_hash` to more
accurately reflect what it does
* Modifies `salt.utils.stringutils.random()` (née `salt.utils.rand_string()`)
such that it returns a string matching the passed size. Previously
this function would get `size` bytes from `os.urandom()`,
base64-encode it, and return the result, which would in most cases not
be equal to the passed size.
2017-07-25 01:47:15 +00:00
|
|
|
from salt.ext import six
|
2014-11-10 16:29:58 +00:00
|
|
|
|
2015-01-29 17:27:31 +00:00
|
|
|
import logging
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
2014-11-10 21:03:35 +00:00
|
|
|
|
2013-08-26 10:03:19 +00:00
|
|
|
@skipIf(NO_MOCK, NO_MOCK_REASON)
|
2013-08-01 00:34:37 +00:00
|
|
|
class PayloadTestCase(TestCase):
|
|
|
|
|
|
|
|
def assertNoOrderedDict(self, data):
|
|
|
|
if isinstance(data, OrderedDict):
|
|
|
|
raise AssertionError(
|
|
|
|
'Found an ordered dictionary'
|
|
|
|
)
|
|
|
|
if isinstance(data, dict):
|
2014-11-22 11:30:30 +00:00
|
|
|
for value in six.itervalues(data):
|
2013-08-01 00:34:37 +00:00
|
|
|
self.assertNoOrderedDict(value)
|
|
|
|
elif isinstance(data, (list, tuple)):
|
|
|
|
for chunk in data:
|
|
|
|
self.assertNoOrderedDict(chunk)
|
|
|
|
|
|
|
|
def test_list_nested_odicts(self):
|
2018-02-28 23:16:31 +00:00
|
|
|
payload = salt.payload.Serial('msgpack')
|
|
|
|
idata = {'pillar': [OrderedDict(environment='dev')]}
|
|
|
|
odata = payload.loads(payload.dumps(idata.copy()))
|
|
|
|
self.assertNoOrderedDict(odata)
|
|
|
|
self.assertEqual(idata, odata)
|
2014-03-31 02:00:24 +00:00
|
|
|
|
2018-02-28 16:23:57 +00:00
|
|
|
def test_datetime_dump_load(self):
|
|
|
|
'''
|
|
|
|
Check the custom datetime handler can understand itself
|
|
|
|
'''
|
|
|
|
payload = salt.payload.Serial('msgpack')
|
2018-02-28 23:16:31 +00:00
|
|
|
dtvalue = datetime.datetime(2001, 2, 3, 4, 5, 6, 7)
|
|
|
|
idata = {dtvalue: dtvalue}
|
|
|
|
sdata = payload.dumps(idata.copy())
|
|
|
|
odata = payload.loads(sdata)
|
|
|
|
self.assertEqual(
|
|
|
|
sdata,
|
|
|
|
b'\x81\xc7\x18N20010203T04:05:06.000007\xc7\x18N20010203T04:05:06.000007')
|
|
|
|
self.assertEqual(idata, odata)
|
|
|
|
|
|
|
|
def test_verylong_dump_load(self):
|
|
|
|
'''
|
|
|
|
Test verylong encoder/decoder
|
|
|
|
'''
|
|
|
|
payload = salt.payload.Serial('msgpack')
|
|
|
|
idata = {'jid': 20180227140750302662}
|
2018-02-28 16:23:57 +00:00
|
|
|
sdata = payload.dumps(idata.copy())
|
|
|
|
odata = payload.loads(sdata)
|
2018-02-28 23:16:31 +00:00
|
|
|
idata['jid'] = '{0}'.format(idata['jid'])
|
|
|
|
self.assertEqual(idata, odata)
|
|
|
|
|
|
|
|
def test_immutable_dict_dump_load(self):
|
|
|
|
'''
|
|
|
|
Test immutable dict encoder/decoder
|
|
|
|
'''
|
|
|
|
payload = salt.payload.Serial('msgpack')
|
|
|
|
idata = {'dict': {'key': 'value'}}
|
|
|
|
sdata = payload.dumps({'dict': immutabletypes.ImmutableDict(idata['dict'])})
|
|
|
|
odata = payload.loads(sdata)
|
|
|
|
self.assertEqual(idata, odata)
|
|
|
|
|
|
|
|
def test_immutable_list_dump_load(self):
|
|
|
|
'''
|
|
|
|
Test immutable list encoder/decoder
|
|
|
|
'''
|
|
|
|
payload = salt.payload.Serial('msgpack')
|
|
|
|
idata = {'list': [1, 2, 3]}
|
|
|
|
sdata = payload.dumps({'list': immutabletypes.ImmutableList(idata['list'])})
|
|
|
|
odata = payload.loads(sdata)
|
|
|
|
self.assertEqual(idata, odata)
|
|
|
|
|
|
|
|
def test_immutable_set_dump_load(self):
|
|
|
|
'''
|
|
|
|
Test immutable set encoder/decoder
|
|
|
|
'''
|
|
|
|
payload = salt.payload.Serial('msgpack')
|
2018-03-02 02:36:30 +00:00
|
|
|
idata = {'set': ['red', 'green', 'blue']}
|
2018-02-28 23:16:31 +00:00
|
|
|
sdata = payload.dumps({'set': immutabletypes.ImmutableSet(idata['set'])})
|
|
|
|
odata = payload.loads(sdata)
|
2018-02-28 16:23:57 +00:00
|
|
|
self.assertEqual(idata, odata)
|
|
|
|
|
2018-02-28 23:16:31 +00:00
|
|
|
def test_odict_dump_load(self):
|
|
|
|
'''
|
|
|
|
Test odict just works. It wasn't until msgpack 0.2.0
|
|
|
|
'''
|
|
|
|
payload = salt.payload.Serial('msgpack')
|
|
|
|
data = OrderedDict()
|
|
|
|
data['a'] = 'b'
|
|
|
|
data['y'] = 'z'
|
|
|
|
data['j'] = 'k'
|
|
|
|
data['w'] = 'x'
|
|
|
|
sdata = payload.dumps({'set': data})
|
|
|
|
odata = payload.loads(sdata)
|
|
|
|
self.assertEqual({'set': dict(data)}, odata)
|
|
|
|
|
|
|
|
def test_mixed_dump_load(self):
|
|
|
|
'''
|
|
|
|
Test we can handle all exceptions at once
|
|
|
|
'''
|
|
|
|
payload = salt.payload.Serial('msgpack')
|
|
|
|
dtvalue = datetime.datetime(2001, 2, 3, 4, 5, 6, 7)
|
|
|
|
od = OrderedDict()
|
|
|
|
od['a'] = 'b'
|
|
|
|
od['y'] = 'z'
|
|
|
|
od['j'] = 'k'
|
|
|
|
od['w'] = 'x'
|
|
|
|
idata = {dtvalue: dtvalue, # datetime
|
|
|
|
'jid': 20180227140750302662, # long int
|
|
|
|
'dict': immutabletypes.ImmutableDict({'key': 'value'}), # immutable dict
|
|
|
|
'list': immutabletypes.ImmutableList([1, 2, 3]), # immutable list
|
2018-03-02 02:36:30 +00:00
|
|
|
'set': immutabletypes.ImmutableSet(('red', 'green', 'blue')), # immutable set
|
2018-02-28 23:16:31 +00:00
|
|
|
'odict': od, # odict
|
|
|
|
}
|
|
|
|
edata = {dtvalue: dtvalue, # datetime, == input
|
|
|
|
'jid': '20180227140750302662', # string repr of long int
|
|
|
|
'dict': {'key': 'value'}, # builtin dict
|
|
|
|
'list': [1, 2, 3], # builtin list
|
2018-03-02 02:36:30 +00:00
|
|
|
'set': ['red', 'green', 'blue'], # builtin set
|
2018-02-28 23:16:31 +00:00
|
|
|
'odict': dict(od), # builtin dict
|
|
|
|
}
|
|
|
|
sdata = payload.dumps(idata)
|
|
|
|
odata = payload.loads(sdata)
|
|
|
|
self.assertEqual(edata, odata)
|
|
|
|
|
2014-03-31 02:00:24 +00:00
|
|
|
|
2014-11-10 16:29:58 +00:00
|
|
|
class SREQTestCase(TestCase):
|
|
|
|
port = 8845 # TODO: dynamically assign a port?
|
2014-11-10 21:03:35 +00:00
|
|
|
|
2014-11-10 16:29:58 +00:00
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
|
|
|
'''
|
|
|
|
Class to set up zmq echo socket
|
|
|
|
'''
|
|
|
|
def echo_server():
|
|
|
|
'''
|
|
|
|
A server that echos the message sent to it over zmq
|
|
|
|
|
|
|
|
Optional "sleep" can be sent to delay response
|
|
|
|
'''
|
|
|
|
context = zmq.Context()
|
|
|
|
socket = context.socket(zmq.REP)
|
2014-11-10 21:03:35 +00:00
|
|
|
socket.bind("tcp://*:{0}".format(SREQTestCase.port))
|
2014-11-10 16:29:58 +00:00
|
|
|
payload = salt.payload.Serial('msgpack')
|
|
|
|
|
|
|
|
while SREQTestCase.thread_running.is_set():
|
|
|
|
try:
|
|
|
|
# Wait for next request from client
|
|
|
|
message = socket.recv(zmq.NOBLOCK)
|
|
|
|
msg_deserialized = payload.loads(message)
|
2017-12-14 06:26:39 +00:00
|
|
|
log.info('Echo server received message: %s', msg_deserialized)
|
2014-11-10 16:29:58 +00:00
|
|
|
if isinstance(msg_deserialized['load'], dict) and msg_deserialized['load'].get('sleep'):
|
2017-12-14 06:26:39 +00:00
|
|
|
log.info('Test echo server sleeping for %s seconds',
|
|
|
|
msg_deserialized['load']['sleep'])
|
2014-11-10 16:29:58 +00:00
|
|
|
time.sleep(msg_deserialized['load']['sleep'])
|
|
|
|
socket.send(message)
|
|
|
|
except zmq.ZMQError as exc:
|
|
|
|
if exc.errno == errno.EAGAIN:
|
|
|
|
continue
|
|
|
|
raise
|
|
|
|
SREQTestCase.thread_running = threading.Event()
|
|
|
|
SREQTestCase.thread_running.set()
|
|
|
|
SREQTestCase.echo_server = threading.Thread(target=echo_server)
|
|
|
|
SREQTestCase.echo_server.start()
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
|
|
|
'''
|
|
|
|
Remove echo server
|
|
|
|
'''
|
|
|
|
# kill the thread
|
|
|
|
SREQTestCase.thread_running.clear()
|
|
|
|
SREQTestCase.echo_server.join()
|
|
|
|
|
|
|
|
def get_sreq(self):
|
|
|
|
return salt.payload.SREQ('tcp://127.0.0.1:{0}'.format(SREQTestCase.port))
|
|
|
|
|
2014-12-04 20:26:04 +00:00
|
|
|
def test_send_auto(self):
|
|
|
|
'''
|
|
|
|
Test creation, send/rect
|
|
|
|
'''
|
|
|
|
sreq = self.get_sreq()
|
|
|
|
# check default of empty load and enc clear
|
|
|
|
assert sreq.send_auto({}) == {'enc': 'clear', 'load': {}}
|
|
|
|
|
|
|
|
# check that the load always gets passed
|
|
|
|
assert sreq.send_auto({'load': 'foo'}) == {'load': 'foo', 'enc': 'clear'}
|
|
|
|
|
2014-11-10 16:29:58 +00:00
|
|
|
def test_send(self):
|
|
|
|
sreq = self.get_sreq()
|
|
|
|
assert sreq.send('clear', 'foo') == {'enc': 'clear', 'load': 'foo'}
|
|
|
|
|
2015-06-10 20:04:14 +00:00
|
|
|
@skipIf(True, 'Disabled until we can figure out how to make this more reliable.')
|
2014-11-10 16:29:58 +00:00
|
|
|
def test_timeout(self):
|
|
|
|
'''
|
|
|
|
Test SREQ Timeouts
|
|
|
|
'''
|
|
|
|
sreq = self.get_sreq()
|
|
|
|
# client-side timeout
|
|
|
|
start = time.time()
|
2015-01-09 18:08:39 +00:00
|
|
|
# This is a try/except instead of an assertRaises because of a possible
|
|
|
|
# subtle bug in zmq wherein a timeout=0 actually exceutes a single poll
|
|
|
|
# before the timeout is reached.
|
2015-01-29 17:27:31 +00:00
|
|
|
log.info('Sending tries=0, timeout=0')
|
2015-01-09 18:08:39 +00:00
|
|
|
try:
|
2014-11-10 16:29:58 +00:00
|
|
|
sreq.send('clear', 'foo', tries=0, timeout=0)
|
2015-01-09 18:08:39 +00:00
|
|
|
except salt.exceptions.SaltReqTimeoutError:
|
|
|
|
pass
|
2014-11-10 16:29:58 +00:00
|
|
|
assert time.time() - start < 1 # ensure we didn't wait
|
|
|
|
|
|
|
|
# server-side timeout
|
2015-01-29 17:27:31 +00:00
|
|
|
log.info('Sending tries=1, timeout=1')
|
2014-11-10 16:29:58 +00:00
|
|
|
start = time.time()
|
|
|
|
with self.assertRaises(salt.exceptions.SaltReqTimeoutError):
|
|
|
|
sreq.send('clear', {'sleep': 2}, tries=1, timeout=1)
|
|
|
|
assert time.time() - start >= 1 # ensure we actually tried once (1s)
|
|
|
|
|
|
|
|
# server-side timeout with retries
|
2015-01-29 17:27:31 +00:00
|
|
|
log.info('Sending tries=2, timeout=1')
|
2014-11-10 16:29:58 +00:00
|
|
|
start = time.time()
|
|
|
|
with self.assertRaises(salt.exceptions.SaltReqTimeoutError):
|
|
|
|
sreq.send('clear', {'sleep': 2}, tries=2, timeout=1)
|
|
|
|
assert time.time() - start >= 2 # ensure we actually tried twice (2s)
|
|
|
|
|
|
|
|
# test a regular send afterwards (to make sure sockets aren't in a twist
|
2015-01-29 17:27:31 +00:00
|
|
|
log.info('Sending regular send')
|
2014-11-10 16:29:58 +00:00
|
|
|
assert sreq.send('clear', 'foo') == {'enc': 'clear', 'load': 'foo'}
|
|
|
|
|
|
|
|
def test_destroy(self):
|
|
|
|
'''
|
|
|
|
Test the __del__ capabilities
|
|
|
|
'''
|
|
|
|
sreq = self.get_sreq()
|
|
|
|
# ensure no exceptions when we go to destroy the sreq, since __del__
|
|
|
|
# swallows exceptions, we have to call destroy directly
|
|
|
|
sreq.destroy()
|