code
stringlengths
1
18.2k
msgLines] if stdout: if not stdout.endswith('\n'): stdout += '\n' msgLines.append(STDOUT_LINE % stdout) if stderr: if not stderr.endswith('\n'): stderr += '\n' msgLines.append(STDERR_LINE % stderr) return ''.join(msgLines)
def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer
def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswi...
def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None
def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handler(result) if self._successful and result.status not in _succes...
def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result.TestCompletionStatus The status of the test. exception : tup...
else: stderr = stdout = None started_time = self._test_timing.get(self._testcase_to_key(test)) if started_time is None and isinstance(test, ErrorHolder): started_time = datetime.utcnow() elif started_time is None: raise RuntimeError( 'Missing test start! Please report this error as a bug in ' 'haas.') completion_time =...
def addError(self, test, exception): """Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.error, exception=exception) self.err...
def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.failure, exception=exception) s...
def addSkip(self, test, reason): """Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. """ result = self._handle_result( test, TestCompletionStatus.skipped, message=reason) self.skipped.append(result)
def addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.expecte...
def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. """ result = self._handle_result( test, TestCompletionStatus.unexpected_success) self.unexpectedSuccesses.append(result)
def set_terminal_key(self, encrypted_key): """ Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master key """ if encrypted_key: try: new_key = bytes.fromhex(encrypted_key) if len(self.terminal_key) != len(new_key): # The keys must have equal length return Fals...
def get_encrypted_pin(self, clear_pin, card_number): """ Get PIN block in ISO 0 format, encrypted with the terminal key """ if not self.terminal_key: print('Terminal key is not set') return '' if self.pinblock_format == '01': try: pinblock = bytes.fromhex(get_pinblock(clear_pin, card_number)) #print('PIN block: {}'.for...
def is_url(string, allowed_schemes=None): """ Check if a string is a valid url. :param string: String to check. :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :return: True if url, false otherwise :rtype: bool """ if not is_full_string(string): return F...
def is_credit_card(string, card_type=None): """ Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card type. :type card_type: str Can b...
* JCB or None. Default to None (any card). :return: True if credit card, false otherwise. :rtype: bool """ if not is_full_string(string): return False if card_type: if card_type not in CREDIT_CARDS: raise KeyError( 'Invalid card type "{}". Valid types are: {}'.format(card_type, ', '.join(CREDIT_CARDS.keys())) ) return ...
def is_snake_case(string, separator='_'): """ Checks if a string is formatted as snake case. A string is considered snake case when: * it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \ and optionally numbers ([0-9]) * it does not start/end with an underscore (or provided separator) ...
:param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. :rtype: bool """ if is_full_string(string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = '^[a-z]+([a-z\d]+{sign}|{sign}[a-z\d]+)+[a-z\d]+$' r = re_map.get(separa...
def is_json(string): """ Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false otherwise :rtype: bool """ if not is_full_string(string): return False if bool(JSON_WRAPPER_RE.search(string)): try: return isinstance(json.loads(string), dict) except (TypeError, V...
def is_palindrome(string, strict=True): """ Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). :param string: String to check. :type string: str :param strict: True if white spaces matter (default), false otherwise. :type strict: bool :return: True if the string is a palindrome (like "otto...
string)) return False
def is_pangram(string): """ Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param string: String to check. :type string: str :return: True if the string is a pangram, False otherwise. """ return is_full_string(string) and set(SPACES_RE.sub('', string)).issuperset(letters_set)
def is_slug(string, sign='-'): """ Checks if a given string is a slug. :param string: String to check. :type string: str :param sign: Join sign used by the slug. :type sign: str :return: True if slug, false otherwise. """ if not is_full_string(string): return False rex = r'^([a-z\d]+' + re.escape(sign) + r'?)*[a-z\d]$'...
def camel_case_to_snake(string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) :param string: String to convert. :type string: str :param separator: Sign to use as separator. :type separator: str :return: Converted string. :rt...
m: m.group(1) + separator, string).lower()
def snake_case_to_camel(string, upper_case_first=True, separator='_'): """ Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) :param string: String to convert. :type string: str :param upper_case_first: True to turn the first letter into uppercase (d...
Converted string :rtype: str """ if not is_string(string): raise TypeError('Expected string') if not is_snake_case(string, separator): return string re_map = { '_': SNAKE_CASE_REPLACE_RE, '-': SNAKE_CASE_REPLACE_DASH_RE } r = re_map.get(separator, re.compile('({sign})([a-z\d])'.format(sign=re.escape(separator)))) strin...
def shuffle(string): """ Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled string :rtype: str """ s = sorted(string) # turn the string into a list of chars random.shuffle(s) # shuffle the list return ''.join(s)
def strip_html(string, keep_tag_content=False): """ Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html re...
def prettify(string): """ Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following: - String cannot start or end with spaces - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \*, =) mu...
themselves - The first letter after a dot, an exclamation or a question mark must be uppercase - One, and only one space should follow a dot, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo...
Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog...
manipulate :return: Prettified string. :rtype: str """ def remove_duplicates(regex_match): return regex_match.group(1)[0] def uppercase_first_letter_after_sign(regex_match): match = regex_match.group(1) return match[:-1] + match[2].upper() def ensure_right_space_only(regex_match): return regex_match.group(1).strip() + ...
p) p = PRETTIFY_RE['LEFT_SPACE'].sub(ensure_left_space_only, p) p = PRETTIFY_RE['SPACES_AROUND'].sub(ensure_spaces_around, p) p = PRETTIFY_RE['SPACES_INSIDE'].sub(remove_internal_spaces, p) p = PRETTIFY_RE['UPPERCASE_AFTER_SIGN'].sub(uppercase_first_letter_after_sign, p) p = PRETTIFY_RE['SAXON_GENITIVE'].sub(fix_saxon_...
def slugify(string, sign='-'): """ Converts a string into a slug using provided join sign. (**(This Is A "Test"!)** -> **this-is-a-test**) :param string: String to convert. :type string: str :param sign: Sign used to join string tokens (default to "-"). :type sign: str :return: Slugified string """ if not is_string(str...
try: string = unicode(string, 'utf-8') except NameError: pass # replace any character that is NOT letter or number with spaces s = NO_LETTERS_OR_NUMBERS_RE.sub(' ', string.lower()).strip() # replace spaces with join sign s = SPACES_RE.sub(sign, s) # normalize joins (remove duplicates) s = re.sub(re.escape(sign) + r'+',...
def setup(app): """Initialize Sphinx extension.""" app.setup_extension('nbsphinx') app.add_source_suffix('.nblink', 'linked_jupyter_notebook') app.add_source_parser(LinkedNotebookParser) app.add_config_value('nbsphinx_link_target_root', None, rebuild='env') return {'version': __version__, 'parallel_read_safe': True}
def parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser. """ link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname(env.doc2path(env.docname)) abs_path = os.path.normpath(o...
parser from nbsphinx for our cutom format try: formats = env.config.nbsphinx_custom_formats except AttributeError: pass else: formats.setdefault( '.nblink', lambda s: nbformat.reads(s, as_version=_ipynbversion)) try: include_file = io.FileInput(source_path=path, encoding='utf8') except UnicodeEncodeError as error: rais...
rawtext = include_file.read() except UnicodeError as error: raise NotebookError(u'Problem with linked notebook "%s":\n%s' % (env.docname, ErrorString(error))) return super(LinkedNotebookParser, self).parse(rawtext, document)
def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print('{} duplicate scripts found'.format(self.total_duplicate)) for duplicate in self.list_duplicate: print(duplicate)
def analyze(self, scratch, **kwargs): """Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks. """ scripts_set = set() for script in self.iter_scripts(scratch): if script[0].type.text == 'define %s': continue # Ignore user defined scripts blocks_list = [] ...
+= 1 self.list_duplicate.append(blocks_list) else: scripts_set.add(blocks_tuple)
def _set_content_type(self, system): """ Set response content type """ request = system.get('request') if request: response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = 'application/json'
def _render_response(self, value, system): """ Render a response """ view = system['view'] enc_class = getattr(view, '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return json.dumps(value, cls=enc_class)
def _get_common_kwargs(self, system): """ Get kwargs common for all methods. """ enc_class = getattr(system['view'], '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return { 'request': system['request'], 'encoder': enc_class, }
def _get_create_update_kwargs(self, value, common_kw): """ Get kwargs common to create, update, replace. """ kw = common_kw.copy() kw['body'] = value if '_self' in value: kw['headers'] = [('Location', value['_self'])] return kw
def render_create(self, value, system, common_kw): """ Render response for view `create` method (collection POST) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPCreated(**kw)
def render_update(self, value, system, common_kw): """ Render response for view `update` method (item PATCH) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPOk('Updated', **kw)
def render_delete_many(self, value, system, common_kw): """ Render response for view `delete_many` method (collection DELETE) """ if isinstance(value, dict): return JHTTPOk(extra=value) msg = 'Deleted {} {}(s) objects'.format( value, system['view'].Model.__name__) return JHTTPOk(msg, **common_kw.copy())
def render_update_many(self, value, system, common_kw): """ Render response for view `update_many` method (collection PUT/PATCH) """ msg = 'Updated {} {}(s) objects'.format( value, system['view'].Model.__name__) return JHTTPOk(msg, **common_kw.copy())
def _render_response(self, value, system): """ Handle response rendering. Calls mixin methods according to request.action value. """ super_call = super(DefaultResponseRendererMixin, self)._render_response try: method_name = 'render_{}'.format(system['request'].action) except (KeyError, AttributeError): return super_cal...
def remember(self, request, username, **kw): """ Returns 'WWW-Authenticate' header with a value that should be used in 'Authorization' header. """ if self.credentials_callback: token = self.credentials_callback(username, request) api_key = 'ApiKey {}:{}'.format(username, token) return [('WWW-Authenticate', api_key)]
def callback(self, username, request): """ Having :username: return user's identifiers or None. """ credentials = self._get_credentials(request) if credentials: username, api_key = credentials if self.check: return self.check(username, api_key, request)
def _get_credentials(self, request): """ Extract username and api key token from 'Authorization' header """ authorization = request.headers.get('Authorization') if not authorization: return None try: authmeth, authbytes = authorization.split(' ', 1) except ValueError: # not enough values to unpack return None if authme...
username, api_key = auth.split(':', 1) except ValueError: # not enough values to unpack return None return username, api_key
def _get_event_kwargs(view_obj): """ Helper function to get event kwargs. :param view_obj: Instance of View that processes the request. :returns dict: Containing event kwargs or None if events shouldn't be fired. """ request = view_obj.request view_method = getattr(view_obj, request.action) do_trigger = not ( getattr(v...
= view_obj.context if hasattr(ctx, 'pk_field') or isinstance(ctx, DataProxy): event_kwargs['instance'] = ctx return event_kwargs
def _get_event_cls(view_obj, events_map): """ Helper function to get event class. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Found event class. """ request = view_obj.request view_method = getattr(view_obj, request.ac...
def _trigger_events(view_obj, events_map, additional_kw=None): """ Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event. """ if additional_kw is None: add...
def subscribe_to_events(config, subscriber, events, model=None): """ Helper function to subscribe to group of events. :param config: Pyramid contig instance. :param subscriber: Event subscriber function. :param events: Sequence of events to subscribe to. :param model: Model predicate value. """ kwargs = {} if model is ...
def add_field_processors(config, processors, model, field): """ Add processors for model field. Under the hood, regular nefertari event subscribed is created which calls field processors in order passed to this function. Processors are passed following params: * **new_value**: New value of of field. * **instance**: Ins...
**field**: Instance of nefertari.utils.data.FieldData instance containing data of changed field. * **request**: Current Pyramid Request instance. * **model**: Model class affected by request. * **event**: Underlying event object. Each processor must return processed value which is passed to next processor. :param confi...
Field name for which processors are registered. """ before_change_events = ( BeforeCreate, BeforeUpdate, BeforeReplace, BeforeUpdateMany, BeforeRegister, ) def wrapper(event, _processors=processors, _field=field): proc_kw = { 'new_value': event.field.new_value, 'instance': event.instance, 'field': event.field, 'request...
def set_field_value(self, field_name, value): """ Set value of request field named `field_name`. Use this method to apply changes to object which is affected by request. Values are set on `view._json_params` dict. If `field_name` is not affected by request, it is added to `self.fields` which makes field processors whic...
events after handler that performs method call). :param field_name: Name of request field value of which should be set. :param value: Value to be set. """ self.view._json_params[field_name] = value if field_name in self.fields: self.fields[field_name].new_value = value return fields = FieldData.from_dict({field_name: v...
def set_field_value(self, field_name, value): """ Set value of response field named `field_name`. If response contains single item, its field is set. If response contains multiple items, all the items in response are edited. To edit response meta(e.g. 'count') edit response directly at `event.response`. :param field_na...
is None: return if 'data' in self.response: items = self.response['data'] else: items = [self.response] for item in items: item[field_name] = value
def process_fields_param(fields): """ Process 'fields' ES param. * Fields list is split if needed * '_type' field is added, if not present, so the actual value is displayed instead of 'None' """ if not fields: return fields if isinstance(fields, six.string_types): fields = split_strip(fields) if '_type' not in fields: ...
def _catch_index_error(self, response): """ Catch and raise index errors which are not critical and thus not raised by elasticsearch-py. """ code, headers, raw_data = response if not raw_data: return data = json.loads(raw_data) if not data or not data.get('errors'): return try: error_dict = data['items'][0]['index'] me...
def setup_mappings(cls, force=False): """ Setup ES mappings for all existing models. This method is meant to be run once at application lauch. ES._mappings_setup flag is set to not run make mapping creation calls on subsequent runs. Use `force=True` to make subsequent calls perform mapping creation calls to ES. """ if ...
currently ' 'running application. Call `setup_mappings` with ' '`force=True` to perform mappings set up again.') return log.info('Setting up ES mappings for all existing models') models = engine.get_document_classes() try: for model_name, model_cls in models.items(): if getattr(model_cls, '_index_enabled', False): es =...
def process_chunks(self, documents, operation): """ Apply `operation` to chunks of `documents` of size `self.chunk_size`. """ chunk_size = self.chunk_size start = end = 0 count = len(documents) while count: if count < chunk_size: chunk_size = count end += chunk_size bulk = documents[start:end] operation(documents_actio...
def index_missing_documents(self, documents, request=None): """ Index documents that are missing from ES index. Determines which documents are missing using ES `mget` call which returns a list of document IDs as `documents`. Then missing `documents` from that list are indexed. """ log.info('Trying to index documents of...
index=self.index_name, doc_type=self.doc_type, fields=['_id'], body={'ids': [d['_pk'] for d in documents]}, ) try: response = self.api.mget(**query_kwargs) except IndexNotFoundException: indexed_ids = set() else: indexed_ids = set( d['_id'] for d in response['docs'] if d.get('found')) documents = [d for d in documents ...
def aggregate(self, **params): """ Perform aggreration Arguments: :_aggregations_params: Dict of aggregation params. Root key is an aggregation name. Required. :_raise_on_empty: Boolean indicating whether to raise exception when IndexNotFoundException exception happens. Optional, defaults to False. """ _aggregations_pa...
0 search_params = self.build_search_params(params) search_params.pop('size', None) search_params.pop('from_', None) search_params.pop('sort', None) search_params['body']['aggregations'] = _aggregations_params log.debug('Performing aggregation: {}'.format(_aggregations_params)) try: response = self.api.search(**search_p...
def bulk_index_relations(cls, items, request=None, **kwargs): """ Index objects related to :items: in bulk. Related items are first grouped in map {model_name: {item1, item2, ...}} and then indexed. :param items: Sequence of DB objects related objects if which should be indexed. :param request: Pyramid Request instance...
'_index_enabled', False) if indexable and related_items: index_map[model_cls.__name__].update(related_items) for model_name, instances in index_map.items(): cls(model_name).index(to_dicts(instances), request=request)
def get_version(path="src/devpy/__init__.py"): """ Return the version of by with regex intead of importing it""" init_content = open(path, "rt").read() pattern = r"^__version__ = ['\"]([^'\"]*)['\"]" return re.search(pattern, init_content, re.M).group(1)
def add_plugin_arguments(self, parser): """Add plugin arguments to argument parser. Parameters ---------- parser : argparse.ArgumentParser The main haas ArgumentParser. """ for manager in self.hook_managers.values(): if len(list(manager)) == 0: continue manager.map(self._add_hook_extension_arguments, parser) for namesp...
def get_enabled_hook_plugins(self, hook, args, **kwargs): """Get enabled plugins for specified hook name. """ manager = self.hook_managers[hook] if len(list(manager)) == 0: return [] return [ plugin for plugin in manager.map( self._create_hook_plugin, args, **kwargs) if plugin is not None ]
def get_driver(self, namespace, parsed_args, **kwargs): """Get mutually-exlusive plugin for plugin namespace. """ option, dest = self._namespace_to_option(namespace) dest_prefix = '{0}_'.format(dest) driver_name = getattr(parsed_args, dest, 'default') driver_extension = self.driver_managers[namespace][driver_name] retu...
def get_description(self): """ Get transaction description (for logging purposes) """ if self.card: card_description = self.card.get_description() else: card_description = 'Cardless' if card_description: card_description += ' | ' return card_description + self.description if self.description else card_description + sel...
def set_amount(self, amount): """ Set transaction amount """ if amount: try: self.IsoMessage.FieldData(4, int(amount)) except ValueError: self.IsoMessage.FieldData(4, 0) self.rebuild()
def set_expected_action(self, expected_response_action): """ Expected outcome of the transaction ('APPROVED' or 'DECLINED') """ if expected_response_action.upper() not in ['APPROVED', 'APPROVE', 'DECLINED', 'DECLINE']: return False self.expected_response_action = expected_response_action.upper() return True
def build_emv_data(self): """ TODO: 95 TVR 82 app_int_prof """ emv_data = '' emv_data += self.TLV.build({'82': self._get_app_interchange_profile()}) emv_data += self.TLV.build({'9A': get_date()}) emv_data += self.TLV.build({'95': self.term.get_tvr()}) emv_data += self.TLV.build({'9F10': self.card.get_iss_application_da...
def set_currency(self, currency_id): """ Set transaction currency code from given currency id, e.g. set 840 from 'USD' """ try: self.currency = currency_codes[currency_id] self.IsoMessage.FieldData(49, self.currency) self.rebuild() except KeyError: self.currency = None
def finalize(self): """Output the aggregate block count results.""" for name, count in sorted(self.blocks.items(), key=lambda x: x[1]): print('{:3} {}'.format(count, name)) print('{:3} total'.format(sum(self.blocks.values())))
def analyze(self, scratch, **kwargs): """Run and return the results from the BlockCounts plugin.""" file_blocks = Counter() for script in self.iter_scripts(scratch): for name, _, _ in self.iter_blocks(script.blocks): file_blocks[name] += 1 self.blocks.update(file_blocks) # Update the overall count return {'types': file...
def analyze(self, scratch, **kwargs): """Run and return the results form the DeadCode plugin. The variable_event indicates that the Scratch file contains at least one instance of a broadcast event based on a variable. When variable_event is True, dead code scripts reported by this plugin that begin with a "when I recei...
{} for sprite, script in self.iter_sprite_scripts(scratch): if not script.reachable: sprites.setdefault(sprite, []).append(script) if sprites: self.dead_code_instances += 1 import pprint pprint.pprint(sprites) variable_event = any(True in self.get_broadcast_events(x) for x in self.iter_scripts(scratch)) return {'dead_c...
def finalize(self): """Output the number of instances that contained dead code.""" if self.total_instances > 1: print('{} of {} instances contained dead code.' .format(self.dead_code_instances, self.total_instances))
def show_help(name): """ Show help and basic usage """ print('Usage: python3 {} [OPTIONS]... '.format(name)) print('ISO8583 message client') print(' -v, --verbose\t\tRun transactions verbosely') print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default') print(' -s, --server=[IP]\t\tIP of the ISO host to con...
DE 42 ISO field, 999999999999001 by default)') print(' -k, --terminal-key=[KEY]\t\tTerminal key (\'DEADBEEF DEADBEEF DEADBEEF DEADBEEF\' by default)') print(' -K, --master-key=[KEY]\t\Master key (\'ABABABAB CDCDCDCD EFEFEFEF AEAEAEAE\' by default)') print(' -f, --file=[file.xml]\t\tUse transaction data from the given X...
def _run_interactive(self): """ Run transactions interactively (by asking user which transaction to run) """ self.term.connect() self._show_available_transactions() while True: trxn_type = self._user_input('\nEnter transaction to send: ') trxn = '' data = '' if trxn_type == 'e': trxn = Transaction('echo', self.card, se...
transaction amount ({} by default): '.format(default_amount)) if not amount: amount = default_amount trxn = Transaction('purchase', self.card, self.term) trxn.set_PIN(self._user_input('Enter PIN: ')) trxn.set_amount(amount) trxn.trace() elif trxn_type == 'q': break else: print('Unknown transaction. Available transactio...
def find_top_level_directory(start_directory): """Finds the top-level directory of a project given a start directory inside the project. Parameters ---------- start_directory : str The directory in which test discovery will start. """ top_level = start_directory while os.path.isfile(os.path.join(top_level, '__init__.py...
def discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a director...