sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def clear_message_streams(self): """ Resets streams and sockets of incoming messages. You can use this method to reuse the same connections for several consecutive test cases. """ for client in self._clients: client.empty() for server in self._servers: server.empty()
Resets streams and sockets of incoming messages. You can use this method to reuse the same connections for several consecutive test cases.
entailment
def new_protocol(self, protocol_name): """Start defining a new protocol template. All messages sent and received from a connection that uses a protocol have to conform to this protocol template. """ if self._protocol_in_progress: raise Exception('Can not start a new protocol definition in middle of old.') if protocol_name in self._protocols: raise Exception('Protocol %s already defined' % protocol_name) self._init_new_message_stack(Protocol(protocol_name, library=self)) self._protocol_in_progress = True
Start defining a new protocol template. All messages sent and received from a connection that uses a protocol have to conform to this protocol template.
entailment
def end_protocol(self): """End protocol definition.""" protocol = self._get_message_template() self._protocols[protocol.name] = protocol self._protocol_in_progress = False
End protocol definition.
entailment
def start_udp_server(self, ip, port, name=None, timeout=None, protocol=None, family='ipv4'): """Starts a new UDP server to given `ip` and `port`. Server can be given a `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. Examples: | Start UDP server | 10.10.10.2 | 53 | | Start UDP server | 10.10.10.2 | 53 | Server1 | | Start UDP server | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start UDP server | 10.10.10.2 | 53 | timeout=5 | | Start UDP server | 0:0:0:0:0:0:0:1 | 53 | family=ipv6 | """ self._start_server(UDPServer, ip, port, name, timeout, protocol, family)
Starts a new UDP server to given `ip` and `port`. Server can be given a `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. Examples: | Start UDP server | 10.10.10.2 | 53 | | Start UDP server | 10.10.10.2 | 53 | Server1 | | Start UDP server | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start UDP server | 10.10.10.2 | 53 | timeout=5 | | Start UDP server | 0:0:0:0:0:0:0:1 | 53 | family=ipv6 |
entailment
def start_tcp_server(self, ip, port, name=None, timeout=None, protocol=None, family='ipv4'): """Starts a new TCP server to given `ip` and `port`. Server can be given a `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. Notice that you have to use `Accept Connection` keyword for server to receive connections. Examples: | Start TCP server | 10.10.10.2 | 53 | | Start TCP server | 10.10.10.2 | 53 | Server1 | | Start TCP server | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start TCP server | 10.10.10.2 | 53 | timeout=5 | | Start TCP server | 0:0:0:0:0:0:0:1 | 53 | family=ipv6 | """ self._start_server(TCPServer, ip, port, name, timeout, protocol, family)
Starts a new TCP server to given `ip` and `port`. Server can be given a `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. Notice that you have to use `Accept Connection` keyword for server to receive connections. Examples: | Start TCP server | 10.10.10.2 | 53 | | Start TCP server | 10.10.10.2 | 53 | Server1 | | Start TCP server | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start TCP server | 10.10.10.2 | 53 | timeout=5 | | Start TCP server | 0:0:0:0:0:0:0:1 | 53 | family=ipv6 |
entailment
def start_sctp_server(self, ip, port, name=None, timeout=None, protocol=None, family='ipv4'): """Starts a new STCP server to given `ip` and `port`. `family` can be either ipv4 (default) or ipv6. pysctp (https://github.com/philpraxis/pysctp) need to be installed your system. Server can be given a `name`, default `timeout` and a `protocol`. Notice that you have to use `Accept Connection` keyword for server to receive connections. Examples: | Start STCP server | 10.10.10.2 | 53 | | Start STCP server | 10.10.10.2 | 53 | Server1 | | Start STCP server | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start STCP server | 10.10.10.2 | 53 | timeout=5 | """ self._start_server(SCTPServer, ip, port, name, timeout, protocol, family)
Starts a new STCP server to given `ip` and `port`. `family` can be either ipv4 (default) or ipv6. pysctp (https://github.com/philpraxis/pysctp) need to be installed your system. Server can be given a `name`, default `timeout` and a `protocol`. Notice that you have to use `Accept Connection` keyword for server to receive connections. Examples: | Start STCP server | 10.10.10.2 | 53 | | Start STCP server | 10.10.10.2 | 53 | Server1 | | Start STCP server | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start STCP server | 10.10.10.2 | 53 | timeout=5 |
entailment
def start_udp_client(self, ip=None, port=None, name=None, timeout=None, protocol=None, family='ipv4'): """Starts a new UDP client. Client can be optionally given `ip` and `port` to bind to, as well as `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. You should use `Connect` keyword to connect client to a host. Examples: | Start UDP client | | Start UDP client | name=Client1 | protocol=GTPV2 | | Start UDP client | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start UDP client | timeout=5 | | Start UDP client | 0:0:0:0:0:0:0:1 | 53 | family=ipv6 | """ self._start_client(UDPClient, ip, port, name, timeout, protocol, family)
Starts a new UDP client. Client can be optionally given `ip` and `port` to bind to, as well as `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. You should use `Connect` keyword to connect client to a host. Examples: | Start UDP client | | Start UDP client | name=Client1 | protocol=GTPV2 | | Start UDP client | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start UDP client | timeout=5 | | Start UDP client | 0:0:0:0:0:0:0:1 | 53 | family=ipv6 |
entailment
def start_tcp_client(self, ip=None, port=None, name=None, timeout=None, protocol=None, family='ipv4'): """Starts a new TCP client. Client can be optionally given `ip` and `port` to bind to, as well as `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. You should use `Connect` keyword to connect client to a host. Examples: | Start TCP client | | Start TCP client | name=Client1 | protocol=GTPV2 | | Start TCP client | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start TCP client | timeout=5 | | Start TCP client | 0:0:0:0:0:0:0:1 | 53 | family=ipv6 | """ self._start_client(TCPClient, ip, port, name, timeout, protocol, family)
Starts a new TCP client. Client can be optionally given `ip` and `port` to bind to, as well as `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. You should use `Connect` keyword to connect client to a host. Examples: | Start TCP client | | Start TCP client | name=Client1 | protocol=GTPV2 | | Start TCP client | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start TCP client | timeout=5 | | Start TCP client | 0:0:0:0:0:0:0:1 | 53 | family=ipv6 |
entailment
def start_sctp_client(self, ip=None, port=None, name=None, timeout=None, protocol=None, family='ipv4'): """Starts a new SCTP client. Client can be optionally given `ip` and `port` to bind to, as well as `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. You should use `Connect` keyword to connect client to a host. Examples: | Start TCP client | | Start TCP client | name=Client1 | protocol=GTPV2 | | Start TCP client | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start TCP client | timeout=5 | """ self._start_client(SCTPClient, ip, port, name, timeout, protocol, family)
Starts a new SCTP client. Client can be optionally given `ip` and `port` to bind to, as well as `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. You should use `Connect` keyword to connect client to a host. Examples: | Start TCP client | | Start TCP client | name=Client1 | protocol=GTPV2 | | Start TCP client | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 | | Start TCP client | timeout=5 |
entailment
def accept_connection(self, name=None, alias=None, timeout=0): """Accepts a connection to server identified by `name` or the latest server if `name` is empty. If given an `alias`, the connection is named and can be later referenced with that name. If `timeout` is > 0, the connection times out after the time specified. `timeout` defaults to 0 which will wait indefinitely. Empty value or None will use socket default timeout. Examples: | Accept connection | | Accept connection | Server1 | my_connection | | Accept connection | Server1 | my_connection | timeout=5 | """ server = self._servers.get(name) server.accept_connection(alias, timeout)
Accepts a connection to server identified by `name` or the latest server if `name` is empty. If given an `alias`, the connection is named and can be later referenced with that name. If `timeout` is > 0, the connection times out after the time specified. `timeout` defaults to 0 which will wait indefinitely. Empty value or None will use socket default timeout. Examples: | Accept connection | | Accept connection | Server1 | my_connection | | Accept connection | Server1 | my_connection | timeout=5 |
entailment
def connect(self, host, port, name=None): """Connects a client to given `host` and `port`. If client `name` is not given then connects the latest client. Examples: | Connect | 127.0.0.1 | 8080 | | Connect | 127.0.0.1 | 8080 | Client1 | """ client = self._clients.get(name) client.connect_to(host, port)
Connects a client to given `host` and `port`. If client `name` is not given then connects the latest client. Examples: | Connect | 127.0.0.1 | 8080 | | Connect | 127.0.0.1 | 8080 | Client1 |
entailment
def client_sends_binary(self, message, name=None, label=None): """Send raw binary `message`. If client `name` is not given, uses the latest client. Optional message `label` is shown on logs. Examples: | Client sends binary | Hello! | | Client sends binary | ${some binary} | Client1 | label=DebugMessage | """ client, name = self._clients.get_with_name(name) client.send(message) self._register_send(client, label, name)
Send raw binary `message`. If client `name` is not given, uses the latest client. Optional message `label` is shown on logs. Examples: | Client sends binary | Hello! | | Client sends binary | ${some binary} | Client1 | label=DebugMessage |
entailment
def server_sends_binary(self, message, name=None, connection=None, label=None): """Send raw binary `message`. If server `name` is not given, uses the latest server. Optional message `label` is shown on logs. Examples: | Server sends binary | Hello! | | Server sends binary | ${some binary} | Server1 | label=DebugMessage | | Server sends binary | ${some binary} | connection=my_connection | """ server, name = self._servers.get_with_name(name) server.send(message, alias=connection) self._register_send(server, label, name, connection=connection)
Send raw binary `message`. If server `name` is not given, uses the latest server. Optional message `label` is shown on logs. Examples: | Server sends binary | Hello! | | Server sends binary | ${some binary} | Server1 | label=DebugMessage | | Server sends binary | ${some binary} | connection=my_connection |
entailment
def client_receives_binary(self, name=None, timeout=None, label=None): """Receive raw binary message. If client `name` is not given, uses the latest client. Optional message `label` is shown on logs. Examples: | ${binary} = | Client receives binary | | ${binary} = | Client receives binary | Client1 | timeout=5 | """ client, name = self._clients.get_with_name(name) msg = client.receive(timeout=timeout) self._register_receive(client, label, name) return msg
Receive raw binary message. If client `name` is not given, uses the latest client. Optional message `label` is shown on logs. Examples: | ${binary} = | Client receives binary | | ${binary} = | Client receives binary | Client1 | timeout=5 |
entailment
def server_receives_binary(self, name=None, timeout=None, connection=None, label=None): """Receive raw binary message. If server `name` is not given, uses the latest server. Optional message `label` is shown on logs. Examples: | ${binary} = | Server receives binary | | ${binary} = | Server receives binary | Server1 | connection=my_connection | timeout=5 | """ return self.server_receives_binary_from(name, timeout, connection=connection, label=label)[0]
Receive raw binary message. If server `name` is not given, uses the latest server. Optional message `label` is shown on logs. Examples: | ${binary} = | Server receives binary | | ${binary} = | Server receives binary | Server1 | connection=my_connection | timeout=5 |
entailment
def server_receives_binary_from(self, name=None, timeout=None, connection=None, label=None): """Receive raw binary message. Returns message, ip, and port. If server `name` is not given, uses the latest server. Optional message `label` is shown on logs. Examples: | ${binary} | ${ip} | ${port} = | Server receives binary from | | ${binary} | ${ip} | ${port} = | Server receives binary from | Server1 | connection=my_connection | timeout=5 | """ server, name = self._servers.get_with_name(name) msg, ip, port = server.receive_from(timeout=timeout, alias=connection) self._register_receive(server, label, name, connection=connection) return msg, ip, port
Receive raw binary message. Returns message, ip, and port. If server `name` is not given, uses the latest server. Optional message `label` is shown on logs. Examples: | ${binary} | ${ip} | ${port} = | Server receives binary from | | ${binary} | ${ip} | ${port} = | Server receives binary from | Server1 | connection=my_connection | timeout=5 |
entailment
def new_message(self, message_name, protocol=None, *parameters): """Define a new message template with `message_name`. `protocol` has to be defined earlier with `Start Protocol Description`. Optional parameters are default values for message header separated with colon. Examples: | New message | MyMessage | MyProtocol | header_field:value | """ proto = self._get_protocol(protocol) if not proto: raise Exception("Protocol not defined! Please define a protocol before creating a message!") if self._protocol_in_progress: raise Exception("Protocol definition in progress. Please finish it before starting to define a message.") configs, fields, header_fields = self._parse_parameters(parameters) self._raise_error_if_configs_or_fields(configs, fields, 'New message') self._init_new_message_stack(MessageTemplate(message_name, proto, header_fields))
Define a new message template with `message_name`. `protocol` has to be defined earlier with `Start Protocol Description`. Optional parameters are default values for message header separated with colon. Examples: | New message | MyMessage | MyProtocol | header_field:value |
entailment
def save_template(self, name, unlocked=False): """Save a message template for later use with `Load template`. If saved template is marked as unlocked, then changes can be made to it afterwards. By default tempaltes are locked. Examples: | Save Template | MyMessage | | Save Template | MyOtherMessage | unlocked=True | """ if isinstance(unlocked, basestring): unlocked = unlocked.lower() != 'false' template = self._get_message_template() if not unlocked: template.set_as_saved() self._message_templates[name] = (template, self._field_values)
Save a message template for later use with `Load template`. If saved template is marked as unlocked, then changes can be made to it afterwards. By default tempaltes are locked. Examples: | Save Template | MyMessage | | Save Template | MyOtherMessage | unlocked=True |
entailment
def load_template(self, name, *parameters): """Load a message template saved with `Save template`. Optional parameters are default values for message header separated with colon. Examples: | Load Template | MyMessage | header_field:value | """ template, fields, header_fields = self._set_templates_fields_and_header_fields(name, parameters) self._init_new_message_stack(template, fields, header_fields)
Load a message template saved with `Save template`. Optional parameters are default values for message header separated with colon. Examples: | Load Template | MyMessage | header_field:value |
entailment
def load_copy_of_template(self, name, *parameters): """Load a copy of message template saved with `Save template` when originally saved values need to be preserved from test to test. Optional parameters are default values for message header separated with colon. Examples: | Load Copy Of Template | MyMessage | header_field:value | """ template, fields, header_fields = self._set_templates_fields_and_header_fields(name, parameters) copy_of_template = copy.deepcopy(template) copy_of_fields = copy.deepcopy(fields) self._init_new_message_stack(copy_of_template, copy_of_fields, header_fields)
Load a copy of message template saved with `Save template` when originally saved values need to be preserved from test to test. Optional parameters are default values for message header separated with colon. Examples: | Load Copy Of Template | MyMessage | header_field:value |
entailment
def get_message(self, *parameters): """Get encoded message. * Send Message -keywords are convenience methods, that will call this to get the message object and then send it. Optional parameters are message field values separated with colon. Examples: | ${msg} = | Get message | | ${msg} = | Get message | field_name:value | """ _, message_fields, header_fields = self._get_parameters_with_defaults(parameters) return self._encode_message(message_fields, header_fields)
Get encoded message. * Send Message -keywords are convenience methods, that will call this to get the message object and then send it. Optional parameters are message field values separated with colon. Examples: | ${msg} = | Get message | | ${msg} = | Get message | field_name:value |
entailment
def client_receives_message(self, *parameters): """Receive a message with template defined using `New Message` and validate field values. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is the latest used) example: `name=Client 1` - `timeout` for receiving message. example: `timeout=0.1` - `latest` if set to True, get latest message from buffer instead first. Default is False. Example: `latest=True` - message field values for validation separated with colon. example: `some_field:0xaf05` Examples: | ${msg} = | Client receives message | | ${msg} = | Client receives message | name=Client1 | timeout=5 | | ${msg} = | Client receives message | message_field:(0|1) | """ with self._receive(self._clients, *parameters) as (msg, message_fields, header_fields): self._validate_message(msg, message_fields, header_fields) return msg
Receive a message with template defined using `New Message` and validate field values. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is the latest used) example: `name=Client 1` - `timeout` for receiving message. example: `timeout=0.1` - `latest` if set to True, get latest message from buffer instead first. Default is False. Example: `latest=True` - message field values for validation separated with colon. example: `some_field:0xaf05` Examples: | ${msg} = | Client receives message | | ${msg} = | Client receives message | name=Client1 | timeout=5 | | ${msg} = | Client receives message | message_field:(0|1) |
entailment
def client_receives_without_validation(self, *parameters): """Receive a message with template defined using `New Message`. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is the latest used) example: `name=Client 1` - `timeout` for receiving message. example: `timeout=0.1` - `latest` if set to True, get latest message from buffer instead first. Default is False. Example: `latest=True` Examples: | ${msg} = | Client receives without validation | | ${msg} = | Client receives without validation | name=Client1 | timeout=5 | """ with self._receive(self._clients, *parameters) as (msg, _, _): return msg
Receive a message with template defined using `New Message`. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is the latest used) example: `name=Client 1` - `timeout` for receiving message. example: `timeout=0.1` - `latest` if set to True, get latest message from buffer instead first. Default is False. Example: `latest=True` Examples: | ${msg} = | Client receives without validation | | ${msg} = | Client receives without validation | name=Client1 | timeout=5 |
entailment
def server_receives_message(self, *parameters): """Receive a message with template defined using `New Message` and validate field values. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is the latest used) example: `name=Client 1` - `connection` alias. example: `connection=connection 1` - `timeout` for receiving message. example: `timeout=0.1` - `latest` if set to True, get latest message from buffer instead first. Default is False. Example: `latest=True` - message field values for validation separated with colon. example: `some_field:0xaf05` Optional parameters are server `name`, `connection` alias and possible `timeout` separated with equals and message field values for validation separated with colon. Examples: | ${msg} = | Server receives message | | ${msg} = | Server receives message | name=Server1 | alias=my_connection | timeout=5 | | ${msg} = | Server receives message | message_field:(0|1) | """ with self._receive(self._servers, *parameters) as (msg, message_fields, header_fields): self._validate_message(msg, message_fields, header_fields) return msg
Receive a message with template defined using `New Message` and validate field values. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is the latest used) example: `name=Client 1` - `connection` alias. example: `connection=connection 1` - `timeout` for receiving message. example: `timeout=0.1` - `latest` if set to True, get latest message from buffer instead first. Default is False. Example: `latest=True` - message field values for validation separated with colon. example: `some_field:0xaf05` Optional parameters are server `name`, `connection` alias and possible `timeout` separated with equals and message field values for validation separated with colon. Examples: | ${msg} = | Server receives message | | ${msg} = | Server receives message | name=Server1 | alias=my_connection | timeout=5 | | ${msg} = | Server receives message | message_field:(0|1) |
entailment
def server_receives_without_validation(self, *parameters): """Receive a message with template defined using `New Message`. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is the latest used) example: `name=Client 1` - `connection` alias. example: `connection=connection 1` - `timeout` for receiving message. example: `timeout=0.1` - `latest` if set to True, get latest message from buffer instead first. Default is False. Example: `latest=True` Examples: | ${msg} = | Server receives without validation | | ${msg} = | Server receives without validation | name=Server1 | alias=my_connection | timeout=5 | """ with self._receive(self._servers, *parameters) as (msg, _, _): return msg
Receive a message with template defined using `New Message`. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is the latest used) example: `name=Client 1` - `connection` alias. example: `connection=connection 1` - `timeout` for receiving message. example: `timeout=0.1` - `latest` if set to True, get latest message from buffer instead first. Default is False. Example: `latest=True` Examples: | ${msg} = | Server receives without validation | | ${msg} = | Server receives without validation | name=Server1 | alias=my_connection | timeout=5 |
entailment
def validate_message(self, msg, *parameters): """Validates given message using template defined with `New Message` and field values given as optional arguments. Examples: | Validate message | ${msg} | | Validate message | ${msg} | status:0 | """ _, message_fields, header_fields = self._get_parameters_with_defaults(parameters) self._validate_message(msg, message_fields, header_fields)
Validates given message using template defined with `New Message` and field values given as optional arguments. Examples: | Validate message | ${msg} | | Validate message | ${msg} | status:0 |
entailment
def uint(self, length, name, value=None, align=None): """Add an unsigned integer to template. `length` is given in bytes and `value` is optional. `align` can be used to align the field to longer byte length. Examples: | uint | 2 | foo | | uint | 2 | foo | 42 | | uint | 2 | fourByteFoo | 42 | align=4 | """ self._add_field(UInt(length, name, value, align=align))
Add an unsigned integer to template. `length` is given in bytes and `value` is optional. `align` can be used to align the field to longer byte length. Examples: | uint | 2 | foo | | uint | 2 | foo | 42 | | uint | 2 | fourByteFoo | 42 | align=4 |
entailment
def int(self, length, name, value=None, align=None): """Add an signed integer to template. `length` is given in bytes and `value` is optional. `align` can be used to align the field to longer byte length. Signed integer uses twos-complement with bits numbered in big-endian. Examples: | int | 2 | foo | | int | 2 | foo | 42 | | int | 2 | fourByteFoo | 42 | align=4 | """ self._add_field(Int(length, name, value, align=align))
Add an signed integer to template. `length` is given in bytes and `value` is optional. `align` can be used to align the field to longer byte length. Signed integer uses twos-complement with bits numbered in big-endian. Examples: | int | 2 | foo | | int | 2 | foo | 42 | | int | 2 | fourByteFoo | 42 | align=4 |
entailment
def chars(self, length, name, value=None, terminator=None): """Add a char array to template. `length` is given in bytes and can refer to earlier numeric fields in template. Special value '*' in length means that length is encoded to length of value and decoded as all available bytes. `value` is optional. `value` could be either a "String" or a "Regular Expression" and if it is a Regular Expression it must be prefixed by 'REGEXP:'. Examples: | chars | 16 | field | Hello World! | | u8 | charLength | | chars | charLength | field | | chars | * | field | Hello World! | | chars | * | field | REGEXP:^{[a-zA-Z ]+}$ | """ self._add_field(Char(length, name, value, terminator))
Add a char array to template. `length` is given in bytes and can refer to earlier numeric fields in template. Special value '*' in length means that length is encoded to length of value and decoded as all available bytes. `value` is optional. `value` could be either a "String" or a "Regular Expression" and if it is a Regular Expression it must be prefixed by 'REGEXP:'. Examples: | chars | 16 | field | Hello World! | | u8 | charLength | | chars | charLength | field | | chars | * | field | Hello World! | | chars | * | field | REGEXP:^{[a-zA-Z ]+}$ |
entailment
def new_struct(self, type, name, *parameters): """Defines a new struct to template. You must call `End Struct` to end struct definition. `type` is the name for generic type and `name` is the field name in containing structure. Possible parameters are values for struct fields separated with colon and optional struct length defined with `length=`. Length can be used in receiveing to validate that struct matches predfeined length. When sending, the struct length can refer to other message field which will then be set dynamically. Examples: | New struct | Pair | myPair | | u8 | first | | u8 | second | | End Struct | """ configs, parameters, _ = self._get_parameters_with_defaults(parameters) self._add_struct_name_to_params(name, parameters) self._message_stack.append(StructTemplate(type, name, self._current_container, parameters, length=configs.get('length'), align=configs.get('align')))
Defines a new struct to template. You must call `End Struct` to end struct definition. `type` is the name for generic type and `name` is the field name in containing structure. Possible parameters are values for struct fields separated with colon and optional struct length defined with `length=`. Length can be used in receiveing to validate that struct matches predfeined length. When sending, the struct length can refer to other message field which will then be set dynamically. Examples: | New struct | Pair | myPair | | u8 | first | | u8 | second | | End Struct |
entailment
def _new_list(self, size, name): """Defines a new list to template of `size` and with `name`. List type must be given after this keyword by defining one field. Then the list definition has to be closed using `End List`. Special value '*' in size means that list will decode values as long as data is available. This free length value is not supported on encoding. Examples: | New list | 5 | myIntList | | u16 | | End List | | u8 | listLength | | New list | listLength | myIntList | | u16 | | End List | | New list | * | myIntList | | u16 | | End List | """ self._message_stack.append(ListTemplate(size, name, self._current_container))
Defines a new list to template of `size` and with `name`. List type must be given after this keyword by defining one field. Then the list definition has to be closed using `End List`. Special value '*' in size means that list will decode values as long as data is available. This free length value is not supported on encoding. Examples: | New list | 5 | myIntList | | u16 | | End List | | u8 | listLength | | New list | listLength | myIntList | | u16 | | End List | | New list | * | myIntList | | u16 | | End List |
entailment
def new_binary_container(self, name): """Defines a new binary container to template. Binary container can only contain binary fields defined with `Bin` keyword. Examples: | New binary container | flags | | bin | 2 | foo | | bin | 6 | bar | | End binary container | """ self._message_stack.append(BinaryContainerTemplate(name, self._current_container))
Defines a new binary container to template. Binary container can only contain binary fields defined with `Bin` keyword. Examples: | New binary container | flags | | bin | 2 | foo | | bin | 6 | bar | | End binary container |
entailment
def end_binary_container(self): """End binary container. See `New Binary Container`. """ binary_container = self._message_stack.pop() binary_container.verify() self._add_field(binary_container)
End binary container. See `New Binary Container`.
entailment
def bin(self, size, name, value=None): """Add new binary field to template. This keyword has to be called within a binary container. See `New Binary Container`. """ self._add_field(Binary(size, name, value))
Add new binary field to template. This keyword has to be called within a binary container. See `New Binary Container`.
entailment
def new_union(self, type, name): """Defines a new union to template of `type` and `name`. Fields inside the union are alternatives and the length of the union is the length of its longest field. Example: | New union | IntOrAddress | foo | | Chars | 16 | ipAddress | | u32 | int | | End union | """ self._message_stack.append(UnionTemplate(type, name, self._current_container))
Defines a new union to template of `type` and `name`. Fields inside the union are alternatives and the length of the union is the length of its longest field. Example: | New union | IntOrAddress | foo | | Chars | 16 | ipAddress | | u32 | int | | End union |
entailment
def start_bag(self, name): """Bags are sets of optional elements with an optional count. The optional elements are given each as a `Case` with the accepted count as first argument. The received elements are matched from the list of cases in order. If the the received value does not validate against the case (for example a value of a field does not match expected), then the next case is tried until a match is found. Note that although the received elements are matched in order that the cases are given, the elements dont need to arrive in the same order as the cases are. This example would match int value 42 0-1 times and in value 1 0-2 times. For example 1, 42, 1 would match, as would 1, 1: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag | A more real world example, where each AVP entry has a type field with a value that is used for matching: | Start bag | avps | | Case | 1 | AVP | result | Result-Code | | Case | 1 | AVP | originHost | Origin-Host | | Case | 1 | AVP | originRealm | Origin-Realm | | Case | 1 | AVP | hostIP | Host-IP-Address | | Case | * | AVP | appId | Vendor-Specific-Application-Id | | Case | 0-1 | AVP | originState | Origin-State | | End bag | For a more complete example on bags, see the [https://github.com/robotframework/Rammbock/blob/master/atest/diameter.robot|diameter.robot] file from Rammbock's acceptance tests. """ self._message_stack.append(BagTemplate(name, self._current_container))
Bags are sets of optional elements with an optional count. The optional elements are given each as a `Case` with the accepted count as first argument. The received elements are matched from the list of cases in order. If the the received value does not validate against the case (for example a value of a field does not match expected), then the next case is tried until a match is found. Note that although the received elements are matched in order that the cases are given, the elements dont need to arrive in the same order as the cases are. This example would match int value 42 0-1 times and in value 1 0-2 times. For example 1, 42, 1 would match, as would 1, 1: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag | A more real world example, where each AVP entry has a type field with a value that is used for matching: | Start bag | avps | | Case | 1 | AVP | result | Result-Code | | Case | 1 | AVP | originHost | Origin-Host | | Case | 1 | AVP | originRealm | Origin-Realm | | Case | 1 | AVP | hostIP | Host-IP-Address | | Case | * | AVP | appId | Vendor-Specific-Application-Id | | Case | 0-1 | AVP | originState | Origin-State | | End bag | For a more complete example on bags, see the [https://github.com/robotframework/Rammbock/blob/master/atest/diameter.robot|diameter.robot] file from Rammbock's acceptance tests.
entailment
def value(self, name, value): """Defines a default `value` for a template field identified by `name`. Default values for header fields can be set with header:field syntax. Examples: | Value | foo | 42 | | Value | struct.sub_field | 0xcafe | | Value | header:version | 0x02 | """ if isinstance(value, _StructuredElement): self._struct_fields_as_values(name, value) elif name.startswith('header:'): self._header_values[name.partition(':')[-1]] = value else: self._field_values[name] = value
Defines a default `value` for a template field identified by `name`. Default values for header fields can be set with header:field syntax. Examples: | Value | foo | 42 | | Value | struct.sub_field | 0xcafe | | Value | header:version | 0x02 |
entailment
def conditional(self, condition, name): """Defines a 'condition' when conditional element of 'name' exists if `condition` is true. `condition` can contain multiple conditions combined together using Logical Expressions(&&,||). Example: | Conditional | mycondition == 1 | foo | | u8 | myelement | 42 | | End conditional | | Conditional | condition1 == 1 && condition2 != 2 | bar | | u8 | myelement | 8 | | End condtional | """ self._message_stack.append(ConditionalTemplate(condition, name, self._current_container))
Defines a 'condition' when conditional element of 'name' exists if `condition` is true. `condition` can contain multiple conditions combined together using Logical Expressions(&&,||). Example: | Conditional | mycondition == 1 | foo | | u8 | myelement | 42 | | End conditional | | Conditional | condition1 == 1 && condition2 != 2 | bar | | u8 | myelement | 8 | | End condtional |
entailment
def get_client_unread_messages_count(self, client_name=None): """Gets count of unread messages from client """ client = self._clients.get_with_name(client_name)[0] return client.get_messages_count_in_buffer()
Gets count of unread messages from client
entailment
def get_server_unread_messages_count(self, server_name=None): """Gets count of unread messages from server """ server = self._servers.get(server_name) return server.get_messages_count_in_buffer()
Gets count of unread messages from server
entailment
def to_twos_comp(val, bits): """compute the 2's compliment of int value val""" if not val.startswith('-'): return to_int(val) value = _invert(to_bin_str_from_int_string(bits, bin(to_int(val[1:])))) return int(value, 2) + 1
compute the 2's compliment of int value val
entailment
def u8(self, name, value=None, align=None): """Add an unsigned 1 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(1, name, value, align)
Add an unsigned 1 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
entailment
def u16(self, name, value=None, align=None): """Add an unsigned 2 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(2, name, value, align)
Add an unsigned 2 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
entailment
def u24(self, name, value=None, align=None): """Add an unsigned 3 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(3, name, value, align)
Add an unsigned 3 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
entailment
def u32(self, name, value=None, align=None): """Add an unsigned 4 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(4, name, value, align)
Add an unsigned 4 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
entailment
def u40(self, name, value=None, align=None): """Add an unsigned 5 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(5, name, value, align)
Add an unsigned 5 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
entailment
def u64(self, name, value=None, align=None): """Add an unsigned 8 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(8, name, value, align)
Add an unsigned 8 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
entailment
def u128(self, name, value=None, align=None): """Add an unsigned 16 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(16, name, value, align)
Add an unsigned 16 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
entailment
def i8(self, name, value=None, align=None): """Add an 1 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.""" self.int(1, name, value, align)
Add an 1 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.
entailment
def i32(self, name, value=None, align=None): """Add an 32 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.""" self.int(4, name, value, align)
Add an 32 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.
entailment
def array(self, size, type, name, *parameters): """Define a new array of given `size` and containing fields of type `type`. `name` if the name of this array element. The `type` is the name of keyword that is executed as the contents of the array and optional extra parameters are passed as arguments to this keyword. Examples: | Array | 8 | u16 | myArray | | u32 | length | | Array | length | someStruct | myArray | <argument for someStruct> | """ self._new_list(size, name) BuiltIn().run_keyword(type, '', *parameters) self._end_list()
Define a new array of given `size` and containing fields of type `type`. `name` if the name of this array element. The `type` is the name of keyword that is executed as the contents of the array and optional extra parameters are passed as arguments to this keyword. Examples: | Array | 8 | u16 | myArray | | u32 | length | | Array | length | someStruct | myArray | <argument for someStruct> |
entailment
def container(self, name, length, type, *parameters): """Define a container with given length. This is a convenience method creating a `Struct` with `length` containing fields defined in `type`. """ self.new_struct('Container', name, 'length=%s' % length) BuiltIn().run_keyword(type, *parameters) self.end_struct()
Define a container with given length. This is a convenience method creating a `Struct` with `length` containing fields defined in `type`.
entailment
def case(self, size, kw, *parameters): """An element inside a bag started with `Start Bag`. The first argument is size which can be absolute value like `1`, a range like `0-3`, or just `*` to accept any number of elements. Examples: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag | """ # TODO: check we are inside a bag! self._start_bag_case(size) BuiltIn().run_keyword(kw, *parameters) self._end_bag_case()
An element inside a bag started with `Start Bag`. The first argument is size which can be absolute value like `1`, a range like `0-3`, or just `*` to accept any number of elements. Examples: | Start bag | intBag | | case | 0-1 | u8 | foo | 42 | | case | 0-2 | u8 | bar | 1 | | End bag |
entailment
def embed_seqdiag_sequence(self): """Create a message sequence diagram png file to output folder and embed the image to log file. You need to have seqdiag installed to create the sequence diagram. See http://blockdiag.com/en/seqdiag/ """ test_name = BuiltIn().replace_variables('${TEST NAME}') outputdir = BuiltIn().replace_variables('${OUTPUTDIR}') path = os.path.join(outputdir, test_name + '.seqdiag') SeqdiagGenerator().compile(path, self._message_sequence)
Create a message sequence diagram png file to output folder and embed the image to log file. You need to have seqdiag installed to create the sequence diagram. See http://blockdiag.com/en/seqdiag/
entailment
def local_error(self, originalValue, calculatedValue): """Calculates the error between the two given values. :param list originalValue: List containing the values of the original data. :param list calculatedValue: List containing the values of the calculated TimeSeries that corresponds to originalValue. :return: Returns the error measure of the two given values. :rtype: numeric """ originalValue = originalValue[0] calculatedValue = calculatedValue[0] # error is zero if not originalValue and not calculatedValue: return 0.0 return abs(calculatedValue - originalValue)/ ((abs(originalValue) + abs(calculatedValue))/2) * 100
Calculates the error between the two given values. :param list originalValue: List containing the values of the original data. :param list calculatedValue: List containing the values of the calculated TimeSeries that corresponds to originalValue. :return: Returns the error measure of the two given values. :rtype: numeric
entailment
def tostring(self, inject): """ Convert an element to a single string and allow the passed inject method to place content before any element. """ injected_parts = '' for part in self.parts: injected = part.tostring(inject) tei_tag = next( (attribute for attribute in part.attributes if attribute.key == "tei-tag"), None) if tei_tag and tei_tag.text == "w" and injected_parts: # make sure words can be tokenized correctly if injected_parts and injected_parts[-1] != ' ': injected_parts += ' ' injected_parts += injected.strip() + ' ' else: injected_parts += injected return inject(self, injected_parts)
Convert an element to a single string and allow the passed inject method to place content before any element.
entailment
def _create_parser(self): """ Create a parser hooking up the command methods below to be run when chosen. :return: CommandParser parser with commands attached. """ parser = CommandParser(get_internal_version_str()) parser.register_list_command(self._setup_run_command(ListCommand)) parser.register_upload_command(self._setup_run_command(UploadCommand)) parser.register_add_user_command(self._setup_run_command(AddUserCommand)) parser.register_remove_user_command(self._setup_run_command(RemoveUserCommand)) parser.register_download_command(self._setup_run_command(DownloadCommand)) parser.register_share_command(self._setup_run_command(ShareCommand)) parser.register_deliver_command(self._setup_run_command(DeliverCommand)) parser.register_delete_command(self._setup_run_command(DeleteCommand)) parser.register_list_auth_roles_command(self._setup_run_command(ListAuthRolesCommand)) return parser
Create a parser hooking up the command methods below to be run when chosen. :return: CommandParser parser with commands attached.
entailment
def _check_pypi_version(self): """ When the version is out of date or we have trouble retrieving it print a error to stderr and pause. """ try: check_version() except VersionException as err: print(str(err), file=sys.stderr) time.sleep(TWO_SECONDS)
When the version is out of date or we have trouble retrieving it print a error to stderr and pause.
entailment
def _run_command(self, command_constructor, args): """ Run command_constructor and call run(args) on the resulting object :param command_constructor: class of an object that implements run(args) :param args: object arguments for specific command created by CommandParser """ verify_terminal_encoding(sys.stdout.encoding) self._check_pypi_version() config = create_config(allow_insecure_config_file=args.allow_insecure_config_file) self.show_error_stack_trace = config.debug_mode command = command_constructor(config) command.run(args)
Run command_constructor and call run(args) on the resulting object :param command_constructor: class of an object that implements run(args) :param args: object arguments for specific command created by CommandParser
entailment
def make_user_list(self, emails, usernames): """ Given a list of emails and usernames fetch DukeDS user info. Parameters that are None will be skipped. :param emails: [str]: list of emails (can be null) :param usernames: [str]: list of usernames(netid) :return: [RemoteUser]: details about any users referenced the two parameters """ to_users = [] remaining_emails = [] if not emails else list(emails) remaining_usernames = [] if not usernames else list(usernames) for user in self.remote_store.fetch_users(): if user.email in remaining_emails: to_users.append(user) remaining_emails.remove(user.email) elif user.username in remaining_usernames: to_users.append(user) remaining_usernames.remove(user.username) if remaining_emails or remaining_usernames: unable_to_find_users = ','.join(remaining_emails + remaining_usernames) msg = "Unable to find users for the following email/usernames: {}".format(unable_to_find_users) raise ValueError(msg) return to_users
Given a list of emails and usernames fetch DukeDS user info. Parameters that are None will be skipped. :param emails: [str]: list of emails (can be null) :param usernames: [str]: list of usernames(netid) :return: [RemoteUser]: details about any users referenced the two parameters
entailment
def run(self, args): """ Upload contents of folders to a project with project_name on remote store. If follow_symlinks we will traverse symlinked directories. If content is already on remote site it will not be sent. :param args: Namespace arguments parsed from the command line. """ project_name_or_id = self.create_project_name_or_id_from_args(args) folders = args.folders # list of local files/folders to upload into the project follow_symlinks = args.follow_symlinks # should we follow symlinks when traversing folders dry_run = args.dry_run # do not upload anything, instead print out what you would upload project_upload = ProjectUpload(self.config, project_name_or_id, folders, follow_symlinks=follow_symlinks) if dry_run: print(project_upload.dry_run_report()) else: print(project_upload.get_differences_summary()) if project_upload.needs_to_upload(): project_upload.run() print('\n') print(project_upload.get_upload_report()) print('\n') print(project_upload.get_url_msg())
Upload contents of folders to a project with project_name on remote store. If follow_symlinks we will traverse symlinked directories. If content is already on remote site it will not be sent. :param args: Namespace arguments parsed from the command line.
entailment
def run(self, args): """ Download a project based on passed in args. :param args: Namespace arguments parsed from the command line. """ project_name_or_id = self.create_project_name_or_id_from_args(args) folder = args.folder # path to a folder to download data into # Default to project name with spaces replaced with '_' if not specified if not folder: folder = replace_invalid_path_chars(project_name_or_id.value.replace(' ', '_')) destination_path = format_destination_path(folder) path_filter = PathFilter(args.include_paths, args.exclude_paths) project = self.fetch_project(args, must_exist=True) project_download = ProjectDownload(self.remote_store, project, destination_path, path_filter) project_download.run()
Download a project based on passed in args. :param args: Namespace arguments parsed from the command line.
entailment
def run(self, args): """ Give the user with user_full_name the auth_role permissions on the remote project with project_name. :param args Namespace arguments parsed from the command line """ email = args.email # email of person to give permissions, will be None if username is specified username = args.username # username of person to give permissions, will be None if email is specified auth_role = args.auth_role # type of permission(project_admin) project = self.fetch_project(args, must_exist=True, include_children=False) user = self.remote_store.lookup_or_register_user_by_email_or_username(email, username) self.remote_store.set_user_project_permission(project, user, auth_role) print(u'Gave user {} {} permissions for project {}.'.format(user.full_name, auth_role, project.name))
Give the user with user_full_name the auth_role permissions on the remote project with project_name. :param args Namespace arguments parsed from the command line
entailment
def run(self, args): """ Remove permissions from the user with user_full_name or email on the remote project with project_name. :param args Namespace arguments parsed from the command line """ email = args.email # email of person to remove permissions from (None if username specified) username = args.username # username of person to remove permissions from (None if email is specified) project = self.fetch_project(args, must_exist=True, include_children=False) user = self.remote_store.lookup_or_register_user_by_email_or_username(email, username) self.remote_store.revoke_user_project_permission(project, user) print(u'Removed permissions from user {} for project {}.'.format(user.full_name, project.name))
Remove permissions from the user with user_full_name or email on the remote project with project_name. :param args Namespace arguments parsed from the command line
entailment
def run(self, args): """ Gives user permission based on auth_role arg and sends email to that user. :param args Namespace arguments parsed from the command line """ email = args.email # email of person to send email to username = args.username # username of person to send email to, will be None if email is specified force_send = args.resend # is this a resend so we should force sending auth_role = args.auth_role # authorization role(project permissions) to give to the user msg_file = args.msg_file # message file who's contents will be sent with the share message = read_argument_file_contents(msg_file) print("Sharing project.") to_user = self.remote_store.lookup_or_register_user_by_email_or_username(email, username) try: project = self.fetch_project(args, must_exist=True, include_children=False) dest_email = self.service.share(project, to_user, force_send, auth_role, message) print("Share email message sent to " + dest_email) except D4S2Error as ex: if ex.warning: print(ex.message) else: raise
Gives user permission based on auth_role arg and sends email to that user. :param args Namespace arguments parsed from the command line
entailment
def run(self, args): """ Begins process that will transfer the project to another user. Send delivery message to D4S2 service specifying a project and a user. When user accepts delivery they receive access and we lose admin privileges. :param args Namespace arguments parsed from the command line """ email = args.email # email of person to deliver to, will be None if username is specified username = args.username # username of person to deliver to, will be None if email is specified copy_project = args.copy_project # should we deliver a copy of the project force_send = args.resend # is this a resend so we should force sending msg_file = args.msg_file # message file who's contents will be sent with the delivery share_usernames = args.share_usernames # usernames who will have this project shared once it is accepted share_emails = args.share_emails # emails of users who will have this project shared once it is accepted message = read_argument_file_contents(msg_file) project = self.fetch_project(args, must_exist=True, include_children=False) share_users = self.make_user_list(share_emails, share_usernames) print("Delivering project.") new_project_name = None if copy_project: new_project_name = self.get_new_project_name(project.name) to_user = self.remote_store.lookup_or_register_user_by_email_or_username(email, username) try: path_filter = PathFilter(args.include_paths, args.exclude_paths) dest_email = self.service.deliver(project, new_project_name, to_user, share_users, force_send, path_filter, message) print("Delivery email message sent to " + dest_email) except D4S2Error as ex: if ex.warning: print(ex.message) else: raise
Begins process that will transfer the project to another user. Send delivery message to D4S2 service specifying a project and a user. When user accepts delivery they receive access and we lose admin privileges. :param args Namespace arguments parsed from the command line
entailment
def get_new_project_name(self, project_name): """ Return a unique project name for the copy. :param project_name: str: name of project we will copy :return: str """ timestamp_str = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M') return "{} {}".format(project_name, timestamp_str)
Return a unique project name for the copy. :param project_name: str: name of project we will copy :return: str
entailment
def run(self, args): """ Lists project names. :param args Namespace arguments parsed from the command line """ long_format = args.long_format # project_name and auth_role args are mutually exclusive if args.project_name or args.project_id: project = self.fetch_project(args, must_exist=True, include_children=True) self.print_project_details(project, long_format) else: self.print_project_list_details(args.auth_role, long_format)
Lists project names. :param args Namespace arguments parsed from the command line
entailment
def print_project_list_details(self, filter_auth_role, long_format): """ Prints project names to stdout for all projects or just those with the specified auth_role :param filter_auth_role: str: optional auth_role to filter project list """ if filter_auth_role: projects_details = self.remote_store.get_projects_with_auth_role(auth_role=filter_auth_role) else: projects_details = self.remote_store.get_projects_details() if projects_details: for projects_detail in projects_details: print(self.get_project_info_line(projects_detail, long_format)) else: print(NO_PROJECTS_FOUND_MESSAGE)
Prints project names to stdout for all projects or just those with the specified auth_role :param filter_auth_role: str: optional auth_role to filter project list
entailment
def run(self, args): """ Deletes a single project specified by project_name in args. :param args Namespace arguments parsed from the command line """ project = self.fetch_project(args, must_exist=True, include_children=False) if not args.force: delete_prompt = "Are you sure you wish to delete {} (y/n)?".format(project.name) if not boolean_input_prompt(delete_prompt): return self.remote_store.delete_project(self.create_project_name_or_id_from_args(args))
Deletes a single project specified by project_name in args. :param args Namespace arguments parsed from the command line
entailment
def run(self, args): """ Prints out non deprecated project-type auth roles. :param args Namespace arguments parsed from the command line """ auth_roles = self.remote_store.get_active_auth_roles(RemoteAuthRole.PROJECT_CONTEXT) if auth_roles: for auth_role in auth_roles: print(auth_role.id, "-", auth_role.description) else: print("No authorization roles found.")
Prints out non deprecated project-type auth roles. :param args Namespace arguments parsed from the command line
entailment
def get_ca_certs(environ=os.environ): """ Retrieve a list of CAs at either the DEFAULT_CERTS_PATH or the env override, TXAWS_CERTS_PATH. In order to find .pem files, this function checks first for presence of the TXAWS_CERTS_PATH environment variable that should point to a directory containing cert files. In the absense of this variable, the module-level DEFAULT_CERTS_PATH will be used instead. Note that both of these variables have have multiple paths in them, just like the familiar PATH environment variable (separated by colons). """ cert_paths = environ.get("TXAWS_CERTS_PATH", DEFAULT_CERTS_PATH).split(":") certificate_authority_map = {} for path in cert_paths: if not path: continue for cert_file_name in glob(os.path.join(path, "*.pem")): # There might be some dead symlinks in there, so let's make sure # it's real. if not os.path.exists(cert_file_name): continue cert_file = open(cert_file_name) data = cert_file.read() cert_file.close() x509 = load_certificate(FILETYPE_PEM, data) digest = x509.digest("sha1") # Now, de-duplicate in case the same cert has multiple names. certificate_authority_map[digest] = x509 values = certificate_authority_map.values() if len(values) == 0: raise exception.CertsNotFoundError("Could not find any .pem files.") return values
Retrieve a list of CAs at either the DEFAULT_CERTS_PATH or the env override, TXAWS_CERTS_PATH. In order to find .pem files, this function checks first for presence of the TXAWS_CERTS_PATH environment variable that should point to a directory containing cert files. In the absense of this variable, the module-level DEFAULT_CERTS_PATH will be used instead. Note that both of these variables have have multiple paths in them, just like the familiar PATH environment variable (separated by colons).
entailment
def _calculate(self, startingPercentage, endPercentage, startDate, endDate): """This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`. Both parameters will be correct at this time. :param float startingPercentage: Defines the start of the interval. This has to be a value in [0.0, 100.0]. It represents the value, where the error calculation should be started. 25.0 for example means that the first 25% of all calculated errors will be ignored. :param float endPercentage: Defines the end of the interval. This has to be a value in [0.0, 100.0]. It represents the value, after which all error values will be ignored. 90.0 for example means that the last 10% of all local errors will be ignored. :param float startDate: Epoch representing the start date used for error calculation. :param float endDate: Epoch representing the end date used in the error calculation. :return: Returns a float representing the error. :rtype: float """ # get the defined subset of error values errorValues = self._get_error_values(startingPercentage, endPercentage, startDate, endDate) errorValues = filter(lambda item: item is None, errorValues) if errorValues[0] is None: return 1.0 share = 1.0 / float(len(errorValues)) product = 1.0 for errorValue in errorValues: # never multiply with zero! if 0 == errorValue: continue product *= errorValue**share return product
This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`. Both parameters will be correct at this time. :param float startingPercentage: Defines the start of the interval. This has to be a value in [0.0, 100.0]. It represents the value, where the error calculation should be started. 25.0 for example means that the first 25% of all calculated errors will be ignored. :param float endPercentage: Defines the end of the interval. This has to be a value in [0.0, 100.0]. It represents the value, after which all error values will be ignored. 90.0 for example means that the last 10% of all local errors will be ignored. :param float startDate: Epoch representing the start date used for error calculation. :param float endDate: Epoch representing the end date used in the error calculation. :return: Returns a float representing the error. :rtype: float
entailment
def iso8601time(time_tuple): """Format time_tuple as a ISO8601 time string. :param time_tuple: Either None, to use the current time, or a tuple tuple. """ if time_tuple: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time_tuple) else: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
Format time_tuple as a ISO8601 time string. :param time_tuple: Either None, to use the current time, or a tuple tuple.
entailment
def parse(url, defaultPort=True): """ Split the given URL into the scheme, host, port, and path. @type url: C{str} @param url: An URL to parse. @type defaultPort: C{bool} @param defaultPort: Whether to return the default port associated with the scheme in the given url, when the url doesn't specify one. @return: A four-tuple of the scheme, host, port, and path of the URL. All of these are C{str} instances except for port, which is an C{int}. """ url = url.strip() parsed = urlparse(url) scheme = parsed[0] path = urlunparse(("", "") + parsed[2:]) host = parsed[1] if ":" in host: host, port = host.split(":") try: port = int(port) except ValueError: # A non-numeric port was given, it will be replaced with # an appropriate default value if defaultPort is True port = None else: port = None if port is None and defaultPort: if scheme == "https": port = 443 else: port = 80 if path == "": path = "/" return (str(scheme), str(host), port, str(path))
Split the given URL into the scheme, host, port, and path. @type url: C{str} @param url: An URL to parse. @type defaultPort: C{bool} @param defaultPort: Whether to return the default port associated with the scheme in the given url, when the url doesn't specify one. @return: A four-tuple of the scheme, host, port, and path of the URL. All of these are C{str} instances except for port, which is an C{int}.
entailment
def tostring(self, inject): """Get the entire text content as str""" return inject(self, '\n'.join(document.tostring(inject) for document in self.documents))
Get the entire text content as str
entailment
def retry_when_service_down(func): """ Decorator that will retry a function while it fails with status code 503 Assumes the first argument to the fuction will be an object with a set_status_message method. :param func: function: will be called until it doesn't fail with DataServiceError status 503 :return: value returned by func """ def retry_function(*args, **kwds): showed_status_msg = False status_watcher = args[0] while True: try: result = func(*args, **kwds) if showed_status_msg: status_watcher.set_status_message('') return result except DataServiceError as dse: if dse.status_code == 503: if not showed_status_msg: message = SERVICE_DOWN_MESSAGE.format(datetime.datetime.utcnow()) status_watcher.set_status_message(message) showed_status_msg = True time.sleep(SERVICE_DOWN_RETRY_SECONDS) else: raise return retry_function
Decorator that will retry a function while it fails with status code 503 Assumes the first argument to the fuction will be an object with a set_status_message method. :param func: function: will be called until it doesn't fail with DataServiceError status 503 :return: value returned by func
entailment
def retry_until_resource_is_consistent(func, monitor): """ Runs func, if func raises DSResourceNotConsistentError will retry func indefinitely. Notifies monitor if we have to wait(only happens if DukeDS API raises DSResourceNotConsistentError. :param func: func(): function to run :param monitor: object: has start_waiting() and done_waiting() methods when waiting for non-consistent resource :return: whatever func returns """ waiting = False while True: try: resp = func() if waiting and monitor: monitor.done_waiting() return resp except DSResourceNotConsistentError: if not waiting and monitor: monitor.start_waiting() waiting = True time.sleep(RESOURCE_NOT_CONSISTENT_RETRY_SECONDS)
Runs func, if func raises DSResourceNotConsistentError will retry func indefinitely. Notifies monitor if we have to wait(only happens if DukeDS API raises DSResourceNotConsistentError. :param func: func(): function to run :param monitor: object: has start_waiting() and done_waiting() methods when waiting for non-consistent resource :return: whatever func returns
entailment
def get_auth(self): """ Gets an active token refreshing it if necessary. :return: str valid active authentication token. """ if self.legacy_auth(): return self._auth if not self.auth_expired(): return self._auth self.claim_new_token() return self._auth
Gets an active token refreshing it if necessary. :return: str valid active authentication token.
entailment
def claim_new_token(self): """ Update internal state to have a new token using a no authorization data service. """ # Intentionally doing this manually so we don't have a chicken and egg problem with DataServiceApi. headers = { 'Content-Type': ContentType.json, 'User-Agent': self.user_agent_str, } data = { "agent_key": self.config.agent_key, "user_key": self.config.user_key, } url_suffix = "/software_agents/api_token" url = self.config.url + url_suffix response = requests.post(url, headers=headers, data=json.dumps(data)) if response.status_code == 404: if not self.config.agent_key: raise MissingInitialSetupError() else: raise SoftwareAgentNotFoundError() elif response.status_code == 503: raise DataServiceError(response, url_suffix, data) elif response.status_code != 201: raise AuthTokenCreationError(response) resp_json = response.json() self._auth = resp_json['api_token'] self._expires = resp_json['expires_on']
Update internal state to have a new token using a no authorization data service.
entailment
def auth_expired(self): """ Compare the expiration value of our current token including a CLOCK_SKEW. :return: true if the token has expired """ if self._auth and self._expires: now_with_skew = time.time() + AUTH_TOKEN_CLOCK_SKEW_MAX return now_with_skew > self._expires return True
Compare the expiration value of our current token including a CLOCK_SKEW. :return: true if the token has expired
entailment
def _url_parts(self, url_suffix, data, content_type): """ Format the url data based on config_type. :param url_suffix: str URL path we are sending a GET/POST/PUT to :param data: object data we are sending :param content_type: str from ContentType that determines how we format the data :return: complete url, formatted data, and headers for sending """ url = self.base_url + url_suffix send_data = data if content_type == ContentType.json: send_data = json.dumps(data) headers = { 'Content-Type': content_type, 'User-Agent': self.user_agent_str, } if self.auth: headers['Authorization'] = self.auth.get_auth() return url, send_data, headers
Format the url data based on config_type. :param url_suffix: str URL path we are sending a GET/POST/PUT to :param data: object data we are sending :param content_type: str from ContentType that determines how we format the data :return: complete url, formatted data, and headers for sending
entailment
def _post(self, url_suffix, data, content_type=ContentType.json): """ Send POST request to API at url_suffix with post_data. Raises error if x-total-pages is contained in the response. :param url_suffix: str URL path we are sending a POST to :param data: object data we are sending :param content_type: str from ContentType that determines how we format the data :return: requests.Response containing the result """ (url, data_str, headers) = self._url_parts(url_suffix, data, content_type=content_type) resp = self.http.post(url, data_str, headers=headers) return self._check_err(resp, url_suffix, data, allow_pagination=False)
Send POST request to API at url_suffix with post_data. Raises error if x-total-pages is contained in the response. :param url_suffix: str URL path we are sending a POST to :param data: object data we are sending :param content_type: str from ContentType that determines how we format the data :return: requests.Response containing the result
entailment
def _put(self, url_suffix, data, content_type=ContentType.json): """ Send PUT request to API at url_suffix with post_data. Raises error if x-total-pages is contained in the response. :param url_suffix: str URL path we are sending a PUT to :param data: object data we are sending :param content_type: str from ContentType that determines how we format the data :return: requests.Response containing the result """ (url, data_str, headers) = self._url_parts(url_suffix, data, content_type=content_type) resp = self.http.put(url, data_str, headers=headers) return self._check_err(resp, url_suffix, data, allow_pagination=False)
Send PUT request to API at url_suffix with post_data. Raises error if x-total-pages is contained in the response. :param url_suffix: str URL path we are sending a PUT to :param data: object data we are sending :param content_type: str from ContentType that determines how we format the data :return: requests.Response containing the result
entailment
def _get_single_item(self, url_suffix, data, content_type=ContentType.json): """ Send GET request to API at url_suffix with post_data. Raises error if x-total-pages is contained in the response. :param url_suffix: str URL path we are sending a GET to :param url_data: object data we are sending :param content_type: str from ContentType that determines how we format the data :return: requests.Response containing the result """ (url, data_str, headers) = self._url_parts(url_suffix, data, content_type=content_type) resp = self.http.get(url, headers=headers, params=data_str) return self._check_err(resp, url_suffix, data, allow_pagination=False)
Send GET request to API at url_suffix with post_data. Raises error if x-total-pages is contained in the response. :param url_suffix: str URL path we are sending a GET to :param url_data: object data we are sending :param content_type: str from ContentType that determines how we format the data :return: requests.Response containing the result
entailment
def _get_single_page(self, url_suffix, data, page_num): """ Send GET request to API at url_suffix with post_data adding page and per_page parameters to retrieve a single page. Page size is determined by config.page_size. :param url_suffix: str URL path we are sending a GET to :param data: object data we are sending :param page_num: int: page number to fetch :return: requests.Response containing the result """ data_with_per_page = dict(data) data_with_per_page['page'] = page_num data_with_per_page['per_page'] = self._get_page_size() (url, data_str, headers) = self._url_parts(url_suffix, data_with_per_page, content_type=ContentType.form) resp = self.http.get(url, headers=headers, params=data_str) return self._check_err(resp, url_suffix, data, allow_pagination=True)
Send GET request to API at url_suffix with post_data adding page and per_page parameters to retrieve a single page. Page size is determined by config.page_size. :param url_suffix: str URL path we are sending a GET to :param data: object data we are sending :param page_num: int: page number to fetch :return: requests.Response containing the result
entailment
def _get_collection(self, url_suffix, data): """ Performs GET for all pages based on x-total-pages in first response headers. Merges the json() 'results' arrays. If x-total-pages is missing or 1 just returns the response without fetching multiple pages. :param url_suffix: str URL path we are sending a GET to :param data: object data we are sending :return: requests.Response containing the result """ response = self._get_single_page(url_suffix, data, page_num=1) total_pages_str = response.headers.get('x-total-pages') if total_pages_str: total_pages = int(total_pages_str) if total_pages > 1: multi_response = MultiJSONResponse(base_response=response, merge_array_field_name="results") for page in range(2, total_pages + 1): additional_response = self._get_single_page(url_suffix, data, page_num=page) multi_response.add_response(additional_response) return multi_response return response
Performs GET for all pages based on x-total-pages in first response headers. Merges the json() 'results' arrays. If x-total-pages is missing or 1 just returns the response without fetching multiple pages. :param url_suffix: str URL path we are sending a GET to :param data: object data we are sending :return: requests.Response containing the result
entailment
def _check_err(resp, url_suffix, data, allow_pagination): """ Raise DataServiceError if the response wasn't successful. :param resp: requests.Response back from the request :param url_suffix: str url to include in an error message :param data: data payload we sent :param allow_pagination: when False and response headers contains 'x-total-pages' raises an error. :return: requests.Response containing the successful result """ total_pages = resp.headers.get('x-total-pages') if not allow_pagination and total_pages: raise UnexpectedPagingReceivedError() if 200 <= resp.status_code < 300: return resp if resp.status_code == 404: if resp.json().get("code") == "resource_not_consistent": raise DSResourceNotConsistentError(resp, url_suffix, data) raise DataServiceError(resp, url_suffix, data)
Raise DataServiceError if the response wasn't successful. :param resp: requests.Response back from the request :param url_suffix: str url to include in an error message :param data: data payload we sent :param allow_pagination: when False and response headers contains 'x-total-pages' raises an error. :return: requests.Response containing the successful result
entailment
def create_project(self, project_name, desc): """ Send POST to /projects creating a new project with the specified name and desc. Raises DataServiceError on error. :param project_name: str name of the project :param desc: str description of the project :return: requests.Response containing the successful result """ data = { "name": project_name, "description": desc } return self._post("/projects", data)
Send POST to /projects creating a new project with the specified name and desc. Raises DataServiceError on error. :param project_name: str name of the project :param desc: str description of the project :return: requests.Response containing the successful result
entailment
def create_folder(self, folder_name, parent_kind_str, parent_uuid): """ Send POST to /folders to create a new folder with specified name and parent. :param folder_name: str name of the new folder :param parent_kind_str: str type of parent folder has(dds-folder,dds-project) :param parent_uuid: str uuid of the parent object :return: requests.Response containing the successful result """ data = { 'name': folder_name, 'parent': { 'kind': parent_kind_str, 'id': parent_uuid } } return self._post("/folders", data)
Send POST to /folders to create a new folder with specified name and parent. :param folder_name: str name of the new folder :param parent_kind_str: str type of parent folder has(dds-folder,dds-project) :param parent_uuid: str uuid of the parent object :return: requests.Response containing the successful result
entailment
def get_project_children(self, project_id, name_contains, exclude_response_fields=None): """ Send GET to /projects/{project_id}/children filtering by a name. :param project_id: str uuid of the project :param name_contains: str name to filter folders by (if not None this method works recursively) :param exclude_response_fields: [str]: list of fields to exclude in the response items :return: requests.Response containing the successful result """ return self._get_children('projects', project_id, name_contains, exclude_response_fields)
Send GET to /projects/{project_id}/children filtering by a name. :param project_id: str uuid of the project :param name_contains: str name to filter folders by (if not None this method works recursively) :param exclude_response_fields: [str]: list of fields to exclude in the response items :return: requests.Response containing the successful result
entailment
def _get_children(self, parent_name, parent_id, name_contains, exclude_response_fields=None): """ Send GET message to /<parent_name>/<parent_id>/children to fetch info about children(files and folders) :param parent_name: str 'projects' or 'folders' :param parent_id: str uuid of project or folder :param name_contains: name filtering (if not None this method works recursively) :param exclude_response_fields: [str]: list of fields to exclude in the response items :return: requests.Response containing the successful result """ data = {} if name_contains is not None: data['name_contains'] = name_contains if exclude_response_fields: data['exclude_response_fields'] = ' '.join(exclude_response_fields) url_prefix = "/{}/{}/children".format(parent_name, parent_id) return self._get_collection(url_prefix, data)
Send GET message to /<parent_name>/<parent_id>/children to fetch info about children(files and folders) :param parent_name: str 'projects' or 'folders' :param parent_id: str uuid of project or folder :param name_contains: name filtering (if not None this method works recursively) :param exclude_response_fields: [str]: list of fields to exclude in the response items :return: requests.Response containing the successful result
entailment
def create_upload(self, project_id, filename, content_type, size, hash_value, hash_alg, storage_provider_id=None, chunked=True): """ Post to /projects/{project_id}/uploads to create a uuid for uploading chunks. NOTE: The optional hash_value and hash_alg parameters are being removed from the DukeDS API. :param project_id: str uuid of the project we are uploading data for. :param filename: str name of the file we want to upload :param content_type: str mime type of the file :param size: int size of the file in bytes :param hash_value: str hash value of the entire file :param hash_alg: str algorithm used to create hash_value :param storage_provider_id: str optional storage provider id :param chunked: is the uploaded file made up of multiple chunks. When False a single upload url is returned. For more see https://github.com/Duke-Translational-Bioinformatics/duke-data-service/blob/develop/api_design/DDS-1182-nonchucked_upload_api_design.md :return: requests.Response containing the successful result """ data = { "name": filename, "content_type": content_type, "size": size, "hash": { "value": hash_value, "algorithm": hash_alg }, "chunked": chunked, } if storage_provider_id: data['storage_provider'] = {'id': storage_provider_id} return self._post("/projects/" + project_id + "/uploads", data)
Post to /projects/{project_id}/uploads to create a uuid for uploading chunks. NOTE: The optional hash_value and hash_alg parameters are being removed from the DukeDS API. :param project_id: str uuid of the project we are uploading data for. :param filename: str name of the file we want to upload :param content_type: str mime type of the file :param size: int size of the file in bytes :param hash_value: str hash value of the entire file :param hash_alg: str algorithm used to create hash_value :param storage_provider_id: str optional storage provider id :param chunked: is the uploaded file made up of multiple chunks. When False a single upload url is returned. For more see https://github.com/Duke-Translational-Bioinformatics/duke-data-service/blob/develop/api_design/DDS-1182-nonchucked_upload_api_design.md :return: requests.Response containing the successful result
entailment
def create_upload_url(self, upload_id, number, size, hash_value, hash_alg): """ Given an upload created by create_upload retrieve a url where we can upload a chunk. :param upload_id: uuid of the upload :param number: int incrementing number of the upload (1-based index) :param size: int size of the chunk in bytes :param hash_value: str hash value of chunk :param hash_alg: str algorithm used to create hash :return: requests.Response containing the successful result """ if number < 1: raise ValueError("Chunk number must be > 0") data = { "number": number, "size": size, "hash": { "value": hash_value, "algorithm": hash_alg } } return self._put("/uploads/" + upload_id + "/chunks", data)
Given an upload created by create_upload retrieve a url where we can upload a chunk. :param upload_id: uuid of the upload :param number: int incrementing number of the upload (1-based index) :param size: int size of the chunk in bytes :param hash_value: str hash value of chunk :param hash_alg: str algorithm used to create hash :return: requests.Response containing the successful result
entailment
def complete_upload(self, upload_id, hash_value, hash_alg): """ Mark the upload we created in create_upload complete. :param upload_id: str uuid of the upload to complete. :param hash_value: str hash value of chunk :param hash_alg: str algorithm used to create hash :return: requests.Response containing the successful result """ data = { "hash[value]": hash_value, "hash[algorithm]": hash_alg } return self._put("/uploads/" + upload_id + "/complete", data, content_type=ContentType.form)
Mark the upload we created in create_upload complete. :param upload_id: str uuid of the upload to complete. :param hash_value: str hash value of chunk :param hash_alg: str algorithm used to create hash :return: requests.Response containing the successful result
entailment
def create_file(self, parent_kind, parent_id, upload_id): """ Create a new file after completing an upload. :param parent_kind: str kind of parent(dds-folder,dds-project) :param parent_id: str uuid of parent :param upload_id: str uuid of complete upload :return: requests.Response containing the successful result """ data = { "parent": { "kind": parent_kind, "id": parent_id }, "upload": { "id": upload_id } } return self._post("/files/", data)
Create a new file after completing an upload. :param parent_kind: str kind of parent(dds-folder,dds-project) :param parent_id: str uuid of parent :param upload_id: str uuid of complete upload :return: requests.Response containing the successful result
entailment
def update_file(self, file_id, upload_id): """ Send PUT request to /files/{file_id} to update the file contents to upload_id and sets a label. :param file_id: str uuid of file :param upload_id: str uuid of the upload where all the file chunks where uploaded :param label: str short display label for the file :return: requests.Response containing the successful result """ put_data = { "upload[id]": upload_id, } return self._put("/files/" + file_id, put_data, content_type=ContentType.form)
Send PUT request to /files/{file_id} to update the file contents to upload_id and sets a label. :param file_id: str uuid of file :param upload_id: str uuid of the upload where all the file chunks where uploaded :param label: str short display label for the file :return: requests.Response containing the successful result
entailment
def send_external(self, http_verb, host, url, http_headers, chunk): """ Used with create_upload_url to send a chunk the the possibly external object store. :param http_verb: str PUT or POST :param host: str host we are sending the chunk to :param url: str url to use when sending :param http_headers: object headers to send with the request :param chunk: content to send :return: requests.Response containing the successful result """ if http_verb == 'PUT': return self.http.put(host + url, data=chunk, headers=http_headers) elif http_verb == 'POST': return self.http.post(host + url, data=chunk, headers=http_headers) else: raise ValueError("Unsupported http_verb:" + http_verb)
Used with create_upload_url to send a chunk the the possibly external object store. :param http_verb: str PUT or POST :param host: str host we are sending the chunk to :param url: str url to use when sending :param http_headers: object headers to send with the request :param chunk: content to send :return: requests.Response containing the successful result
entailment
def receive_external(self, http_verb, host, url, http_headers): """ Retrieve a streaming request for a file. :param http_verb: str GET is only supported right now :param host: str host we are requesting the file from :param url: str url to ask the host for :param http_headers: object headers to send with the request :return: requests.Response containing the successful result """ if http_verb == 'GET': return self.http.get(host + url, headers=http_headers, stream=True) else: raise ValueError("Unsupported http_verb:" + http_verb)
Retrieve a streaming request for a file. :param http_verb: str GET is only supported right now :param host: str host we are requesting the file from :param url: str url to ask the host for :param http_headers: object headers to send with the request :return: requests.Response containing the successful result
entailment
def get_users(self, full_name=None, email=None, username=None): """ Send GET request to /users for users with optional full_name, email, and/or username filtering. :param full_name: str name of the user we are searching for :param email: str: optional email to filter by :param username: str: optional username to filter by :return: requests.Response containing the successful result """ data = {} if full_name: data['full_name_contains'] = full_name if email: data['email'] = email if username: data['username'] = username return self._get_collection('/users', data)
Send GET request to /users for users with optional full_name, email, and/or username filtering. :param full_name: str name of the user we are searching for :param email: str: optional email to filter by :param username: str: optional username to filter by :return: requests.Response containing the successful result
entailment