desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
':param string consumer_key: Key provided by Yahoo.
:param string consumer_secret: Secret corresponding to the key
provided by Yahoo.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception.
:param dict proxies: If specified, rout... | def __init__(self, consumer_key, consumer_secret, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
| if requests_missing:
raise ImportError('requests-oauthlib is needed for YahooPlaceFinder. Install with `pip install geopy -e ".[placefinder]"`.')
super(YahooPlaceFinder, self).__init__(timeout=timeout, proxies=proxies, user_agent=user_agent)
self.consumer_key = (unic... |
'Returns only the results that meet the minimum quality threshold
and are located in expected countries.'
| @staticmethod
def _filtered_results(results, min_quality, valid_country_codes):
| if min_quality:
results = [loc for loc in results if (int(loc.raw['quality']) > min_quality)]
if valid_country_codes:
results = [loc for loc in results if (loc.raw['countrycode'] in valid_country_codes)]
return results
|
'Returns the parsed result of a PlaceFinder API call.'
| def _parse_response(self, content):
| try:
placefinder = content['bossresponse']['placefinder']
if ((not len(placefinder)) or (not len(placefinder.get('results', [])))):
return None
results = [Location(self.humanize(place), (float(place['latitude']), float(place['longitude'])), raw=place) for place in placefinder['re... |
'Returns a human readable representation of a raw PlaceFinder location'
| @staticmethod
def humanize(location):
| return ', '.join([location[line] for line in ['line1', 'line2', 'line3', 'line4'] if location[line]])
|
'Geocode a location query.
:param string query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int min_quality:
:param bool reverse:
:param valid_country_codes:
:type valid_country_codes: list or tuple
:param bool with_timezone: Include th... | def geocode(self, query, exactly_one=True, timeout=None, min_quality=0, reverse=False, valid_country_codes=None, with_timezone=False):
| params = {'location': query, 'flags': 'J'}
if (reverse is True):
params['gflags'] = 'R'
if (exactly_one is True):
params['count'] = '1'
if (with_timezone is True):
params['flags'] += 'T'
response = self._call_geocoder(self.api, timeout=timeout, requester=get, params=params, a... |
'Returns a reverse geocoded location using Yahoo"s PlaceFinder API.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of (latitude,
longitude), or string as "%(latitude)s, %(longitude)s"
:param bool exactly_one: Return... | def reverse(self, query, exactly_one=True, timeout=None):
| query = self._coerce_point_to_string(query)
if isinstance(query, string_compare):
query = query.replace(' ', '')
return self.geocode(query, exactly_one=exactly_one, timeout=timeout, reverse=True)
|
'Initialize a customized Baidu geocoder using the v2 API.
.. versionadded:: 1.0.0
:param string api_key: The API key required by Baidu Map to perform
geocoding requests. API keys are managed through the Baidu APIs
console (http://lbsyun.baidu.com/apiconsole/key).
:param string scheme: Use \'https\' or \'http\' as the A... | def __init__(self, api_key, scheme='http', timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
| super(Baidu, self).__init__(scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent)
self.api_key = api_key
self.scheme = scheme
self.doc = {}
self.api = 'http://api.map.baidu.com/geocoder/v2/'
|
'Format the components dict to something Baidu understands.'
| @staticmethod
def _format_components_param(components):
| return '|'.join((':'.join(item) for item in components.items()))
|
'Geocode a location query.
:param string query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set ... | def geocode(self, query, exactly_one=True, timeout=None):
| params = {'ak': self.api_key, 'output': 'json', 'address': (self.format_string % query)}
url = '?'.join((self.api, urlencode(params)))
logger.debug('%s.geocode: %s', self.__class__.__name__, url)
return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one=exactly_one)
|
'Given a point, find an address.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of (latitude,
longitude), or string as "%(latitude)s, %(longitude)s"
:param int timeout: Time, in seconds, to wait for the geocoding se... | def reverse(self, query, timeout=None):
| params = {'ak': self.api_key, 'output': 'json', 'location': self._coerce_point_to_string(query)}
url = '?'.join((self.api, urlencode(params)))
logger.debug('%s.reverse: %s', self.__class__.__name__, url)
return self._parse_reverse_json(self._call_geocoder(url, timeout=timeout))
|
'Parses a location from a single-result reverse API call.'
| @staticmethod
def _parse_reverse_json(page):
| place = page.get('result')
location = place.get('formatted_address').encode('utf-8')
latitude = place['location']['lat']
longitude = place['location']['lng']
return Location(location, (latitude, longitude), place)
|
'Returns location, (latitude, longitude) from JSON feed.'
| def _parse_json(self, page, exactly_one=True):
| place = page.get('result', None)
if (not place):
self._check_status(page.get('status'))
return None
def parse_place(place):
'\n Get the location, lat, lng from a single JSON place.\n ... |
'Validates error statuses.'
| @staticmethod
def _check_status(status):
| if (status == '0'):
return
if (status == '1'):
raise GeocoderQueryError('Internal server error.')
elif (status == '2'):
raise GeocoderQueryError('Invalid request.')
elif (status == '3'):
raise GeocoderAuthenticationFailure('Authentication failure.')
elif (... |
'Initialize a customized Open Cage Data geocoder.
:param string api_key: The API key required by Open Cage Data
to perform geocoding requests. You can get your key here:
https://developer.opencagedata.com/
:param string domain: Currently it is \'api.opencagedata.com\', can
be changed for testing purposes.
:param string... | def __init__(self, api_key, domain='api.opencagedata.com', scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
| super(OpenCage, self).__init__(scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent)
self.api_key = api_key
self.domain = domain.strip('/')
self.scheme = scheme
self.api = ('%s://%s/geocode/v1/json' % (self.scheme, self.domain))
|
'Geocode a location query.
:param string query: The query string to be geocoded; this must
be URL encoded.
:param string language: an IETF format language code (such as `es`
for Spanish or pt-BR for Brazilian Portuguese); if this is
omitted a code of `en` (English) will be assumed by the remote
service.
:param string b... | def geocode(self, query, bounds=None, country=None, language=None, exactly_one=True, timeout=None):
| params = {'key': self.api_key, 'q': (self.format_string % query)}
if bounds:
params['bounds'] = bounds
if language:
params['language'] = language
if country:
params['country'] = country
url = '?'.join((self.api, urlencode(params)))
logger.debug('%s.geocode: %s', self._... |
'Given a point, find an address.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of (latitude,
longitude), or string as "%(latitude)s, %(longitude)s"
:param string language: The language in which to return results.
:... | def reverse(self, query, language=None, exactly_one=False, timeout=None):
| params = {'key': self.api_key, 'q': self._coerce_point_to_string(query)}
if language:
params['language'] = language
url = '?'.join((self.api, urlencode(params)))
logger.debug('%s.reverse: %s', self.__class__.__name__, url)
return self._parse_json(self._call_geocoder(url, timeout=timeout),... |
'Returns location, (latitude, longitude) from json feed.'
| def _parse_json(self, page, exactly_one=True):
| places = page.get('results', [])
if (not len(places)):
self._check_status(page.get('status'))
return None
def parse_place(place):
'Get the location, lat, lng from a single json place.'
location = place.get('formatted')
latitude = place['geom... |
'Validates error statuses.'
| @staticmethod
def _check_status(status):
| status_code = status['code']
if (status_code == 429):
raise GeocoderQuotaExceeded('The given key has gone over the requests limit in the 24 hour period or has submitted too many requests in too short a period of time.')
if... |
'Location as a formatted string returned by the geocoder or constructed
by geopy, depending on the service.
:rtype: unicode'
| @property
def address(self):
| return self._address
|
'Location\'s latitude.
:rtype: float or None'
| @property
def latitude(self):
| return self._point[0]
|
'Location\'s longitude.
:rtype: float or None'
| @property
def longitude(self):
| return self._point[1]
|
'Location\'s altitude.
:rtype: float or None'
| @property
def altitude(self):
| return self._point[2]
|
':class:`geopy.point.Point` instance representing the location\'s
latitude, longitude, and altitude.
:rtype: :class:`geopy.point.Point` or None'
| @property
def point(self):
| return (self._point if (self._point != (None, None, None)) else None)
|
'Location\'s raw, unparsed geocoder response. For details on this,
consult the service\'s documentation.
:rtype: dict or None'
| @property
def raw(self):
| return self._raw
|
'Backwards compatibility with geopy<0.98 tuples.'
| def __getitem__(self, index):
| return self._tuple[index]
|
'Abstract method for measure'
| def measure(self, a, b):
| raise NotImplementedError()
|
'TODO docs.'
| def destination(self, point, bearing, distance=None):
| point = Point(point)
lat1 = units.radians(degrees=point.latitude)
lng1 = units.radians(degrees=point.longitude)
bearing = units.radians(degrees=bearing)
if (distance is None):
distance = self
if isinstance(distance, Distance):
distance = distance.kilometers
d_div_r = (float(d... |
'Change the ellipsoid used in the calculation.'
| def set_ellipsoid(self, ellipsoid):
| if (not isinstance(ellipsoid, (list, tuple))):
try:
self.ELLIPSOID = ELLIPSOIDS[ellipsoid]
self.ellipsoid_key = ellipsoid
except KeyError:
raise Exception('Invalid ellipsoid. See geopy.distance.ELIPSOIDS')
else:
self.ELLIPSOID = ellipsoid
... |
'TODO docs.'
| def destination(self, point, bearing, distance=None):
| point = Point(point)
lat1 = units.radians(degrees=point.latitude)
lng1 = units.radians(degrees=point.longitude)
bearing = units.radians(degrees=bearing)
if (distance is None):
distance = self
if isinstance(distance, Distance):
distance = distance.kilometers
ellipsoid = self.E... |
':param float latitude: Latitude of point.
:param float longitude: Longitude of point.
:param float altitude: Altitude of point.'
| def __new__(cls, latitude=None, longitude=None, altitude=None):
| single_arg = ((longitude is None) and (altitude is None))
if (single_arg and (not isinstance(latitude, util.NUMBER_TYPES))):
arg = latitude
if (arg is None):
pass
elif isinstance(arg, Point):
return cls.from_point(arg)
elif isinstance(arg, string_compare):... |
'Format decimal degrees (DD) to degrees minutes seconds (DMS)'
| def format(self, altitude=None, deg_char='', min_char='m', sec_char='s'):
| latitude = ('%s %s' % (format_degrees(abs(self.latitude), symbols={'deg': deg_char, 'arcmin': min_char, 'arcsec': sec_char}), (((self.latitude >= 0) and 'N') or 'S')))
longitude = ('%s %s' % (format_degrees(abs(self.longitude), symbols={'deg': deg_char, 'arcmin': min_char, 'arcsec': sec_char}), (((self.lo... |
'Format decimal degrees with altitude'
| def format_decimal(self, altitude=None):
| coordinates = [str(self.latitude), str(self.longitude)]
if (altitude is None):
altitude = bool(self.altitude)
if (altitude is True):
if (not isinstance(altitude, string_compare)):
altitude = 'km'
coordinates.append(self.format_altitude(altitude))
return ', '.join(c... |
'Foamt altitude with unit'
| def format_altitude(self, unit='km'):
| return format_distance(self.altitude, unit=unit)
|
'Parse degrees minutes seconds including direction (N, S, E, W)'
| @classmethod
def parse_degrees(cls, degrees, arcminutes, arcseconds, direction=None):
| degrees = float(degrees)
negative = (degrees < 0)
arcminutes = float(arcminutes)
arcseconds = float(arcseconds)
if (arcminutes or arcseconds):
more = units.degrees(arcminutes=arcminutes, arcseconds=arcseconds)
if negative:
degrees -= more
else:
degrees... |
'Parse altitude managing units conversion'
| @classmethod
def parse_altitude(cls, distance, unit):
| if (distance is not None):
distance = float(distance)
CONVERTERS = {'km': (lambda d: d), 'm': (lambda d: units.kilometers(meters=d)), 'mi': (lambda d: units.kilometers(miles=d)), 'ft': (lambda d: units.kilometers(feet=d)), 'nm': (lambda d: units.kilometers(nautical=d)), 'nmi': (lambda d: units.kilom... |
'Create and return a ``Point`` instance from a string containing
latitude and longitude, and optionally, altitude.
Latitude and longitude must be in degrees and may be in decimal form
or indicate arcminutes and arcseconds (labeled with Unicode prime and
double prime, ASCII quote and double quote or \'m\' and \'s\'). Th... | @classmethod
def from_string(cls, string):
| match = re.match(cls.POINT_PATTERN, re.sub("''", '"', string))
if match:
latitude_direction = None
if match.group('latitude_direction_front'):
latitude_direction = match.group('latitude_direction_front')
elif match.group('latitude_direction_back'):
latitude_direct... |
'Create and return a new ``Point`` instance from any iterable with 0 to
3 elements. The elements, if present, must be latitude, longitude,
and altitude, respectively.'
| @classmethod
def from_sequence(cls, seq):
| args = tuple(islice(seq, 4))
return cls(*args)
|
'Create and return a new ``Point`` instance from another ``Point``
instance.'
| @classmethod
def from_point(cls, point):
| return cls(point.latitude, point.longitude, point.altitude)
|
'Init the Parser'
| def __init__(self):
| self.main_parser = argparse.ArgumentParser()
self.add_args()
|
'Add new arguments'
| def add_args(self):
| self.main_parser.add_argument('-i', type=str, default='eth0', dest='iface', required=False, help='the interface to dump themaster runs on(default:eth0)')
self.main_parser.add_argument('-n', type=int, default=5, dest='ival', required=False, help='interval for printing stats (default... |
'parses and returns the given arguments in a namespace object'
| def parse_args(self):
| return self.main_parser.parse_args()
|
'main loop for the packet-parser'
| def run(self):
| cap = pcapy.open_live(self.iface, 65536, 1, 0)
count = 0
l_time = None
while 1:
packet_data = {'ip': {}, 'tcp': {}}
(header, packet) = cap.next()
(eth_length, eth_protocol) = self.parse_ether(packet)
if (eth_protocol == 8):
(version_ihl, version, ihl, iph_leng... |
'parse ethernet_header and return size and protocol'
| def parse_ether(self, packet):
| eth_length = 14
eth_header = packet[:eth_length]
eth = unpack('!6s6sH', eth_header)
eth_protocol = socket.ntohs(eth[2])
return (eth_length, eth_protocol)
|
'parse ip_header and return all ip data fields'
| def parse_ip(self, packet, eth_length):
| ip_header = packet[eth_length:(20 + eth_length)]
iph = unpack('!BBHHHBBH4s4s', ip_header)
version_ihl = iph[0]
version = (version_ihl >> 4)
ihl = (version_ihl & 15)
iph_length = (ihl * 4)
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8])
d_addr = socket.inet_ntoa(i... |
'parse tcp_data and return source_port,
dest_port and actual packet data'
| def parse_tcp(self, packet, iph_length, eth_length):
| p_len = (iph_length + eth_length)
tcp_header = packet[p_len:(p_len + 20)]
tcph = unpack('!H HLLBBHHH', tcp_header)
source_port = tcph[0]
dest_port = tcph[1]
sequence = tcph[2]
acknowledgement = tcph[3]
doff_reserved = tcph[4]
tcph_length = (doff_reserved >> 4)
tcp_flags = tcph... |
'Read the table of tcp connections & remove header'
| def proc_tcp(self):
| with open('/proc/net/tcp', 'r') as tcp_f:
content = tcp_f.readlines()
content.pop(0)
return content
|
'convert hex to dezimal'
| def hex2dec(self, hex_s):
| return str(int(hex_s, 16))
|
'convert into readable ip'
| def ip(self, hex_s):
| ip = [self.hex2dec(hex_s[6:8]), self.hex2dec(hex_s[4:6]), self.hex2dec(hex_s[2:4]), self.hex2dec(hex_s[0:2])]
return '.'.join(ip)
|
'create new list without empty entries'
| def remove_empty(self, array):
| return [x for x in array if (x != '')]
|
'hex_ip:hex_port to str_ip:str_port'
| def convert_ip_port(self, array):
| (host, port) = array.split(':')
return (self.ip(host), self.hex2dec(port))
|
'main loop for netstat'
| def run(self):
| while 1:
ips = {'ips/4505': {}, 'ips/4506': {}}
content = self.proc_tcp()
for line in content:
line_array = self.remove_empty(line.split(' '))
(l_host, l_port) = self.convert_ip_port(line_array[1])
(r_host, r_port) = self.convert_ip_port(line_array[2])
... |
'Test cli function'
| def test_cli(self):
| cmd_iter = self.client.cmd_cli('minion', 'test.ping')
for ret in cmd_iter:
self.assertTrue(ret['minion'])
cmd_iter = self.client.cmd_cli('minion', 'test.sleep', [6])
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert (num_ret > 0)
key_... |
'test cmd_iter'
| def test_iter(self):
| cmd_iter = self.client.cmd_iter('minion', 'test.ping')
for ret in cmd_iter:
self.assertTrue(ret['minion'])
|
'test cmd_iter_no_block'
| def test_iter_no_block(self):
| cmd_iter = self.client.cmd_iter_no_block('minion', 'test.ping')
for ret in cmd_iter:
if (ret is None):
continue
self.assertTrue(ret['minion'])
|
'test cmd_batch'
| def test_batch(self):
| cmd_batch = self.client.cmd_batch('minion', 'test.ping')
for ret in cmd_batch:
self.assertTrue(ret['minion'])
|
'test cmd_batch with raw option'
| def test_batch_raw(self):
| cmd_batch = self.client.cmd_batch('minion', 'test.ping', raw=True)
for ret in cmd_batch:
self.assertTrue(ret['data']['success'])
|
'test cmd_iter'
| def test_full_returns(self):
| ret = self.client.cmd_full_return('minion', 'test.ping')
self.assertIn('minion', ret)
self.assertEqual({'ret': True, 'success': True}, ret['minion'])
|
'Test return/messaging on a disconnected minion'
| def test_disconnected_return(self):
| test_ret = {'ret': 'Minion did not return. [No response]', 'out': 'no_return'}
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'disconnected')
with salt.utils.files.fopen(key_file, 'a'):
pass
try:
cmd_iter = self.client.cmd_cli('disconnected', 'test.ping', ... |
'Test cli function'
| def test_cli(self):
| cmd_iter = self.client.cmd_cli('minion', 'test.arg', ['foo', 'bar', 'baz'], kwarg={'qux': 'quux'})
for ret in cmd_iter:
data = ret['minion']['ret']
self.assertEqual(data['args'], ['foo', 'bar', 'baz'])
self.assertEqual(data['kwargs']['qux'], 'quux')
|
'test cmd_iter'
| def test_iter(self):
| cmd_iter = self.client.cmd_iter('minion', 'test.arg', ['foo', 'bar', 'baz'], kwarg={'qux': 'quux'})
for ret in cmd_iter:
data = ret['minion']['ret']
self.assertEqual(data['args'], ['foo', 'bar', 'baz'])
self.assertEqual(data['kwargs']['qux'], 'quux')
|
'test cmd_iter_no_block'
| def test_iter_no_block(self):
| cmd_iter = self.client.cmd_iter_no_block('minion', 'test.arg', ['foo', 'bar', 'baz'], kwarg={'qux': 'quux'})
for ret in cmd_iter:
if (ret is None):
continue
data = ret['minion']['ret']
self.assertEqual(data['args'], ['foo', 'bar', 'baz'])
self.assertEqual(data['kwargs... |
'test cmd_iter'
| def test_full_returns(self):
| ret = self.client.cmd_full_return('minion', 'test.arg', ['foo', 'bar', 'baz'], kwarg={'qux': 'quux'})
data = ret['minion']['ret']
self.assertEqual(data['args'], ['foo', 'bar', 'baz'])
self.assertEqual(data['kwargs']['qux'], 'quux')
|
'Test that kwargs end up on the client as the same type'
| def test_kwarg_type(self):
| terrible_yaml_string = 'foo: ""\n# \''
ret = self.client.cmd_full_return('minion', 'test.arg_type', ['a', 1], kwarg={'outer': {'a': terrible_yaml_string}, 'inner': 'value'})
data = ret['minion']['ret']
self.assertIn('str', data['args'][0])
self.assertIn('int', data['args'][1])
self.assertI... |
'Configure an eauth user to test with'
| def setUp(self):
| self.runner = salt.runner.RunnerClient(self.get_config('client_config'))
|
'Test executing master_call with lowdata
The choice of using error.error for this is arbitrary and should be
changed to some mocked function that is more testing friendly.'
| def test_eauth(self):
| low = {'client': 'runner', 'fun': 'error.error'}
low.update(self.eauth_creds)
self.runner.master_call(**low)
|
'Test executing master_call with lowdata
The choice of using error.error for this is arbitrary and should be
changed to some mocked function that is more testing friendly.'
| def test_token(self):
| import salt.auth
auth = salt.auth.LoadAuth(self.get_config('client_config'))
token = auth.mk_token(self.eauth_creds)
self.runner.master_call(**{'client': 'runner', 'fun': 'error.error', 'token': token['token']})
|
'test.ping'
| def test_ping(self):
| self.assertTrue(self.run_function('test.ping'))
|
'test.fib'
| def test_fib(self):
| self.assertEqual(self.run_function('test.fib', ['20'])[0], 6765)
|
'Test the calculations'
| def test_count_runtimes(self):
| results = librato_return._calculate_runtimes(MOCK_RET_OBJ['return'])
self.assertEqual(results['num_failed_states'], 1)
self.assertEqual(results['num_passed_states'], 1)
self.assertEqual(results['runtime'], 7.29)
|
'Tests executing a simple batch command to help catch regressions'
| def test_batch_run(self):
| ret = "Executing run on ['sub_minion']"
cmd = self.run_salt("'*' test.echo 'batch testing' -b 50%")
self.assertIn(ret, cmd)
|
'Tests executing a simple batch command using a number division instead of
a percentage with full batch CLI call.'
| def test_batch_run_number(self):
| ret = "Executing run on ['minion', 'sub_minion']"
cmd = self.run_salt("'*' test.ping --batch-size 2")
self.assertIn(ret, cmd)
|
'Tests executing a batch command using a percentage divisor as well as grains
targeting.'
| def test_batch_run_grains_targeting(self):
| os_grain = ''
sub_min_ret = "Executing run on ['sub_minion']"
min_ret = "Executing run on ['minion']"
for item in self.run_salt('minion grains.get os'):
if (item != 'minion'):
os_grain = item
os_grain = os_grain.strip()
cmd = self.run_salt("-G 'os:{... |
'Test that a failed state returns a non-zero exit code in batch mode'
| def test_batch_exit_code(self):
| cmd = self.run_salt(' "*" state.single test.fail_without_changes name=test_me -b 25%', with_retcode=True)
self.assertEqual(cmd[(-1)], 2)
|
'Test regular module work using SSHCase environment'
| def test_ssh_regular_module(self):
| expected = 'hello'
cmd = self.run_function('test.echo', arg=['hello'])
self.assertEqual(expected, cmd)
|
'Test custom module work using SSHCase environment'
| def test_ssh_custom_module(self):
| expected = 'hello'[::(-1)]
cmd = self.run_function('test.recho', arg=['hello'])
self.assertEqual(expected, cmd)
|
'Test sls with custom module work using SSHCase environment'
| def test_ssh_sls_with_custom_module(self):
| expected = {'module_|-regular-module_|-test.echo_|-run': 'hello', 'module_|-custom-module_|-test.recho_|-run': 'olleh'}
cmd = self.run_function('state.sls', arg=['custom_module'])
for key in cmd:
if ((not isinstance(cmd, dict)) or (not isinstance(cmd[key], dict))):
raise AssertionError('... |
'Tests running "salt -G \'os:<system-os>\' test.ping and minions both return True'
| def test_grains_targeting_os_running(self):
| test_ret = ['sub_minion:', ' True', 'minion:', ' True']
os_grain = ''
for item in self.run_salt('minion grains.get os'):
if (item != 'minion:'):
os_grain = item.strip()
ret = self.run_salt("-G 'os:{0}' test.ping".format(os_grain))
self.as... |
'Tests return of each running test minion targeting with minion id grain'
| def test_grains_targeting_minion_id_running(self):
| minion = self.run_salt("-G 'id:minion' test.ping")
self.assertEqual(sorted(minion), sorted(['minion:', ' True']))
sub_minion = self.run_salt("-G 'id:sub_minion' test.ping")
self.assertEqual(sorted(sub_minion), sorted(['sub_minion:', ' True']))
|
'Tests return of minion using grains targeting on a disconnected minion.'
| def test_grains_targeting_disconnected(self):
| test_ret = 'Minion did not return. [No response]'
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'disconnected')
with salt.utils.files.fopen(key_file, 'a'):
pass
import logging
log = logging.getLogger(__name__)
try:
ret = ''
for item in sel... |
'Test salt-ssh grains id work for localhost.'
| def test_grains_id(self):
| cmd = self.run_function('grains.get', ['id'])
self.assertEqual(cmd, 'localhost')
|
'Start a master and minion'
| def __enter__(self):
| salt_log_setup.setup_multiprocessing_logging_listener(self.master_opts)
self._enter_mockbin()
if (self.parser.options.transport == 'zeromq'):
self.start_zeromq_daemons()
elif (self.parser.options.transport == 'raet'):
self.start_raet_daemons()
elif (self.parser.options.transport == '... |
'Fire up the daemons used for zeromq tests'
| def start_zeromq_daemons(self):
| self.log_server = ThreadedSocketServer(('localhost', SALT_LOG_PORT), SocketServerRequestHandler)
self.log_server_process = threading.Thread(target=self.log_server.serve_forever)
self.log_server_process.daemon = True
self.log_server_process.start()
try:
sys.stdout.write(' * {LIGHT_YELLO... |
'Fire up the raet daemons!'
| def start_raet_daemons(self):
| import salt.daemons.flo
self.master_process = self.start_daemon(salt.daemons.flo.IofloMaster, self.master_opts, 'start')
self.minion_process = self.start_daemon(salt.daemons.flo.IofloMinion, self.minion_opts, 'tune_in')
self.sub_minion_process = self.start_daemon(salt.daemons.flo.IofloMinion, self.sub_m... |
'Generate keys and start an ssh daemon on an alternate port'
| def prep_ssh(self):
| sys.stdout.write(' * {LIGHT_GREEN}Starting {0} ... {ENDC}'.format('SSH server', **self.colors))
keygen = salt.utils.path.which('ssh-keygen')
sshd = salt.utils.path.which('sshd')
if (not (keygen and sshd)):
print('WARNING: Could not initialize SSH subsystem. Te... |
'Return a configuration for a master/minion/syndic.
Currently these roles are:
* master
* minion
* syndic
* syndic_master
* sub_minion
* proxy'
| @classmethod
def config(cls, role):
| return RUNTIME_VARS.RUNTIME_CONFIGS[role]
|
'Return a local client which will be used for example to ping and sync
the test minions.
This client is defined as a class attribute because its creation needs
to be deferred to a latter stage. If created it on `__enter__` like it
previously was, it would not receive the master events.'
| @property
def client(self):
| if ('runtime_client' not in RUNTIME_VARS.RUNTIME_CONFIGS):
RUNTIME_VARS.RUNTIME_CONFIGS['runtime_client'] = salt.client.get_local_client(mopts=self.master_opts)
return RUNTIME_VARS.RUNTIME_CONFIGS['runtime_client']
|
'Kill the minion and master processes'
| def __exit__(self, type, value, traceback):
| self.sub_minion_process.terminate()
self.minion_process.terminate()
if hasattr(self, 'proxy_process'):
self.proxy_process.terminate()
self.master_process.terminate()
try:
self.syndic_process.terminate()
except AttributeError:
pass
try:
self.smaster_process.ter... |
'Clean out the tmp files'
| @classmethod
def clean(cls):
| def remove_readonly(func, path, excinfo):
os.chmod(path, stat.S_IRWXU)
func(path)
for dirname in (TMP, RUNTIME_VARS.TMP_STATE_TREE, RUNTIME_VARS.TMP_PRODENV_STATE_TREE):
if os.path.isdir(dirname):
shutil.rmtree(dirname, onerror=remove_readonly)
|
'Tests the return of json-formatted data'
| def test_output_json(self):
| ret = self.run_call('test.ping --out=json')
self.assertIn('{', ret)
self.assertIn('"local": true', ''.join(ret))
self.assertIn('}', ''.join(ret))
|
'Tests the return of nested-formatted data'
| def test_output_nested(self):
| expected = ['local:', ' True']
ret = self.run_call('test.ping --out=nested')
self.assertEqual(ret, expected)
|
'Tests the return of an out=quiet query'
| def test_output_quiet(self):
| expected = []
ret = self.run_call('test.ping --out=quiet')
self.assertEqual(ret, expected)
|
'Tests the return of pprint-formatted data'
| def test_output_pprint(self):
| expected = ["{'local': True}"]
ret = self.run_call('test.ping --out=pprint')
self.assertEqual(ret, expected)
|
'Tests the return of raw-formatted data'
| def test_output_raw(self):
| expected = ["{'local': True}"]
ret = self.run_call('test.ping --out=raw')
self.assertEqual(ret, expected)
|
'Tests the return of txt-formatted data'
| def test_output_txt(self):
| expected = ['local: True']
ret = self.run_call('test.ping --out=txt')
self.assertEqual(ret, expected)
|
'Tests the return of yaml-formatted data'
| def test_output_yaml(self):
| expected = ['local: true']
ret = self.run_call('test.ping --out=yaml')
self.assertEqual(ret, expected)
|
'Tests outputter reliability with utf8'
| def test_output_unicodebad(self):
| opts = salt.config.minion_config(os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'minion'))
opts['output_file'] = os.path.join(RUNTIME_VARS.TMP, 'outputtest')
data = {'foo': {'result': False, 'aaa': 'azerzaer\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9', 'comment': u'\xe9\xe9\xe9\xe9\xe0\xe0\xe0\xe0'}}
try:
display... |
'Ensure correct exit status when the master is configured to run as an unknown user.'
| def test_exit_status_unknown_user(self):
| master = testprogram.TestDaemonSaltMaster(name='unknown_user', configs={'master': {'map': {'user': 'some_unknown_user_xyz'}}}, parent_dir=self._test_dir)
master.setup()
(stdout, stderr, status) = master.run(args=['-d'], catch_stderr=True, with_retcode=True)
try:
self.assert_exit_status(status, '... |
'Ensure correct exit status when an unknown argument is passed to salt-master.'
| def test_exit_status_unknown_argument(self):
| master = testprogram.TestDaemonSaltMaster(name='unknown_argument', parent_dir=self._test_dir)
master.setup()
(stdout, stderr, status) = master.run(args=['-d', '--unknown-argument'], catch_stderr=True, with_retcode=True)
try:
self.assert_exit_status(status, 'EX_USAGE', message='unknown argumen... |
'Ensure correct exit status when salt-master starts correctly.'
| def test_exit_status_correct_usage(self):
| master = testprogram.TestDaemonSaltMaster(name='correct_usage', parent_dir=self._test_dir)
master.setup()
(stdout, stderr, status) = master.run(args=['-d'], catch_stderr=True, with_retcode=True)
try:
self.assert_exit_status(status, 'EX_OK', message='correct usage', stdout=stdout, stderr=tests... |
'test that pam auth mechanism works with a valid user'
| def test_pam_auth_valid_user(self):
| (password, hashed_pwd) = gen_password()
set_pw_cmd = "shadow.set_password {0} '{1}'".format(self.userA, (password if salt.utils.platform.is_darwin() else hashed_pwd))
self.run_call(set_pw_cmd)
cmd = '-a pam "*" test.ping --username {0} --password {1}'.format(self.userA, passwo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.