id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
11,700
|
HttpRunner/har2case
|
har2case/utils.py
|
dump_json
|
def dump_json(testcase, json_file):
""" dump HAR entries to json testcase
"""
logging.info("dump testcase to JSON format.")
with io.open(json_file, 'w', encoding="utf-8") as outfile:
my_json_str = json.dumps(testcase, ensure_ascii=ensure_ascii, indent=4)
if isinstance(my_json_str, bytes):
my_json_str = my_json_str.decode("utf-8")
outfile.write(my_json_str)
logging.info("Generate JSON testcase successfully: {}".format(json_file))
|
python
|
def dump_json(testcase, json_file):
""" dump HAR entries to json testcase
"""
logging.info("dump testcase to JSON format.")
with io.open(json_file, 'w', encoding="utf-8") as outfile:
my_json_str = json.dumps(testcase, ensure_ascii=ensure_ascii, indent=4)
if isinstance(my_json_str, bytes):
my_json_str = my_json_str.decode("utf-8")
outfile.write(my_json_str)
logging.info("Generate JSON testcase successfully: {}".format(json_file))
|
[
"def",
"dump_json",
"(",
"testcase",
",",
"json_file",
")",
":",
"logging",
".",
"info",
"(",
"\"dump testcase to JSON format.\"",
")",
"with",
"io",
".",
"open",
"(",
"json_file",
",",
"'w'",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"outfile",
":",
"my_json_str",
"=",
"json",
".",
"dumps",
"(",
"testcase",
",",
"ensure_ascii",
"=",
"ensure_ascii",
",",
"indent",
"=",
"4",
")",
"if",
"isinstance",
"(",
"my_json_str",
",",
"bytes",
")",
":",
"my_json_str",
"=",
"my_json_str",
".",
"decode",
"(",
"\"utf-8\"",
")",
"outfile",
".",
"write",
"(",
"my_json_str",
")",
"logging",
".",
"info",
"(",
"\"Generate JSON testcase successfully: {}\"",
".",
"format",
"(",
"json_file",
")",
")"
] |
dump HAR entries to json testcase
|
[
"dump",
"HAR",
"entries",
"to",
"json",
"testcase"
] |
369e576b24b3521832c35344b104828e30742170
|
https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/utils.py#L117-L129
|
11,701
|
dabapps/django-log-request-id
|
log_request_id/session.py
|
Session.prepare_request
|
def prepare_request(self, request):
"""Include the request ID, if available, in the outgoing request"""
try:
request_id = local.request_id
except AttributeError:
request_id = NO_REQUEST_ID
if self.request_id_header and request_id != NO_REQUEST_ID:
request.headers[self.request_id_header] = request_id
return super(Session, self).prepare_request(request)
|
python
|
def prepare_request(self, request):
"""Include the request ID, if available, in the outgoing request"""
try:
request_id = local.request_id
except AttributeError:
request_id = NO_REQUEST_ID
if self.request_id_header and request_id != NO_REQUEST_ID:
request.headers[self.request_id_header] = request_id
return super(Session, self).prepare_request(request)
|
[
"def",
"prepare_request",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"request_id",
"=",
"local",
".",
"request_id",
"except",
"AttributeError",
":",
"request_id",
"=",
"NO_REQUEST_ID",
"if",
"self",
".",
"request_id_header",
"and",
"request_id",
"!=",
"NO_REQUEST_ID",
":",
"request",
".",
"headers",
"[",
"self",
".",
"request_id_header",
"]",
"=",
"request_id",
"return",
"super",
"(",
"Session",
",",
"self",
")",
".",
"prepare_request",
"(",
"request",
")"
] |
Include the request ID, if available, in the outgoing request
|
[
"Include",
"the",
"request",
"ID",
"if",
"available",
"in",
"the",
"outgoing",
"request"
] |
e5d7023d54885f7d1d7235348ba1ec4b0d77bba6
|
https://github.com/dabapps/django-log-request-id/blob/e5d7023d54885f7d1d7235348ba1ec4b0d77bba6/log_request_id/session.py#L22-L32
|
11,702
|
ellisonleao/pyshorteners
|
pyshorteners/base.py
|
BaseShortener._get
|
def _get(self, url, params=None, headers=None):
"""Wraps a GET request with a url check"""
url = self.clean_url(url)
response = requests.get(url, params=params, verify=self.verify,
timeout=self.timeout, headers=headers)
return response
|
python
|
def _get(self, url, params=None, headers=None):
"""Wraps a GET request with a url check"""
url = self.clean_url(url)
response = requests.get(url, params=params, verify=self.verify,
timeout=self.timeout, headers=headers)
return response
|
[
"def",
"_get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"clean_url",
"(",
"url",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
",",
"verify",
"=",
"self",
".",
"verify",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"headers",
"=",
"headers",
")",
"return",
"response"
] |
Wraps a GET request with a url check
|
[
"Wraps",
"a",
"GET",
"request",
"with",
"a",
"url",
"check"
] |
116155751c943f8d875c819d5a41db10515db18d
|
https://github.com/ellisonleao/pyshorteners/blob/116155751c943f8d875c819d5a41db10515db18d/pyshorteners/base.py#L23-L28
|
11,703
|
ellisonleao/pyshorteners
|
pyshorteners/base.py
|
BaseShortener._post
|
def _post(self, url, data=None, json=None, params=None, headers=None):
"""Wraps a POST request with a url check"""
url = self.clean_url(url)
response = requests.post(url, data=data, json=json, params=params,
headers=headers, timeout=self.timeout,
verify=self.verify)
return response
|
python
|
def _post(self, url, data=None, json=None, params=None, headers=None):
"""Wraps a POST request with a url check"""
url = self.clean_url(url)
response = requests.post(url, data=data, json=json, params=params,
headers=headers, timeout=self.timeout,
verify=self.verify)
return response
|
[
"def",
"_post",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"clean_url",
"(",
"url",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
",",
"json",
"=",
"json",
",",
"params",
"=",
"params",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"verify",
"=",
"self",
".",
"verify",
")",
"return",
"response"
] |
Wraps a POST request with a url check
|
[
"Wraps",
"a",
"POST",
"request",
"with",
"a",
"url",
"check"
] |
116155751c943f8d875c819d5a41db10515db18d
|
https://github.com/ellisonleao/pyshorteners/blob/116155751c943f8d875c819d5a41db10515db18d/pyshorteners/base.py#L30-L36
|
11,704
|
ellisonleao/pyshorteners
|
pyshorteners/base.py
|
BaseShortener.expand
|
def expand(self, url):
"""Base expand method. Only visits the link, and return the response
url"""
url = self.clean_url(url)
response = self._get(url)
if response.ok:
return response.url
raise ExpandingErrorException
|
python
|
def expand(self, url):
"""Base expand method. Only visits the link, and return the response
url"""
url = self.clean_url(url)
response = self._get(url)
if response.ok:
return response.url
raise ExpandingErrorException
|
[
"def",
"expand",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"self",
".",
"clean_url",
"(",
"url",
")",
"response",
"=",
"self",
".",
"_get",
"(",
"url",
")",
"if",
"response",
".",
"ok",
":",
"return",
"response",
".",
"url",
"raise",
"ExpandingErrorException"
] |
Base expand method. Only visits the link, and return the response
url
|
[
"Base",
"expand",
"method",
".",
"Only",
"visits",
"the",
"link",
"and",
"return",
"the",
"response",
"url"
] |
116155751c943f8d875c819d5a41db10515db18d
|
https://github.com/ellisonleao/pyshorteners/blob/116155751c943f8d875c819d5a41db10515db18d/pyshorteners/base.py#L41-L48
|
11,705
|
ellisonleao/pyshorteners
|
pyshorteners/base.py
|
BaseShortener.clean_url
|
def clean_url(url):
"""URL Validation function"""
if not url.startswith(('http://', 'https://')):
url = f'http://{url}'
if not URL_RE.match(url):
raise BadURLException(f'{url} is not valid')
return url
|
python
|
def clean_url(url):
"""URL Validation function"""
if not url.startswith(('http://', 'https://')):
url = f'http://{url}'
if not URL_RE.match(url):
raise BadURLException(f'{url} is not valid')
return url
|
[
"def",
"clean_url",
"(",
"url",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"(",
"'http://'",
",",
"'https://'",
")",
")",
":",
"url",
"=",
"f'http://{url}'",
"if",
"not",
"URL_RE",
".",
"match",
"(",
"url",
")",
":",
"raise",
"BadURLException",
"(",
"f'{url} is not valid'",
")",
"return",
"url"
] |
URL Validation function
|
[
"URL",
"Validation",
"function"
] |
116155751c943f8d875c819d5a41db10515db18d
|
https://github.com/ellisonleao/pyshorteners/blob/116155751c943f8d875c819d5a41db10515db18d/pyshorteners/base.py#L51-L59
|
11,706
|
AdvancedClimateSystems/uModbus
|
umodbus/functions.py
|
create_function_from_request_pdu
|
def create_function_from_request_pdu(pdu):
""" Return function instance, based on request PDU.
:param pdu: Array of bytes.
:return: Instance of a function.
"""
function_code = get_function_code_from_request_pdu(pdu)
try:
function_class = function_code_to_function_map[function_code]
except KeyError:
raise IllegalFunctionError(function_code)
return function_class.create_from_request_pdu(pdu)
|
python
|
def create_function_from_request_pdu(pdu):
""" Return function instance, based on request PDU.
:param pdu: Array of bytes.
:return: Instance of a function.
"""
function_code = get_function_code_from_request_pdu(pdu)
try:
function_class = function_code_to_function_map[function_code]
except KeyError:
raise IllegalFunctionError(function_code)
return function_class.create_from_request_pdu(pdu)
|
[
"def",
"create_function_from_request_pdu",
"(",
"pdu",
")",
":",
"function_code",
"=",
"get_function_code_from_request_pdu",
"(",
"pdu",
")",
"try",
":",
"function_class",
"=",
"function_code_to_function_map",
"[",
"function_code",
"]",
"except",
"KeyError",
":",
"raise",
"IllegalFunctionError",
"(",
"function_code",
")",
"return",
"function_class",
".",
"create_from_request_pdu",
"(",
"pdu",
")"
] |
Return function instance, based on request PDU.
:param pdu: Array of bytes.
:return: Instance of a function.
|
[
"Return",
"function",
"instance",
"based",
"on",
"request",
"PDU",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L137-L149
|
11,707
|
AdvancedClimateSystems/uModbus
|
umodbus/functions.py
|
ReadCoils.request_pdu
|
def request_pdu(self):
""" Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.starting_address,
self.quantity)
|
python
|
def request_pdu(self):
""" Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.starting_address,
self.quantity)
|
[
"def",
"request_pdu",
"(",
"self",
")",
":",
"if",
"None",
"in",
"[",
"self",
".",
"starting_address",
",",
"self",
".",
"quantity",
"]",
":",
"# TODO Raise proper exception.",
"raise",
"Exception",
"return",
"struct",
".",
"pack",
"(",
"'>BHH'",
",",
"self",
".",
"function_code",
",",
"self",
".",
"starting_address",
",",
"self",
".",
"quantity",
")"
] |
Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
|
[
"Build",
"request",
"PDU",
"to",
"read",
"coils",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L262-L272
|
11,708
|
AdvancedClimateSystems/uModbus
|
umodbus/functions.py
|
WriteSingleCoil.request_pdu
|
def request_pdu(self):
""" Build request PDU to write single coil.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.address,
self._value)
|
python
|
def request_pdu(self):
""" Build request PDU to write single coil.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.address,
self._value)
|
[
"def",
"request_pdu",
"(",
"self",
")",
":",
"if",
"None",
"in",
"[",
"self",
".",
"address",
",",
"self",
".",
"value",
"]",
":",
"# TODO Raise proper exception.",
"raise",
"Exception",
"return",
"struct",
".",
"pack",
"(",
"'>BHH'",
",",
"self",
".",
"function_code",
",",
"self",
".",
"address",
",",
"self",
".",
"_value",
")"
] |
Build request PDU to write single coil.
:return: Byte array of 5 bytes with PDU.
|
[
"Build",
"request",
"PDU",
"to",
"write",
"single",
"coil",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L1028-L1038
|
11,709
|
AdvancedClimateSystems/uModbus
|
umodbus/functions.py
|
WriteSingleRegister.value
|
def value(self, value):
""" Value to be written on register.
:param value: An integer.
:raises: IllegalDataValueError when value isn't in range.
"""
try:
struct.pack('>' + conf.TYPE_CHAR, value)
except struct.error:
raise IllegalDataValueError
self._value = value
|
python
|
def value(self, value):
""" Value to be written on register.
:param value: An integer.
:raises: IllegalDataValueError when value isn't in range.
"""
try:
struct.pack('>' + conf.TYPE_CHAR, value)
except struct.error:
raise IllegalDataValueError
self._value = value
|
[
"def",
"value",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"struct",
".",
"pack",
"(",
"'>'",
"+",
"conf",
".",
"TYPE_CHAR",
",",
"value",
")",
"except",
"struct",
".",
"error",
":",
"raise",
"IllegalDataValueError",
"self",
".",
"_value",
"=",
"value"
] |
Value to be written on register.
:param value: An integer.
:raises: IllegalDataValueError when value isn't in range.
|
[
"Value",
"to",
"be",
"written",
"on",
"register",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L1165-L1176
|
11,710
|
AdvancedClimateSystems/uModbus
|
umodbus/functions.py
|
WriteSingleRegister.request_pdu
|
def request_pdu(self):
""" Build request PDU to write single register.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BH' + conf.TYPE_CHAR, self.function_code,
self.address, self.value)
|
python
|
def request_pdu(self):
""" Build request PDU to write single register.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BH' + conf.TYPE_CHAR, self.function_code,
self.address, self.value)
|
[
"def",
"request_pdu",
"(",
"self",
")",
":",
"if",
"None",
"in",
"[",
"self",
".",
"address",
",",
"self",
".",
"value",
"]",
":",
"# TODO Raise proper exception.",
"raise",
"Exception",
"return",
"struct",
".",
"pack",
"(",
"'>BH'",
"+",
"conf",
".",
"TYPE_CHAR",
",",
"self",
".",
"function_code",
",",
"self",
".",
"address",
",",
"self",
".",
"value",
")"
] |
Build request PDU to write single register.
:return: Byte array of 5 bytes with PDU.
|
[
"Build",
"request",
"PDU",
"to",
"write",
"single",
"register",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L1179-L1189
|
11,711
|
AdvancedClimateSystems/uModbus
|
umodbus/server/serial/__init__.py
|
AbstractSerialServer.serve_forever
|
def serve_forever(self, poll_interval=0.5):
""" Wait for incomming requests. """
self.serial_port.timeout = poll_interval
while not self._shutdown_request:
try:
self.serve_once()
except (CRCError, struct.error) as e:
log.error('Can\'t handle request: {0}'.format(e))
except (SerialTimeoutException, ValueError):
pass
|
python
|
def serve_forever(self, poll_interval=0.5):
""" Wait for incomming requests. """
self.serial_port.timeout = poll_interval
while not self._shutdown_request:
try:
self.serve_once()
except (CRCError, struct.error) as e:
log.error('Can\'t handle request: {0}'.format(e))
except (SerialTimeoutException, ValueError):
pass
|
[
"def",
"serve_forever",
"(",
"self",
",",
"poll_interval",
"=",
"0.5",
")",
":",
"self",
".",
"serial_port",
".",
"timeout",
"=",
"poll_interval",
"while",
"not",
"self",
".",
"_shutdown_request",
":",
"try",
":",
"self",
".",
"serve_once",
"(",
")",
"except",
"(",
"CRCError",
",",
"struct",
".",
"error",
")",
"as",
"e",
":",
"log",
".",
"error",
"(",
"'Can\\'t handle request: {0}'",
".",
"format",
"(",
"e",
")",
")",
"except",
"(",
"SerialTimeoutException",
",",
"ValueError",
")",
":",
"pass"
] |
Wait for incomming requests.
|
[
"Wait",
"for",
"incomming",
"requests",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/__init__.py#L62-L72
|
11,712
|
AdvancedClimateSystems/uModbus
|
umodbus/server/serial/__init__.py
|
AbstractSerialServer.execute_route
|
def execute_route(self, meta_data, request_pdu):
""" Execute configured route based on requests meta data and request
PDU.
:param meta_data: A dict with meta data. It must at least contain
key 'unit_id'.
:param request_pdu: A bytearray containing request PDU.
:return: A bytearry containing reponse PDU.
"""
try:
function = create_function_from_request_pdu(request_pdu)
results =\
function.execute(meta_data['unit_id'], self.route_map)
try:
# ReadFunction's use results of callbacks to build response
# PDU...
return function.create_response_pdu(results)
except TypeError:
# ...other functions don't.
return function.create_response_pdu()
except ModbusError as e:
function_code = get_function_code_from_request_pdu(request_pdu)
return pack_exception_pdu(function_code, e.error_code)
except Exception as e:
log.exception('Could not handle request: {0}.'.format(e))
function_code = get_function_code_from_request_pdu(request_pdu)
return pack_exception_pdu(function_code,
ServerDeviceFailureError.error_code)
|
python
|
def execute_route(self, meta_data, request_pdu):
""" Execute configured route based on requests meta data and request
PDU.
:param meta_data: A dict with meta data. It must at least contain
key 'unit_id'.
:param request_pdu: A bytearray containing request PDU.
:return: A bytearry containing reponse PDU.
"""
try:
function = create_function_from_request_pdu(request_pdu)
results =\
function.execute(meta_data['unit_id'], self.route_map)
try:
# ReadFunction's use results of callbacks to build response
# PDU...
return function.create_response_pdu(results)
except TypeError:
# ...other functions don't.
return function.create_response_pdu()
except ModbusError as e:
function_code = get_function_code_from_request_pdu(request_pdu)
return pack_exception_pdu(function_code, e.error_code)
except Exception as e:
log.exception('Could not handle request: {0}.'.format(e))
function_code = get_function_code_from_request_pdu(request_pdu)
return pack_exception_pdu(function_code,
ServerDeviceFailureError.error_code)
|
[
"def",
"execute_route",
"(",
"self",
",",
"meta_data",
",",
"request_pdu",
")",
":",
"try",
":",
"function",
"=",
"create_function_from_request_pdu",
"(",
"request_pdu",
")",
"results",
"=",
"function",
".",
"execute",
"(",
"meta_data",
"[",
"'unit_id'",
"]",
",",
"self",
".",
"route_map",
")",
"try",
":",
"# ReadFunction's use results of callbacks to build response",
"# PDU...",
"return",
"function",
".",
"create_response_pdu",
"(",
"results",
")",
"except",
"TypeError",
":",
"# ...other functions don't.",
"return",
"function",
".",
"create_response_pdu",
"(",
")",
"except",
"ModbusError",
"as",
"e",
":",
"function_code",
"=",
"get_function_code_from_request_pdu",
"(",
"request_pdu",
")",
"return",
"pack_exception_pdu",
"(",
"function_code",
",",
"e",
".",
"error_code",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"'Could not handle request: {0}.'",
".",
"format",
"(",
"e",
")",
")",
"function_code",
"=",
"get_function_code_from_request_pdu",
"(",
"request_pdu",
")",
"return",
"pack_exception_pdu",
"(",
"function_code",
",",
"ServerDeviceFailureError",
".",
"error_code",
")"
] |
Execute configured route based on requests meta data and request
PDU.
:param meta_data: A dict with meta data. It must at least contain
key 'unit_id'.
:param request_pdu: A bytearray containing request PDU.
:return: A bytearry containing reponse PDU.
|
[
"Execute",
"configured",
"route",
"based",
"on",
"requests",
"meta",
"data",
"and",
"request",
"PDU",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/__init__.py#L88-L117
|
11,713
|
AdvancedClimateSystems/uModbus
|
umodbus/server/serial/rtu.py
|
RTUServer.serial_port
|
def serial_port(self, serial_port):
""" Set timeouts on serial port based on baudrate to detect frames. """
char_size = get_char_size(serial_port.baudrate)
# See docstring of get_char_size() for meaning of constants below.
serial_port.inter_byte_timeout = 1.5 * char_size
serial_port.timeout = 3.5 * char_size
self._serial_port = serial_port
|
python
|
def serial_port(self, serial_port):
""" Set timeouts on serial port based on baudrate to detect frames. """
char_size = get_char_size(serial_port.baudrate)
# See docstring of get_char_size() for meaning of constants below.
serial_port.inter_byte_timeout = 1.5 * char_size
serial_port.timeout = 3.5 * char_size
self._serial_port = serial_port
|
[
"def",
"serial_port",
"(",
"self",
",",
"serial_port",
")",
":",
"char_size",
"=",
"get_char_size",
"(",
"serial_port",
".",
"baudrate",
")",
"# See docstring of get_char_size() for meaning of constants below.",
"serial_port",
".",
"inter_byte_timeout",
"=",
"1.5",
"*",
"char_size",
"serial_port",
".",
"timeout",
"=",
"3.5",
"*",
"char_size",
"self",
".",
"_serial_port",
"=",
"serial_port"
] |
Set timeouts on serial port based on baudrate to detect frames.
|
[
"Set",
"timeouts",
"on",
"serial",
"port",
"based",
"on",
"baudrate",
"to",
"detect",
"frames",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/rtu.py#L39-L46
|
11,714
|
AdvancedClimateSystems/uModbus
|
umodbus/server/serial/rtu.py
|
RTUServer.serve_once
|
def serve_once(self):
""" Listen and handle 1 request. """
# 256 is the maximum size of a Modbus RTU frame.
request_adu = self.serial_port.read(256)
log.debug('<-- {0}'.format(hexlify(request_adu)))
if len(request_adu) == 0:
raise ValueError
response_adu = self.process(request_adu)
self.respond(response_adu)
|
python
|
def serve_once(self):
""" Listen and handle 1 request. """
# 256 is the maximum size of a Modbus RTU frame.
request_adu = self.serial_port.read(256)
log.debug('<-- {0}'.format(hexlify(request_adu)))
if len(request_adu) == 0:
raise ValueError
response_adu = self.process(request_adu)
self.respond(response_adu)
|
[
"def",
"serve_once",
"(",
"self",
")",
":",
"# 256 is the maximum size of a Modbus RTU frame.",
"request_adu",
"=",
"self",
".",
"serial_port",
".",
"read",
"(",
"256",
")",
"log",
".",
"debug",
"(",
"'<-- {0}'",
".",
"format",
"(",
"hexlify",
"(",
"request_adu",
")",
")",
")",
"if",
"len",
"(",
"request_adu",
")",
"==",
"0",
":",
"raise",
"ValueError",
"response_adu",
"=",
"self",
".",
"process",
"(",
"request_adu",
")",
"self",
".",
"respond",
"(",
"response_adu",
")"
] |
Listen and handle 1 request.
|
[
"Listen",
"and",
"handle",
"1",
"request",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/rtu.py#L48-L58
|
11,715
|
AdvancedClimateSystems/uModbus
|
umodbus/client/serial/redundancy_check.py
|
generate_look_up_table
|
def generate_look_up_table():
""" Generate look up table.
:return: List
"""
poly = 0xA001
table = []
for index in range(256):
data = index << 1
crc = 0
for _ in range(8, 0, -1):
data >>= 1
if (data ^ crc) & 0x0001:
crc = (crc >> 1) ^ poly
else:
crc >>= 1
table.append(crc)
return table
|
python
|
def generate_look_up_table():
""" Generate look up table.
:return: List
"""
poly = 0xA001
table = []
for index in range(256):
data = index << 1
crc = 0
for _ in range(8, 0, -1):
data >>= 1
if (data ^ crc) & 0x0001:
crc = (crc >> 1) ^ poly
else:
crc >>= 1
table.append(crc)
return table
|
[
"def",
"generate_look_up_table",
"(",
")",
":",
"poly",
"=",
"0xA001",
"table",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"256",
")",
":",
"data",
"=",
"index",
"<<",
"1",
"crc",
"=",
"0",
"for",
"_",
"in",
"range",
"(",
"8",
",",
"0",
",",
"-",
"1",
")",
":",
"data",
">>=",
"1",
"if",
"(",
"data",
"^",
"crc",
")",
"&",
"0x0001",
":",
"crc",
"=",
"(",
"crc",
">>",
"1",
")",
"^",
"poly",
"else",
":",
"crc",
">>=",
"1",
"table",
".",
"append",
"(",
"crc",
")",
"return",
"table"
] |
Generate look up table.
:return: List
|
[
"Generate",
"look",
"up",
"table",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/redundancy_check.py#L8-L28
|
11,716
|
AdvancedClimateSystems/uModbus
|
umodbus/client/serial/redundancy_check.py
|
get_crc
|
def get_crc(msg):
""" Return CRC of 2 byte for message.
>>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12')
:param msg: A byte array.
:return: Byte array of 2 bytes.
"""
register = 0xFFFF
for byte_ in msg:
try:
val = struct.unpack('<B', byte_)[0]
# Iterating over a bit-like objects in Python 3 gets you ints.
# Because fuck logic.
except TypeError:
val = byte_
register = \
(register >> 8) ^ look_up_table[(register ^ val) & 0xFF]
# CRC is little-endian!
return struct.pack('<H', register)
|
python
|
def get_crc(msg):
""" Return CRC of 2 byte for message.
>>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12')
:param msg: A byte array.
:return: Byte array of 2 bytes.
"""
register = 0xFFFF
for byte_ in msg:
try:
val = struct.unpack('<B', byte_)[0]
# Iterating over a bit-like objects in Python 3 gets you ints.
# Because fuck logic.
except TypeError:
val = byte_
register = \
(register >> 8) ^ look_up_table[(register ^ val) & 0xFF]
# CRC is little-endian!
return struct.pack('<H', register)
|
[
"def",
"get_crc",
"(",
"msg",
")",
":",
"register",
"=",
"0xFFFF",
"for",
"byte_",
"in",
"msg",
":",
"try",
":",
"val",
"=",
"struct",
".",
"unpack",
"(",
"'<B'",
",",
"byte_",
")",
"[",
"0",
"]",
"# Iterating over a bit-like objects in Python 3 gets you ints.",
"# Because fuck logic.",
"except",
"TypeError",
":",
"val",
"=",
"byte_",
"register",
"=",
"(",
"register",
">>",
"8",
")",
"^",
"look_up_table",
"[",
"(",
"register",
"^",
"val",
")",
"&",
"0xFF",
"]",
"# CRC is little-endian!",
"return",
"struct",
".",
"pack",
"(",
"'<H'",
",",
"register",
")"
] |
Return CRC of 2 byte for message.
>>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12')
:param msg: A byte array.
:return: Byte array of 2 bytes.
|
[
"Return",
"CRC",
"of",
"2",
"byte",
"for",
"message",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/redundancy_check.py#L34-L56
|
11,717
|
AdvancedClimateSystems/uModbus
|
umodbus/client/serial/redundancy_check.py
|
validate_crc
|
def validate_crc(msg):
""" Validate CRC of message.
:param msg: Byte array with message with CRC.
:raise: CRCError.
"""
if not struct.unpack('<H', get_crc(msg[:-2])) ==\
struct.unpack('<H', msg[-2:]):
raise CRCError('CRC validation failed.')
|
python
|
def validate_crc(msg):
""" Validate CRC of message.
:param msg: Byte array with message with CRC.
:raise: CRCError.
"""
if not struct.unpack('<H', get_crc(msg[:-2])) ==\
struct.unpack('<H', msg[-2:]):
raise CRCError('CRC validation failed.')
|
[
"def",
"validate_crc",
"(",
"msg",
")",
":",
"if",
"not",
"struct",
".",
"unpack",
"(",
"'<H'",
",",
"get_crc",
"(",
"msg",
"[",
":",
"-",
"2",
"]",
")",
")",
"==",
"struct",
".",
"unpack",
"(",
"'<H'",
",",
"msg",
"[",
"-",
"2",
":",
"]",
")",
":",
"raise",
"CRCError",
"(",
"'CRC validation failed.'",
")"
] |
Validate CRC of message.
:param msg: Byte array with message with CRC.
:raise: CRCError.
|
[
"Validate",
"CRC",
"of",
"message",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/redundancy_check.py#L68-L76
|
11,718
|
AdvancedClimateSystems/uModbus
|
umodbus/client/serial/rtu.py
|
_create_request_adu
|
def _create_request_adu(slave_id, req_pdu):
""" Return request ADU for Modbus RTU.
:param slave_id: Slave id.
:param req_pdu: Byte array with PDU.
:return: Byte array with ADU.
"""
first_part_adu = struct.pack('>B', slave_id) + req_pdu
return first_part_adu + get_crc(first_part_adu)
|
python
|
def _create_request_adu(slave_id, req_pdu):
""" Return request ADU for Modbus RTU.
:param slave_id: Slave id.
:param req_pdu: Byte array with PDU.
:return: Byte array with ADU.
"""
first_part_adu = struct.pack('>B', slave_id) + req_pdu
return first_part_adu + get_crc(first_part_adu)
|
[
"def",
"_create_request_adu",
"(",
"slave_id",
",",
"req_pdu",
")",
":",
"first_part_adu",
"=",
"struct",
".",
"pack",
"(",
"'>B'",
",",
"slave_id",
")",
"+",
"req_pdu",
"return",
"first_part_adu",
"+",
"get_crc",
"(",
"first_part_adu",
")"
] |
Return request ADU for Modbus RTU.
:param slave_id: Slave id.
:param req_pdu: Byte array with PDU.
:return: Byte array with ADU.
|
[
"Return",
"request",
"ADU",
"for",
"Modbus",
"RTU",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/rtu.py#L58-L67
|
11,719
|
AdvancedClimateSystems/uModbus
|
umodbus/client/serial/rtu.py
|
send_message
|
def send_message(adu, serial_port):
""" Send ADU over serial to to server and return parsed response.
:param adu: Request ADU.
:param sock: Serial port instance.
:return: Parsed response from server.
"""
serial_port.write(adu)
serial_port.flush()
# Check exception ADU (which is shorter than all other responses) first.
exception_adu_size = 5
response_error_adu = recv_exactly(serial_port.read, exception_adu_size)
raise_for_exception_adu(response_error_adu)
expected_response_size = \
expected_response_pdu_size_from_request_pdu(adu[1:-2]) + 3
response_remainder = recv_exactly(
serial_port.read, expected_response_size - exception_adu_size)
return parse_response_adu(response_error_adu + response_remainder, adu)
|
python
|
def send_message(adu, serial_port):
""" Send ADU over serial to to server and return parsed response.
:param adu: Request ADU.
:param sock: Serial port instance.
:return: Parsed response from server.
"""
serial_port.write(adu)
serial_port.flush()
# Check exception ADU (which is shorter than all other responses) first.
exception_adu_size = 5
response_error_adu = recv_exactly(serial_port.read, exception_adu_size)
raise_for_exception_adu(response_error_adu)
expected_response_size = \
expected_response_pdu_size_from_request_pdu(adu[1:-2]) + 3
response_remainder = recv_exactly(
serial_port.read, expected_response_size - exception_adu_size)
return parse_response_adu(response_error_adu + response_remainder, adu)
|
[
"def",
"send_message",
"(",
"adu",
",",
"serial_port",
")",
":",
"serial_port",
".",
"write",
"(",
"adu",
")",
"serial_port",
".",
"flush",
"(",
")",
"# Check exception ADU (which is shorter than all other responses) first.",
"exception_adu_size",
"=",
"5",
"response_error_adu",
"=",
"recv_exactly",
"(",
"serial_port",
".",
"read",
",",
"exception_adu_size",
")",
"raise_for_exception_adu",
"(",
"response_error_adu",
")",
"expected_response_size",
"=",
"expected_response_pdu_size_from_request_pdu",
"(",
"adu",
"[",
"1",
":",
"-",
"2",
"]",
")",
"+",
"3",
"response_remainder",
"=",
"recv_exactly",
"(",
"serial_port",
".",
"read",
",",
"expected_response_size",
"-",
"exception_adu_size",
")",
"return",
"parse_response_adu",
"(",
"response_error_adu",
"+",
"response_remainder",
",",
"adu",
")"
] |
Send ADU over serial to to server and return parsed response.
:param adu: Request ADU.
:param sock: Serial port instance.
:return: Parsed response from server.
|
[
"Send",
"ADU",
"over",
"serial",
"to",
"to",
"server",
"and",
"return",
"parsed",
"response",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/rtu.py#L205-L225
|
11,720
|
AdvancedClimateSystems/uModbus
|
umodbus/utils.py
|
pack_mbap
|
def pack_mbap(transaction_id, protocol_id, length, unit_id):
""" Create and return response MBAP.
:param transaction_id: Transaction id.
:param protocol_id: Protocol id.
:param length: Length of following bytes in ADU.
:param unit_id: Unit id.
:return: Byte array of 7 bytes.
"""
return struct.pack('>HHHB', transaction_id, protocol_id, length, unit_id)
|
python
|
def pack_mbap(transaction_id, protocol_id, length, unit_id):
""" Create and return response MBAP.
:param transaction_id: Transaction id.
:param protocol_id: Protocol id.
:param length: Length of following bytes in ADU.
:param unit_id: Unit id.
:return: Byte array of 7 bytes.
"""
return struct.pack('>HHHB', transaction_id, protocol_id, length, unit_id)
|
[
"def",
"pack_mbap",
"(",
"transaction_id",
",",
"protocol_id",
",",
"length",
",",
"unit_id",
")",
":",
"return",
"struct",
".",
"pack",
"(",
"'>HHHB'",
",",
"transaction_id",
",",
"protocol_id",
",",
"length",
",",
"unit_id",
")"
] |
Create and return response MBAP.
:param transaction_id: Transaction id.
:param protocol_id: Protocol id.
:param length: Length of following bytes in ADU.
:param unit_id: Unit id.
:return: Byte array of 7 bytes.
|
[
"Create",
"and",
"return",
"response",
"MBAP",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/utils.py#L45-L54
|
11,721
|
AdvancedClimateSystems/uModbus
|
umodbus/utils.py
|
memoize
|
def memoize(f):
""" Decorator which caches function's return value each it is called.
If called later with same arguments, the cached value is returned.
"""
cache = {}
@wraps(f)
def inner(arg):
if arg not in cache:
cache[arg] = f(arg)
return cache[arg]
return inner
|
python
|
def memoize(f):
""" Decorator which caches function's return value each it is called.
If called later with same arguments, the cached value is returned.
"""
cache = {}
@wraps(f)
def inner(arg):
if arg not in cache:
cache[arg] = f(arg)
return cache[arg]
return inner
|
[
"def",
"memoize",
"(",
"f",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"arg",
")",
":",
"if",
"arg",
"not",
"in",
"cache",
":",
"cache",
"[",
"arg",
"]",
"=",
"f",
"(",
"arg",
")",
"return",
"cache",
"[",
"arg",
"]",
"return",
"inner"
] |
Decorator which caches function's return value each it is called.
If called later with same arguments, the cached value is returned.
|
[
"Decorator",
"which",
"caches",
"function",
"s",
"return",
"value",
"each",
"it",
"is",
"called",
".",
"If",
"called",
"later",
"with",
"same",
"arguments",
"the",
"cached",
"value",
"is",
"returned",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/utils.py#L103-L114
|
11,722
|
AdvancedClimateSystems/uModbus
|
umodbus/utils.py
|
recv_exactly
|
def recv_exactly(recv_fn, size):
""" Use the function to read and return exactly number of bytes desired.
https://docs.python.org/3/howto/sockets.html#socket-programming-howto for
more information about why this is necessary.
:param recv_fn: Function that can return up to given bytes
(i.e. socket.recv, file.read)
:param size: Number of bytes to read.
:return: Byte string with length size.
:raises ValueError: Could not receive enough data (usually timeout).
"""
recv_bytes = 0
chunks = []
while recv_bytes < size:
chunk = recv_fn(size - recv_bytes)
if len(chunk) == 0: # when closed or empty
break
recv_bytes += len(chunk)
chunks.append(chunk)
response = b''.join(chunks)
if len(response) != size:
raise ValueError
return response
|
python
|
def recv_exactly(recv_fn, size):
""" Use the function to read and return exactly number of bytes desired.
https://docs.python.org/3/howto/sockets.html#socket-programming-howto for
more information about why this is necessary.
:param recv_fn: Function that can return up to given bytes
(i.e. socket.recv, file.read)
:param size: Number of bytes to read.
:return: Byte string with length size.
:raises ValueError: Could not receive enough data (usually timeout).
"""
recv_bytes = 0
chunks = []
while recv_bytes < size:
chunk = recv_fn(size - recv_bytes)
if len(chunk) == 0: # when closed or empty
break
recv_bytes += len(chunk)
chunks.append(chunk)
response = b''.join(chunks)
if len(response) != size:
raise ValueError
return response
|
[
"def",
"recv_exactly",
"(",
"recv_fn",
",",
"size",
")",
":",
"recv_bytes",
"=",
"0",
"chunks",
"=",
"[",
"]",
"while",
"recv_bytes",
"<",
"size",
":",
"chunk",
"=",
"recv_fn",
"(",
"size",
"-",
"recv_bytes",
")",
"if",
"len",
"(",
"chunk",
")",
"==",
"0",
":",
"# when closed or empty",
"break",
"recv_bytes",
"+=",
"len",
"(",
"chunk",
")",
"chunks",
".",
"append",
"(",
"chunk",
")",
"response",
"=",
"b''",
".",
"join",
"(",
"chunks",
")",
"if",
"len",
"(",
"response",
")",
"!=",
"size",
":",
"raise",
"ValueError",
"return",
"response"
] |
Use the function to read and return exactly number of bytes desired.
https://docs.python.org/3/howto/sockets.html#socket-programming-howto for
more information about why this is necessary.
:param recv_fn: Function that can return up to given bytes
(i.e. socket.recv, file.read)
:param size: Number of bytes to read.
:return: Byte string with length size.
:raises ValueError: Could not receive enough data (usually timeout).
|
[
"Use",
"the",
"function",
"to",
"read",
"and",
"return",
"exactly",
"number",
"of",
"bytes",
"desired",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/utils.py#L117-L143
|
11,723
|
AdvancedClimateSystems/uModbus
|
umodbus/client/tcp.py
|
_create_mbap_header
|
def _create_mbap_header(slave_id, pdu):
""" Return byte array with MBAP header for PDU.
:param slave_id: Number of slave.
:param pdu: Byte array with PDU.
:return: Byte array of 7 bytes with MBAP header.
"""
# 65535 = (2**16)-1 aka maximum number that fits in 2 bytes.
transaction_id = randint(0, 65535)
length = len(pdu) + 1
return struct.pack('>HHHB', transaction_id, 0, length, slave_id)
|
python
|
def _create_mbap_header(slave_id, pdu):
""" Return byte array with MBAP header for PDU.
:param slave_id: Number of slave.
:param pdu: Byte array with PDU.
:return: Byte array of 7 bytes with MBAP header.
"""
# 65535 = (2**16)-1 aka maximum number that fits in 2 bytes.
transaction_id = randint(0, 65535)
length = len(pdu) + 1
return struct.pack('>HHHB', transaction_id, 0, length, slave_id)
|
[
"def",
"_create_mbap_header",
"(",
"slave_id",
",",
"pdu",
")",
":",
"# 65535 = (2**16)-1 aka maximum number that fits in 2 bytes.",
"transaction_id",
"=",
"randint",
"(",
"0",
",",
"65535",
")",
"length",
"=",
"len",
"(",
"pdu",
")",
"+",
"1",
"return",
"struct",
".",
"pack",
"(",
"'>HHHB'",
",",
"transaction_id",
",",
"0",
",",
"length",
",",
"slave_id",
")"
] |
Return byte array with MBAP header for PDU.
:param slave_id: Number of slave.
:param pdu: Byte array with PDU.
:return: Byte array of 7 bytes with MBAP header.
|
[
"Return",
"byte",
"array",
"with",
"MBAP",
"header",
"for",
"PDU",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/tcp.py#L108-L119
|
11,724
|
AdvancedClimateSystems/uModbus
|
umodbus/client/tcp.py
|
send_message
|
def send_message(adu, sock):
""" Send ADU over socket to to server and return parsed response.
:param adu: Request ADU.
:param sock: Socket instance.
:return: Parsed response from server.
"""
sock.sendall(adu)
# Check exception ADU (which is shorter than all other responses) first.
exception_adu_size = 9
response_error_adu = recv_exactly(sock.recv, exception_adu_size)
raise_for_exception_adu(response_error_adu)
expected_response_size = \
expected_response_pdu_size_from_request_pdu(adu[7:]) + 7
response_remainder = recv_exactly(
sock.recv, expected_response_size - exception_adu_size)
return parse_response_adu(response_error_adu + response_remainder, adu)
|
python
|
def send_message(adu, sock):
""" Send ADU over socket to to server and return parsed response.
:param adu: Request ADU.
:param sock: Socket instance.
:return: Parsed response from server.
"""
sock.sendall(adu)
# Check exception ADU (which is shorter than all other responses) first.
exception_adu_size = 9
response_error_adu = recv_exactly(sock.recv, exception_adu_size)
raise_for_exception_adu(response_error_adu)
expected_response_size = \
expected_response_pdu_size_from_request_pdu(adu[7:]) + 7
response_remainder = recv_exactly(
sock.recv, expected_response_size - exception_adu_size)
return parse_response_adu(response_error_adu + response_remainder, adu)
|
[
"def",
"send_message",
"(",
"adu",
",",
"sock",
")",
":",
"sock",
".",
"sendall",
"(",
"adu",
")",
"# Check exception ADU (which is shorter than all other responses) first.",
"exception_adu_size",
"=",
"9",
"response_error_adu",
"=",
"recv_exactly",
"(",
"sock",
".",
"recv",
",",
"exception_adu_size",
")",
"raise_for_exception_adu",
"(",
"response_error_adu",
")",
"expected_response_size",
"=",
"expected_response_pdu_size_from_request_pdu",
"(",
"adu",
"[",
"7",
":",
"]",
")",
"+",
"7",
"response_remainder",
"=",
"recv_exactly",
"(",
"sock",
".",
"recv",
",",
"expected_response_size",
"-",
"exception_adu_size",
")",
"return",
"parse_response_adu",
"(",
"response_error_adu",
"+",
"response_remainder",
",",
"adu",
")"
] |
Send ADU over socket to to server and return parsed response.
:param adu: Request ADU.
:param sock: Socket instance.
:return: Parsed response from server.
|
[
"Send",
"ADU",
"over",
"socket",
"to",
"to",
"server",
"and",
"return",
"parsed",
"response",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/tcp.py#L250-L269
|
11,725
|
AdvancedClimateSystems/uModbus
|
scripts/examples/simple_rtu_client.py
|
get_serial_port
|
def get_serial_port():
""" Return serial.Serial instance, ready to use for RS485."""
port = Serial(port='/dev/ttyS1', baudrate=9600, parity=PARITY_NONE,
stopbits=1, bytesize=8, timeout=1)
fh = port.fileno()
# A struct with configuration for serial port.
serial_rs485 = struct.pack('hhhhhhhh', 1, 0, 0, 0, 0, 0, 0, 0)
fcntl.ioctl(fh, 0x542F, serial_rs485)
return port
|
python
|
def get_serial_port():
""" Return serial.Serial instance, ready to use for RS485."""
port = Serial(port='/dev/ttyS1', baudrate=9600, parity=PARITY_NONE,
stopbits=1, bytesize=8, timeout=1)
fh = port.fileno()
# A struct with configuration for serial port.
serial_rs485 = struct.pack('hhhhhhhh', 1, 0, 0, 0, 0, 0, 0, 0)
fcntl.ioctl(fh, 0x542F, serial_rs485)
return port
|
[
"def",
"get_serial_port",
"(",
")",
":",
"port",
"=",
"Serial",
"(",
"port",
"=",
"'/dev/ttyS1'",
",",
"baudrate",
"=",
"9600",
",",
"parity",
"=",
"PARITY_NONE",
",",
"stopbits",
"=",
"1",
",",
"bytesize",
"=",
"8",
",",
"timeout",
"=",
"1",
")",
"fh",
"=",
"port",
".",
"fileno",
"(",
")",
"# A struct with configuration for serial port.",
"serial_rs485",
"=",
"struct",
".",
"pack",
"(",
"'hhhhhhhh'",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"fcntl",
".",
"ioctl",
"(",
"fh",
",",
"0x542F",
",",
"serial_rs485",
")",
"return",
"port"
] |
Return serial.Serial instance, ready to use for RS485.
|
[
"Return",
"serial",
".",
"Serial",
"instance",
"ready",
"to",
"use",
"for",
"RS485",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/scripts/examples/simple_rtu_client.py#L10-L21
|
11,726
|
AdvancedClimateSystems/uModbus
|
umodbus/config.py
|
Config._set_multi_bit_value_format_character
|
def _set_multi_bit_value_format_character(self):
""" Set format character for multibit values.
The format character depends on size of the value and whether values
are signed or unsigned.
"""
self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \
self.MULTI_BIT_VALUE_FORMAT_CHARACTER.upper()
if self.SIGNED_VALUES:
self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \
self.MULTI_BIT_VALUE_FORMAT_CHARACTER.lower()
|
python
|
def _set_multi_bit_value_format_character(self):
""" Set format character for multibit values.
The format character depends on size of the value and whether values
are signed or unsigned.
"""
self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \
self.MULTI_BIT_VALUE_FORMAT_CHARACTER.upper()
if self.SIGNED_VALUES:
self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \
self.MULTI_BIT_VALUE_FORMAT_CHARACTER.lower()
|
[
"def",
"_set_multi_bit_value_format_character",
"(",
"self",
")",
":",
"self",
".",
"MULTI_BIT_VALUE_FORMAT_CHARACTER",
"=",
"self",
".",
"MULTI_BIT_VALUE_FORMAT_CHARACTER",
".",
"upper",
"(",
")",
"if",
"self",
".",
"SIGNED_VALUES",
":",
"self",
".",
"MULTI_BIT_VALUE_FORMAT_CHARACTER",
"=",
"self",
".",
"MULTI_BIT_VALUE_FORMAT_CHARACTER",
".",
"lower",
"(",
")"
] |
Set format character for multibit values.
The format character depends on size of the value and whether values
are signed or unsigned.
|
[
"Set",
"format",
"character",
"for",
"multibit",
"values",
"."
] |
0560a42308003f4072d988f28042b8d55b694ad4
|
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/config.py#L41-L53
|
11,727
|
jgm/pandocfilters
|
pandocfilters.py
|
get_filename4code
|
def get_filename4code(module, content, ext=None):
"""Generate filename based on content
The function ensures that the (temporary) directory exists, so that the
file can be written.
Example:
filename = get_filename4code("myfilter", code)
"""
imagedir = module + "-images"
fn = hashlib.sha1(content.encode(sys.getfilesystemencoding())).hexdigest()
try:
os.mkdir(imagedir)
sys.stderr.write('Created directory ' + imagedir + '\n')
except OSError:
pass
if ext:
fn += "." + ext
return os.path.join(imagedir, fn)
|
python
|
def get_filename4code(module, content, ext=None):
"""Generate filename based on content
The function ensures that the (temporary) directory exists, so that the
file can be written.
Example:
filename = get_filename4code("myfilter", code)
"""
imagedir = module + "-images"
fn = hashlib.sha1(content.encode(sys.getfilesystemencoding())).hexdigest()
try:
os.mkdir(imagedir)
sys.stderr.write('Created directory ' + imagedir + '\n')
except OSError:
pass
if ext:
fn += "." + ext
return os.path.join(imagedir, fn)
|
[
"def",
"get_filename4code",
"(",
"module",
",",
"content",
",",
"ext",
"=",
"None",
")",
":",
"imagedir",
"=",
"module",
"+",
"\"-images\"",
"fn",
"=",
"hashlib",
".",
"sha1",
"(",
"content",
".",
"encode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
")",
")",
".",
"hexdigest",
"(",
")",
"try",
":",
"os",
".",
"mkdir",
"(",
"imagedir",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Created directory '",
"+",
"imagedir",
"+",
"'\\n'",
")",
"except",
"OSError",
":",
"pass",
"if",
"ext",
":",
"fn",
"+=",
"\".\"",
"+",
"ext",
"return",
"os",
".",
"path",
".",
"join",
"(",
"imagedir",
",",
"fn",
")"
] |
Generate filename based on content
The function ensures that the (temporary) directory exists, so that the
file can be written.
Example:
filename = get_filename4code("myfilter", code)
|
[
"Generate",
"filename",
"based",
"on",
"content"
] |
0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5
|
https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L21-L39
|
11,728
|
jgm/pandocfilters
|
pandocfilters.py
|
toJSONFilters
|
def toJSONFilters(actions):
"""Generate a JSON-to-JSON filter from stdin to stdout
The filter:
* reads a JSON-formatted pandoc document from stdin
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document to stdout
The argument `actions` is a list of functions of the form
`action(key, value, format, meta)`, as described in more
detail under `walk`.
This function calls `applyJSONFilters`, with the `format`
argument provided by the first command-line argument,
if present. (Pandoc sets this by default when calling
filters.)
"""
try:
input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
except AttributeError:
# Python 2 does not have sys.stdin.buffer.
# REF: https://stackoverflow.com/questions/2467928/python-unicodeencode
input_stream = codecs.getreader("utf-8")(sys.stdin)
source = input_stream.read()
if len(sys.argv) > 1:
format = sys.argv[1]
else:
format = ""
sys.stdout.write(applyJSONFilters(actions, source, format))
|
python
|
def toJSONFilters(actions):
"""Generate a JSON-to-JSON filter from stdin to stdout
The filter:
* reads a JSON-formatted pandoc document from stdin
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document to stdout
The argument `actions` is a list of functions of the form
`action(key, value, format, meta)`, as described in more
detail under `walk`.
This function calls `applyJSONFilters`, with the `format`
argument provided by the first command-line argument,
if present. (Pandoc sets this by default when calling
filters.)
"""
try:
input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
except AttributeError:
# Python 2 does not have sys.stdin.buffer.
# REF: https://stackoverflow.com/questions/2467928/python-unicodeencode
input_stream = codecs.getreader("utf-8")(sys.stdin)
source = input_stream.read()
if len(sys.argv) > 1:
format = sys.argv[1]
else:
format = ""
sys.stdout.write(applyJSONFilters(actions, source, format))
|
[
"def",
"toJSONFilters",
"(",
"actions",
")",
":",
"try",
":",
"input_stream",
"=",
"io",
".",
"TextIOWrapper",
"(",
"sys",
".",
"stdin",
".",
"buffer",
",",
"encoding",
"=",
"'utf-8'",
")",
"except",
"AttributeError",
":",
"# Python 2 does not have sys.stdin.buffer.",
"# REF: https://stackoverflow.com/questions/2467928/python-unicodeencode",
"input_stream",
"=",
"codecs",
".",
"getreader",
"(",
"\"utf-8\"",
")",
"(",
"sys",
".",
"stdin",
")",
"source",
"=",
"input_stream",
".",
"read",
"(",
")",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
":",
"format",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"else",
":",
"format",
"=",
"\"\"",
"sys",
".",
"stdout",
".",
"write",
"(",
"applyJSONFilters",
"(",
"actions",
",",
"source",
",",
"format",
")",
")"
] |
Generate a JSON-to-JSON filter from stdin to stdout
The filter:
* reads a JSON-formatted pandoc document from stdin
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document to stdout
The argument `actions` is a list of functions of the form
`action(key, value, format, meta)`, as described in more
detail under `walk`.
This function calls `applyJSONFilters`, with the `format`
argument provided by the first command-line argument,
if present. (Pandoc sets this by default when calling
filters.)
|
[
"Generate",
"a",
"JSON",
"-",
"to",
"-",
"JSON",
"filter",
"from",
"stdin",
"to",
"stdout"
] |
0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5
|
https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L135-L166
|
11,729
|
jgm/pandocfilters
|
pandocfilters.py
|
applyJSONFilters
|
def applyJSONFilters(actions, source, format=""):
"""Walk through JSON structure and apply filters
This:
* reads a JSON-formatted pandoc document from a source string
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document as a string
The `actions` argument is a list of functions (see `walk`
for a full description).
The argument `source` is a string encoded JSON object.
The argument `format` is a string describing the output format.
Returns a the new JSON-formatted pandoc document.
"""
doc = json.loads(source)
if 'meta' in doc:
meta = doc['meta']
elif doc[0]: # old API
meta = doc[0]['unMeta']
else:
meta = {}
altered = doc
for action in actions:
altered = walk(altered, action, format, meta)
return json.dumps(altered)
|
python
|
def applyJSONFilters(actions, source, format=""):
"""Walk through JSON structure and apply filters
This:
* reads a JSON-formatted pandoc document from a source string
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document as a string
The `actions` argument is a list of functions (see `walk`
for a full description).
The argument `source` is a string encoded JSON object.
The argument `format` is a string describing the output format.
Returns a the new JSON-formatted pandoc document.
"""
doc = json.loads(source)
if 'meta' in doc:
meta = doc['meta']
elif doc[0]: # old API
meta = doc[0]['unMeta']
else:
meta = {}
altered = doc
for action in actions:
altered = walk(altered, action, format, meta)
return json.dumps(altered)
|
[
"def",
"applyJSONFilters",
"(",
"actions",
",",
"source",
",",
"format",
"=",
"\"\"",
")",
":",
"doc",
"=",
"json",
".",
"loads",
"(",
"source",
")",
"if",
"'meta'",
"in",
"doc",
":",
"meta",
"=",
"doc",
"[",
"'meta'",
"]",
"elif",
"doc",
"[",
"0",
"]",
":",
"# old API",
"meta",
"=",
"doc",
"[",
"0",
"]",
"[",
"'unMeta'",
"]",
"else",
":",
"meta",
"=",
"{",
"}",
"altered",
"=",
"doc",
"for",
"action",
"in",
"actions",
":",
"altered",
"=",
"walk",
"(",
"altered",
",",
"action",
",",
"format",
",",
"meta",
")",
"return",
"json",
".",
"dumps",
"(",
"altered",
")"
] |
Walk through JSON structure and apply filters
This:
* reads a JSON-formatted pandoc document from a source string
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document as a string
The `actions` argument is a list of functions (see `walk`
for a full description).
The argument `source` is a string encoded JSON object.
The argument `format` is a string describing the output format.
Returns a the new JSON-formatted pandoc document.
|
[
"Walk",
"through",
"JSON",
"structure",
"and",
"apply",
"filters"
] |
0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5
|
https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L168-L199
|
11,730
|
jgm/pandocfilters
|
pandocfilters.py
|
stringify
|
def stringify(x):
"""Walks the tree x and returns concatenated string content,
leaving out all formatting.
"""
result = []
def go(key, val, format, meta):
if key in ['Str', 'MetaString']:
result.append(val)
elif key == 'Code':
result.append(val[1])
elif key == 'Math':
result.append(val[1])
elif key == 'LineBreak':
result.append(" ")
elif key == 'SoftBreak':
result.append(" ")
elif key == 'Space':
result.append(" ")
walk(x, go, "", {})
return ''.join(result)
|
python
|
def stringify(x):
"""Walks the tree x and returns concatenated string content,
leaving out all formatting.
"""
result = []
def go(key, val, format, meta):
if key in ['Str', 'MetaString']:
result.append(val)
elif key == 'Code':
result.append(val[1])
elif key == 'Math':
result.append(val[1])
elif key == 'LineBreak':
result.append(" ")
elif key == 'SoftBreak':
result.append(" ")
elif key == 'Space':
result.append(" ")
walk(x, go, "", {})
return ''.join(result)
|
[
"def",
"stringify",
"(",
"x",
")",
":",
"result",
"=",
"[",
"]",
"def",
"go",
"(",
"key",
",",
"val",
",",
"format",
",",
"meta",
")",
":",
"if",
"key",
"in",
"[",
"'Str'",
",",
"'MetaString'",
"]",
":",
"result",
".",
"append",
"(",
"val",
")",
"elif",
"key",
"==",
"'Code'",
":",
"result",
".",
"append",
"(",
"val",
"[",
"1",
"]",
")",
"elif",
"key",
"==",
"'Math'",
":",
"result",
".",
"append",
"(",
"val",
"[",
"1",
"]",
")",
"elif",
"key",
"==",
"'LineBreak'",
":",
"result",
".",
"append",
"(",
"\" \"",
")",
"elif",
"key",
"==",
"'SoftBreak'",
":",
"result",
".",
"append",
"(",
"\" \"",
")",
"elif",
"key",
"==",
"'Space'",
":",
"result",
".",
"append",
"(",
"\" \"",
")",
"walk",
"(",
"x",
",",
"go",
",",
"\"\"",
",",
"{",
"}",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] |
Walks the tree x and returns concatenated string content,
leaving out all formatting.
|
[
"Walks",
"the",
"tree",
"x",
"and",
"returns",
"concatenated",
"string",
"content",
"leaving",
"out",
"all",
"formatting",
"."
] |
0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5
|
https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L202-L223
|
11,731
|
jgm/pandocfilters
|
pandocfilters.py
|
attributes
|
def attributes(attrs):
"""Returns an attribute list, constructed from the
dictionary attrs.
"""
attrs = attrs or {}
ident = attrs.get("id", "")
classes = attrs.get("classes", [])
keyvals = [[x, attrs[x]] for x in attrs if (x != "classes" and x != "id")]
return [ident, classes, keyvals]
|
python
|
def attributes(attrs):
"""Returns an attribute list, constructed from the
dictionary attrs.
"""
attrs = attrs or {}
ident = attrs.get("id", "")
classes = attrs.get("classes", [])
keyvals = [[x, attrs[x]] for x in attrs if (x != "classes" and x != "id")]
return [ident, classes, keyvals]
|
[
"def",
"attributes",
"(",
"attrs",
")",
":",
"attrs",
"=",
"attrs",
"or",
"{",
"}",
"ident",
"=",
"attrs",
".",
"get",
"(",
"\"id\"",
",",
"\"\"",
")",
"classes",
"=",
"attrs",
".",
"get",
"(",
"\"classes\"",
",",
"[",
"]",
")",
"keyvals",
"=",
"[",
"[",
"x",
",",
"attrs",
"[",
"x",
"]",
"]",
"for",
"x",
"in",
"attrs",
"if",
"(",
"x",
"!=",
"\"classes\"",
"and",
"x",
"!=",
"\"id\"",
")",
"]",
"return",
"[",
"ident",
",",
"classes",
",",
"keyvals",
"]"
] |
Returns an attribute list, constructed from the
dictionary attrs.
|
[
"Returns",
"an",
"attribute",
"list",
"constructed",
"from",
"the",
"dictionary",
"attrs",
"."
] |
0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5
|
https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L226-L234
|
11,732
|
Turbo87/utm
|
utm/conversion.py
|
to_latlon
|
def to_latlon(easting, northing, zone_number, zone_letter=None, northern=None, strict=True):
"""This function convert an UTM coordinate into Latitude and Longitude
Parameters
----------
easting: int
Easting value of UTM coordinate
northing: int
Northing value of UTM coordinate
zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. More information see utmzones [1]_
zone_letter: str
Zone Letter can be represented as string values. Where UTM Zone
Designators can be accessed in [1]_
northern: bool
You can set True or False to set this parameter. Default is None
.. _[1]: http://www.jaworski.ca/utmzones.htm
"""
if not zone_letter and northern is None:
raise ValueError('either zone_letter or northern needs to be set')
elif zone_letter and northern is not None:
raise ValueError('set either zone_letter or northern, but not both')
if strict:
if not in_bounds(easting, 100000, 1000000, upper_strict=True):
raise OutOfRangeError('easting out of range (must be between 100.000 m and 999.999 m)')
if not in_bounds(northing, 0, 10000000):
raise OutOfRangeError('northing out of range (must be between 0 m and 10.000.000 m)')
check_valid_zone(zone_number, zone_letter)
if zone_letter:
zone_letter = zone_letter.upper()
northern = (zone_letter >= 'N')
x = easting - 500000
y = northing
if not northern:
y -= 10000000
m = y / K0
mu = m / (R * M1)
p_rad = (mu +
P2 * mathlib.sin(2 * mu) +
P3 * mathlib.sin(4 * mu) +
P4 * mathlib.sin(6 * mu) +
P5 * mathlib.sin(8 * mu))
p_sin = mathlib.sin(p_rad)
p_sin2 = p_sin * p_sin
p_cos = mathlib.cos(p_rad)
p_tan = p_sin / p_cos
p_tan2 = p_tan * p_tan
p_tan4 = p_tan2 * p_tan2
ep_sin = 1 - E * p_sin2
ep_sin_sqrt = mathlib.sqrt(1 - E * p_sin2)
n = R / ep_sin_sqrt
r = (1 - E) / ep_sin
c = _E * p_cos**2
c2 = c * c
d = x / (n * K0)
d2 = d * d
d3 = d2 * d
d4 = d3 * d
d5 = d4 * d
d6 = d5 * d
latitude = (p_rad - (p_tan / r) *
(d2 / 2 -
d4 / 24 * (5 + 3 * p_tan2 + 10 * c - 4 * c2 - 9 * E_P2)) +
d6 / 720 * (61 + 90 * p_tan2 + 298 * c + 45 * p_tan4 - 252 * E_P2 - 3 * c2))
longitude = (d -
d3 / 6 * (1 + 2 * p_tan2 + c) +
d5 / 120 * (5 - 2 * c + 28 * p_tan2 - 3 * c2 + 8 * E_P2 + 24 * p_tan4)) / p_cos
return (mathlib.degrees(latitude),
mathlib.degrees(longitude) + zone_number_to_central_longitude(zone_number))
|
python
|
def to_latlon(easting, northing, zone_number, zone_letter=None, northern=None, strict=True):
"""This function convert an UTM coordinate into Latitude and Longitude
Parameters
----------
easting: int
Easting value of UTM coordinate
northing: int
Northing value of UTM coordinate
zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. More information see utmzones [1]_
zone_letter: str
Zone Letter can be represented as string values. Where UTM Zone
Designators can be accessed in [1]_
northern: bool
You can set True or False to set this parameter. Default is None
.. _[1]: http://www.jaworski.ca/utmzones.htm
"""
if not zone_letter and northern is None:
raise ValueError('either zone_letter or northern needs to be set')
elif zone_letter and northern is not None:
raise ValueError('set either zone_letter or northern, but not both')
if strict:
if not in_bounds(easting, 100000, 1000000, upper_strict=True):
raise OutOfRangeError('easting out of range (must be between 100.000 m and 999.999 m)')
if not in_bounds(northing, 0, 10000000):
raise OutOfRangeError('northing out of range (must be between 0 m and 10.000.000 m)')
check_valid_zone(zone_number, zone_letter)
if zone_letter:
zone_letter = zone_letter.upper()
northern = (zone_letter >= 'N')
x = easting - 500000
y = northing
if not northern:
y -= 10000000
m = y / K0
mu = m / (R * M1)
p_rad = (mu +
P2 * mathlib.sin(2 * mu) +
P3 * mathlib.sin(4 * mu) +
P4 * mathlib.sin(6 * mu) +
P5 * mathlib.sin(8 * mu))
p_sin = mathlib.sin(p_rad)
p_sin2 = p_sin * p_sin
p_cos = mathlib.cos(p_rad)
p_tan = p_sin / p_cos
p_tan2 = p_tan * p_tan
p_tan4 = p_tan2 * p_tan2
ep_sin = 1 - E * p_sin2
ep_sin_sqrt = mathlib.sqrt(1 - E * p_sin2)
n = R / ep_sin_sqrt
r = (1 - E) / ep_sin
c = _E * p_cos**2
c2 = c * c
d = x / (n * K0)
d2 = d * d
d3 = d2 * d
d4 = d3 * d
d5 = d4 * d
d6 = d5 * d
latitude = (p_rad - (p_tan / r) *
(d2 / 2 -
d4 / 24 * (5 + 3 * p_tan2 + 10 * c - 4 * c2 - 9 * E_P2)) +
d6 / 720 * (61 + 90 * p_tan2 + 298 * c + 45 * p_tan4 - 252 * E_P2 - 3 * c2))
longitude = (d -
d3 / 6 * (1 + 2 * p_tan2 + c) +
d5 / 120 * (5 - 2 * c + 28 * p_tan2 - 3 * c2 + 8 * E_P2 + 24 * p_tan4)) / p_cos
return (mathlib.degrees(latitude),
mathlib.degrees(longitude) + zone_number_to_central_longitude(zone_number))
|
[
"def",
"to_latlon",
"(",
"easting",
",",
"northing",
",",
"zone_number",
",",
"zone_letter",
"=",
"None",
",",
"northern",
"=",
"None",
",",
"strict",
"=",
"True",
")",
":",
"if",
"not",
"zone_letter",
"and",
"northern",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'either zone_letter or northern needs to be set'",
")",
"elif",
"zone_letter",
"and",
"northern",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'set either zone_letter or northern, but not both'",
")",
"if",
"strict",
":",
"if",
"not",
"in_bounds",
"(",
"easting",
",",
"100000",
",",
"1000000",
",",
"upper_strict",
"=",
"True",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'easting out of range (must be between 100.000 m and 999.999 m)'",
")",
"if",
"not",
"in_bounds",
"(",
"northing",
",",
"0",
",",
"10000000",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'northing out of range (must be between 0 m and 10.000.000 m)'",
")",
"check_valid_zone",
"(",
"zone_number",
",",
"zone_letter",
")",
"if",
"zone_letter",
":",
"zone_letter",
"=",
"zone_letter",
".",
"upper",
"(",
")",
"northern",
"=",
"(",
"zone_letter",
">=",
"'N'",
")",
"x",
"=",
"easting",
"-",
"500000",
"y",
"=",
"northing",
"if",
"not",
"northern",
":",
"y",
"-=",
"10000000",
"m",
"=",
"y",
"/",
"K0",
"mu",
"=",
"m",
"/",
"(",
"R",
"*",
"M1",
")",
"p_rad",
"=",
"(",
"mu",
"+",
"P2",
"*",
"mathlib",
".",
"sin",
"(",
"2",
"*",
"mu",
")",
"+",
"P3",
"*",
"mathlib",
".",
"sin",
"(",
"4",
"*",
"mu",
")",
"+",
"P4",
"*",
"mathlib",
".",
"sin",
"(",
"6",
"*",
"mu",
")",
"+",
"P5",
"*",
"mathlib",
".",
"sin",
"(",
"8",
"*",
"mu",
")",
")",
"p_sin",
"=",
"mathlib",
".",
"sin",
"(",
"p_rad",
")",
"p_sin2",
"=",
"p_sin",
"*",
"p_sin",
"p_cos",
"=",
"mathlib",
".",
"cos",
"(",
"p_rad",
")",
"p_tan",
"=",
"p_sin",
"/",
"p_cos",
"p_tan2",
"=",
"p_tan",
"*",
"p_tan",
"p_tan4",
"=",
"p_tan2",
"*",
"p_tan2",
"ep_sin",
"=",
"1",
"-",
"E",
"*",
"p_sin2",
"ep_sin_sqrt",
"=",
"mathlib",
".",
"sqrt",
"(",
"1",
"-",
"E",
"*",
"p_sin2",
")",
"n",
"=",
"R",
"/",
"ep_sin_sqrt",
"r",
"=",
"(",
"1",
"-",
"E",
")",
"/",
"ep_sin",
"c",
"=",
"_E",
"*",
"p_cos",
"**",
"2",
"c2",
"=",
"c",
"*",
"c",
"d",
"=",
"x",
"/",
"(",
"n",
"*",
"K0",
")",
"d2",
"=",
"d",
"*",
"d",
"d3",
"=",
"d2",
"*",
"d",
"d4",
"=",
"d3",
"*",
"d",
"d5",
"=",
"d4",
"*",
"d",
"d6",
"=",
"d5",
"*",
"d",
"latitude",
"=",
"(",
"p_rad",
"-",
"(",
"p_tan",
"/",
"r",
")",
"*",
"(",
"d2",
"/",
"2",
"-",
"d4",
"/",
"24",
"*",
"(",
"5",
"+",
"3",
"*",
"p_tan2",
"+",
"10",
"*",
"c",
"-",
"4",
"*",
"c2",
"-",
"9",
"*",
"E_P2",
")",
")",
"+",
"d6",
"/",
"720",
"*",
"(",
"61",
"+",
"90",
"*",
"p_tan2",
"+",
"298",
"*",
"c",
"+",
"45",
"*",
"p_tan4",
"-",
"252",
"*",
"E_P2",
"-",
"3",
"*",
"c2",
")",
")",
"longitude",
"=",
"(",
"d",
"-",
"d3",
"/",
"6",
"*",
"(",
"1",
"+",
"2",
"*",
"p_tan2",
"+",
"c",
")",
"+",
"d5",
"/",
"120",
"*",
"(",
"5",
"-",
"2",
"*",
"c",
"+",
"28",
"*",
"p_tan2",
"-",
"3",
"*",
"c2",
"+",
"8",
"*",
"E_P2",
"+",
"24",
"*",
"p_tan4",
")",
")",
"/",
"p_cos",
"return",
"(",
"mathlib",
".",
"degrees",
"(",
"latitude",
")",
",",
"mathlib",
".",
"degrees",
"(",
"longitude",
")",
"+",
"zone_number_to_central_longitude",
"(",
"zone_number",
")",
")"
] |
This function convert an UTM coordinate into Latitude and Longitude
Parameters
----------
easting: int
Easting value of UTM coordinate
northing: int
Northing value of UTM coordinate
zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. More information see utmzones [1]_
zone_letter: str
Zone Letter can be represented as string values. Where UTM Zone
Designators can be accessed in [1]_
northern: bool
You can set True or False to set this parameter. Default is None
.. _[1]: http://www.jaworski.ca/utmzones.htm
|
[
"This",
"function",
"convert",
"an",
"UTM",
"coordinate",
"into",
"Latitude",
"and",
"Longitude"
] |
efdd46ab0a341ce2aa45f8144d8b05a4fa0fd592
|
https://github.com/Turbo87/utm/blob/efdd46ab0a341ce2aa45f8144d8b05a4fa0fd592/utm/conversion.py#L74-L168
|
11,733
|
Turbo87/utm
|
utm/conversion.py
|
from_latlon
|
def from_latlon(latitude, longitude, force_zone_number=None, force_zone_letter=None):
"""This function convert Latitude and Longitude to UTM coordinate
Parameters
----------
latitude: float
Latitude between 80 deg S and 84 deg N, e.g. (-80.0 to 84.0)
longitude: float
Longitude between 180 deg W and 180 deg E, e.g. (-180.0 to 180.0).
force_zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. You may force conversion including one UTM Zone Number.
More information see utmzones [1]_
.. _[1]: http://www.jaworski.ca/utmzones.htm
"""
if not in_bounds(latitude, -80.0, 84.0):
raise OutOfRangeError('latitude out of range (must be between 80 deg S and 84 deg N)')
if not in_bounds(longitude, -180.0, 180.0):
raise OutOfRangeError('longitude out of range (must be between 180 deg W and 180 deg E)')
if force_zone_number is not None:
check_valid_zone(force_zone_number, force_zone_letter)
lat_rad = mathlib.radians(latitude)
lat_sin = mathlib.sin(lat_rad)
lat_cos = mathlib.cos(lat_rad)
lat_tan = lat_sin / lat_cos
lat_tan2 = lat_tan * lat_tan
lat_tan4 = lat_tan2 * lat_tan2
if force_zone_number is None:
zone_number = latlon_to_zone_number(latitude, longitude)
else:
zone_number = force_zone_number
if force_zone_letter is None:
zone_letter = latitude_to_zone_letter(latitude)
else:
zone_letter = force_zone_letter
lon_rad = mathlib.radians(longitude)
central_lon = zone_number_to_central_longitude(zone_number)
central_lon_rad = mathlib.radians(central_lon)
n = R / mathlib.sqrt(1 - E * lat_sin**2)
c = E_P2 * lat_cos**2
a = lat_cos * (lon_rad - central_lon_rad)
a2 = a * a
a3 = a2 * a
a4 = a3 * a
a5 = a4 * a
a6 = a5 * a
m = R * (M1 * lat_rad -
M2 * mathlib.sin(2 * lat_rad) +
M3 * mathlib.sin(4 * lat_rad) -
M4 * mathlib.sin(6 * lat_rad))
easting = K0 * n * (a +
a3 / 6 * (1 - lat_tan2 + c) +
a5 / 120 * (5 - 18 * lat_tan2 + lat_tan4 + 72 * c - 58 * E_P2)) + 500000
northing = K0 * (m + n * lat_tan * (a2 / 2 +
a4 / 24 * (5 - lat_tan2 + 9 * c + 4 * c**2) +
a6 / 720 * (61 - 58 * lat_tan2 + lat_tan4 + 600 * c - 330 * E_P2)))
if mixed_signs(latitude):
raise ValueError("latitudes must all have the same sign")
elif negative(latitude):
northing += 10000000
return easting, northing, zone_number, zone_letter
|
python
|
def from_latlon(latitude, longitude, force_zone_number=None, force_zone_letter=None):
"""This function convert Latitude and Longitude to UTM coordinate
Parameters
----------
latitude: float
Latitude between 80 deg S and 84 deg N, e.g. (-80.0 to 84.0)
longitude: float
Longitude between 180 deg W and 180 deg E, e.g. (-180.0 to 180.0).
force_zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. You may force conversion including one UTM Zone Number.
More information see utmzones [1]_
.. _[1]: http://www.jaworski.ca/utmzones.htm
"""
if not in_bounds(latitude, -80.0, 84.0):
raise OutOfRangeError('latitude out of range (must be between 80 deg S and 84 deg N)')
if not in_bounds(longitude, -180.0, 180.0):
raise OutOfRangeError('longitude out of range (must be between 180 deg W and 180 deg E)')
if force_zone_number is not None:
check_valid_zone(force_zone_number, force_zone_letter)
lat_rad = mathlib.radians(latitude)
lat_sin = mathlib.sin(lat_rad)
lat_cos = mathlib.cos(lat_rad)
lat_tan = lat_sin / lat_cos
lat_tan2 = lat_tan * lat_tan
lat_tan4 = lat_tan2 * lat_tan2
if force_zone_number is None:
zone_number = latlon_to_zone_number(latitude, longitude)
else:
zone_number = force_zone_number
if force_zone_letter is None:
zone_letter = latitude_to_zone_letter(latitude)
else:
zone_letter = force_zone_letter
lon_rad = mathlib.radians(longitude)
central_lon = zone_number_to_central_longitude(zone_number)
central_lon_rad = mathlib.radians(central_lon)
n = R / mathlib.sqrt(1 - E * lat_sin**2)
c = E_P2 * lat_cos**2
a = lat_cos * (lon_rad - central_lon_rad)
a2 = a * a
a3 = a2 * a
a4 = a3 * a
a5 = a4 * a
a6 = a5 * a
m = R * (M1 * lat_rad -
M2 * mathlib.sin(2 * lat_rad) +
M3 * mathlib.sin(4 * lat_rad) -
M4 * mathlib.sin(6 * lat_rad))
easting = K0 * n * (a +
a3 / 6 * (1 - lat_tan2 + c) +
a5 / 120 * (5 - 18 * lat_tan2 + lat_tan4 + 72 * c - 58 * E_P2)) + 500000
northing = K0 * (m + n * lat_tan * (a2 / 2 +
a4 / 24 * (5 - lat_tan2 + 9 * c + 4 * c**2) +
a6 / 720 * (61 - 58 * lat_tan2 + lat_tan4 + 600 * c - 330 * E_P2)))
if mixed_signs(latitude):
raise ValueError("latitudes must all have the same sign")
elif negative(latitude):
northing += 10000000
return easting, northing, zone_number, zone_letter
|
[
"def",
"from_latlon",
"(",
"latitude",
",",
"longitude",
",",
"force_zone_number",
"=",
"None",
",",
"force_zone_letter",
"=",
"None",
")",
":",
"if",
"not",
"in_bounds",
"(",
"latitude",
",",
"-",
"80.0",
",",
"84.0",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'latitude out of range (must be between 80 deg S and 84 deg N)'",
")",
"if",
"not",
"in_bounds",
"(",
"longitude",
",",
"-",
"180.0",
",",
"180.0",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'longitude out of range (must be between 180 deg W and 180 deg E)'",
")",
"if",
"force_zone_number",
"is",
"not",
"None",
":",
"check_valid_zone",
"(",
"force_zone_number",
",",
"force_zone_letter",
")",
"lat_rad",
"=",
"mathlib",
".",
"radians",
"(",
"latitude",
")",
"lat_sin",
"=",
"mathlib",
".",
"sin",
"(",
"lat_rad",
")",
"lat_cos",
"=",
"mathlib",
".",
"cos",
"(",
"lat_rad",
")",
"lat_tan",
"=",
"lat_sin",
"/",
"lat_cos",
"lat_tan2",
"=",
"lat_tan",
"*",
"lat_tan",
"lat_tan4",
"=",
"lat_tan2",
"*",
"lat_tan2",
"if",
"force_zone_number",
"is",
"None",
":",
"zone_number",
"=",
"latlon_to_zone_number",
"(",
"latitude",
",",
"longitude",
")",
"else",
":",
"zone_number",
"=",
"force_zone_number",
"if",
"force_zone_letter",
"is",
"None",
":",
"zone_letter",
"=",
"latitude_to_zone_letter",
"(",
"latitude",
")",
"else",
":",
"zone_letter",
"=",
"force_zone_letter",
"lon_rad",
"=",
"mathlib",
".",
"radians",
"(",
"longitude",
")",
"central_lon",
"=",
"zone_number_to_central_longitude",
"(",
"zone_number",
")",
"central_lon_rad",
"=",
"mathlib",
".",
"radians",
"(",
"central_lon",
")",
"n",
"=",
"R",
"/",
"mathlib",
".",
"sqrt",
"(",
"1",
"-",
"E",
"*",
"lat_sin",
"**",
"2",
")",
"c",
"=",
"E_P2",
"*",
"lat_cos",
"**",
"2",
"a",
"=",
"lat_cos",
"*",
"(",
"lon_rad",
"-",
"central_lon_rad",
")",
"a2",
"=",
"a",
"*",
"a",
"a3",
"=",
"a2",
"*",
"a",
"a4",
"=",
"a3",
"*",
"a",
"a5",
"=",
"a4",
"*",
"a",
"a6",
"=",
"a5",
"*",
"a",
"m",
"=",
"R",
"*",
"(",
"M1",
"*",
"lat_rad",
"-",
"M2",
"*",
"mathlib",
".",
"sin",
"(",
"2",
"*",
"lat_rad",
")",
"+",
"M3",
"*",
"mathlib",
".",
"sin",
"(",
"4",
"*",
"lat_rad",
")",
"-",
"M4",
"*",
"mathlib",
".",
"sin",
"(",
"6",
"*",
"lat_rad",
")",
")",
"easting",
"=",
"K0",
"*",
"n",
"*",
"(",
"a",
"+",
"a3",
"/",
"6",
"*",
"(",
"1",
"-",
"lat_tan2",
"+",
"c",
")",
"+",
"a5",
"/",
"120",
"*",
"(",
"5",
"-",
"18",
"*",
"lat_tan2",
"+",
"lat_tan4",
"+",
"72",
"*",
"c",
"-",
"58",
"*",
"E_P2",
")",
")",
"+",
"500000",
"northing",
"=",
"K0",
"*",
"(",
"m",
"+",
"n",
"*",
"lat_tan",
"*",
"(",
"a2",
"/",
"2",
"+",
"a4",
"/",
"24",
"*",
"(",
"5",
"-",
"lat_tan2",
"+",
"9",
"*",
"c",
"+",
"4",
"*",
"c",
"**",
"2",
")",
"+",
"a6",
"/",
"720",
"*",
"(",
"61",
"-",
"58",
"*",
"lat_tan2",
"+",
"lat_tan4",
"+",
"600",
"*",
"c",
"-",
"330",
"*",
"E_P2",
")",
")",
")",
"if",
"mixed_signs",
"(",
"latitude",
")",
":",
"raise",
"ValueError",
"(",
"\"latitudes must all have the same sign\"",
")",
"elif",
"negative",
"(",
"latitude",
")",
":",
"northing",
"+=",
"10000000",
"return",
"easting",
",",
"northing",
",",
"zone_number",
",",
"zone_letter"
] |
This function convert Latitude and Longitude to UTM coordinate
Parameters
----------
latitude: float
Latitude between 80 deg S and 84 deg N, e.g. (-80.0 to 84.0)
longitude: float
Longitude between 180 deg W and 180 deg E, e.g. (-180.0 to 180.0).
force_zone number: int
Zone Number is represented with global map numbers of an UTM Zone
Numbers Map. You may force conversion including one UTM Zone Number.
More information see utmzones [1]_
.. _[1]: http://www.jaworski.ca/utmzones.htm
|
[
"This",
"function",
"convert",
"Latitude",
"and",
"Longitude",
"to",
"UTM",
"coordinate"
] |
efdd46ab0a341ce2aa45f8144d8b05a4fa0fd592
|
https://github.com/Turbo87/utm/blob/efdd46ab0a341ce2aa45f8144d8b05a4fa0fd592/utm/conversion.py#L171-L246
|
11,734
|
uber/doubles
|
doubles/patch.py
|
Patch._capture_original_object
|
def _capture_original_object(self):
"""Capture the original python object."""
try:
self._doubles_target = getattr(self.target, self._name)
except AttributeError:
raise VerifyingDoubleError(self.target, self._name)
|
python
|
def _capture_original_object(self):
"""Capture the original python object."""
try:
self._doubles_target = getattr(self.target, self._name)
except AttributeError:
raise VerifyingDoubleError(self.target, self._name)
|
[
"def",
"_capture_original_object",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_doubles_target",
"=",
"getattr",
"(",
"self",
".",
"target",
",",
"self",
".",
"_name",
")",
"except",
"AttributeError",
":",
"raise",
"VerifyingDoubleError",
"(",
"self",
".",
"target",
",",
"self",
".",
"_name",
")"
] |
Capture the original python object.
|
[
"Capture",
"the",
"original",
"python",
"object",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/patch.py#L18-L23
|
11,735
|
uber/doubles
|
doubles/patch.py
|
Patch.set_value
|
def set_value(self, value):
"""Set the value of the target.
:param obj value: The value to set.
"""
self._value = value
setattr(self.target, self._name, value)
|
python
|
def set_value(self, value):
"""Set the value of the target.
:param obj value: The value to set.
"""
self._value = value
setattr(self.target, self._name, value)
|
[
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_value",
"=",
"value",
"setattr",
"(",
"self",
".",
"target",
",",
"self",
".",
"_name",
",",
"value",
")"
] |
Set the value of the target.
:param obj value: The value to set.
|
[
"Set",
"the",
"value",
"of",
"the",
"target",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/patch.py#L25-L31
|
11,736
|
uber/doubles
|
doubles/class_double.py
|
patch_class
|
def patch_class(input_class):
"""Create a new class based on the input_class.
:param class input_class: The class to patch.
:rtype class:
"""
class Instantiator(object):
@classmethod
def _doubles__new__(self, *args, **kwargs):
pass
new_class = type(input_class.__name__, (input_class, Instantiator), {})
return new_class
|
python
|
def patch_class(input_class):
"""Create a new class based on the input_class.
:param class input_class: The class to patch.
:rtype class:
"""
class Instantiator(object):
@classmethod
def _doubles__new__(self, *args, **kwargs):
pass
new_class = type(input_class.__name__, (input_class, Instantiator), {})
return new_class
|
[
"def",
"patch_class",
"(",
"input_class",
")",
":",
"class",
"Instantiator",
"(",
"object",
")",
":",
"@",
"classmethod",
"def",
"_doubles__new__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pass",
"new_class",
"=",
"type",
"(",
"input_class",
".",
"__name__",
",",
"(",
"input_class",
",",
"Instantiator",
")",
",",
"{",
"}",
")",
"return",
"new_class"
] |
Create a new class based on the input_class.
:param class input_class: The class to patch.
:rtype class:
|
[
"Create",
"a",
"new",
"class",
"based",
"on",
"the",
"input_class",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/class_double.py#L7-L20
|
11,737
|
uber/doubles
|
doubles/expectation.py
|
Expectation.satisfy_any_args_match
|
def satisfy_any_args_match(self):
"""
Returns a boolean indicating whether or not the mock will accept arbitrary arguments.
This will be true unless the user has specified otherwise using ``with_args`` or
``with_no_args``.
:return: Whether or not the mock accepts arbitrary arguments.
:rtype: bool
"""
is_match = super(Expectation, self).satisfy_any_args_match()
if is_match:
self._satisfy()
return is_match
|
python
|
def satisfy_any_args_match(self):
"""
Returns a boolean indicating whether or not the mock will accept arbitrary arguments.
This will be true unless the user has specified otherwise using ``with_args`` or
``with_no_args``.
:return: Whether or not the mock accepts arbitrary arguments.
:rtype: bool
"""
is_match = super(Expectation, self).satisfy_any_args_match()
if is_match:
self._satisfy()
return is_match
|
[
"def",
"satisfy_any_args_match",
"(",
"self",
")",
":",
"is_match",
"=",
"super",
"(",
"Expectation",
",",
"self",
")",
".",
"satisfy_any_args_match",
"(",
")",
"if",
"is_match",
":",
"self",
".",
"_satisfy",
"(",
")",
"return",
"is_match"
] |
Returns a boolean indicating whether or not the mock will accept arbitrary arguments.
This will be true unless the user has specified otherwise using ``with_args`` or
``with_no_args``.
:return: Whether or not the mock accepts arbitrary arguments.
:rtype: bool
|
[
"Returns",
"a",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"mock",
"will",
"accept",
"arbitrary",
"arguments",
".",
"This",
"will",
"be",
"true",
"unless",
"the",
"user",
"has",
"specified",
"otherwise",
"using",
"with_args",
"or",
"with_no_args",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/expectation.py#L17-L32
|
11,738
|
uber/doubles
|
doubles/expectation.py
|
Expectation.is_satisfied
|
def is_satisfied(self):
"""
Returns a boolean indicating whether or not the double has been satisfied. Stubs are
always satisfied, but mocks are only satisfied if they've been called as was declared,
or if call is expected not to happen.
:return: Whether or not the double is satisfied.
:rtype: bool
"""
return self._call_counter.has_correct_call_count() and (
self._call_counter.never() or self._is_satisfied)
|
python
|
def is_satisfied(self):
"""
Returns a boolean indicating whether or not the double has been satisfied. Stubs are
always satisfied, but mocks are only satisfied if they've been called as was declared,
or if call is expected not to happen.
:return: Whether or not the double is satisfied.
:rtype: bool
"""
return self._call_counter.has_correct_call_count() and (
self._call_counter.never() or self._is_satisfied)
|
[
"def",
"is_satisfied",
"(",
"self",
")",
":",
"return",
"self",
".",
"_call_counter",
".",
"has_correct_call_count",
"(",
")",
"and",
"(",
"self",
".",
"_call_counter",
".",
"never",
"(",
")",
"or",
"self",
".",
"_is_satisfied",
")"
] |
Returns a boolean indicating whether or not the double has been satisfied. Stubs are
always satisfied, but mocks are only satisfied if they've been called as was declared,
or if call is expected not to happen.
:return: Whether or not the double is satisfied.
:rtype: bool
|
[
"Returns",
"a",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"double",
"has",
"been",
"satisfied",
".",
"Stubs",
"are",
"always",
"satisfied",
"but",
"mocks",
"are",
"only",
"satisfied",
"if",
"they",
"ve",
"been",
"called",
"as",
"was",
"declared",
"or",
"if",
"call",
"is",
"expected",
"not",
"to",
"happen",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/expectation.py#L79-L90
|
11,739
|
uber/doubles
|
doubles/call_count_accumulator.py
|
CallCountAccumulator.has_too_many_calls
|
def has_too_many_calls(self):
"""Test if there have been too many calls
:rtype boolean
"""
if self.has_exact and self._call_count > self._exact:
return True
if self.has_maximum and self._call_count > self._maximum:
return True
return False
|
python
|
def has_too_many_calls(self):
"""Test if there have been too many calls
:rtype boolean
"""
if self.has_exact and self._call_count > self._exact:
return True
if self.has_maximum and self._call_count > self._maximum:
return True
return False
|
[
"def",
"has_too_many_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_exact",
"and",
"self",
".",
"_call_count",
">",
"self",
".",
"_exact",
":",
"return",
"True",
"if",
"self",
".",
"has_maximum",
"and",
"self",
".",
"_call_count",
">",
"self",
".",
"_maximum",
":",
"return",
"True",
"return",
"False"
] |
Test if there have been too many calls
:rtype boolean
|
[
"Test",
"if",
"there",
"have",
"been",
"too",
"many",
"calls"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/call_count_accumulator.py#L33-L43
|
11,740
|
uber/doubles
|
doubles/call_count_accumulator.py
|
CallCountAccumulator.has_too_few_calls
|
def has_too_few_calls(self):
"""Test if there have not been enough calls
:rtype boolean
"""
if self.has_exact and self._call_count < self._exact:
return True
if self.has_minimum and self._call_count < self._minimum:
return True
return False
|
python
|
def has_too_few_calls(self):
"""Test if there have not been enough calls
:rtype boolean
"""
if self.has_exact and self._call_count < self._exact:
return True
if self.has_minimum and self._call_count < self._minimum:
return True
return False
|
[
"def",
"has_too_few_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_exact",
"and",
"self",
".",
"_call_count",
"<",
"self",
".",
"_exact",
":",
"return",
"True",
"if",
"self",
".",
"has_minimum",
"and",
"self",
".",
"_call_count",
"<",
"self",
".",
"_minimum",
":",
"return",
"True",
"return",
"False"
] |
Test if there have not been enough calls
:rtype boolean
|
[
"Test",
"if",
"there",
"have",
"not",
"been",
"enough",
"calls"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/call_count_accumulator.py#L45-L55
|
11,741
|
uber/doubles
|
doubles/call_count_accumulator.py
|
CallCountAccumulator._restriction_string
|
def _restriction_string(self):
"""Get a string explaining the expectation currently set
e.g `at least 5 times`, `at most 1 time`, or `2 times`
:rtype string
"""
if self.has_minimum:
string = 'at least '
value = self._minimum
elif self.has_maximum:
string = 'at most '
value = self._maximum
elif self.has_exact:
string = ''
value = self._exact
return (string + '{} {}').format(
value,
pluralize('time', value)
)
|
python
|
def _restriction_string(self):
"""Get a string explaining the expectation currently set
e.g `at least 5 times`, `at most 1 time`, or `2 times`
:rtype string
"""
if self.has_minimum:
string = 'at least '
value = self._minimum
elif self.has_maximum:
string = 'at most '
value = self._maximum
elif self.has_exact:
string = ''
value = self._exact
return (string + '{} {}').format(
value,
pluralize('time', value)
)
|
[
"def",
"_restriction_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_minimum",
":",
"string",
"=",
"'at least '",
"value",
"=",
"self",
".",
"_minimum",
"elif",
"self",
".",
"has_maximum",
":",
"string",
"=",
"'at most '",
"value",
"=",
"self",
".",
"_maximum",
"elif",
"self",
".",
"has_exact",
":",
"string",
"=",
"''",
"value",
"=",
"self",
".",
"_exact",
"return",
"(",
"string",
"+",
"'{} {}'",
")",
".",
"format",
"(",
"value",
",",
"pluralize",
"(",
"'time'",
",",
"value",
")",
")"
] |
Get a string explaining the expectation currently set
e.g `at least 5 times`, `at most 1 time`, or `2 times`
:rtype string
|
[
"Get",
"a",
"string",
"explaining",
"the",
"expectation",
"currently",
"set"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/call_count_accumulator.py#L123-L144
|
11,742
|
uber/doubles
|
doubles/call_count_accumulator.py
|
CallCountAccumulator.error_string
|
def error_string(self):
"""Returns a well formed error message
e.g at least 5 times but was called 4 times
:rtype string
"""
if self.has_correct_call_count():
return ''
return '{} instead of {} {} '.format(
self._restriction_string(),
self.count,
pluralize('time', self.count)
)
|
python
|
def error_string(self):
"""Returns a well formed error message
e.g at least 5 times but was called 4 times
:rtype string
"""
if self.has_correct_call_count():
return ''
return '{} instead of {} {} '.format(
self._restriction_string(),
self.count,
pluralize('time', self.count)
)
|
[
"def",
"error_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_correct_call_count",
"(",
")",
":",
"return",
"''",
"return",
"'{} instead of {} {} '",
".",
"format",
"(",
"self",
".",
"_restriction_string",
"(",
")",
",",
"self",
".",
"count",
",",
"pluralize",
"(",
"'time'",
",",
"self",
".",
"count",
")",
")"
] |
Returns a well formed error message
e.g at least 5 times but was called 4 times
:rtype string
|
[
"Returns",
"a",
"well",
"formed",
"error",
"message"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/call_count_accumulator.py#L146-L161
|
11,743
|
uber/doubles
|
doubles/space.py
|
Space.patch_for
|
def patch_for(self, path):
"""Returns the ``Patch`` for the target path, creating it if necessary.
:param str path: The absolute module path to the target.
:return: The mapped ``Patch``.
:rtype: Patch
"""
if path not in self._patches:
self._patches[path] = Patch(path)
return self._patches[path]
|
python
|
def patch_for(self, path):
"""Returns the ``Patch`` for the target path, creating it if necessary.
:param str path: The absolute module path to the target.
:return: The mapped ``Patch``.
:rtype: Patch
"""
if path not in self._patches:
self._patches[path] = Patch(path)
return self._patches[path]
|
[
"def",
"patch_for",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"_patches",
":",
"self",
".",
"_patches",
"[",
"path",
"]",
"=",
"Patch",
"(",
"path",
")",
"return",
"self",
".",
"_patches",
"[",
"path",
"]"
] |
Returns the ``Patch`` for the target path, creating it if necessary.
:param str path: The absolute module path to the target.
:return: The mapped ``Patch``.
:rtype: Patch
|
[
"Returns",
"the",
"Patch",
"for",
"the",
"target",
"path",
"creating",
"it",
"if",
"necessary",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/space.py#L18-L29
|
11,744
|
uber/doubles
|
doubles/space.py
|
Space.proxy_for
|
def proxy_for(self, obj):
"""Returns the ``Proxy`` for the target object, creating it if necessary.
:param object obj: The object that will be doubled.
:return: The mapped ``Proxy``.
:rtype: Proxy
"""
obj_id = id(obj)
if obj_id not in self._proxies:
self._proxies[obj_id] = Proxy(obj)
return self._proxies[obj_id]
|
python
|
def proxy_for(self, obj):
"""Returns the ``Proxy`` for the target object, creating it if necessary.
:param object obj: The object that will be doubled.
:return: The mapped ``Proxy``.
:rtype: Proxy
"""
obj_id = id(obj)
if obj_id not in self._proxies:
self._proxies[obj_id] = Proxy(obj)
return self._proxies[obj_id]
|
[
"def",
"proxy_for",
"(",
"self",
",",
"obj",
")",
":",
"obj_id",
"=",
"id",
"(",
"obj",
")",
"if",
"obj_id",
"not",
"in",
"self",
".",
"_proxies",
":",
"self",
".",
"_proxies",
"[",
"obj_id",
"]",
"=",
"Proxy",
"(",
"obj",
")",
"return",
"self",
".",
"_proxies",
"[",
"obj_id",
"]"
] |
Returns the ``Proxy`` for the target object, creating it if necessary.
:param object obj: The object that will be doubled.
:return: The mapped ``Proxy``.
:rtype: Proxy
|
[
"Returns",
"the",
"Proxy",
"for",
"the",
"target",
"object",
"creating",
"it",
"if",
"necessary",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/space.py#L31-L44
|
11,745
|
uber/doubles
|
doubles/space.py
|
Space.teardown
|
def teardown(self):
"""Restores all doubled objects to their original state."""
for proxy in self._proxies.values():
proxy.restore_original_object()
for patch in self._patches.values():
patch.restore_original_object()
|
python
|
def teardown(self):
"""Restores all doubled objects to their original state."""
for proxy in self._proxies.values():
proxy.restore_original_object()
for patch in self._patches.values():
patch.restore_original_object()
|
[
"def",
"teardown",
"(",
"self",
")",
":",
"for",
"proxy",
"in",
"self",
".",
"_proxies",
".",
"values",
"(",
")",
":",
"proxy",
".",
"restore_original_object",
"(",
")",
"for",
"patch",
"in",
"self",
".",
"_patches",
".",
"values",
"(",
")",
":",
"patch",
".",
"restore_original_object",
"(",
")"
] |
Restores all doubled objects to their original state.
|
[
"Restores",
"all",
"doubled",
"objects",
"to",
"their",
"original",
"state",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/space.py#L46-L53
|
11,746
|
uber/doubles
|
doubles/space.py
|
Space.verify
|
def verify(self):
"""Verifies expectations on all doubled objects.
:raise: ``MockExpectationError`` on the first expectation that is not satisfied, if any.
"""
if self._is_verified:
return
for proxy in self._proxies.values():
proxy.verify()
self._is_verified = True
|
python
|
def verify(self):
"""Verifies expectations on all doubled objects.
:raise: ``MockExpectationError`` on the first expectation that is not satisfied, if any.
"""
if self._is_verified:
return
for proxy in self._proxies.values():
proxy.verify()
self._is_verified = True
|
[
"def",
"verify",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_verified",
":",
"return",
"for",
"proxy",
"in",
"self",
".",
"_proxies",
".",
"values",
"(",
")",
":",
"proxy",
".",
"verify",
"(",
")",
"self",
".",
"_is_verified",
"=",
"True"
] |
Verifies expectations on all doubled objects.
:raise: ``MockExpectationError`` on the first expectation that is not satisfied, if any.
|
[
"Verifies",
"expectations",
"on",
"all",
"doubled",
"objects",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/space.py#L63-L75
|
11,747
|
uber/doubles
|
doubles/proxy_method.py
|
ProxyMethod.restore_original_method
|
def restore_original_method(self):
"""Replaces the proxy method on the target object with its original value."""
if self._target.is_class_or_module():
setattr(self._target.obj, self._method_name, self._original_method)
if self._method_name == '__new__' and sys.version_info >= (3, 0):
_restore__new__(self._target.obj, self._original_method)
else:
setattr(self._target.obj, self._method_name, self._original_method)
elif self._attr.kind == 'property':
setattr(self._target.obj.__class__, self._method_name, self._original_method)
del self._target.obj.__dict__[double_name(self._method_name)]
elif self._attr.kind == 'attribute':
self._target.obj.__dict__[self._method_name] = self._original_method
else:
# TODO: Could there ever have been a value here that needs to be restored?
del self._target.obj.__dict__[self._method_name]
if self._method_name in ['__call__', '__enter__', '__exit__']:
self._target.restore_attr(self._method_name)
|
python
|
def restore_original_method(self):
"""Replaces the proxy method on the target object with its original value."""
if self._target.is_class_or_module():
setattr(self._target.obj, self._method_name, self._original_method)
if self._method_name == '__new__' and sys.version_info >= (3, 0):
_restore__new__(self._target.obj, self._original_method)
else:
setattr(self._target.obj, self._method_name, self._original_method)
elif self._attr.kind == 'property':
setattr(self._target.obj.__class__, self._method_name, self._original_method)
del self._target.obj.__dict__[double_name(self._method_name)]
elif self._attr.kind == 'attribute':
self._target.obj.__dict__[self._method_name] = self._original_method
else:
# TODO: Could there ever have been a value here that needs to be restored?
del self._target.obj.__dict__[self._method_name]
if self._method_name in ['__call__', '__enter__', '__exit__']:
self._target.restore_attr(self._method_name)
|
[
"def",
"restore_original_method",
"(",
"self",
")",
":",
"if",
"self",
".",
"_target",
".",
"is_class_or_module",
"(",
")",
":",
"setattr",
"(",
"self",
".",
"_target",
".",
"obj",
",",
"self",
".",
"_method_name",
",",
"self",
".",
"_original_method",
")",
"if",
"self",
".",
"_method_name",
"==",
"'__new__'",
"and",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"_restore__new__",
"(",
"self",
".",
"_target",
".",
"obj",
",",
"self",
".",
"_original_method",
")",
"else",
":",
"setattr",
"(",
"self",
".",
"_target",
".",
"obj",
",",
"self",
".",
"_method_name",
",",
"self",
".",
"_original_method",
")",
"elif",
"self",
".",
"_attr",
".",
"kind",
"==",
"'property'",
":",
"setattr",
"(",
"self",
".",
"_target",
".",
"obj",
".",
"__class__",
",",
"self",
".",
"_method_name",
",",
"self",
".",
"_original_method",
")",
"del",
"self",
".",
"_target",
".",
"obj",
".",
"__dict__",
"[",
"double_name",
"(",
"self",
".",
"_method_name",
")",
"]",
"elif",
"self",
".",
"_attr",
".",
"kind",
"==",
"'attribute'",
":",
"self",
".",
"_target",
".",
"obj",
".",
"__dict__",
"[",
"self",
".",
"_method_name",
"]",
"=",
"self",
".",
"_original_method",
"else",
":",
"# TODO: Could there ever have been a value here that needs to be restored?",
"del",
"self",
".",
"_target",
".",
"obj",
".",
"__dict__",
"[",
"self",
".",
"_method_name",
"]",
"if",
"self",
".",
"_method_name",
"in",
"[",
"'__call__'",
",",
"'__enter__'",
",",
"'__exit__'",
"]",
":",
"self",
".",
"_target",
".",
"restore_attr",
"(",
"self",
".",
"_method_name",
")"
] |
Replaces the proxy method on the target object with its original value.
|
[
"Replaces",
"the",
"proxy",
"method",
"on",
"the",
"target",
"object",
"with",
"its",
"original",
"value",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/proxy_method.py#L105-L124
|
11,748
|
uber/doubles
|
doubles/proxy_method.py
|
ProxyMethod._hijack_target
|
def _hijack_target(self):
"""Replaces the target method on the target object with the proxy method."""
if self._target.is_class_or_module():
setattr(self._target.obj, self._method_name, self)
elif self._attr.kind == 'property':
proxy_property = ProxyProperty(
double_name(self._method_name),
self._original_method,
)
setattr(self._target.obj.__class__, self._method_name, proxy_property)
self._target.obj.__dict__[double_name(self._method_name)] = self
else:
self._target.obj.__dict__[self._method_name] = self
if self._method_name in ['__call__', '__enter__', '__exit__']:
self._target.hijack_attr(self._method_name)
|
python
|
def _hijack_target(self):
"""Replaces the target method on the target object with the proxy method."""
if self._target.is_class_or_module():
setattr(self._target.obj, self._method_name, self)
elif self._attr.kind == 'property':
proxy_property = ProxyProperty(
double_name(self._method_name),
self._original_method,
)
setattr(self._target.obj.__class__, self._method_name, proxy_property)
self._target.obj.__dict__[double_name(self._method_name)] = self
else:
self._target.obj.__dict__[self._method_name] = self
if self._method_name in ['__call__', '__enter__', '__exit__']:
self._target.hijack_attr(self._method_name)
|
[
"def",
"_hijack_target",
"(",
"self",
")",
":",
"if",
"self",
".",
"_target",
".",
"is_class_or_module",
"(",
")",
":",
"setattr",
"(",
"self",
".",
"_target",
".",
"obj",
",",
"self",
".",
"_method_name",
",",
"self",
")",
"elif",
"self",
".",
"_attr",
".",
"kind",
"==",
"'property'",
":",
"proxy_property",
"=",
"ProxyProperty",
"(",
"double_name",
"(",
"self",
".",
"_method_name",
")",
",",
"self",
".",
"_original_method",
",",
")",
"setattr",
"(",
"self",
".",
"_target",
".",
"obj",
".",
"__class__",
",",
"self",
".",
"_method_name",
",",
"proxy_property",
")",
"self",
".",
"_target",
".",
"obj",
".",
"__dict__",
"[",
"double_name",
"(",
"self",
".",
"_method_name",
")",
"]",
"=",
"self",
"else",
":",
"self",
".",
"_target",
".",
"obj",
".",
"__dict__",
"[",
"self",
".",
"_method_name",
"]",
"=",
"self",
"if",
"self",
".",
"_method_name",
"in",
"[",
"'__call__'",
",",
"'__enter__'",
",",
"'__exit__'",
"]",
":",
"self",
".",
"_target",
".",
"hijack_attr",
"(",
"self",
".",
"_method_name",
")"
] |
Replaces the target method on the target object with the proxy method.
|
[
"Replaces",
"the",
"target",
"method",
"on",
"the",
"target",
"object",
"with",
"the",
"proxy",
"method",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/proxy_method.py#L131-L147
|
11,749
|
uber/doubles
|
doubles/proxy_method.py
|
ProxyMethod._raise_exception
|
def _raise_exception(self, args, kwargs):
""" Raises an ``UnallowedMethodCallError`` with a useful message.
:raise: ``UnallowedMethodCallError``
"""
error_message = (
"Received unexpected call to '{}' on {!r}. The supplied arguments "
"{} do not match any available allowances."
)
raise UnallowedMethodCallError(
error_message.format(
self._method_name,
self._target.obj,
build_argument_repr_string(args, kwargs)
)
)
|
python
|
def _raise_exception(self, args, kwargs):
""" Raises an ``UnallowedMethodCallError`` with a useful message.
:raise: ``UnallowedMethodCallError``
"""
error_message = (
"Received unexpected call to '{}' on {!r}. The supplied arguments "
"{} do not match any available allowances."
)
raise UnallowedMethodCallError(
error_message.format(
self._method_name,
self._target.obj,
build_argument_repr_string(args, kwargs)
)
)
|
[
"def",
"_raise_exception",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"error_message",
"=",
"(",
"\"Received unexpected call to '{}' on {!r}. The supplied arguments \"",
"\"{} do not match any available allowances.\"",
")",
"raise",
"UnallowedMethodCallError",
"(",
"error_message",
".",
"format",
"(",
"self",
".",
"_method_name",
",",
"self",
".",
"_target",
".",
"obj",
",",
"build_argument_repr_string",
"(",
"args",
",",
"kwargs",
")",
")",
")"
] |
Raises an ``UnallowedMethodCallError`` with a useful message.
:raise: ``UnallowedMethodCallError``
|
[
"Raises",
"an",
"UnallowedMethodCallError",
"with",
"a",
"useful",
"message",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/proxy_method.py#L149-L166
|
11,750
|
uber/doubles
|
doubles/proxy.py
|
Proxy.method_double_for
|
def method_double_for(self, method_name):
"""Returns the method double for the provided method name, creating one if necessary.
:param str method_name: The name of the method to retrieve a method double for.
:return: The mapped ``MethodDouble``.
:rtype: MethodDouble
"""
if method_name not in self._method_doubles:
self._method_doubles[method_name] = MethodDouble(method_name, self._target)
return self._method_doubles[method_name]
|
python
|
def method_double_for(self, method_name):
"""Returns the method double for the provided method name, creating one if necessary.
:param str method_name: The name of the method to retrieve a method double for.
:return: The mapped ``MethodDouble``.
:rtype: MethodDouble
"""
if method_name not in self._method_doubles:
self._method_doubles[method_name] = MethodDouble(method_name, self._target)
return self._method_doubles[method_name]
|
[
"def",
"method_double_for",
"(",
"self",
",",
"method_name",
")",
":",
"if",
"method_name",
"not",
"in",
"self",
".",
"_method_doubles",
":",
"self",
".",
"_method_doubles",
"[",
"method_name",
"]",
"=",
"MethodDouble",
"(",
"method_name",
",",
"self",
".",
"_target",
")",
"return",
"self",
".",
"_method_doubles",
"[",
"method_name",
"]"
] |
Returns the method double for the provided method name, creating one if necessary.
:param str method_name: The name of the method to retrieve a method double for.
:return: The mapped ``MethodDouble``.
:rtype: MethodDouble
|
[
"Returns",
"the",
"method",
"double",
"for",
"the",
"provided",
"method",
"name",
"creating",
"one",
"if",
"necessary",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/proxy.py#L58-L69
|
11,751
|
uber/doubles
|
doubles/instance_double.py
|
_get_doubles_target
|
def _get_doubles_target(module, class_name, path):
"""Validate and return the class to be doubled.
:param module module: The module that contains the class that will be doubled.
:param str class_name: The name of the class that will be doubled.
:param str path: The full path to the class that will be doubled.
:return: The class that will be doubled.
:rtype: type
:raise: ``VerifyingDoubleImportError`` if the target object doesn't exist or isn't a class.
"""
try:
doubles_target = getattr(module, class_name)
if isinstance(doubles_target, ObjectDouble):
return doubles_target._doubles_target
if not isclass(doubles_target):
raise VerifyingDoubleImportError(
'Path does not point to a class: {}.'.format(path)
)
return doubles_target
except AttributeError:
raise VerifyingDoubleImportError(
'No object at path: {}.'.format(path)
)
|
python
|
def _get_doubles_target(module, class_name, path):
"""Validate and return the class to be doubled.
:param module module: The module that contains the class that will be doubled.
:param str class_name: The name of the class that will be doubled.
:param str path: The full path to the class that will be doubled.
:return: The class that will be doubled.
:rtype: type
:raise: ``VerifyingDoubleImportError`` if the target object doesn't exist or isn't a class.
"""
try:
doubles_target = getattr(module, class_name)
if isinstance(doubles_target, ObjectDouble):
return doubles_target._doubles_target
if not isclass(doubles_target):
raise VerifyingDoubleImportError(
'Path does not point to a class: {}.'.format(path)
)
return doubles_target
except AttributeError:
raise VerifyingDoubleImportError(
'No object at path: {}.'.format(path)
)
|
[
"def",
"_get_doubles_target",
"(",
"module",
",",
"class_name",
",",
"path",
")",
":",
"try",
":",
"doubles_target",
"=",
"getattr",
"(",
"module",
",",
"class_name",
")",
"if",
"isinstance",
"(",
"doubles_target",
",",
"ObjectDouble",
")",
":",
"return",
"doubles_target",
".",
"_doubles_target",
"if",
"not",
"isclass",
"(",
"doubles_target",
")",
":",
"raise",
"VerifyingDoubleImportError",
"(",
"'Path does not point to a class: {}.'",
".",
"format",
"(",
"path",
")",
")",
"return",
"doubles_target",
"except",
"AttributeError",
":",
"raise",
"VerifyingDoubleImportError",
"(",
"'No object at path: {}.'",
".",
"format",
"(",
"path",
")",
")"
] |
Validate and return the class to be doubled.
:param module module: The module that contains the class that will be doubled.
:param str class_name: The name of the class that will be doubled.
:param str path: The full path to the class that will be doubled.
:return: The class that will be doubled.
:rtype: type
:raise: ``VerifyingDoubleImportError`` if the target object doesn't exist or isn't a class.
|
[
"Validate",
"and",
"return",
"the",
"class",
"to",
"be",
"doubled",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/instance_double.py#L8-L33
|
11,752
|
uber/doubles
|
doubles/allowance.py
|
Allowance.and_raise
|
def and_raise(self, exception, *args, **kwargs):
"""Causes the double to raise the provided exception when called.
If provided, additional arguments (positional and keyword) passed to
`and_raise` are used in the exception instantiation.
:param Exception exception: The exception to raise.
"""
def proxy_exception(*proxy_args, **proxy_kwargs):
raise exception
self._return_value = proxy_exception
return self
|
python
|
def and_raise(self, exception, *args, **kwargs):
"""Causes the double to raise the provided exception when called.
If provided, additional arguments (positional and keyword) passed to
`and_raise` are used in the exception instantiation.
:param Exception exception: The exception to raise.
"""
def proxy_exception(*proxy_args, **proxy_kwargs):
raise exception
self._return_value = proxy_exception
return self
|
[
"def",
"and_raise",
"(",
"self",
",",
"exception",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"proxy_exception",
"(",
"*",
"proxy_args",
",",
"*",
"*",
"proxy_kwargs",
")",
":",
"raise",
"exception",
"self",
".",
"_return_value",
"=",
"proxy_exception",
"return",
"self"
] |
Causes the double to raise the provided exception when called.
If provided, additional arguments (positional and keyword) passed to
`and_raise` are used in the exception instantiation.
:param Exception exception: The exception to raise.
|
[
"Causes",
"the",
"double",
"to",
"raise",
"the",
"provided",
"exception",
"when",
"called",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L71-L83
|
11,753
|
uber/doubles
|
doubles/allowance.py
|
Allowance.and_raise_future
|
def and_raise_future(self, exception):
"""Similar to `and_raise` but the doubled method returns a future.
:param Exception exception: The exception to raise.
"""
future = _get_future()
future.set_exception(exception)
return self.and_return(future)
|
python
|
def and_raise_future(self, exception):
"""Similar to `and_raise` but the doubled method returns a future.
:param Exception exception: The exception to raise.
"""
future = _get_future()
future.set_exception(exception)
return self.and_return(future)
|
[
"def",
"and_raise_future",
"(",
"self",
",",
"exception",
")",
":",
"future",
"=",
"_get_future",
"(",
")",
"future",
".",
"set_exception",
"(",
"exception",
")",
"return",
"self",
".",
"and_return",
"(",
"future",
")"
] |
Similar to `and_raise` but the doubled method returns a future.
:param Exception exception: The exception to raise.
|
[
"Similar",
"to",
"and_raise",
"but",
"the",
"doubled",
"method",
"returns",
"a",
"future",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L85-L92
|
11,754
|
uber/doubles
|
doubles/allowance.py
|
Allowance.and_return_future
|
def and_return_future(self, *return_values):
"""Similar to `and_return` but the doubled method returns a future.
:param object return_values: The values the double will return when called,
"""
futures = []
for value in return_values:
future = _get_future()
future.set_result(value)
futures.append(future)
return self.and_return(*futures)
|
python
|
def and_return_future(self, *return_values):
"""Similar to `and_return` but the doubled method returns a future.
:param object return_values: The values the double will return when called,
"""
futures = []
for value in return_values:
future = _get_future()
future.set_result(value)
futures.append(future)
return self.and_return(*futures)
|
[
"def",
"and_return_future",
"(",
"self",
",",
"*",
"return_values",
")",
":",
"futures",
"=",
"[",
"]",
"for",
"value",
"in",
"return_values",
":",
"future",
"=",
"_get_future",
"(",
")",
"future",
".",
"set_result",
"(",
"value",
")",
"futures",
".",
"append",
"(",
"future",
")",
"return",
"self",
".",
"and_return",
"(",
"*",
"futures",
")"
] |
Similar to `and_return` but the doubled method returns a future.
:param object return_values: The values the double will return when called,
|
[
"Similar",
"to",
"and_return",
"but",
"the",
"doubled",
"method",
"returns",
"a",
"future",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L94-L104
|
11,755
|
uber/doubles
|
doubles/allowance.py
|
Allowance.and_return
|
def and_return(self, *return_values):
"""Set a return value for an allowance
Causes the double to return the provided values in order. If multiple
values are provided, they are returned one at a time in sequence as the double is called.
If the double is called more times than there are return values, it should continue to
return the last value in the list.
:param object return_values: The values the double will return when called,
"""
if not return_values:
raise TypeError('and_return() expected at least 1 return value')
return_values = list(return_values)
final_value = return_values.pop()
self.and_return_result_of(
lambda: return_values.pop(0) if return_values else final_value
)
return self
|
python
|
def and_return(self, *return_values):
"""Set a return value for an allowance
Causes the double to return the provided values in order. If multiple
values are provided, they are returned one at a time in sequence as the double is called.
If the double is called more times than there are return values, it should continue to
return the last value in the list.
:param object return_values: The values the double will return when called,
"""
if not return_values:
raise TypeError('and_return() expected at least 1 return value')
return_values = list(return_values)
final_value = return_values.pop()
self.and_return_result_of(
lambda: return_values.pop(0) if return_values else final_value
)
return self
|
[
"def",
"and_return",
"(",
"self",
",",
"*",
"return_values",
")",
":",
"if",
"not",
"return_values",
":",
"raise",
"TypeError",
"(",
"'and_return() expected at least 1 return value'",
")",
"return_values",
"=",
"list",
"(",
"return_values",
")",
"final_value",
"=",
"return_values",
".",
"pop",
"(",
")",
"self",
".",
"and_return_result_of",
"(",
"lambda",
":",
"return_values",
".",
"pop",
"(",
"0",
")",
"if",
"return_values",
"else",
"final_value",
")",
"return",
"self"
] |
Set a return value for an allowance
Causes the double to return the provided values in order. If multiple
values are provided, they are returned one at a time in sequence as the double is called.
If the double is called more times than there are return values, it should continue to
return the last value in the list.
:param object return_values: The values the double will return when called,
|
[
"Set",
"a",
"return",
"value",
"for",
"an",
"allowance"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L106-L127
|
11,756
|
uber/doubles
|
doubles/allowance.py
|
Allowance.and_return_result_of
|
def and_return_result_of(self, return_value):
""" Causes the double to return the result of calling the provided value.
:param return_value: A callable that will be invoked to determine the double's return value.
:type return_value: any callable object
"""
if not check_func_takes_args(return_value):
self._return_value = lambda *args, **kwargs: return_value()
else:
self._return_value = return_value
return self
|
python
|
def and_return_result_of(self, return_value):
""" Causes the double to return the result of calling the provided value.
:param return_value: A callable that will be invoked to determine the double's return value.
:type return_value: any callable object
"""
if not check_func_takes_args(return_value):
self._return_value = lambda *args, **kwargs: return_value()
else:
self._return_value = return_value
return self
|
[
"def",
"and_return_result_of",
"(",
"self",
",",
"return_value",
")",
":",
"if",
"not",
"check_func_takes_args",
"(",
"return_value",
")",
":",
"self",
".",
"_return_value",
"=",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"return_value",
"(",
")",
"else",
":",
"self",
".",
"_return_value",
"=",
"return_value",
"return",
"self"
] |
Causes the double to return the result of calling the provided value.
:param return_value: A callable that will be invoked to determine the double's return value.
:type return_value: any callable object
|
[
"Causes",
"the",
"double",
"to",
"return",
"the",
"result",
"of",
"calling",
"the",
"provided",
"value",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L129-L140
|
11,757
|
uber/doubles
|
doubles/allowance.py
|
Allowance.with_args
|
def with_args(self, *args, **kwargs):
"""Declares that the double can only be called with the provided arguments.
:param args: Any positional arguments required for invocation.
:param kwargs: Any keyword arguments required for invocation.
"""
self.args = args
self.kwargs = kwargs
self.verify_arguments()
return self
|
python
|
def with_args(self, *args, **kwargs):
"""Declares that the double can only be called with the provided arguments.
:param args: Any positional arguments required for invocation.
:param kwargs: Any keyword arguments required for invocation.
"""
self.args = args
self.kwargs = kwargs
self.verify_arguments()
return self
|
[
"def",
"with_args",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"args",
"=",
"args",
"self",
".",
"kwargs",
"=",
"kwargs",
"self",
".",
"verify_arguments",
"(",
")",
"return",
"self"
] |
Declares that the double can only be called with the provided arguments.
:param args: Any positional arguments required for invocation.
:param kwargs: Any keyword arguments required for invocation.
|
[
"Declares",
"that",
"the",
"double",
"can",
"only",
"be",
"called",
"with",
"the",
"provided",
"arguments",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L153-L163
|
11,758
|
uber/doubles
|
doubles/allowance.py
|
Allowance.with_args_validator
|
def with_args_validator(self, matching_function):
"""Define a custom function for testing arguments
:param func matching_function: The function used to test arguments passed to the stub.
"""
self.args = None
self.kwargs = None
self._custom_matcher = matching_function
return self
|
python
|
def with_args_validator(self, matching_function):
"""Define a custom function for testing arguments
:param func matching_function: The function used to test arguments passed to the stub.
"""
self.args = None
self.kwargs = None
self._custom_matcher = matching_function
return self
|
[
"def",
"with_args_validator",
"(",
"self",
",",
"matching_function",
")",
":",
"self",
".",
"args",
"=",
"None",
"self",
".",
"kwargs",
"=",
"None",
"self",
".",
"_custom_matcher",
"=",
"matching_function",
"return",
"self"
] |
Define a custom function for testing arguments
:param func matching_function: The function used to test arguments passed to the stub.
|
[
"Define",
"a",
"custom",
"function",
"for",
"testing",
"arguments"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L165-L173
|
11,759
|
uber/doubles
|
doubles/allowance.py
|
Allowance.satisfy_exact_match
|
def satisfy_exact_match(self, args, kwargs):
"""Returns a boolean indicating whether or not the stub will accept the provided arguments.
:return: Whether or not the stub accepts the provided arguments.
:rtype: bool
"""
if self.args is None and self.kwargs is None:
return False
elif self.args is _any and self.kwargs is _any:
return True
elif args == self.args and kwargs == self.kwargs:
return True
elif len(args) != len(self.args) or len(kwargs) != len(self.kwargs):
return False
if not all(x == y or y == x for x, y in zip(args, self.args)):
return False
for key, value in self.kwargs.items():
if key not in kwargs:
return False
elif not (kwargs[key] == value or value == kwargs[key]):
return False
return True
|
python
|
def satisfy_exact_match(self, args, kwargs):
"""Returns a boolean indicating whether or not the stub will accept the provided arguments.
:return: Whether or not the stub accepts the provided arguments.
:rtype: bool
"""
if self.args is None and self.kwargs is None:
return False
elif self.args is _any and self.kwargs is _any:
return True
elif args == self.args and kwargs == self.kwargs:
return True
elif len(args) != len(self.args) or len(kwargs) != len(self.kwargs):
return False
if not all(x == y or y == x for x, y in zip(args, self.args)):
return False
for key, value in self.kwargs.items():
if key not in kwargs:
return False
elif not (kwargs[key] == value or value == kwargs[key]):
return False
return True
|
[
"def",
"satisfy_exact_match",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"self",
".",
"args",
"is",
"None",
"and",
"self",
".",
"kwargs",
"is",
"None",
":",
"return",
"False",
"elif",
"self",
".",
"args",
"is",
"_any",
"and",
"self",
".",
"kwargs",
"is",
"_any",
":",
"return",
"True",
"elif",
"args",
"==",
"self",
".",
"args",
"and",
"kwargs",
"==",
"self",
".",
"kwargs",
":",
"return",
"True",
"elif",
"len",
"(",
"args",
")",
"!=",
"len",
"(",
"self",
".",
"args",
")",
"or",
"len",
"(",
"kwargs",
")",
"!=",
"len",
"(",
"self",
".",
"kwargs",
")",
":",
"return",
"False",
"if",
"not",
"all",
"(",
"x",
"==",
"y",
"or",
"y",
"==",
"x",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"args",
",",
"self",
".",
"args",
")",
")",
":",
"return",
"False",
"for",
"key",
",",
"value",
"in",
"self",
".",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"kwargs",
":",
"return",
"False",
"elif",
"not",
"(",
"kwargs",
"[",
"key",
"]",
"==",
"value",
"or",
"value",
"==",
"kwargs",
"[",
"key",
"]",
")",
":",
"return",
"False",
"return",
"True"
] |
Returns a boolean indicating whether or not the stub will accept the provided arguments.
:return: Whether or not the stub accepts the provided arguments.
:rtype: bool
|
[
"Returns",
"a",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"stub",
"will",
"accept",
"the",
"provided",
"arguments",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L208-L233
|
11,760
|
uber/doubles
|
doubles/allowance.py
|
Allowance.satisfy_custom_matcher
|
def satisfy_custom_matcher(self, args, kwargs):
"""Return a boolean indicating if the args satisfy the stub
:return: Whether or not the stub accepts the provided arguments.
:rtype: bool
"""
if not self._custom_matcher:
return False
try:
return self._custom_matcher(*args, **kwargs)
except Exception:
return False
|
python
|
def satisfy_custom_matcher(self, args, kwargs):
"""Return a boolean indicating if the args satisfy the stub
:return: Whether or not the stub accepts the provided arguments.
:rtype: bool
"""
if not self._custom_matcher:
return False
try:
return self._custom_matcher(*args, **kwargs)
except Exception:
return False
|
[
"def",
"satisfy_custom_matcher",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_custom_matcher",
":",
"return",
"False",
"try",
":",
"return",
"self",
".",
"_custom_matcher",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"return",
"False"
] |
Return a boolean indicating if the args satisfy the stub
:return: Whether or not the stub accepts the provided arguments.
:rtype: bool
|
[
"Return",
"a",
"boolean",
"indicating",
"if",
"the",
"args",
"satisfy",
"the",
"stub"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L235-L246
|
11,761
|
uber/doubles
|
doubles/allowance.py
|
Allowance.return_value
|
def return_value(self, *args, **kwargs):
"""Extracts the real value to be returned from the wrapping callable.
:return: The value the double should return when called.
"""
self._called()
return self._return_value(*args, **kwargs)
|
python
|
def return_value(self, *args, **kwargs):
"""Extracts the real value to be returned from the wrapping callable.
:return: The value the double should return when called.
"""
self._called()
return self._return_value(*args, **kwargs)
|
[
"def",
"return_value",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_called",
"(",
")",
"return",
"self",
".",
"_return_value",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Extracts the real value to be returned from the wrapping callable.
:return: The value the double should return when called.
|
[
"Extracts",
"the",
"real",
"value",
"to",
"be",
"returned",
"from",
"the",
"wrapping",
"callable",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L248-L255
|
11,762
|
uber/doubles
|
doubles/allowance.py
|
Allowance.verify_arguments
|
def verify_arguments(self, args=None, kwargs=None):
"""Ensures that the arguments specified match the signature of the real method.
:raise: ``VerifyingDoubleError`` if the arguments do not match.
"""
args = self.args if args is None else args
kwargs = self.kwargs if kwargs is None else kwargs
try:
verify_arguments(self._target, self._method_name, args, kwargs)
except VerifyingBuiltinDoubleArgumentError:
if doubles.lifecycle.ignore_builtin_verification():
raise
|
python
|
def verify_arguments(self, args=None, kwargs=None):
"""Ensures that the arguments specified match the signature of the real method.
:raise: ``VerifyingDoubleError`` if the arguments do not match.
"""
args = self.args if args is None else args
kwargs = self.kwargs if kwargs is None else kwargs
try:
verify_arguments(self._target, self._method_name, args, kwargs)
except VerifyingBuiltinDoubleArgumentError:
if doubles.lifecycle.ignore_builtin_verification():
raise
|
[
"def",
"verify_arguments",
"(",
"self",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"args",
"=",
"self",
".",
"args",
"if",
"args",
"is",
"None",
"else",
"args",
"kwargs",
"=",
"self",
".",
"kwargs",
"if",
"kwargs",
"is",
"None",
"else",
"kwargs",
"try",
":",
"verify_arguments",
"(",
"self",
".",
"_target",
",",
"self",
".",
"_method_name",
",",
"args",
",",
"kwargs",
")",
"except",
"VerifyingBuiltinDoubleArgumentError",
":",
"if",
"doubles",
".",
"lifecycle",
".",
"ignore_builtin_verification",
"(",
")",
":",
"raise"
] |
Ensures that the arguments specified match the signature of the real method.
:raise: ``VerifyingDoubleError`` if the arguments do not match.
|
[
"Ensures",
"that",
"the",
"arguments",
"specified",
"match",
"the",
"signature",
"of",
"the",
"real",
"method",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L257-L270
|
11,763
|
uber/doubles
|
doubles/allowance.py
|
Allowance.raise_failure_exception
|
def raise_failure_exception(self, expect_or_allow='Allowed'):
"""Raises a ``MockExpectationError`` with a useful message.
:raise: ``MockExpectationError``
"""
raise MockExpectationError(
"{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})".format(
expect_or_allow,
self._method_name,
self._call_counter.error_string(),
self._target.obj,
self._expected_argument_string(),
self._caller.filename,
self._caller.lineno,
)
)
|
python
|
def raise_failure_exception(self, expect_or_allow='Allowed'):
"""Raises a ``MockExpectationError`` with a useful message.
:raise: ``MockExpectationError``
"""
raise MockExpectationError(
"{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})".format(
expect_or_allow,
self._method_name,
self._call_counter.error_string(),
self._target.obj,
self._expected_argument_string(),
self._caller.filename,
self._caller.lineno,
)
)
|
[
"def",
"raise_failure_exception",
"(",
"self",
",",
"expect_or_allow",
"=",
"'Allowed'",
")",
":",
"raise",
"MockExpectationError",
"(",
"\"{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})\"",
".",
"format",
"(",
"expect_or_allow",
",",
"self",
".",
"_method_name",
",",
"self",
".",
"_call_counter",
".",
"error_string",
"(",
")",
",",
"self",
".",
"_target",
".",
"obj",
",",
"self",
".",
"_expected_argument_string",
"(",
")",
",",
"self",
".",
"_caller",
".",
"filename",
",",
"self",
".",
"_caller",
".",
"lineno",
",",
")",
")"
] |
Raises a ``MockExpectationError`` with a useful message.
:raise: ``MockExpectationError``
|
[
"Raises",
"a",
"MockExpectationError",
"with",
"a",
"useful",
"message",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L334-L350
|
11,764
|
uber/doubles
|
doubles/allowance.py
|
Allowance._expected_argument_string
|
def _expected_argument_string(self):
"""Generates a string describing what arguments the double expected.
:return: A string describing expected arguments.
:rtype: str
"""
if self.args is _any and self.kwargs is _any:
return 'any args'
elif self._custom_matcher:
return "custom matcher: '{}'".format(self._custom_matcher.__name__)
else:
return build_argument_repr_string(self.args, self.kwargs)
|
python
|
def _expected_argument_string(self):
"""Generates a string describing what arguments the double expected.
:return: A string describing expected arguments.
:rtype: str
"""
if self.args is _any and self.kwargs is _any:
return 'any args'
elif self._custom_matcher:
return "custom matcher: '{}'".format(self._custom_matcher.__name__)
else:
return build_argument_repr_string(self.args, self.kwargs)
|
[
"def",
"_expected_argument_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"args",
"is",
"_any",
"and",
"self",
".",
"kwargs",
"is",
"_any",
":",
"return",
"'any args'",
"elif",
"self",
".",
"_custom_matcher",
":",
"return",
"\"custom matcher: '{}'\"",
".",
"format",
"(",
"self",
".",
"_custom_matcher",
".",
"__name__",
")",
"else",
":",
"return",
"build_argument_repr_string",
"(",
"self",
".",
"args",
",",
"self",
".",
"kwargs",
")"
] |
Generates a string describing what arguments the double expected.
:return: A string describing expected arguments.
:rtype: str
|
[
"Generates",
"a",
"string",
"describing",
"what",
"arguments",
"the",
"double",
"expected",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L352-L364
|
11,765
|
uber/doubles
|
doubles/target.py
|
Target.is_class_or_module
|
def is_class_or_module(self):
"""Determines if the object is a class or a module
:return: True if the object is a class or a module, False otherwise.
:rtype: bool
"""
if isinstance(self.obj, ObjectDouble):
return self.obj.is_class
return isclass(self.doubled_obj) or ismodule(self.doubled_obj)
|
python
|
def is_class_or_module(self):
"""Determines if the object is a class or a module
:return: True if the object is a class or a module, False otherwise.
:rtype: bool
"""
if isinstance(self.obj, ObjectDouble):
return self.obj.is_class
return isclass(self.doubled_obj) or ismodule(self.doubled_obj)
|
[
"def",
"is_class_or_module",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"obj",
",",
"ObjectDouble",
")",
":",
"return",
"self",
".",
"obj",
".",
"is_class",
"return",
"isclass",
"(",
"self",
".",
"doubled_obj",
")",
"or",
"ismodule",
"(",
"self",
".",
"doubled_obj",
")"
] |
Determines if the object is a class or a module
:return: True if the object is a class or a module, False otherwise.
:rtype: bool
|
[
"Determines",
"if",
"the",
"object",
"is",
"a",
"class",
"or",
"a",
"module"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L36-L46
|
11,766
|
uber/doubles
|
doubles/target.py
|
Target._determine_doubled_obj
|
def _determine_doubled_obj(self):
"""Return the target object.
Returns the object that should be treated as the target object. For partial doubles, this
will be the same as ``self.obj``, but for pure doubles, it's pulled from the special
``_doubles_target`` attribute.
:return: The object to be doubled.
:rtype: object
"""
if isinstance(self.obj, ObjectDouble):
return self.obj._doubles_target
else:
return self.obj
|
python
|
def _determine_doubled_obj(self):
"""Return the target object.
Returns the object that should be treated as the target object. For partial doubles, this
will be the same as ``self.obj``, but for pure doubles, it's pulled from the special
``_doubles_target`` attribute.
:return: The object to be doubled.
:rtype: object
"""
if isinstance(self.obj, ObjectDouble):
return self.obj._doubles_target
else:
return self.obj
|
[
"def",
"_determine_doubled_obj",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"obj",
",",
"ObjectDouble",
")",
":",
"return",
"self",
".",
"obj",
".",
"_doubles_target",
"else",
":",
"return",
"self",
".",
"obj"
] |
Return the target object.
Returns the object that should be treated as the target object. For partial doubles, this
will be the same as ``self.obj``, but for pure doubles, it's pulled from the special
``_doubles_target`` attribute.
:return: The object to be doubled.
:rtype: object
|
[
"Return",
"the",
"target",
"object",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L48-L62
|
11,767
|
uber/doubles
|
doubles/target.py
|
Target._generate_attrs
|
def _generate_attrs(self):
"""Get detailed info about target object.
Uses ``inspect.classify_class_attrs`` to get several important details about each attribute
on the target object.
:return: The attribute details dict.
:rtype: dict
"""
attrs = {}
if ismodule(self.doubled_obj):
for name, func in getmembers(self.doubled_obj, is_callable):
attrs[name] = Attribute(func, 'toplevel', self.doubled_obj)
else:
for attr in classify_class_attrs(self.doubled_obj_type):
attrs[attr.name] = attr
return attrs
|
python
|
def _generate_attrs(self):
"""Get detailed info about target object.
Uses ``inspect.classify_class_attrs`` to get several important details about each attribute
on the target object.
:return: The attribute details dict.
:rtype: dict
"""
attrs = {}
if ismodule(self.doubled_obj):
for name, func in getmembers(self.doubled_obj, is_callable):
attrs[name] = Attribute(func, 'toplevel', self.doubled_obj)
else:
for attr in classify_class_attrs(self.doubled_obj_type):
attrs[attr.name] = attr
return attrs
|
[
"def",
"_generate_attrs",
"(",
"self",
")",
":",
"attrs",
"=",
"{",
"}",
"if",
"ismodule",
"(",
"self",
".",
"doubled_obj",
")",
":",
"for",
"name",
",",
"func",
"in",
"getmembers",
"(",
"self",
".",
"doubled_obj",
",",
"is_callable",
")",
":",
"attrs",
"[",
"name",
"]",
"=",
"Attribute",
"(",
"func",
",",
"'toplevel'",
",",
"self",
".",
"doubled_obj",
")",
"else",
":",
"for",
"attr",
"in",
"classify_class_attrs",
"(",
"self",
".",
"doubled_obj_type",
")",
":",
"attrs",
"[",
"attr",
".",
"name",
"]",
"=",
"attr",
"return",
"attrs"
] |
Get detailed info about target object.
Uses ``inspect.classify_class_attrs`` to get several important details about each attribute
on the target object.
:return: The attribute details dict.
:rtype: dict
|
[
"Get",
"detailed",
"info",
"about",
"target",
"object",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L76-L94
|
11,768
|
uber/doubles
|
doubles/target.py
|
Target.hijack_attr
|
def hijack_attr(self, attr_name):
"""Hijack an attribute on the target object.
Updates the underlying class and delegating the call to the instance.
This allows specially-handled attributes like __call__, __enter__,
and __exit__ to be mocked on a per-instance basis.
:param str attr_name: the name of the attribute to hijack
"""
if not self._original_attr(attr_name):
setattr(
self.obj.__class__,
attr_name,
_proxy_class_method_to_instance(
getattr(self.obj.__class__, attr_name, None), attr_name
),
)
|
python
|
def hijack_attr(self, attr_name):
"""Hijack an attribute on the target object.
Updates the underlying class and delegating the call to the instance.
This allows specially-handled attributes like __call__, __enter__,
and __exit__ to be mocked on a per-instance basis.
:param str attr_name: the name of the attribute to hijack
"""
if not self._original_attr(attr_name):
setattr(
self.obj.__class__,
attr_name,
_proxy_class_method_to_instance(
getattr(self.obj.__class__, attr_name, None), attr_name
),
)
|
[
"def",
"hijack_attr",
"(",
"self",
",",
"attr_name",
")",
":",
"if",
"not",
"self",
".",
"_original_attr",
"(",
"attr_name",
")",
":",
"setattr",
"(",
"self",
".",
"obj",
".",
"__class__",
",",
"attr_name",
",",
"_proxy_class_method_to_instance",
"(",
"getattr",
"(",
"self",
".",
"obj",
".",
"__class__",
",",
"attr_name",
",",
"None",
")",
",",
"attr_name",
")",
",",
")"
] |
Hijack an attribute on the target object.
Updates the underlying class and delegating the call to the instance.
This allows specially-handled attributes like __call__, __enter__,
and __exit__ to be mocked on a per-instance basis.
:param str attr_name: the name of the attribute to hijack
|
[
"Hijack",
"an",
"attribute",
"on",
"the",
"target",
"object",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L96-L112
|
11,769
|
uber/doubles
|
doubles/target.py
|
Target.restore_attr
|
def restore_attr(self, attr_name):
"""Restore an attribute back onto the target object.
:param str attr_name: the name of the attribute to restore
"""
original_attr = self._original_attr(attr_name)
if self._original_attr(attr_name):
setattr(self.obj.__class__, attr_name, original_attr)
|
python
|
def restore_attr(self, attr_name):
"""Restore an attribute back onto the target object.
:param str attr_name: the name of the attribute to restore
"""
original_attr = self._original_attr(attr_name)
if self._original_attr(attr_name):
setattr(self.obj.__class__, attr_name, original_attr)
|
[
"def",
"restore_attr",
"(",
"self",
",",
"attr_name",
")",
":",
"original_attr",
"=",
"self",
".",
"_original_attr",
"(",
"attr_name",
")",
"if",
"self",
".",
"_original_attr",
"(",
"attr_name",
")",
":",
"setattr",
"(",
"self",
".",
"obj",
".",
"__class__",
",",
"attr_name",
",",
"original_attr",
")"
] |
Restore an attribute back onto the target object.
:param str attr_name: the name of the attribute to restore
|
[
"Restore",
"an",
"attribute",
"back",
"onto",
"the",
"target",
"object",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L114-L121
|
11,770
|
uber/doubles
|
doubles/target.py
|
Target._original_attr
|
def _original_attr(self, attr_name):
"""Return the original attribute off of the proxy on the target object.
:param str attr_name: the name of the original attribute to return
:return: Func or None.
:rtype: func
"""
try:
return getattr(
getattr(self.obj.__class__, attr_name), '_doubles_target_method', None
)
except AttributeError:
return None
|
python
|
def _original_attr(self, attr_name):
"""Return the original attribute off of the proxy on the target object.
:param str attr_name: the name of the original attribute to return
:return: Func or None.
:rtype: func
"""
try:
return getattr(
getattr(self.obj.__class__, attr_name), '_doubles_target_method', None
)
except AttributeError:
return None
|
[
"def",
"_original_attr",
"(",
"self",
",",
"attr_name",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"getattr",
"(",
"self",
".",
"obj",
".",
"__class__",
",",
"attr_name",
")",
",",
"'_doubles_target_method'",
",",
"None",
")",
"except",
"AttributeError",
":",
"return",
"None"
] |
Return the original attribute off of the proxy on the target object.
:param str attr_name: the name of the original attribute to return
:return: Func or None.
:rtype: func
|
[
"Return",
"the",
"original",
"attribute",
"off",
"of",
"the",
"proxy",
"on",
"the",
"target",
"object",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L123-L135
|
11,771
|
uber/doubles
|
doubles/target.py
|
Target.get_callable_attr
|
def get_callable_attr(self, attr_name):
"""Used to double methods added to an object after creation
:param str attr_name: the name of the original attribute to return
:return: Attribute or None.
:rtype: func
"""
if not hasattr(self.doubled_obj, attr_name):
return None
func = getattr(self.doubled_obj, attr_name)
if not is_callable(func):
return None
attr = Attribute(
func,
'attribute',
self.doubled_obj if self.is_class_or_module() else self.doubled_obj_type,
)
self.attrs[attr_name] = attr
return attr
|
python
|
def get_callable_attr(self, attr_name):
"""Used to double methods added to an object after creation
:param str attr_name: the name of the original attribute to return
:return: Attribute or None.
:rtype: func
"""
if not hasattr(self.doubled_obj, attr_name):
return None
func = getattr(self.doubled_obj, attr_name)
if not is_callable(func):
return None
attr = Attribute(
func,
'attribute',
self.doubled_obj if self.is_class_or_module() else self.doubled_obj_type,
)
self.attrs[attr_name] = attr
return attr
|
[
"def",
"get_callable_attr",
"(",
"self",
",",
"attr_name",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"doubled_obj",
",",
"attr_name",
")",
":",
"return",
"None",
"func",
"=",
"getattr",
"(",
"self",
".",
"doubled_obj",
",",
"attr_name",
")",
"if",
"not",
"is_callable",
"(",
"func",
")",
":",
"return",
"None",
"attr",
"=",
"Attribute",
"(",
"func",
",",
"'attribute'",
",",
"self",
".",
"doubled_obj",
"if",
"self",
".",
"is_class_or_module",
"(",
")",
"else",
"self",
".",
"doubled_obj_type",
",",
")",
"self",
".",
"attrs",
"[",
"attr_name",
"]",
"=",
"attr",
"return",
"attr"
] |
Used to double methods added to an object after creation
:param str attr_name: the name of the original attribute to return
:return: Attribute or None.
:rtype: func
|
[
"Used",
"to",
"double",
"methods",
"added",
"to",
"an",
"object",
"after",
"creation"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L137-L158
|
11,772
|
uber/doubles
|
doubles/target.py
|
Target.get_attr
|
def get_attr(self, method_name):
"""Get attribute from the target object"""
return self.attrs.get(method_name) or self.get_callable_attr(method_name)
|
python
|
def get_attr(self, method_name):
"""Get attribute from the target object"""
return self.attrs.get(method_name) or self.get_callable_attr(method_name)
|
[
"def",
"get_attr",
"(",
"self",
",",
"method_name",
")",
":",
"return",
"self",
".",
"attrs",
".",
"get",
"(",
"method_name",
")",
"or",
"self",
".",
"get_callable_attr",
"(",
"method_name",
")"
] |
Get attribute from the target object
|
[
"Get",
"attribute",
"from",
"the",
"target",
"object"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L160-L162
|
11,773
|
uber/doubles
|
doubles/method_double.py
|
MethodDouble.add_allowance
|
def add_allowance(self, caller):
"""Adds a new allowance for the method.
:param: tuple caller: A tuple indicating where the method was called
:return: The new ``Allowance``.
:rtype: Allowance
"""
allowance = Allowance(self._target, self._method_name, caller)
self._allowances.insert(0, allowance)
return allowance
|
python
|
def add_allowance(self, caller):
"""Adds a new allowance for the method.
:param: tuple caller: A tuple indicating where the method was called
:return: The new ``Allowance``.
:rtype: Allowance
"""
allowance = Allowance(self._target, self._method_name, caller)
self._allowances.insert(0, allowance)
return allowance
|
[
"def",
"add_allowance",
"(",
"self",
",",
"caller",
")",
":",
"allowance",
"=",
"Allowance",
"(",
"self",
".",
"_target",
",",
"self",
".",
"_method_name",
",",
"caller",
")",
"self",
".",
"_allowances",
".",
"insert",
"(",
"0",
",",
"allowance",
")",
"return",
"allowance"
] |
Adds a new allowance for the method.
:param: tuple caller: A tuple indicating where the method was called
:return: The new ``Allowance``.
:rtype: Allowance
|
[
"Adds",
"a",
"new",
"allowance",
"for",
"the",
"method",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L30-L40
|
11,774
|
uber/doubles
|
doubles/method_double.py
|
MethodDouble.add_expectation
|
def add_expectation(self, caller):
"""Adds a new expectation for the method.
:return: The new ``Expectation``.
:rtype: Expectation
"""
expectation = Expectation(self._target, self._method_name, caller)
self._expectations.insert(0, expectation)
return expectation
|
python
|
def add_expectation(self, caller):
"""Adds a new expectation for the method.
:return: The new ``Expectation``.
:rtype: Expectation
"""
expectation = Expectation(self._target, self._method_name, caller)
self._expectations.insert(0, expectation)
return expectation
|
[
"def",
"add_expectation",
"(",
"self",
",",
"caller",
")",
":",
"expectation",
"=",
"Expectation",
"(",
"self",
".",
"_target",
",",
"self",
".",
"_method_name",
",",
"caller",
")",
"self",
".",
"_expectations",
".",
"insert",
"(",
"0",
",",
"expectation",
")",
"return",
"expectation"
] |
Adds a new expectation for the method.
:return: The new ``Expectation``.
:rtype: Expectation
|
[
"Adds",
"a",
"new",
"expectation",
"for",
"the",
"method",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L42-L51
|
11,775
|
uber/doubles
|
doubles/method_double.py
|
MethodDouble._find_matching_allowance
|
def _find_matching_allowance(self, args, kwargs):
"""Return a matching allowance.
Returns the first allowance that matches the ones declared. Tries one with specific
arguments first, then falls back to an allowance that allows arbitrary arguments.
:return: The matching ``Allowance``, if one was found.
:rtype: Allowance, None
"""
for allowance in self._allowances:
if allowance.satisfy_exact_match(args, kwargs):
return allowance
for allowance in self._allowances:
if allowance.satisfy_custom_matcher(args, kwargs):
return allowance
for allowance in self._allowances:
if allowance.satisfy_any_args_match():
return allowance
|
python
|
def _find_matching_allowance(self, args, kwargs):
"""Return a matching allowance.
Returns the first allowance that matches the ones declared. Tries one with specific
arguments first, then falls back to an allowance that allows arbitrary arguments.
:return: The matching ``Allowance``, if one was found.
:rtype: Allowance, None
"""
for allowance in self._allowances:
if allowance.satisfy_exact_match(args, kwargs):
return allowance
for allowance in self._allowances:
if allowance.satisfy_custom_matcher(args, kwargs):
return allowance
for allowance in self._allowances:
if allowance.satisfy_any_args_match():
return allowance
|
[
"def",
"_find_matching_allowance",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"for",
"allowance",
"in",
"self",
".",
"_allowances",
":",
"if",
"allowance",
".",
"satisfy_exact_match",
"(",
"args",
",",
"kwargs",
")",
":",
"return",
"allowance",
"for",
"allowance",
"in",
"self",
".",
"_allowances",
":",
"if",
"allowance",
".",
"satisfy_custom_matcher",
"(",
"args",
",",
"kwargs",
")",
":",
"return",
"allowance",
"for",
"allowance",
"in",
"self",
".",
"_allowances",
":",
"if",
"allowance",
".",
"satisfy_any_args_match",
"(",
")",
":",
"return",
"allowance"
] |
Return a matching allowance.
Returns the first allowance that matches the ones declared. Tries one with specific
arguments first, then falls back to an allowance that allows arbitrary arguments.
:return: The matching ``Allowance``, if one was found.
:rtype: Allowance, None
|
[
"Return",
"a",
"matching",
"allowance",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L68-L88
|
11,776
|
uber/doubles
|
doubles/method_double.py
|
MethodDouble._find_matching_double
|
def _find_matching_double(self, args, kwargs):
"""Returns the first matching expectation or allowance.
Returns the first allowance or expectation that matches the ones declared. Tries one
with specific arguments first, then falls back to an expectation that allows arbitrary
arguments.
:return: The matching ``Allowance`` or ``Expectation``, if one was found.
:rtype: Allowance, Expectation, None
"""
expectation = self._find_matching_expectation(args, kwargs)
if expectation:
return expectation
allowance = self._find_matching_allowance(args, kwargs)
if allowance:
return allowance
|
python
|
def _find_matching_double(self, args, kwargs):
"""Returns the first matching expectation or allowance.
Returns the first allowance or expectation that matches the ones declared. Tries one
with specific arguments first, then falls back to an expectation that allows arbitrary
arguments.
:return: The matching ``Allowance`` or ``Expectation``, if one was found.
:rtype: Allowance, Expectation, None
"""
expectation = self._find_matching_expectation(args, kwargs)
if expectation:
return expectation
allowance = self._find_matching_allowance(args, kwargs)
if allowance:
return allowance
|
[
"def",
"_find_matching_double",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"expectation",
"=",
"self",
".",
"_find_matching_expectation",
"(",
"args",
",",
"kwargs",
")",
"if",
"expectation",
":",
"return",
"expectation",
"allowance",
"=",
"self",
".",
"_find_matching_allowance",
"(",
"args",
",",
"kwargs",
")",
"if",
"allowance",
":",
"return",
"allowance"
] |
Returns the first matching expectation or allowance.
Returns the first allowance or expectation that matches the ones declared. Tries one
with specific arguments first, then falls back to an expectation that allows arbitrary
arguments.
:return: The matching ``Allowance`` or ``Expectation``, if one was found.
:rtype: Allowance, Expectation, None
|
[
"Returns",
"the",
"first",
"matching",
"expectation",
"or",
"allowance",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L90-L109
|
11,777
|
uber/doubles
|
doubles/method_double.py
|
MethodDouble._find_matching_expectation
|
def _find_matching_expectation(self, args, kwargs):
"""Return a matching expectation.
Returns the first expectation that matches the ones declared. Tries one with specific
arguments first, then falls back to an expectation that allows arbitrary arguments.
:return: The matching ``Expectation``, if one was found.
:rtype: Expectation, None
"""
for expectation in self._expectations:
if expectation.satisfy_exact_match(args, kwargs):
return expectation
for expectation in self._expectations:
if expectation.satisfy_custom_matcher(args, kwargs):
return expectation
for expectation in self._expectations:
if expectation.satisfy_any_args_match():
return expectation
|
python
|
def _find_matching_expectation(self, args, kwargs):
"""Return a matching expectation.
Returns the first expectation that matches the ones declared. Tries one with specific
arguments first, then falls back to an expectation that allows arbitrary arguments.
:return: The matching ``Expectation``, if one was found.
:rtype: Expectation, None
"""
for expectation in self._expectations:
if expectation.satisfy_exact_match(args, kwargs):
return expectation
for expectation in self._expectations:
if expectation.satisfy_custom_matcher(args, kwargs):
return expectation
for expectation in self._expectations:
if expectation.satisfy_any_args_match():
return expectation
|
[
"def",
"_find_matching_expectation",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"for",
"expectation",
"in",
"self",
".",
"_expectations",
":",
"if",
"expectation",
".",
"satisfy_exact_match",
"(",
"args",
",",
"kwargs",
")",
":",
"return",
"expectation",
"for",
"expectation",
"in",
"self",
".",
"_expectations",
":",
"if",
"expectation",
".",
"satisfy_custom_matcher",
"(",
"args",
",",
"kwargs",
")",
":",
"return",
"expectation",
"for",
"expectation",
"in",
"self",
".",
"_expectations",
":",
"if",
"expectation",
".",
"satisfy_any_args_match",
"(",
")",
":",
"return",
"expectation"
] |
Return a matching expectation.
Returns the first expectation that matches the ones declared. Tries one with specific
arguments first, then falls back to an expectation that allows arbitrary arguments.
:return: The matching ``Expectation``, if one was found.
:rtype: Expectation, None
|
[
"Return",
"a",
"matching",
"expectation",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L111-L131
|
11,778
|
uber/doubles
|
doubles/method_double.py
|
MethodDouble._verify_method
|
def _verify_method(self):
"""Verify that a method may be doubled.
Verifies that the target object has a method matching the name the user is attempting to
double.
:raise: ``VerifyingDoubleError`` if no matching method is found.
"""
class_level = self._target.is_class_or_module()
verify_method(self._target, self._method_name, class_level=class_level)
|
python
|
def _verify_method(self):
"""Verify that a method may be doubled.
Verifies that the target object has a method matching the name the user is attempting to
double.
:raise: ``VerifyingDoubleError`` if no matching method is found.
"""
class_level = self._target.is_class_or_module()
verify_method(self._target, self._method_name, class_level=class_level)
|
[
"def",
"_verify_method",
"(",
"self",
")",
":",
"class_level",
"=",
"self",
".",
"_target",
".",
"is_class_or_module",
"(",
")",
"verify_method",
"(",
"self",
".",
"_target",
",",
"self",
".",
"_method_name",
",",
"class_level",
"=",
"class_level",
")"
] |
Verify that a method may be doubled.
Verifies that the target object has a method matching the name the user is attempting to
double.
:raise: ``VerifyingDoubleError`` if no matching method is found.
|
[
"Verify",
"that",
"a",
"method",
"may",
"be",
"doubled",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L133-L144
|
11,779
|
uber/doubles
|
doubles/verification.py
|
verify_method
|
def verify_method(target, method_name, class_level=False):
"""Verifies that the provided method exists on the target object.
:param Target target: A ``Target`` object containing the object with the method to double.
:param str method_name: The name of the method to double.
:raise: ``VerifyingDoubleError`` if the attribute doesn't exist, if it's not a callable object,
and in the case where the target is a class, that the attribute isn't an instance method.
"""
attr = target.get_attr(method_name)
if not attr:
raise VerifyingDoubleError(method_name, target.doubled_obj).no_matching_method()
if attr.kind == 'data' and not isbuiltin(attr.object) and not is_callable(attr.object):
raise VerifyingDoubleError(method_name, target.doubled_obj).not_callable()
if class_level and attr.kind == 'method' and method_name != '__new__':
raise VerifyingDoubleError(method_name, target.doubled_obj).requires_instance()
|
python
|
def verify_method(target, method_name, class_level=False):
"""Verifies that the provided method exists on the target object.
:param Target target: A ``Target`` object containing the object with the method to double.
:param str method_name: The name of the method to double.
:raise: ``VerifyingDoubleError`` if the attribute doesn't exist, if it's not a callable object,
and in the case where the target is a class, that the attribute isn't an instance method.
"""
attr = target.get_attr(method_name)
if not attr:
raise VerifyingDoubleError(method_name, target.doubled_obj).no_matching_method()
if attr.kind == 'data' and not isbuiltin(attr.object) and not is_callable(attr.object):
raise VerifyingDoubleError(method_name, target.doubled_obj).not_callable()
if class_level and attr.kind == 'method' and method_name != '__new__':
raise VerifyingDoubleError(method_name, target.doubled_obj).requires_instance()
|
[
"def",
"verify_method",
"(",
"target",
",",
"method_name",
",",
"class_level",
"=",
"False",
")",
":",
"attr",
"=",
"target",
".",
"get_attr",
"(",
"method_name",
")",
"if",
"not",
"attr",
":",
"raise",
"VerifyingDoubleError",
"(",
"method_name",
",",
"target",
".",
"doubled_obj",
")",
".",
"no_matching_method",
"(",
")",
"if",
"attr",
".",
"kind",
"==",
"'data'",
"and",
"not",
"isbuiltin",
"(",
"attr",
".",
"object",
")",
"and",
"not",
"is_callable",
"(",
"attr",
".",
"object",
")",
":",
"raise",
"VerifyingDoubleError",
"(",
"method_name",
",",
"target",
".",
"doubled_obj",
")",
".",
"not_callable",
"(",
")",
"if",
"class_level",
"and",
"attr",
".",
"kind",
"==",
"'method'",
"and",
"method_name",
"!=",
"'__new__'",
":",
"raise",
"VerifyingDoubleError",
"(",
"method_name",
",",
"target",
".",
"doubled_obj",
")",
".",
"requires_instance",
"(",
")"
] |
Verifies that the provided method exists on the target object.
:param Target target: A ``Target`` object containing the object with the method to double.
:param str method_name: The name of the method to double.
:raise: ``VerifyingDoubleError`` if the attribute doesn't exist, if it's not a callable object,
and in the case where the target is a class, that the attribute isn't an instance method.
|
[
"Verifies",
"that",
"the",
"provided",
"method",
"exists",
"on",
"the",
"target",
"object",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/verification.py#L76-L94
|
11,780
|
uber/doubles
|
doubles/verification.py
|
verify_arguments
|
def verify_arguments(target, method_name, args, kwargs):
"""Verifies that the provided arguments match the signature of the provided method.
:param Target target: A ``Target`` object containing the object with the method to double.
:param str method_name: The name of the method to double.
:param tuple args: The positional arguments the method should be called with.
:param dict kwargs: The keyword arguments the method should be called with.
:raise: ``VerifyingDoubleError`` if the provided arguments do not match the signature.
"""
if method_name == '_doubles__new__':
return _verify_arguments_of_doubles__new__(target, args, kwargs)
attr = target.get_attr(method_name)
method = attr.object
if attr.kind in ('data', 'attribute', 'toplevel', 'class method', 'static method'):
try:
method = method.__get__(None, attr.defining_class)
except AttributeError:
method = method.__call__
elif attr.kind == 'property':
if args or kwargs:
raise VerifyingDoubleArgumentError("Properties do not accept arguments.")
return
else:
args = ['self_or_cls'] + list(args)
_verify_arguments(method, method_name, args, kwargs)
|
python
|
def verify_arguments(target, method_name, args, kwargs):
"""Verifies that the provided arguments match the signature of the provided method.
:param Target target: A ``Target`` object containing the object with the method to double.
:param str method_name: The name of the method to double.
:param tuple args: The positional arguments the method should be called with.
:param dict kwargs: The keyword arguments the method should be called with.
:raise: ``VerifyingDoubleError`` if the provided arguments do not match the signature.
"""
if method_name == '_doubles__new__':
return _verify_arguments_of_doubles__new__(target, args, kwargs)
attr = target.get_attr(method_name)
method = attr.object
if attr.kind in ('data', 'attribute', 'toplevel', 'class method', 'static method'):
try:
method = method.__get__(None, attr.defining_class)
except AttributeError:
method = method.__call__
elif attr.kind == 'property':
if args or kwargs:
raise VerifyingDoubleArgumentError("Properties do not accept arguments.")
return
else:
args = ['self_or_cls'] + list(args)
_verify_arguments(method, method_name, args, kwargs)
|
[
"def",
"verify_arguments",
"(",
"target",
",",
"method_name",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"method_name",
"==",
"'_doubles__new__'",
":",
"return",
"_verify_arguments_of_doubles__new__",
"(",
"target",
",",
"args",
",",
"kwargs",
")",
"attr",
"=",
"target",
".",
"get_attr",
"(",
"method_name",
")",
"method",
"=",
"attr",
".",
"object",
"if",
"attr",
".",
"kind",
"in",
"(",
"'data'",
",",
"'attribute'",
",",
"'toplevel'",
",",
"'class method'",
",",
"'static method'",
")",
":",
"try",
":",
"method",
"=",
"method",
".",
"__get__",
"(",
"None",
",",
"attr",
".",
"defining_class",
")",
"except",
"AttributeError",
":",
"method",
"=",
"method",
".",
"__call__",
"elif",
"attr",
".",
"kind",
"==",
"'property'",
":",
"if",
"args",
"or",
"kwargs",
":",
"raise",
"VerifyingDoubleArgumentError",
"(",
"\"Properties do not accept arguments.\"",
")",
"return",
"else",
":",
"args",
"=",
"[",
"'self_or_cls'",
"]",
"+",
"list",
"(",
"args",
")",
"_verify_arguments",
"(",
"method",
",",
"method_name",
",",
"args",
",",
"kwargs",
")"
] |
Verifies that the provided arguments match the signature of the provided method.
:param Target target: A ``Target`` object containing the object with the method to double.
:param str method_name: The name of the method to double.
:param tuple args: The positional arguments the method should be called with.
:param dict kwargs: The keyword arguments the method should be called with.
:raise: ``VerifyingDoubleError`` if the provided arguments do not match the signature.
|
[
"Verifies",
"that",
"the",
"provided",
"arguments",
"match",
"the",
"signature",
"of",
"the",
"provided",
"method",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/verification.py#L97-L125
|
11,781
|
uber/doubles
|
doubles/targets/allowance_target.py
|
allow_constructor
|
def allow_constructor(target):
"""
Set an allowance on a ``ClassDouble`` constructor
This allows the caller to control what a ClassDouble returns when a new instance is created.
:param ClassDouble target: The ClassDouble to set the allowance on.
:return: an ``Allowance`` for the __new__ method.
:raise: ``ConstructorDoubleError`` if target is not a ClassDouble.
"""
if not isinstance(target, ClassDouble):
raise ConstructorDoubleError(
'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target),
)
return allow(target)._doubles__new__
|
python
|
def allow_constructor(target):
"""
Set an allowance on a ``ClassDouble`` constructor
This allows the caller to control what a ClassDouble returns when a new instance is created.
:param ClassDouble target: The ClassDouble to set the allowance on.
:return: an ``Allowance`` for the __new__ method.
:raise: ``ConstructorDoubleError`` if target is not a ClassDouble.
"""
if not isinstance(target, ClassDouble):
raise ConstructorDoubleError(
'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target),
)
return allow(target)._doubles__new__
|
[
"def",
"allow_constructor",
"(",
"target",
")",
":",
"if",
"not",
"isinstance",
"(",
"target",
",",
"ClassDouble",
")",
":",
"raise",
"ConstructorDoubleError",
"(",
"'Cannot allow_constructor of {} since it is not a ClassDouble.'",
".",
"format",
"(",
"target",
")",
",",
")",
"return",
"allow",
"(",
"target",
")",
".",
"_doubles__new__"
] |
Set an allowance on a ``ClassDouble`` constructor
This allows the caller to control what a ClassDouble returns when a new instance is created.
:param ClassDouble target: The ClassDouble to set the allowance on.
:return: an ``Allowance`` for the __new__ method.
:raise: ``ConstructorDoubleError`` if target is not a ClassDouble.
|
[
"Set",
"an",
"allowance",
"on",
"a",
"ClassDouble",
"constructor"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/targets/allowance_target.py#L25-L40
|
11,782
|
uber/doubles
|
doubles/targets/patch_target.py
|
patch
|
def patch(target, value):
"""
Replace the specified object
:param str target: A string pointing to the target to patch.
:param object value: The value to replace the target with.
:return: A ``Patch`` object.
"""
patch = current_space().patch_for(target)
patch.set_value(value)
return patch
|
python
|
def patch(target, value):
"""
Replace the specified object
:param str target: A string pointing to the target to patch.
:param object value: The value to replace the target with.
:return: A ``Patch`` object.
"""
patch = current_space().patch_for(target)
patch.set_value(value)
return patch
|
[
"def",
"patch",
"(",
"target",
",",
"value",
")",
":",
"patch",
"=",
"current_space",
"(",
")",
".",
"patch_for",
"(",
"target",
")",
"patch",
".",
"set_value",
"(",
"value",
")",
"return",
"patch"
] |
Replace the specified object
:param str target: A string pointing to the target to patch.
:param object value: The value to replace the target with.
:return: A ``Patch`` object.
|
[
"Replace",
"the",
"specified",
"object"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/targets/patch_target.py#L18-L28
|
11,783
|
uber/doubles
|
doubles/utils.py
|
get_path_components
|
def get_path_components(path):
"""Extract the module name and class name out of the fully qualified path to the class.
:param str path: The full path to the class.
:return: The module path and the class name.
:rtype: str, str
:raise: ``VerifyingDoubleImportError`` if the path is to a top-level module.
"""
path_segments = path.split('.')
module_path = '.'.join(path_segments[:-1])
if module_path == '':
raise VerifyingDoubleImportError('Invalid import path: {}.'.format(path))
class_name = path_segments[-1]
return module_path, class_name
|
python
|
def get_path_components(path):
"""Extract the module name and class name out of the fully qualified path to the class.
:param str path: The full path to the class.
:return: The module path and the class name.
:rtype: str, str
:raise: ``VerifyingDoubleImportError`` if the path is to a top-level module.
"""
path_segments = path.split('.')
module_path = '.'.join(path_segments[:-1])
if module_path == '':
raise VerifyingDoubleImportError('Invalid import path: {}.'.format(path))
class_name = path_segments[-1]
return module_path, class_name
|
[
"def",
"get_path_components",
"(",
"path",
")",
":",
"path_segments",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"module_path",
"=",
"'.'",
".",
"join",
"(",
"path_segments",
"[",
":",
"-",
"1",
"]",
")",
"if",
"module_path",
"==",
"''",
":",
"raise",
"VerifyingDoubleImportError",
"(",
"'Invalid import path: {}.'",
".",
"format",
"(",
"path",
")",
")",
"class_name",
"=",
"path_segments",
"[",
"-",
"1",
"]",
"return",
"module_path",
",",
"class_name"
] |
Extract the module name and class name out of the fully qualified path to the class.
:param str path: The full path to the class.
:return: The module path and the class name.
:rtype: str, str
:raise: ``VerifyingDoubleImportError`` if the path is to a top-level module.
|
[
"Extract",
"the",
"module",
"name",
"and",
"class",
"name",
"out",
"of",
"the",
"fully",
"qualified",
"path",
"to",
"the",
"class",
"."
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/utils.py#L22-L39
|
11,784
|
uber/doubles
|
doubles/targets/expectation_target.py
|
expect_constructor
|
def expect_constructor(target):
"""
Set an expectation on a ``ClassDouble`` constructor
:param ClassDouble target: The ClassDouble to set the expectation on.
:return: an ``Expectation`` for the __new__ method.
:raise: ``ConstructorDoubleError`` if target is not a ClassDouble.
"""
if not isinstance(target, ClassDouble):
raise ConstructorDoubleError(
'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target),
)
return expect(target)._doubles__new__
|
python
|
def expect_constructor(target):
"""
Set an expectation on a ``ClassDouble`` constructor
:param ClassDouble target: The ClassDouble to set the expectation on.
:return: an ``Expectation`` for the __new__ method.
:raise: ``ConstructorDoubleError`` if target is not a ClassDouble.
"""
if not isinstance(target, ClassDouble):
raise ConstructorDoubleError(
'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target),
)
return expect(target)._doubles__new__
|
[
"def",
"expect_constructor",
"(",
"target",
")",
":",
"if",
"not",
"isinstance",
"(",
"target",
",",
"ClassDouble",
")",
":",
"raise",
"ConstructorDoubleError",
"(",
"'Cannot allow_constructor of {} since it is not a ClassDouble.'",
".",
"format",
"(",
"target",
")",
",",
")",
"return",
"expect",
"(",
"target",
")",
".",
"_doubles__new__"
] |
Set an expectation on a ``ClassDouble`` constructor
:param ClassDouble target: The ClassDouble to set the expectation on.
:return: an ``Expectation`` for the __new__ method.
:raise: ``ConstructorDoubleError`` if target is not a ClassDouble.
|
[
"Set",
"an",
"expectation",
"on",
"a",
"ClassDouble",
"constructor"
] |
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
|
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/targets/expectation_target.py#L25-L38
|
11,785
|
thombashi/pytablewriter
|
pytablewriter/writer/text/_markdown.py
|
MarkdownTableWriter.write_table
|
def write_table(self):
"""
|write_table| with Markdown table format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Example:
:ref:`example-markdown-table-writer`
.. note::
- |None| values are written as an empty string
- Vertical bar characters (``'|'``) in table items are escaped
"""
with self._logger:
self._verify_property()
self.__write_chapter()
self._write_table()
if self.is_write_null_line_after_table:
self.write_null_line()
|
python
|
def write_table(self):
"""
|write_table| with Markdown table format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Example:
:ref:`example-markdown-table-writer`
.. note::
- |None| values are written as an empty string
- Vertical bar characters (``'|'``) in table items are escaped
"""
with self._logger:
self._verify_property()
self.__write_chapter()
self._write_table()
if self.is_write_null_line_after_table:
self.write_null_line()
|
[
"def",
"write_table",
"(",
"self",
")",
":",
"with",
"self",
".",
"_logger",
":",
"self",
".",
"_verify_property",
"(",
")",
"self",
".",
"__write_chapter",
"(",
")",
"self",
".",
"_write_table",
"(",
")",
"if",
"self",
".",
"is_write_null_line_after_table",
":",
"self",
".",
"write_null_line",
"(",
")"
] |
|write_table| with Markdown table format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Example:
:ref:`example-markdown-table-writer`
.. note::
- |None| values are written as an empty string
- Vertical bar characters (``'|'``) in table items are escaped
|
[
"|write_table|",
"with",
"Markdown",
"table",
"format",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_markdown.py#L86-L104
|
11,786
|
thombashi/pytablewriter
|
pytablewriter/writer/text/_html.py
|
HtmlTableWriter.write_table
|
def write_table(self):
"""
|write_table| with HTML table format.
:Example:
:ref:`example-html-table-writer`
.. note::
- |None| is not written
"""
tags = _get_tags_module()
with self._logger:
self._verify_property()
self._preprocess()
if typepy.is_not_null_string(self.table_name):
self._table_tag = tags.table(id=sanitize_python_var_name(self.table_name))
self._table_tag += tags.caption(MultiByteStrDecoder(self.table_name).unicode_str)
else:
self._table_tag = tags.table()
try:
self._write_header()
except EmptyHeaderError:
pass
self._write_body()
|
python
|
def write_table(self):
"""
|write_table| with HTML table format.
:Example:
:ref:`example-html-table-writer`
.. note::
- |None| is not written
"""
tags = _get_tags_module()
with self._logger:
self._verify_property()
self._preprocess()
if typepy.is_not_null_string(self.table_name):
self._table_tag = tags.table(id=sanitize_python_var_name(self.table_name))
self._table_tag += tags.caption(MultiByteStrDecoder(self.table_name).unicode_str)
else:
self._table_tag = tags.table()
try:
self._write_header()
except EmptyHeaderError:
pass
self._write_body()
|
[
"def",
"write_table",
"(",
"self",
")",
":",
"tags",
"=",
"_get_tags_module",
"(",
")",
"with",
"self",
".",
"_logger",
":",
"self",
".",
"_verify_property",
"(",
")",
"self",
".",
"_preprocess",
"(",
")",
"if",
"typepy",
".",
"is_not_null_string",
"(",
"self",
".",
"table_name",
")",
":",
"self",
".",
"_table_tag",
"=",
"tags",
".",
"table",
"(",
"id",
"=",
"sanitize_python_var_name",
"(",
"self",
".",
"table_name",
")",
")",
"self",
".",
"_table_tag",
"+=",
"tags",
".",
"caption",
"(",
"MultiByteStrDecoder",
"(",
"self",
".",
"table_name",
")",
".",
"unicode_str",
")",
"else",
":",
"self",
".",
"_table_tag",
"=",
"tags",
".",
"table",
"(",
")",
"try",
":",
"self",
".",
"_write_header",
"(",
")",
"except",
"EmptyHeaderError",
":",
"pass",
"self",
".",
"_write_body",
"(",
")"
] |
|write_table| with HTML table format.
:Example:
:ref:`example-html-table-writer`
.. note::
- |None| is not written
|
[
"|write_table|",
"with",
"HTML",
"table",
"format",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_html.py#L57-L85
|
11,787
|
thombashi/pytablewriter
|
pytablewriter/writer/text/_text_writer.py
|
TextTableWriter.dump
|
def dump(self, output, close_after_write=True):
"""Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the output after write.
Defaults to |True|.
"""
try:
output.write
self.stream = output
except AttributeError:
self.stream = io.open(output, "w", encoding="utf-8")
try:
self.write_table()
finally:
if close_after_write:
self.stream.close()
self.stream = sys.stdout
|
python
|
def dump(self, output, close_after_write=True):
"""Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the output after write.
Defaults to |True|.
"""
try:
output.write
self.stream = output
except AttributeError:
self.stream = io.open(output, "w", encoding="utf-8")
try:
self.write_table()
finally:
if close_after_write:
self.stream.close()
self.stream = sys.stdout
|
[
"def",
"dump",
"(",
"self",
",",
"output",
",",
"close_after_write",
"=",
"True",
")",
":",
"try",
":",
"output",
".",
"write",
"self",
".",
"stream",
"=",
"output",
"except",
"AttributeError",
":",
"self",
".",
"stream",
"=",
"io",
".",
"open",
"(",
"output",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"try",
":",
"self",
".",
"write_table",
"(",
")",
"finally",
":",
"if",
"close_after_write",
":",
"self",
".",
"stream",
".",
"close",
"(",
")",
"self",
".",
"stream",
"=",
"sys",
".",
"stdout"
] |
Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the output after write.
Defaults to |True|.
|
[
"Write",
"data",
"to",
"the",
"output",
"with",
"tabular",
"format",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_text_writer.py#L179-L201
|
11,788
|
thombashi/pytablewriter
|
pytablewriter/writer/text/_text_writer.py
|
TextTableWriter.dumps
|
def dumps(self):
"""Get rendered tabular text from the table data.
Only available for text format table writers.
Returns:
str: Rendered tabular text.
"""
old_stream = self.stream
try:
self.stream = six.StringIO()
self.write_table()
tabular_text = self.stream.getvalue()
finally:
self.stream = old_stream
return tabular_text
|
python
|
def dumps(self):
"""Get rendered tabular text from the table data.
Only available for text format table writers.
Returns:
str: Rendered tabular text.
"""
old_stream = self.stream
try:
self.stream = six.StringIO()
self.write_table()
tabular_text = self.stream.getvalue()
finally:
self.stream = old_stream
return tabular_text
|
[
"def",
"dumps",
"(",
"self",
")",
":",
"old_stream",
"=",
"self",
".",
"stream",
"try",
":",
"self",
".",
"stream",
"=",
"six",
".",
"StringIO",
"(",
")",
"self",
".",
"write_table",
"(",
")",
"tabular_text",
"=",
"self",
".",
"stream",
".",
"getvalue",
"(",
")",
"finally",
":",
"self",
".",
"stream",
"=",
"old_stream",
"return",
"tabular_text"
] |
Get rendered tabular text from the table data.
Only available for text format table writers.
Returns:
str: Rendered tabular text.
|
[
"Get",
"rendered",
"tabular",
"text",
"from",
"the",
"table",
"data",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_text_writer.py#L203-L221
|
11,789
|
thombashi/pytablewriter
|
pytablewriter/writer/binary/_excel.py
|
ExcelTableWriter.open
|
def open(self, file_path):
"""
Open an Excel workbook file.
:param str file_path: Excel workbook file path to open.
"""
if self.is_opened() and self.workbook.file_path == file_path:
self._logger.logger.debug("workbook already opened: {}".format(self.workbook.file_path))
return
self.close()
self._open(file_path)
|
python
|
def open(self, file_path):
"""
Open an Excel workbook file.
:param str file_path: Excel workbook file path to open.
"""
if self.is_opened() and self.workbook.file_path == file_path:
self._logger.logger.debug("workbook already opened: {}".format(self.workbook.file_path))
return
self.close()
self._open(file_path)
|
[
"def",
"open",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"self",
".",
"is_opened",
"(",
")",
"and",
"self",
".",
"workbook",
".",
"file_path",
"==",
"file_path",
":",
"self",
".",
"_logger",
".",
"logger",
".",
"debug",
"(",
"\"workbook already opened: {}\"",
".",
"format",
"(",
"self",
".",
"workbook",
".",
"file_path",
")",
")",
"return",
"self",
".",
"close",
"(",
")",
"self",
".",
"_open",
"(",
"file_path",
")"
] |
Open an Excel workbook file.
:param str file_path: Excel workbook file path to open.
|
[
"Open",
"an",
"Excel",
"workbook",
"file",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_excel.py#L129-L141
|
11,790
|
thombashi/pytablewriter
|
pytablewriter/writer/binary/_excel.py
|
ExcelTableWriter.from_tabledata
|
def from_tabledata(self, value, is_overwrite_table_name=True):
"""
Set following attributes from |TableData|
- :py:attr:`~.table_name`.
- :py:attr:`~.headers`.
- :py:attr:`~.value_matrix`.
And create worksheet named from :py:attr:`~.table_name` ABC
if not existed yet.
:param tabledata.TableData value: Input table data.
"""
super(ExcelTableWriter, self).from_tabledata(value)
if self.is_opened():
self.make_worksheet(self.table_name)
|
python
|
def from_tabledata(self, value, is_overwrite_table_name=True):
"""
Set following attributes from |TableData|
- :py:attr:`~.table_name`.
- :py:attr:`~.headers`.
- :py:attr:`~.value_matrix`.
And create worksheet named from :py:attr:`~.table_name` ABC
if not existed yet.
:param tabledata.TableData value: Input table data.
"""
super(ExcelTableWriter, self).from_tabledata(value)
if self.is_opened():
self.make_worksheet(self.table_name)
|
[
"def",
"from_tabledata",
"(",
"self",
",",
"value",
",",
"is_overwrite_table_name",
"=",
"True",
")",
":",
"super",
"(",
"ExcelTableWriter",
",",
"self",
")",
".",
"from_tabledata",
"(",
"value",
")",
"if",
"self",
".",
"is_opened",
"(",
")",
":",
"self",
".",
"make_worksheet",
"(",
"self",
".",
"table_name",
")"
] |
Set following attributes from |TableData|
- :py:attr:`~.table_name`.
- :py:attr:`~.headers`.
- :py:attr:`~.value_matrix`.
And create worksheet named from :py:attr:`~.table_name` ABC
if not existed yet.
:param tabledata.TableData value: Input table data.
|
[
"Set",
"following",
"attributes",
"from",
"|TableData|"
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_excel.py#L166-L183
|
11,791
|
thombashi/pytablewriter
|
pytablewriter/writer/binary/_excel.py
|
ExcelTableWriter.make_worksheet
|
def make_worksheet(self, sheet_name=None):
"""Make a worksheet to the current workbook.
Args:
sheet_name (str):
Name of the worksheet to create. The name will be automatically generated
(like ``"Sheet1"``) if the ``sheet_name`` is empty.
"""
if sheet_name is None:
sheet_name = self.table_name
if not sheet_name:
sheet_name = ""
self._stream = self.workbook.add_worksheet(sheet_name)
self._current_data_row = self._first_data_row
|
python
|
def make_worksheet(self, sheet_name=None):
"""Make a worksheet to the current workbook.
Args:
sheet_name (str):
Name of the worksheet to create. The name will be automatically generated
(like ``"Sheet1"``) if the ``sheet_name`` is empty.
"""
if sheet_name is None:
sheet_name = self.table_name
if not sheet_name:
sheet_name = ""
self._stream = self.workbook.add_worksheet(sheet_name)
self._current_data_row = self._first_data_row
|
[
"def",
"make_worksheet",
"(",
"self",
",",
"sheet_name",
"=",
"None",
")",
":",
"if",
"sheet_name",
"is",
"None",
":",
"sheet_name",
"=",
"self",
".",
"table_name",
"if",
"not",
"sheet_name",
":",
"sheet_name",
"=",
"\"\"",
"self",
".",
"_stream",
"=",
"self",
".",
"workbook",
".",
"add_worksheet",
"(",
"sheet_name",
")",
"self",
".",
"_current_data_row",
"=",
"self",
".",
"_first_data_row"
] |
Make a worksheet to the current workbook.
Args:
sheet_name (str):
Name of the worksheet to create. The name will be automatically generated
(like ``"Sheet1"``) if the ``sheet_name`` is empty.
|
[
"Make",
"a",
"worksheet",
"to",
"the",
"current",
"workbook",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_excel.py#L185-L200
|
11,792
|
thombashi/pytablewriter
|
pytablewriter/writer/binary/_excel.py
|
ExcelTableWriter.dump
|
def dump(self, output, close_after_write=True):
"""Write a worksheet to the current workbook.
Args:
output (str):
Path to the workbook file to write.
close_after_write (bool, optional):
Close the workbook after write.
Defaults to |True|.
"""
self.open(output)
try:
self.make_worksheet(self.table_name)
self.write_table()
finally:
if close_after_write:
self.close()
|
python
|
def dump(self, output, close_after_write=True):
"""Write a worksheet to the current workbook.
Args:
output (str):
Path to the workbook file to write.
close_after_write (bool, optional):
Close the workbook after write.
Defaults to |True|.
"""
self.open(output)
try:
self.make_worksheet(self.table_name)
self.write_table()
finally:
if close_after_write:
self.close()
|
[
"def",
"dump",
"(",
"self",
",",
"output",
",",
"close_after_write",
"=",
"True",
")",
":",
"self",
".",
"open",
"(",
"output",
")",
"try",
":",
"self",
".",
"make_worksheet",
"(",
"self",
".",
"table_name",
")",
"self",
".",
"write_table",
"(",
")",
"finally",
":",
"if",
"close_after_write",
":",
"self",
".",
"close",
"(",
")"
] |
Write a worksheet to the current workbook.
Args:
output (str):
Path to the workbook file to write.
close_after_write (bool, optional):
Close the workbook after write.
Defaults to |True|.
|
[
"Write",
"a",
"worksheet",
"to",
"the",
"current",
"workbook",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_excel.py#L202-L219
|
11,793
|
thombashi/pytablewriter
|
pytablewriter/writer/binary/_sqlite.py
|
SqliteTableWriter.open
|
def open(self, file_path):
"""
Open a SQLite database file.
:param str file_path: SQLite database file path to open.
"""
from simplesqlite import SimpleSQLite
if self.is_opened():
if self.stream.database_path == abspath(file_path):
self._logger.logger.debug(
"database already opened: {}".format(self.stream.database_path)
)
return
self.close()
self._stream = SimpleSQLite(file_path, "w")
|
python
|
def open(self, file_path):
"""
Open a SQLite database file.
:param str file_path: SQLite database file path to open.
"""
from simplesqlite import SimpleSQLite
if self.is_opened():
if self.stream.database_path == abspath(file_path):
self._logger.logger.debug(
"database already opened: {}".format(self.stream.database_path)
)
return
self.close()
self._stream = SimpleSQLite(file_path, "w")
|
[
"def",
"open",
"(",
"self",
",",
"file_path",
")",
":",
"from",
"simplesqlite",
"import",
"SimpleSQLite",
"if",
"self",
".",
"is_opened",
"(",
")",
":",
"if",
"self",
".",
"stream",
".",
"database_path",
"==",
"abspath",
"(",
"file_path",
")",
":",
"self",
".",
"_logger",
".",
"logger",
".",
"debug",
"(",
"\"database already opened: {}\"",
".",
"format",
"(",
"self",
".",
"stream",
".",
"database_path",
")",
")",
"return",
"self",
".",
"close",
"(",
")",
"self",
".",
"_stream",
"=",
"SimpleSQLite",
"(",
"file_path",
",",
"\"w\"",
")"
] |
Open a SQLite database file.
:param str file_path: SQLite database file path to open.
|
[
"Open",
"a",
"SQLite",
"database",
"file",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_sqlite.py#L61-L79
|
11,794
|
thombashi/pytablewriter
|
pytablewriter/writer/_table_writer.py
|
AbstractTableWriter.set_style
|
def set_style(self, column, style):
"""Set |Style| for a specific column.
Args:
column (|int| or |str|):
Column specifier. column index or header name correlated with the column.
style (|Style|):
Style value to be set to the column.
Raises:
ValueError: If the column specifier is invalid.
"""
column_idx = None
while len(self.headers) > len(self.__style_list):
self.__style_list.append(None)
if isinstance(column, six.integer_types):
column_idx = column
elif isinstance(column, six.string_types):
try:
column_idx = self.headers.index(column)
except ValueError:
pass
if column_idx is not None:
self.__style_list[column_idx] = style
self.__clear_preprocess()
self._dp_extractor.format_flags_list = [
_ts_to_flag[self.__get_thousand_separator(col_idx)]
for col_idx in range(len(self.__style_list))
]
return
raise ValueError("column must be an int or string: actual={}".format(column))
|
python
|
def set_style(self, column, style):
"""Set |Style| for a specific column.
Args:
column (|int| or |str|):
Column specifier. column index or header name correlated with the column.
style (|Style|):
Style value to be set to the column.
Raises:
ValueError: If the column specifier is invalid.
"""
column_idx = None
while len(self.headers) > len(self.__style_list):
self.__style_list.append(None)
if isinstance(column, six.integer_types):
column_idx = column
elif isinstance(column, six.string_types):
try:
column_idx = self.headers.index(column)
except ValueError:
pass
if column_idx is not None:
self.__style_list[column_idx] = style
self.__clear_preprocess()
self._dp_extractor.format_flags_list = [
_ts_to_flag[self.__get_thousand_separator(col_idx)]
for col_idx in range(len(self.__style_list))
]
return
raise ValueError("column must be an int or string: actual={}".format(column))
|
[
"def",
"set_style",
"(",
"self",
",",
"column",
",",
"style",
")",
":",
"column_idx",
"=",
"None",
"while",
"len",
"(",
"self",
".",
"headers",
")",
">",
"len",
"(",
"self",
".",
"__style_list",
")",
":",
"self",
".",
"__style_list",
".",
"append",
"(",
"None",
")",
"if",
"isinstance",
"(",
"column",
",",
"six",
".",
"integer_types",
")",
":",
"column_idx",
"=",
"column",
"elif",
"isinstance",
"(",
"column",
",",
"six",
".",
"string_types",
")",
":",
"try",
":",
"column_idx",
"=",
"self",
".",
"headers",
".",
"index",
"(",
"column",
")",
"except",
"ValueError",
":",
"pass",
"if",
"column_idx",
"is",
"not",
"None",
":",
"self",
".",
"__style_list",
"[",
"column_idx",
"]",
"=",
"style",
"self",
".",
"__clear_preprocess",
"(",
")",
"self",
".",
"_dp_extractor",
".",
"format_flags_list",
"=",
"[",
"_ts_to_flag",
"[",
"self",
".",
"__get_thousand_separator",
"(",
"col_idx",
")",
"]",
"for",
"col_idx",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"__style_list",
")",
")",
"]",
"return",
"raise",
"ValueError",
"(",
"\"column must be an int or string: actual={}\"",
".",
"format",
"(",
"column",
")",
")"
] |
Set |Style| for a specific column.
Args:
column (|int| or |str|):
Column specifier. column index or header name correlated with the column.
style (|Style|):
Style value to be set to the column.
Raises:
ValueError: If the column specifier is invalid.
|
[
"Set",
"|Style|",
"for",
"a",
"specific",
"column",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/_table_writer.py#L458-L493
|
11,795
|
thombashi/pytablewriter
|
pytablewriter/writer/_table_writer.py
|
AbstractTableWriter.close
|
def close(self):
"""
Close the current |stream|.
"""
if self.stream is None:
return
try:
self.stream.isatty()
if self.stream.name in ["<stdin>", "<stdout>", "<stderr>"]:
return
except AttributeError:
pass
except ValueError:
# raised when executing an operation to a closed stream
pass
try:
from _pytest.compat import CaptureIO
from _pytest.capture import EncodedFile
if isinstance(self.stream, (CaptureIO, EncodedFile)):
# avoid closing streams for pytest
return
except ImportError:
pass
try:
from ipykernel.iostream import OutStream
if isinstance(self.stream, OutStream):
# avoid closing streams for Jupyter Notebook
return
except ImportError:
pass
try:
self.stream.close()
except AttributeError:
self._logger.logger.warn(
"the stream has no close method implementation: type={}".format(type(self.stream))
)
finally:
self._stream = None
|
python
|
def close(self):
"""
Close the current |stream|.
"""
if self.stream is None:
return
try:
self.stream.isatty()
if self.stream.name in ["<stdin>", "<stdout>", "<stderr>"]:
return
except AttributeError:
pass
except ValueError:
# raised when executing an operation to a closed stream
pass
try:
from _pytest.compat import CaptureIO
from _pytest.capture import EncodedFile
if isinstance(self.stream, (CaptureIO, EncodedFile)):
# avoid closing streams for pytest
return
except ImportError:
pass
try:
from ipykernel.iostream import OutStream
if isinstance(self.stream, OutStream):
# avoid closing streams for Jupyter Notebook
return
except ImportError:
pass
try:
self.stream.close()
except AttributeError:
self._logger.logger.warn(
"the stream has no close method implementation: type={}".format(type(self.stream))
)
finally:
self._stream = None
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"stream",
"is",
"None",
":",
"return",
"try",
":",
"self",
".",
"stream",
".",
"isatty",
"(",
")",
"if",
"self",
".",
"stream",
".",
"name",
"in",
"[",
"\"<stdin>\"",
",",
"\"<stdout>\"",
",",
"\"<stderr>\"",
"]",
":",
"return",
"except",
"AttributeError",
":",
"pass",
"except",
"ValueError",
":",
"# raised when executing an operation to a closed stream",
"pass",
"try",
":",
"from",
"_pytest",
".",
"compat",
"import",
"CaptureIO",
"from",
"_pytest",
".",
"capture",
"import",
"EncodedFile",
"if",
"isinstance",
"(",
"self",
".",
"stream",
",",
"(",
"CaptureIO",
",",
"EncodedFile",
")",
")",
":",
"# avoid closing streams for pytest",
"return",
"except",
"ImportError",
":",
"pass",
"try",
":",
"from",
"ipykernel",
".",
"iostream",
"import",
"OutStream",
"if",
"isinstance",
"(",
"self",
".",
"stream",
",",
"OutStream",
")",
":",
"# avoid closing streams for Jupyter Notebook",
"return",
"except",
"ImportError",
":",
"pass",
"try",
":",
"self",
".",
"stream",
".",
"close",
"(",
")",
"except",
"AttributeError",
":",
"self",
".",
"_logger",
".",
"logger",
".",
"warn",
"(",
"\"the stream has no close method implementation: type={}\"",
".",
"format",
"(",
"type",
"(",
"self",
".",
"stream",
")",
")",
")",
"finally",
":",
"self",
".",
"_stream",
"=",
"None"
] |
Close the current |stream|.
|
[
"Close",
"the",
"current",
"|stream|",
"."
] |
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/_table_writer.py#L495-L540
|
11,796
|
heroku/heroku.py
|
heroku/models.py
|
BaseResource._ids
|
def _ids(self):
"""The list of primary keys to validate against."""
for pk in self._pks:
yield getattr(self, pk)
for pk in self._pks:
try:
yield str(getattr(self, pk))
except ValueError:
pass
|
python
|
def _ids(self):
"""The list of primary keys to validate against."""
for pk in self._pks:
yield getattr(self, pk)
for pk in self._pks:
try:
yield str(getattr(self, pk))
except ValueError:
pass
|
[
"def",
"_ids",
"(",
"self",
")",
":",
"for",
"pk",
"in",
"self",
".",
"_pks",
":",
"yield",
"getattr",
"(",
"self",
",",
"pk",
")",
"for",
"pk",
"in",
"self",
".",
"_pks",
":",
"try",
":",
"yield",
"str",
"(",
"getattr",
"(",
"self",
",",
"pk",
")",
")",
"except",
"ValueError",
":",
"pass"
] |
The list of primary keys to validate against.
|
[
"The",
"list",
"of",
"primary",
"keys",
"to",
"validate",
"against",
"."
] |
cadc0a074896cf29c65a457c5c5bdb2069470af0
|
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L57-L67
|
11,797
|
heroku/heroku.py
|
heroku/models.py
|
Addon.upgrade
|
def upgrade(self, name, params=None):
"""Upgrades an addon to the given tier."""
# Allow non-namespaced upgrades. (e.g. advanced vs logging:advanced)
if ':' not in name:
name = '{0}:{1}'.format(self.type, name)
r = self._h._http_resource(
method='PUT',
resource=('apps', self.app.name, 'addons', quote(name)),
params=params,
data=' ' # Server weirdness.
)
r.raise_for_status()
return self.app.addons[name]
|
python
|
def upgrade(self, name, params=None):
"""Upgrades an addon to the given tier."""
# Allow non-namespaced upgrades. (e.g. advanced vs logging:advanced)
if ':' not in name:
name = '{0}:{1}'.format(self.type, name)
r = self._h._http_resource(
method='PUT',
resource=('apps', self.app.name, 'addons', quote(name)),
params=params,
data=' ' # Server weirdness.
)
r.raise_for_status()
return self.app.addons[name]
|
[
"def",
"upgrade",
"(",
"self",
",",
"name",
",",
"params",
"=",
"None",
")",
":",
"# Allow non-namespaced upgrades. (e.g. advanced vs logging:advanced)",
"if",
"':'",
"not",
"in",
"name",
":",
"name",
"=",
"'{0}:{1}'",
".",
"format",
"(",
"self",
".",
"type",
",",
"name",
")",
"r",
"=",
"self",
".",
"_h",
".",
"_http_resource",
"(",
"method",
"=",
"'PUT'",
",",
"resource",
"=",
"(",
"'apps'",
",",
"self",
".",
"app",
".",
"name",
",",
"'addons'",
",",
"quote",
"(",
"name",
")",
")",
",",
"params",
"=",
"params",
",",
"data",
"=",
"' '",
"# Server weirdness.",
")",
"r",
".",
"raise_for_status",
"(",
")",
"return",
"self",
".",
"app",
".",
"addons",
"[",
"name",
"]"
] |
Upgrades an addon to the given tier.
|
[
"Upgrades",
"an",
"addon",
"to",
"the",
"given",
"tier",
"."
] |
cadc0a074896cf29c65a457c5c5bdb2069470af0
|
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L153-L166
|
11,798
|
heroku/heroku.py
|
heroku/models.py
|
App.new
|
def new(self, name=None, stack='cedar', region=None):
"""Creates a new app."""
payload = {}
if name:
payload['app[name]'] = name
if stack:
payload['app[stack]'] = stack
if region:
payload['app[region]'] = region
r = self._h._http_resource(
method='POST',
resource=('apps',),
data=payload
)
name = json.loads(r.content).get('name')
return self._h.apps.get(name)
|
python
|
def new(self, name=None, stack='cedar', region=None):
"""Creates a new app."""
payload = {}
if name:
payload['app[name]'] = name
if stack:
payload['app[stack]'] = stack
if region:
payload['app[region]'] = region
r = self._h._http_resource(
method='POST',
resource=('apps',),
data=payload
)
name = json.loads(r.content).get('name')
return self._h.apps.get(name)
|
[
"def",
"new",
"(",
"self",
",",
"name",
"=",
"None",
",",
"stack",
"=",
"'cedar'",
",",
"region",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"}",
"if",
"name",
":",
"payload",
"[",
"'app[name]'",
"]",
"=",
"name",
"if",
"stack",
":",
"payload",
"[",
"'app[stack]'",
"]",
"=",
"stack",
"if",
"region",
":",
"payload",
"[",
"'app[region]'",
"]",
"=",
"region",
"r",
"=",
"self",
".",
"_h",
".",
"_http_resource",
"(",
"method",
"=",
"'POST'",
",",
"resource",
"=",
"(",
"'apps'",
",",
")",
",",
"data",
"=",
"payload",
")",
"name",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"content",
")",
".",
"get",
"(",
"'name'",
")",
"return",
"self",
".",
"_h",
".",
"apps",
".",
"get",
"(",
"name",
")"
] |
Creates a new app.
|
[
"Creates",
"a",
"new",
"app",
"."
] |
cadc0a074896cf29c65a457c5c5bdb2069470af0
|
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L183-L204
|
11,799
|
heroku/heroku.py
|
heroku/models.py
|
App.collaborators
|
def collaborators(self):
"""The collaborators for this app."""
return self._h._get_resources(
resource=('apps', self.name, 'collaborators'),
obj=Collaborator, app=self
)
|
python
|
def collaborators(self):
"""The collaborators for this app."""
return self._h._get_resources(
resource=('apps', self.name, 'collaborators'),
obj=Collaborator, app=self
)
|
[
"def",
"collaborators",
"(",
"self",
")",
":",
"return",
"self",
".",
"_h",
".",
"_get_resources",
"(",
"resource",
"=",
"(",
"'apps'",
",",
"self",
".",
"name",
",",
"'collaborators'",
")",
",",
"obj",
"=",
"Collaborator",
",",
"app",
"=",
"self",
")"
] |
The collaborators for this app.
|
[
"The",
"collaborators",
"for",
"this",
"app",
"."
] |
cadc0a074896cf29c65a457c5c5bdb2069470af0
|
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L214-L219
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.