signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def assert_checked_checkbox(self, value): | check_box = find_field(world.browser, '<STR_LIT>', value)<EOL>assert check_box, "<STR_LIT>".format(value)<EOL>assert check_box.is_selected(), "<STR_LIT>"<EOL> | Assert the checkbox with label (recommended), name or id is checked. | f2696:m30 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def assert_not_checked_checkbox(self, value): | check_box = find_field(world.browser, '<STR_LIT>', value)<EOL>assert check_box, "<STR_LIT>".format(value)<EOL>assert not check_box.is_selected(), "<STR_LIT>"<EOL> | Assert the checkbox with label (recommended), name or id is not checked. | f2696:m31 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def select_single_item(self, option_name, select_name): | option_box = find_option(world.browser, select_name, option_name)<EOL>assert option_box, "<STR_LIT>".format(option_name)<EOL>option_box.click()<EOL> | Select the named option from select with label (recommended), name or id. | f2696:m32 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def select_multi_items(self, select_name): | <EOL>option_names = self.multiline.split('<STR_LIT:\n>')<EOL>select_box = find_field(world.browser, '<STR_LIT>', select_name)<EOL>assert select_box, "<STR_LIT>".format(select_name)<EOL>select = Select(select_box)<EOL>select.deselect_all()<EOL>for option in option_names:<EOL><INDENT>try:<EOL><INDENT>select.select_by_value(option)<EOL><DEDENT>except NoSuchElementException:<EOL><INDENT>try:<EOL><INDENT>select.select_by_visible_text(option)<EOL><DEDENT>except NoSuchElementException:<EOL><INDENT>raise AssertionError("<STR_LIT>".format(option))<EOL><DEDENT><DEDENT><DEDENT> | Select multiple options from select with label (recommended), name, or
id. Pass a multiline string of options. e.g.
.. code-block:: gherkin
When I select the following from "Contact Methods":
\"\"\"
Email
Phone
Fax
\"\"\" | f2696:m33 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def assert_single_selected(self, option_name, select_name): | option = find_option(world.browser, select_name, option_name)<EOL>assert option.is_selected(), "<STR_LIT>"<EOL> | Assert the given option is selected from the select with label
(recommended), name or id.
If multiple selections are supported other options may be selected. | f2696:m34 |
@step(r'<STR_LIT>')<EOL>@step(r"<STR_LIT>")<EOL>@wait_for<EOL>def select_contains(self, option, id_): | assert option_in_select(world.browser, id_, option) is not None,"<STR_LIT>"<EOL> | Assert the select contains the given option. | f2696:m36 |
@step(r'<STR_LIT>')<EOL>@step(r"<STR_LIT>")<EOL>@wait_for<EOL>def select_does_not_contain(self, option, id_): | assert option_in_select(world.browser, id_, option) is None,"<STR_LIT>"<EOL> | Assert the select does not contain the given option. | f2696:m37 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def choose_radio(self, value): | box = find_field(world.browser, '<STR_LIT>', value)<EOL>assert box, "<STR_LIT>".format(value)<EOL>box.click()<EOL> | Click (and choose) the radio button with the given label (recommended),
name or id. | f2696:m38 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def assert_radio_selected(self, value): | radio = find_field(world.browser, '<STR_LIT>', value)<EOL>assert radio, "<STR_LIT>".format(value)<EOL>assert radio.is_selected(), "<STR_LIT>"<EOL> | Assert the radio button with the given label (recommended), name or id is
chosen. | f2696:m39 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def assert_radio_not_selected(self, value): | radio = find_field(world.browser, '<STR_LIT>', value)<EOL>assert radio, "<STR_LIT>".format(value)<EOL>assert not radio.is_selected(), "<STR_LIT>"<EOL> | Assert the radio button with the given label (recommended), name or id is
not chosen. | f2696:m40 |
@step('<STR_LIT>')<EOL>def accept_alert(self): | try:<EOL><INDENT>alert = Alert(world.browser)<EOL>alert.accept()<EOL><DEDENT>except WebDriverException:<EOL><INDENT>pass<EOL><DEDENT> | Accept the alert. | f2696:m41 |
@step('<STR_LIT>')<EOL>def dismiss_alert(self): | try:<EOL><INDENT>alert = Alert(world.browser)<EOL>alert.dismiss()<EOL><DEDENT>except WebDriverException:<EOL><INDENT>pass<EOL><DEDENT> | Dismiss the alert. | f2696:m42 |
@step(r'<STR_LIT>')<EOL>@step(r"<STR_LIT>")<EOL>def check_alert(self, text): | try:<EOL><INDENT>alert = Alert(world.browser)<EOL>if alert.text != text:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(<EOL>text, alert.text))<EOL><DEDENT><DEDENT>except WebDriverException:<EOL><INDENT>pass<EOL><DEDENT> | Assert an alert is showing with the given text. | f2696:m43 |
@step('<STR_LIT>')<EOL>def check_no_alert(self): | try:<EOL><INDENT>alert = Alert(world.browser)<EOL>raise AssertionError("<STR_LIT>" %<EOL>alert.text)<EOL><DEDENT>except NoAlertPresentException:<EOL><INDENT>pass<EOL><DEDENT> | Assert there is no alert. | f2696:m44 |
def find_by_tooltip(browser, tooltip): | return ElementSelector(<EOL>world.browser,<EOL>str('<STR_LIT>' %<EOL>dict(tooltip=string_literal(tooltip))),<EOL>filter_displayed=True,<EOL>)<EOL> | Find elements with the given tooltip.
:param browser: ``world.browser``
:param tooltip: Tooltip to search for
Returns: an :class:`ElementSelector` | f2696:m45 |
@step(r'<STR_LIT>')<EOL>@step(r"<STR_LIT>")<EOL>@wait_for<EOL>def see_tooltip(self, tooltip): | assert find_by_tooltip(world.browser, tooltip),"<STR_LIT>"<EOL> | Assert an element with the given tooltip (title) is visible.
N.B. tooltip may not be visible. | f2696:m46 |
@step(r'<STR_LIT>')<EOL>@step(r"<STR_LIT>")<EOL>@wait_for<EOL>def no_see_tooltip(self, tooltip): | assert not find_by_tooltip(world.browser, tooltip),"<STR_LIT>"<EOL> | Assert an element with the given tooltip (title) is not visible. | f2696:m47 |
@step(r'<STR_LIT>')<EOL>@step(r"<STR_LIT>")<EOL>def press_by_tooltip(self, tooltip): | for button in find_by_tooltip(world.browser, tooltip):<EOL><INDENT>try:<EOL><INDENT>button.click()<EOL>break<EOL><DEDENT>except: <EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>.format(tooltip))<EOL><DEDENT> | Click on a HTML element with a given tooltip.
This is very useful if you're clicking on icon buttons, etc. | f2696:m48 |
@step(r'<STR_LIT>')<EOL>def switch_to_frame_with_id(self, frame): | elem = world.browser.find_element_by_id(frame)<EOL>world.browser.switch_to.frame(elem)<EOL> | Swap Selenium's context to the given frame or iframe. | f2696:m49 |
@step(r'<STR_LIT>')<EOL>def switch_to_frame_with_class(self, frame): | elem = world.browser.find_element_by_class_name(frame)<EOL>world.browser.switch_to.frame(elem)<EOL> | Swap Selenium's context to the given frame or iframe. | f2696:m50 |
@step(r'<STR_LIT>')<EOL>def switch_to_main(self): | world.browser.switch_to.default_content()<EOL> | Swap Selenium's context back to the main window. | f2696:m51 |
@after.each_step<EOL>def take_screenshot(self): | if not self.failed:<EOL><INDENT>return<EOL><DEDENT>browser = getattr(world, '<STR_LIT>', None)<EOL>if not browser:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>scenario_name = self.scenario.name<EOL>scenario_index =self.scenario.feature.scenarios.index(self.scenario) + <NUM_LIT:1><EOL><DEDENT>except AttributeError:<EOL><INDENT>scenario_name = self.background.keyword<EOL>scenario_index = <NUM_LIT:0><EOL><DEDENT>if self.outline is None:<EOL><INDENT>outline_index_str = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>outline_index = self.scenario.outlines.index(self.outline) + <NUM_LIT:1><EOL>outline_index_str = '<STR_LIT>'.format(outline_index)<EOL><DEDENT>base_name = FORMAT.format(<EOL>feature_file=os.path.relpath(self.feature.filename),<EOL>scenario_index=scenario_index,<EOL>scenario_name=scenario_name,<EOL>outline_index=outline_index_str,<EOL>)<EOL>base_name = re.sub(r'<STR_LIT>', '<STR_LIT:_>', base_name, flags=re.UNICODE)<EOL>base_name = os.path.join(DIRECTORY, base_name)<EOL>world.browser.save_screenshot('<STR_LIT>'.format(base_name))<EOL>with open('<STR_LIT>'.format(base_name), '<STR_LIT:w>') as page_source_file:<EOL><INDENT>page_source_file.write(world.browser.page_source)<EOL><DEDENT> | Take a screenshot after a failed step. | f2697:m0 |
def set_last_hash(h): | global last_hash<EOL>last_hash = h<EOL> | Sets the hash for which a CallDescriptor completed last | f2726:m0 |
def get_last_hash(): | return last_hash<EOL> | Gets the hash for which a CallDescriptor completed last | f2726:m1 |
def set_current_hash(h): | global current_hash<EOL>current_hash = h<EOL> | Sets the hash for which a CallDescriptor is currently executing | f2726:m2 |
def get_current_hash(): | return current_hash<EOL> | Gets the hash for which a CallDescriptor is currently executing | f2726:m3 |
def register_suite(): | global test_suite<EOL>frm = inspect.stack()[<NUM_LIT:1>]<EOL>test_suite = "<STR_LIT:.>".join(os.path.basename(frm[<NUM_LIT:1>]).split('<STR_LIT:.>')[<NUM_LIT:0>:-<NUM_LIT:1>])<EOL> | Call this method in a module containing a test suite. The stack trace from
which call descriptor hashes are derived will be truncated at this module. | f2726:m4 |
def is_primitive(var): | primitives = ( float, long, str, int, dict, list, unicode, tuple, set, frozenset, datetime.datetime, datetime.timedelta, type(None) )<EOL>for primitive in primitives:<EOL><INDENT>if type( var ) == primitive:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL> | Checks if an object is in ( float, long, str, int, dict, list, unicode, tuple, set, frozenset, datetime.datetime, datetime.timedelta ) | f2726:m5 |
def serialize_args(args): | return str([serialize_item(a) for a in args])<EOL> | Attempts to serialize arguments in a consistently ordered way.
If you're having problems getting some CallDescriptors to save it's likely
because this method fails to serialize an argument or a returnvalue.
:param mixed args: Tuple of function arguments to serialize.
:rtype: List of arguments, serialized in a consistently ordered fashion. | f2726:m7 |
def seq(): | current_frame = inspect.currentframe().f_back<EOL>trace_string = "<STR_LIT>"<EOL>while current_frame.f_back:<EOL><INDENT>trace_string = trace_string + current_frame.f_back.f_code.co_name<EOL>current_frame = current_frame.f_back<EOL><DEDENT>return counter.get_from_trace(trace_string)<EOL> | Counts up sequentially from a number based on the current time
:rtype int: | f2726:m8 |
def random(*args): | current_frame = inspect.currentframe().f_back<EOL>trace_string = "<STR_LIT>"<EOL>while current_frame.f_back:<EOL><INDENT>trace_string = trace_string + current_frame.f_back.f_code.co_name<EOL>current_frame = current_frame.f_back<EOL><DEDENT>return counter.get_from_trace(trace_string)<EOL> | Counts up sequentially from a number based on the current time
:rtype int: | f2726:m9 |
def recache( methodname=None, filename=None ): | if not methodname and not filename:<EOL><INDENT>hashes = get_unique_hashes()<EOL>deleted = <NUM_LIT:0><EOL>for hash in hashes:<EOL><INDENT>delete_io(hash)<EOL>deleted = deleted + <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>reqd_strings = []<EOL>if methodname:<EOL><INDENT>reqd_strings.append( methodname )<EOL><DEDENT>if filename:<EOL><INDENT>reqd_strings.append( filename )<EOL><DEDENT>hashes = get_unique_hashes()<EOL>deleted = <NUM_LIT:0><EOL>for hash in hashes:<EOL><INDENT>cd = call_descriptor.fetch( hash )<EOL>if all( [ s in cd.stack for s in reqd_strings ] ):<EOL><INDENT>delete_io( hash )<EOL>deleted = deleted + <NUM_LIT:1><EOL><DEDENT><DEDENT>return deleted<EOL><DEDENT> | Deletes entries corresponding to methodname in filename. If no arguments are passed it recaches the entire table.
:param str methodname: The name of the method to target. This will delete ALL entries this method appears in the stack trace for.
:param str filename: The filename the method is executed in. (include .py extension)
:rtype int: The number of deleted entries | f2726:m10 |
def get_stack(method_name): | global test_suite<EOL>trace_string = method_name + "<STR_LIT:U+0020>"<EOL>for f in inspect.stack():<EOL><INDENT>module_name = os.path.basename(f[<NUM_LIT:1>])<EOL>method_name = f[<NUM_LIT:3>]<EOL>trace_string = trace_string + "<STR_LIT>" % (module_name, method_name)<EOL>if test_suite and module_name == test_suite or (module_name == '<STR_LIT>' and method_name == '<STR_LIT>'):<EOL><INDENT>return trace_string<EOL><DEDENT><DEDENT>return trace_string<EOL> | Returns the stack trace to hash to identify a call descriptor
:param str method_name: The calling method.
:rtype str: | f2726:m11 |
def record_used(kind, hash): | if os.path.exists(LOG_FILEPATH):<EOL><INDENT>log = open(os.path.join(ROOT, '<STR_LIT>'), '<STR_LIT:a>')<EOL><DEDENT>else:<EOL><INDENT>log = open(os.path.join(ROOT, '<STR_LIT>'), '<STR_LIT>')<EOL><DEDENT>log.writelines(["<STR_LIT>" % (kind, hash)])<EOL> | Indicates a cachefile with the name 'hash' of a particular kind has been used so it will note be deleted on the next purge.
:param str kind: The kind of cachefile. One of 'cache', 'seeds', or 'evs'
:param str hash: The hash for the call descriptor, expected value descriptor, or counter seed.
:rtype: None | f2728:m0 |
def delete_io( hash ): | global CACHE_<EOL>load_cache(True)<EOL>record_used('<STR_LIT>', hash)<EOL>num_deleted = len(CACHE_['<STR_LIT>'].get(hash, []))<EOL>if hash in CACHE_['<STR_LIT>']:<EOL><INDENT>del CACHE_['<STR_LIT>'][hash]<EOL><DEDENT>write_out()<EOL>return num_deleted<EOL> | Deletes records associated with a particular hash
:param str hash: The hash
:rtype int: The number of records deleted | f2728:m2 |
def insert_io( args ): | global CACHE_<EOL>load_cache()<EOL>hash = args['<STR_LIT>']<EOL>record_used('<STR_LIT>', hash)<EOL>packet_num = args['<STR_LIT>']<EOL>if hash not in CACHE_['<STR_LIT>']:<EOL><INDENT>CACHE_['<STR_LIT>'][hash] = {}<EOL><DEDENT>CACHE_['<STR_LIT>'][hash][packet_num] = pickle.dumps(args, PPROT)<EOL>write_out()<EOL> | Inserts a method's i/o into the datastore
:param dict args: A dictionary of the hash, stack, packet_num, methodname, args, and returnval
:rtype None: | f2728:m3 |
def select_io( hash ): | load_cache(True)<EOL>global CACHE_<EOL>res = []<EOL>record_used('<STR_LIT>', hash)<EOL>for d in CACHE_['<STR_LIT>'].get(hash, {}).values():<EOL><INDENT>d = pickle.loads(d)<EOL>res += [(d['<STR_LIT>'], d['<STR_LIT>'], d['<STR_LIT>'], d['<STR_LIT>'], d['<STR_LIT:args>'], d['<STR_LIT>'])]<EOL><DEDENT>return res<EOL> | Returns the relevant i/o for a method whose call is characterized by the hash
:param hash: The hash for the CallDescriptor
:rtype list(tuple( hash, stack, methodname, returnval, args, packet_num )): | f2728:m4 |
def get_unique_hashes(): | load_cache(True)<EOL>global CACHE_<EOL>return CACHE_['<STR_LIT>'].keys()<EOL> | Returns all the hashes for cached calls
:rtype list(<string>) | f2728:m10 |
def delete_from_directory_by_hashes(cache_type, hashes): | global CACHE_<EOL>if hashes == '<STR_LIT:*>':<EOL><INDENT>CACHE_[cache_type] = {}<EOL><DEDENT>for h in hashes:<EOL><INDENT>if h in CACHE_[cache_type]:<EOL><INDENT>del CACHE_[cache_type][h]<EOL><DEDENT><DEDENT>write_out()<EOL> | Deletes all cache files corresponding to a list of hashes from a directory
:param str directory: The type of cache to delete files for.
:param list(str) hashes: The hashes to delete the files for | f2728:m11 |
def read_used(): | used_hashes = {"<STR_LIT>": set([]),<EOL>"<STR_LIT>": set([]),<EOL>"<STR_LIT>": set([])}<EOL>with open(LOG_FILEPATH, '<STR_LIT:rb>') as logfile:<EOL><INDENT>for line in logfile.readlines():<EOL><INDENT>kind, hash = tuple(line.split('<STR_LIT>'))<EOL>used_hashes[kind].add(hash.rstrip())<EOL><DEDENT><DEDENT>return used_hashes<EOL> | Read all hashes that have been used since the last call to purge (or reset_hashes).
:rtype: dict
:returns: A dictionary of sets of hashes organized by type | f2728:m12 |
def read_all(): | global CACHE_<EOL>load_cache(True)<EOL>evs = CACHE_['<STR_LIT>'].keys()<EOL>cache = CACHE_['<STR_LIT>'].keys()<EOL>seeds = CACHE_['<STR_LIT>'].keys()<EOL>return {"<STR_LIT>" : evs,<EOL>"<STR_LIT>": cache,<EOL>"<STR_LIT>": seeds}<EOL> | Reads all the hashes and returns them in a dictionary by type
:rtype: dict
:returns: A dictionary of sets of hashes by type | f2728:m13 |
def reset_used(): | with open(LOG_FILEPATH, '<STR_LIT>') as logfile:<EOL><INDENT>pass<EOL><DEDENT> | Deletes all the records of which hashes have been used since the last call to this method. | f2728:m14 |
def purge(): | all_hashes = read_all()<EOL>used_hashes = read_used()<EOL>for kind, hashes in used_hashes.items():<EOL><INDENT>hashes = set(hashes)<EOL>to_remove = set(all_hashes[kind]).difference(hashes)<EOL>delete_from_directory_by_hashes(kind, to_remove)<EOL><DEDENT>reset_used()<EOL>write_out()<EOL> | Deletes all the cached files since the last call to reset_used that have not been used. | f2728:m15 |
def save_stack(stack): | global CACHE_<EOL>serialized = pickle.dumps(stack, PPROT)<EOL>CACHE_['<STR_LIT>']["<STR_LIT>".format(stack.module, stack.caller)] = serialized<EOL>write_out()<EOL> | Saves a stack object to a flatfile.
:param caliendo.hooks.CallStack stack: The stack to save. | f2728:m16 |
def load_stack(stack): | global CACHE_<EOL>load_cache(True)<EOL>key = "<STR_LIT>".format(stack.module, stack.caller)<EOL>if key in CACHE_['<STR_LIT>']:<EOL><INDENT>return pickle.loads(CACHE_['<STR_LIT>'][key])<EOL><DEDENT> | Loads the saved state of a CallStack and returns a whole instance given an instance with incomplete state.
:param caliendo.hooks.CallStack stack: The stack to load
:returns: A CallStack previously built in the context of a patch call.
:rtype: caliendo.hooks.CallStack | f2728:m17 |
def delete_stack(stack): | global CACHE_<EOL>key = "<STR_LIT>".format(stack.module, stack.caller)<EOL>if key in CACHE_['<STR_LIT>']:<EOL><INDENT>del CACHE_['<STR_LIT>'][key]<EOL>write_out()<EOL><DEDENT> | Deletes a stack that was previously saved.load_stack
:param caliendo.hooks.CallStack stack: The stack to delete. | f2728:m18 |
def objwalk(obj, path=(), memo=None): | if len( path ) > MAX_DEPTH + <NUM_LIT:1>:<EOL><INDENT>yield path, obj <EOL><DEDENT>if memo is None:<EOL><INDENT>memo = set()<EOL><DEDENT>iterator = None<EOL>if isinstance(obj, Mapping):<EOL><INDENT>iterator = iteritems<EOL><DEDENT>elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types):<EOL><INDENT>iterator = enumerate<EOL><DEDENT>elif hasattr( obj, '<STR_LIT>' ) and hasattr( obj, '<STR_LIT>' ) and type(obj) not in primitives: <EOL><INDENT>iterator = class_iterator<EOL><DEDENT>elif hasattr(obj, '<STR_LIT>') or isinstance(obj, types.GeneratorType):<EOL><INDENT>obj = [o for o in obj]<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT>if iterator:<EOL><INDENT>if id(obj) not in memo:<EOL><INDENT>memo.add(id(obj))<EOL>for path_component, value in iterator(obj):<EOL><INDENT>for result in objwalk(value, path + (path_component,), memo):<EOL><INDENT>yield result<EOL><DEDENT><DEDENT>memo.remove(id(obj))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield path, obj<EOL><DEDENT> | Walks an arbitrary python pbject.
:param mixed obj: Any python object
:param tuple path: A tuple of the set attributes representing the path to the value
:param set memo: The list of attributes traversed thus far
:rtype <tuple<tuple>, <mixed>>: The path to the value on the object, the value. | f2729:m2 |
def setattr_at_path( obj, path, val ): | target = obj<EOL>last_attr = path[-<NUM_LIT:1>]<EOL>for attr in path[<NUM_LIT:0>:-<NUM_LIT:1>]:<EOL><INDENT>try:<EOL><INDENT>if type(attr) in ( str, unicode ) and target and hasattr( target, attr ):<EOL><INDENT>target = getattr( target, attr )<EOL><DEDENT>else:<EOL><INDENT>target = target[attr]<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>setattr( target, last_attr, val )<EOL><DEDENT>except:<EOL><INDENT>target[last_attr] = val<EOL><DEDENT> | Traverses a set of nested attributes to the value on an object
:param mixed obj: The object to set the attribute on
:param tuple path: The path to the attribute on the object
:param mixed val: The value at the attribute
:rtype None: | f2729:m3 |
def truncate_attr_at_path( obj, path ): | target = obj<EOL>last_attr = path[-<NUM_LIT:1>]<EOL>message = []<EOL>if type(last_attr) == tuple:<EOL><INDENT>last_attr = last_attr[-<NUM_LIT:1>]<EOL><DEDENT>for attr in path[<NUM_LIT:0>:-<NUM_LIT:1>]:<EOL><INDENT>try:<EOL><INDENT>if type(attr) in ( str, unicode ) and target and hasattr( target, attr ) and hasattr( target, '<STR_LIT>' ):<EOL><INDENT>target = getattr( target, attr )<EOL><DEDENT>elif target:<EOL><INDENT>try: target = target[attr]<EOL>except: target = eval( "<STR_LIT>" + str( attr ) )<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if not target: return<EOL><DEDENT>except: return<EOL>if isinstance( target, ( tuple, list ) ): target = list(target) <EOL><DEDENT>try:<EOL><INDENT>del_statement = "<STR_LIT>" + str( last_attr )<EOL>eval( del_statement )<EOL>return<EOL><DEDENT>except: pass<EOL>if type( last_attr ) in ( str, unicode ) and target and hasattr( target, last_attr ):<EOL><INDENT>try: delattr( target, last_attr )<EOL>except: message.append("<STR_LIT>" + str(last_attr) + "<STR_LIT>" + str(target) )<EOL><DEDENT>elif type(target) == list:<EOL><INDENT>try: target.pop(last_attr)<EOL>except: message.append( "<STR_LIT>" + str(target) + "<STR_LIT>" + str(last_attr) )<EOL><DEDENT>else:<EOL><INDENT>try: del target[str(last_attr)]<EOL>except: message.append( "<STR_LIT>" )<EOL><DEDENT> | Traverses a set of nested attributes and truncates the value on an object
:param mixed obj: The object to set the attribute on
:param tuple path: The path to the attribute on the object
:rtype None: | f2729:m4 |
def pickle_with_weak_refs( o ): | if isinstance(o, types.GeneratorType):<EOL><INDENT>o = [i for i in o]<EOL><DEDENT>walk = dict([ (path,val) for path, val in objwalk(o)])<EOL>for path, val in walk.items():<EOL><INDENT>if len(path) > MAX_DEPTH or is_lambda(val):<EOL><INDENT>truncate_attr_at_path(o, path)<EOL><DEDENT>if isinstance(val, weakref.ref):<EOL><INDENT>setattr_at_path( o, path, val() ) <EOL><DEDENT><DEDENT>return pickle.dumps(o)<EOL> | Pickles an object containing weak references.
:param mixed o: Any object
:rtype str: The pickled object | f2729:m5 |
def should_exclude(type_or_instance, exclusion_list): | if type_or_instance in exclusion_list: <EOL><INDENT>return True<EOL><DEDENT>if type(type_or_instance) in exclusion_list: <EOL><INDENT>return True<EOL><DEDENT>try:<EOL><INDENT>if type_or_instance.__class__ in exclusion_list: <EOL><INDENT>return True<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>return False<EOL> | Tests whether an object should be simply returned when being wrapped | f2730:m0 |
def Facade( some_instance=None, exclusion_list=[], cls=None, args=tuple(), kwargs={} ): | if not USE_CALIENDO or should_exclude( some_instance, exclusion_list ):<EOL><INDENT>if not util.is_primitive(some_instance):<EOL><INDENT>some_instance.wrapper__unwrap = lambda : None<EOL>some_instance.wrapper__delete_last_cached = lambda : None<EOL><DEDENT>return some_instance <EOL><DEDENT>else:<EOL><INDENT>if util.is_primitive(some_instance) and not cls:<EOL><INDENT>return some_instance<EOL><DEDENT>return Wrapper(o=some_instance, exclusion_list=list(exclusion_list), cls=cls, args=args, kwargs=kwargs )<EOL><DEDENT> | Top-level interface to the Facade functionality. Determines what to return when passed arbitrary objects.
:param mixed some_instance: Anything.
:param list exclusion_list: The list of types NOT to wrap
:param class cls: The class definition for the object being mocked
:param tuple args: The arguments for the class definition to return the desired instance
:param dict kwargs: The keywork arguments for the class definition to return the desired instance
:rtype instance: Either the instance passed or an instance of the Wrapper wrapping the instance passed. | f2730:m2 |
def cache(handle=lambda *args, **kwargs: None, args=UNDEFINED, kwargs=UNDEFINED, ignore=UNDEFINED, call_stack=UNDEFINED, callback=UNDEFINED, subsequent_rvalue=UNDEFINED): | if args == UNDEFINED:<EOL><INDENT>args = tuple()<EOL><DEDENT>if kwargs == UNDEFINED:<EOL><INDENT>kwargs = {}<EOL><DEDENT>if not USE_CALIENDO:<EOL><INDENT>return handle(*args, **kwargs)<EOL><DEDENT>filtered_args = ignore.filter_args(args) if ignore is not UNDEFINED else args<EOL>filtered_kwargs = ignore.filter_kwargs(kwargs) if ignore is not UNDEFINED else args<EOL>trace_string = util.get_stack(handle.__name__)<EOL>call_hash = get_hash(filtered_args, trace_string, filtered_kwargs, ignore)<EOL>cd = call_descriptor.fetch(call_hash)<EOL>modify_or_replace = '<STR_LIT>'<EOL>util.set_current_hash(call_hash)<EOL>if config.CALIENDO_PROMPT:<EOL><INDENT>display_name = ("<STR_LIT>" % caliendo.util.current_test) if caliendo.util.current_test else '<STR_LIT>'<EOL>if hasattr(handle, '<STR_LIT>') and hasattr(handle, '<STR_LIT>'):<EOL><INDENT>display_name += "<STR_LIT>" % (handle.__module__, handle.__name__)<EOL><DEDENT>else:<EOL><INDENT>display_name += handle<EOL><DEDENT>if cd:<EOL><INDENT>modify_or_replace = prompt.should_modify_or_replace_cached(display_name)<EOL><DEDENT><DEDENT>if not cd or modify_or_replace == '<STR_LIT:replace>':<EOL><INDENT>returnval = handle(*args, **kwargs)<EOL><DEDENT>elif cd and modify_or_replace == '<STR_LIT>':<EOL><INDENT>returnval = prompt.modify_cached_value(cd.returnval,<EOL>calling_method=display_name,<EOL>calling_test='<STR_LIT>')<EOL><DEDENT>if cd and subsequent_rvalue != UNDEFINED:<EOL><INDENT>return subsequent_rvalue<EOL><DEDENT>elif subsequent_rvalue != UNDEFINED:<EOL><INDENT>original_rvalue = returnval<EOL>returnval = subsequent_rvalue<EOL><DEDENT>if not cd or modify_or_replace != '<STR_LIT>':<EOL><INDENT>if isinstance(handle, types.MethodType):<EOL><INDENT>filtered_args = list(filtered_args)<EOL>filtered_args[<NUM_LIT:0>] = util.serialize_item(filtered_args[<NUM_LIT:0>])<EOL>filtered_args = tuple(filtered_args)<EOL><DEDENT>cd = call_descriptor.CallDescriptor( hash = call_hash,<EOL>stack = trace_string,<EOL>method = handle.__name__,<EOL>returnval = returnval,<EOL>args = filtered_args,<EOL>kwargs = filtered_kwargs )<EOL>cd.save()<EOL><DEDENT>util.set_last_hash(cd.hash)<EOL>if call_stack != UNDEFINED:<EOL><INDENT>call_stack.add(cd)<EOL>if callback != UNDEFINED:<EOL><INDENT>call_stack.add_hook(Hook(call_descriptor_hash=cd.hash,<EOL>callback=callback))<EOL><DEDENT><DEDENT>if subsequent_rvalue == UNDEFINED:<EOL><INDENT>return cd.returnval<EOL><DEDENT>else:<EOL><INDENT>return original_rvalue<EOL><DEDENT> | Store a call descriptor
:param lambda handle: Any callable will work here. The method to cache.
:param tuple args: The arguments to the method.
:param dict kwargs: The keyword arguments to the method.
:param tuple(list(int), list(str)) ignore: A tuple of arguments to ignore. The first element should be a list of positional arguments. The second should be a list of keys for keyword arguments.
:param caliendo.hooks.CallStack call_stack: The stack of calls thus far for this patch.
:param function callback: The callback function to execute each time there is a cache hit for 'handle' (actually mechanism is more complicated, but this is what it boils down to)
:param mixed subsequent_rvalue: If passed; this will be the return value each time this method is run regardless of what is returned when it is initially cached. Caching for this method will be skipped. This is useful when the method returns something unpickleable but we still need to stub it out.
:returns: The value of handle(*args, **kwargs) | f2730:m3 |
def patch(*args, **kwargs): | from caliendo.patch import patch as p<EOL>return p(*args, **kwargs)<EOL> | Deprecated. Patch should now be imported from caliendo.patch.patch | f2730:m4 |
def wrapper__ignore(self, type_): | if type_ not in self.__exclusion_list:<EOL><INDENT>self.__exclusion_list.append(type_)<EOL><DEDENT>return self.__exclusion_list<EOL> | Selectively ignore certain types when wrapping attributes.
:param class type: The class/type definition to ignore.
:rtype list(type): The current list of ignored types | f2730:c1:m0 |
def wrapper__unignore(self, type_): | if type_ in self.__exclusion_list:<EOL><INDENT>self.__exclusion_list.remove( type_ )<EOL><DEDENT>return self.__exclusion_list<EOL> | Stop selectively ignoring certain types when wrapping attributes.
:param class type: The class/type definition to stop ignoring.
:rtype list(type): The current list of ignored types | f2730:c1:m1 |
def wrapper__delete_last_cached(self): | return delete_io( self.last_cached )<EOL> | Deletes the last object that was cached by this instance of caliendo's Facade | f2730:c1:m2 |
def wrapper__unwrap(self): | return self['<STR_LIT>']<EOL> | Returns the original object passed to the initializer for Wrapper
:rtype mixed: | f2730:c1:m3 |
def __get_hash(self, args, trace_string, kwargs ): | return get_hash(args, trace_string, kwargs)<EOL> | Returns the hash from a trace string, args, and kwargs
:param tuple args: The positional arguments to the function call
:param str trace_string: The serialized stack trace for the function call
:param dict kwargs: The keyword arguments to the function call
:rtype str: The sha1 hashed result of the inputs plus a thuper-sthecial counter incremented in the local context of the call | f2730:c1:m4 |
def __cache( self, method_name, *args, **kwargs ): | trace_string = util.get_stack(method_name)<EOL>call_hash = self.__get_hash(args, trace_string, kwargs)<EOL>cd = call_descriptor.fetch( call_hash )<EOL>if not cd:<EOL><INDENT>c = self.__store__['<STR_LIT>'][method_name]<EOL>if hasattr( c, '<STR_LIT>' ) and c.__class__ == LazyBones:<EOL><INDENT>c = c.init()<EOL><DEDENT>returnval = c(*args, **kwargs)<EOL>cd = call_descriptor.CallDescriptor( hash = call_hash,<EOL>stack = trace_string,<EOL>method = method_name,<EOL>returnval = returnval,<EOL>args = args,<EOL>kwargs = kwargs )<EOL>cd.save()<EOL>if not call_hash:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>util.last_hash = call_hash<EOL>self.last_cached = call_hash<EOL><DEDENT>else:<EOL><INDENT>returnval = cd.returnval<EOL><DEDENT>if inspect.isclass(returnval):<EOL><INDENT>returnval = LazyBones( c, args, kwargs )<EOL><DEDENT>return returnval<EOL> | Store a call descriptor | f2730:c1:m5 |
def __wrap( self, method_name ): | return lambda *args, **kwargs: Facade( self.__cache( method_name, *args, **kwargs ), list(self.__exclusion_list) )<EOL> | This method actually does the wrapping. When it's given a method to copy it
returns that method with facilities to log the call so it can be repeated.
:param str method_name: The name of the method precisely as it's called on
the object to wrap.
:rtype lambda function: | f2730:c1:m6 |
def wrapper__get_store(self): | return self.__store__<EOL> | Returns the method/attribute store of the wrapper | f2730:c1:m8 |
def __store_callable(self, o, method_name, member): | self.__store__['<STR_LIT>'][method_name] = eval( "<STR_LIT>" + method_name )<EOL>self.__store__['<STR_LIT>'][method_name[<NUM_LIT:0>].lower() + method_name[<NUM_LIT:1>:]] = eval( "<STR_LIT>" + method_name )<EOL>ret_val = self.__wrap( method_name )<EOL>self.__store__[ method_name ] = ret_val<EOL>self.__store__[ method_name[<NUM_LIT:0>].lower() + method_name[<NUM_LIT:1>:] ] = ret_val<EOL> | Stores a callable member to the private __store__
:param mixed o: Any callable (function or method)
:param str method_name: The name of the attribute
:param mixed member: A reference to the member | f2730:c1:m9 |
def __store_class(self, o, method_name, member): | self.__store__['<STR_LIT>'][method_name] = eval( "<STR_LIT>" + method_name )<EOL>self.__store__['<STR_LIT>'][method_name[<NUM_LIT:0>].lower() + method_name[<NUM_LIT:1>:]] = eval( "<STR_LIT>" + method_name )<EOL>ret_val = self.__wrap( method_name )<EOL>self.__store__[ method_name ] = ret_val<EOL>self.__store__[ method_name[<NUM_LIT:0>].lower() + method_name[<NUM_LIT:1>:] ] = ret_val<EOL> | Stores a class to the private __store__
:param class o: The class to store
:param str method_name: The name of the method
:param class member: The actual class definition | f2730:c1:m10 |
def __store_nonprimitive(self, o, method_name, member): | self.__store__[ method_name ] = ( '<STR_LIT>', member )<EOL>self.__store__[ method_name[<NUM_LIT:0>].lower() + method_name[<NUM_LIT:1>:] ] = ( '<STR_LIT>', member )<EOL> | Stores any 'non-primitive'. A primitive is in ( float, long, str, int, dict, list, unicode, tuple, set, frozenset, datetime.datetime, datetime.timedelta )
:param mixed o: The non-primitive to store
:param str method_name: The name of the attribute
:param mixed member: The reference to the non-primitive | f2730:c1:m11 |
def __store_other(self, o, method_name, member): | self.__store__[ method_name ] = eval( "<STR_LIT>" + method_name )<EOL>self.__store__[ method_name[<NUM_LIT:0>].lower() + method_name[<NUM_LIT:1>:] ] = eval( "<STR_LIT>" + method_name )<EOL> | Stores a reference to an attribute on o
:param mixed o: Some object
:param str method_name: The name of the attribute
:param mixed member: The attribute | f2730:c1:m12 |
def __save_reference(self, o, cls, args, kwargs): | if not o and cls:<EOL><INDENT>self['<STR_LIT>'] = LazyBones( cls, args, kwargs )<EOL><DEDENT>else:<EOL><INDENT>while hasattr( o, '<STR_LIT>' ) and o.__class__ == Wrapper:<EOL><INDENT>o = o.wrapper__unwrap()<EOL><DEDENT>self['<STR_LIT>'] = o<EOL><DEDENT> | Saves a reference to the original object Facade is passed. This will either
be the object itself or a LazyBones instance for lazy-loading later
:param mixed o: The original object
:param class cls: The class definition for the original object
:param tuple args: The positional arguments to the original object
:param dict kwargs: The keyword arguments to the original object | f2730:c1:m13 |
def __store_any(self, o, method_name, member): | if should_exclude( eval( "<STR_LIT>" + method_name ), self.__exclusion_list ):<EOL><INDENT>self.__store__[ method_name ] = eval( "<STR_LIT>" + method_name )<EOL>return<EOL><DEDENT>if hasattr( member, '<STR_LIT>' ):<EOL><INDENT>self.__store_callable( o, method_name, member )<EOL><DEDENT>elif inspect.isclass( member ):<EOL><INDENT>self.__store_class( o, method_name, member ) <EOL><DEDENT>elif not util.is_primitive( member ):<EOL><INDENT>self.__store_nonprimitive( o, method_name, member )<EOL><DEDENT>else:<EOL><INDENT>self.__store_other( o, method_name, member )<EOL><DEDENT> | Determines type of member and stores it accordingly
:param mixed o: Any parent object
:param str method_name: The name of the method or attribuet
:param mixed member: Any child object | f2730:c1:m14 |
def __init__( self, o=None, exclusion_list=[], cls=None, args=tuple(), kwargs={} ): | self.__store__ = {'<STR_LIT>': {}}<EOL>self.__class = cls<EOL>self.__args = args<EOL>self.__kwargs = kwargs<EOL>self.__exclusion_list = exclusion_list<EOL>self.__save_reference(o, cls, args, kwargs)<EOL>for method_name, member in inspect.getmembers(o):<EOL><INDENT>self.__store_any(o, method_name, member)<EOL><DEDENT>try: <EOL><INDENT>if o.wrapper__get_store: <EOL><INDENT>store = o.wrapper__get_store()<EOL>for key, val in store.items():<EOL><INDENT>if key == '<STR_LIT>':<EOL><INDENT>self.__store__[key].update( val )<EOL><DEDENT>self.__store__[key] = val<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT> | The init method for the Wrapper class.
:param mixed o: Some object to wrap.
:param list exclusion_list: The list of types NOT to wrap
:param class cls: The class definition for the object being mocked
:param tuple args: The arguments for the class definition to return the desired instance
:param dict kwargs: The keywork arguments for the class definition to return the desired instance | f2730:c1:m15 |
@staticmethod<EOL><INDENT>def exists(method):<DEDENT> | if hasattr(method, '<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | Static method to determine if a method has an existing context.
:param function method:
:rtype: bool
:returns: True if the method has a context. | f2731:c1:m1 |
@staticmethod<EOL><INDENT>def increment(method):<DEDENT> | if not hasattr(method, '<STR_LIT>'):<EOL><INDENT>raise ContextException("<STR_LIT>")<EOL><DEDENT>ctxt = getattr(method, '<STR_LIT>')<EOL>ctxt.enter()<EOL>return ctxt<EOL> | Static method used to increment the depth of a context belonging to 'method'
:param function method: A method with a context
:rtype: caliendo.hooks.Context
:returns: The context instance for the method. | f2731:c1:m2 |
def skip_once(self, call_descriptor_hash): | if call_descriptor_hash not in self.__skip:<EOL><INDENT>self.__skip[call_descriptor_hash] = <NUM_LIT:0><EOL><DEDENT>self.__skip[call_descriptor_hash] += <NUM_LIT:1><EOL> | Indicates the next encounter of a particular CallDescriptor hash should be ignored. (Used when hooks are created for methods to be executed when some parent call is executed)
:param str call_descriptor_hash: The CallDescriptor hash to ignore. This will prevent that descriptor from being executed. | f2731:c2:m1 |
def load(self): | s = load_stack(self)<EOL>if s:<EOL><INDENT>self.hooks = s.hooks<EOL>self.calls = s.calls<EOL><DEDENT> | Loads the state of a previously saved CallStack to this instance. | f2731:c2:m2 |
def set_caller(self, caller): | self.caller = caller.__name__<EOL>self.module = inspect.getmodule(caller).__name__<EOL>self.load()<EOL> | Sets the caller after instantiation. | f2731:c2:m3 |
def save(self): | s = load_stack(self)<EOL>if not load_stack(self):<EOL><INDENT>save_stack(self)<EOL><DEDENT> | Saves this stack if it has not been previously saved. If it needs to be changed the stack must first be deleted. | f2731:c2:m4 |
def delete(self): | delete_stack(self)<EOL> | Deletes this stack from disk so a new one can be saved. | f2731:c2:m5 |
def add(self, call_descriptor): | h = call_descriptor.hash<EOL>self.calls.append(h)<EOL>if h in self.__skip:<EOL><INDENT>self.__skip[h] -= <NUM_LIT:1><EOL>if self.__skip[h] == <NUM_LIT:0>:<EOL><INDENT>del self.__skip[h]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>hook = self.hooks.get(h, False)<EOL>if hook:<EOL><INDENT>hook.callback(call_descriptor)<EOL><DEDENT><DEDENT> | Adds a CallDescriptor hash to the stack. If there is a hook associated with this call it will be executed and passed an instance of the call descriptor.
:param caliendo.call_descriptor.CallDescriptor call_descriptor: The call descriptor to add to the stack. | f2731:c2:m6 |
def add_hook(self, hook): | h = hook.hash<EOL>self.hooks[h] = hook<EOL> | Adds a hook to the CallStack. Which will be executed next time. | f2731:c2:m7 |
def fetch( call_hash ): | res = select_expected_value(call_hash)<EOL>if not res:<EOL><INDENT>return None<EOL><DEDENT>last_packet_number = -<NUM_LIT:1><EOL>expected_value = "<STR_LIT>"<EOL>for packet in res:<EOL><INDENT>call_hash, expected_value_fragment, packet_num = packet<EOL>expected_value += expected_value_fragment<EOL>if packet_num <= last_packet_number:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>last_packet_number = packet_num<EOL><DEDENT>return ExpectedValue( call_hash = call_hash,<EOL>expected_value = pickle.loads(str(expected_value)) )<EOL> | Fetches CallDescriptor from the local database given a hash key representing the call. If it doesn't exist returns None.
:param str hash: The sha1 hexdigest to look the CallDescriptor up by.
:rtype: CallDescriptor corresponding to the hash passed or None if it wasn't found. | f2734:m7 |
def save( self ): | packets = self.__enumerate_packets()<EOL>delete_expected_value(self.call_hash)<EOL>for packet in packets:<EOL><INDENT>packet['<STR_LIT>'] = self.call_hash<EOL>insert_expected_value(packet)<EOL><DEDENT>return self<EOL> | Save method for the ExpectedValue of a call. | f2734:c1:m3 |
def find_dependencies(module, depth=<NUM_LIT:0>, deps=None, seen=None, max_depth=<NUM_LIT>): | deps = {} if not deps else deps<EOL>seen = set([]) if not seen else seen<EOL>if not isinstance(module, types.ModuleType) or module in seen or depth > max_depth:<EOL><INDENT>return None<EOL><DEDENT>for name, object in module.__dict__.items():<EOL><INDENT>seen.add(module)<EOL>if not hasattr(object, '<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>if depth in deps:<EOL><INDENT>deps[depth].append((module, name, object))<EOL><DEDENT>else:<EOL><INDENT>deps[depth] = [(module, name, object)]<EOL><DEDENT>find_dependencies(inspect.getmodule(object), depth=depth+<NUM_LIT:1>, deps=deps, seen=seen)<EOL><DEDENT>return deps<EOL> | Finds all objects a module depends on up to a certain depth truncating cyclic dependencies at the first instance
:param module: The module to find dependencies of
:type module: types.ModuleType
:param depth: The current depth of the dependency resolution from module
:type depth: int
:param deps: The dependencies we've encountered organized by depth.
:type deps: dict
:param seen: The modules we've already resolved dependencies for
:type seen: set
:param max_depth: The maximum depth to resolve dependencies
:type max_depth: int
:rtype: dict
:returns: A dictionary of lists containing tuples describing dependencies. (module, name, object) Where module is a reference to the module, name is the name of the object according to that module's scope, and object is the object itself in that module. | f2735:m0 |
def find_modules_importing(dot_path, starting_with): | klass = None<EOL>filtered = []<EOL>if '<STR_LIT:.>' not in dot_path:<EOL><INDENT>module_or_method = __import__(dot_path)<EOL><DEDENT>else:<EOL><INDENT>getter, attribute = _get_target(dot_path)<EOL>module_or_method = getattr(getter(), attribute)<EOL><DEDENT>if isinstance(module_or_method, types.UnboundMethodType):<EOL><INDENT>klass = getter()<EOL>module_or_method = klass<EOL><DEDENT>deps = find_dependencies(inspect.getmodule(starting_with))<EOL>for depth, dependencies in deps.items():<EOL><INDENT>for dependency in dependencies:<EOL><INDENT>module, name, object = dependency<EOL>if object == module_or_method:<EOL><INDENT>if klass:<EOL><INDENT>filtered.append((module, name, (klass, attribute)))<EOL><DEDENT>else:<EOL><INDENT>filtered.append((module, name, object))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return filtered<EOL> | Finds all the modules importing a particular attribute of a module pointed to by dot_path that starting_with is dependent on.
:param dot_path: The dot path to the object of interest
:type dot_path: str
:param starting_with: The module from which to start resolving dependencies. The only modules importing dot_path returned will be dependencies of this module.
:type starting_with: types.ModuleType
:rtype: list of tuples
:returns: A list of module, name, object representing modules depending on dot_path where module is a reference to the module, name is the name of the object in that module, and object is the imported object in that module. | f2735:m1 |
def execute_side_effect(side_effect=UNDEFINED, args=UNDEFINED, kwargs=UNDEFINED): | if args == UNDEFINED:<EOL><INDENT>args = tuple()<EOL><DEDENT>if kwargs == UNDEFINED:<EOL><INDENT>kwargs = {}<EOL><DEDENT>if isinstance(side_effect, (BaseException, Exception, StandardError)):<EOL><INDENT>raise side_effect<EOL><DEDENT>elif hasattr(side_effect, '<STR_LIT>'): <EOL><INDENT>return side_effect(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>".format(side_effect))<EOL><DEDENT> | Executes a side effect if one is defined.
:param side_effect: The side effect to execute
:type side_effect: Mixed. If it's an exception it's raised. If it's callable it's called with teh parameters.
:param tuple args: The arguments passed to the stubbed out method
:param dict kwargs: The kwargs passed to the subbed out method.
:rtype: mixed
:returns: Whatever the passed side_effect returns
:raises: Whatever error is defined as the side_effect | f2735:m2 |
def get_replacement_method(method_to_patch, side_effect=UNDEFINED, rvalue=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, context=UNDEFINED, subsequent_rvalue=UNDEFINED): | def patch_with(*args, **kwargs):<EOL><INDENT>if side_effect != UNDEFINED:<EOL><INDENT>return execute_side_effect(side_effect, args, kwargs)<EOL><DEDENT>if rvalue != UNDEFINED:<EOL><INDENT>return rvalue<EOL><DEDENT>return cache(method_to_patch, args=args, kwargs=kwargs, ignore=ignore, call_stack=context.stack, callback=callback, subsequent_rvalue=subsequent_rvalue)<EOL><DEDENT>return patch_with<EOL> | Returns the method to be applied in place of an original method. This method either executes a side effect, returns an rvalue, or implements caching in place of the method_to_patch
:param function method_to_patch: A reference to the method that will be patched.
:param mixed side_effect: The side effect to execute. Either a callable with the same parameters as the target, or an exception.
:param mixed rvalue: The value that should be immediately returned without executing the target.
:param caliendo.Ignore ignore: The parameters that should be ignored when determining cachekeys. These are typically the dynamic values such as datetime.datetime.now() or a setting from an environment specific file.
:param function callback: A pickleable callback to execute when the patched method is called and the cache is hit. (has to have been cached the first time).
:param caliendo.hooks.Context ctxt: The context this patch should be executed under. Generally reserved for internal use. The vast majority of use cases should leave this parameter alone.
:param mixed subsequent_rvalue: If passed; this will be the return value each time this method is run regardless of what is returned when it is initially cached. Caching for this method will be skipped. This is useful when the method returns something unpickleable but we still need to stub it out.
:rtype: function
:returns: The function to replace all references to method_to_patch with. | f2735:m3 |
def get_context(method): | if Context.exists(method):<EOL><INDENT>return Context.increment(method)<EOL><DEDENT>else:<EOL><INDENT>return Context(method)<EOL><DEDENT> | Gets a context for a target function.
:rtype: caliendo.hooks.Context
:returns: The context for the call. Patches are applied and removed within a context. | f2735:m5 |
def patch(import_path, rvalue=UNDEFINED, side_effect=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, ctxt=UNDEFINED, subsequent_rvalue=UNDEFINED): | def patch_test(unpatched_test):<EOL><INDENT>"""<STR_LIT>"""<EOL>if ctxt == UNDEFINED:<EOL><INDENT>context = get_context(unpatched_test)<EOL><DEDENT>else:<EOL><INDENT>context = ctxt<EOL>context.enter()<EOL><DEDENT>patched_test = get_patched_test(import_path=import_path,<EOL>unpatched_test=unpatched_test,<EOL>rvalue=rvalue,<EOL>side_effect=side_effect,<EOL>context=context,<EOL>ignore=ignore,<EOL>callback=callback,<EOL>subsequent_rvalue=subsequent_rvalue)<EOL>patched_test.__context = context<EOL>patched_test.__name__ = context.name<EOL>return patched_test<EOL><DEDENT>return patch_test<EOL> | Patches an attribute of a module referenced on import_path with a decorated
version that will use the caliendo cache if rvalue is None. Otherwise it will
patch the attribute of the module to return rvalue when called.
This class provides a context in which to use the patched module. After the
decorated method is called patch_in_place unpatches the patched module with
the original method.
:param str import_path: The import path of the method to patch.
:param mixed rvalue: The return value of the patched method.
:param mixed side_effect: The side effect to execute. Either a callable with the same parameters as the target, or an exception.
:param caliendo.Ignore ignore: Arguments to ignore. The first element should be a list of positional arguments. The second should be a list of keys for keyword arguments.
:param function callback: A pickleable callback to execute when the patched method is called and the cache is hit. (has to have been cached the first time).
:param caliendo.hooks.Context ctxt: The context this patch should be executed under. Generally reserved for internal use. The vast majority of use cases should leave this parameter alone.
:param mixed subsequent_rvalue: If passed; this will be the return value each time this method is run regardless of what is returned when it is initially cached. Caching for this method will be skipped. This is useful when the method returns something unpickleable but we still need to stub it out. | f2735:m6 |
def get_recorder(import_path, ctxt): | getter, attribute = _get_target(import_path)<EOL>method_to_patch = getattr(getter(), attribute)<EOL>def recorder(*args, **kwargs):<EOL><INDENT>ctxt.stack.add_hook(Hook(call_descriptor_hash=util.get_current_hash(),<EOL>callback=lambda cd: method_to_patch(*args, **kwargs)))<EOL>ctxt.stack.skip_once(util.get_current_hash())<EOL>return method_to_patch(*args, **kwargs)<EOL><DEDENT>return recorder<EOL> | Gets a recorder for a particular target given a particular context
:param str import_path: The import path of the method to record
:param caliendo.hooks.Context ctxt: The context to record
:rtype: function
:returns: A method that acts like the target, but adds a hook for each call. | f2735:m7 |
def replay(import_path): | def patch_method(unpatched_method):<EOL><INDENT>context = get_context(unpatched_method)<EOL>recorder = get_recorder(import_path, context)<EOL>@patch(import_path, side_effect=recorder, ctxt=context)<EOL>def patched_method(*args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return unpatched_method(*args, **kwargs)<EOL><DEDENT>finally:<EOL><INDENT>context.exit()<EOL><DEDENT><DEDENT>patched_method.__context = context<EOL>return patched_method<EOL><DEDENT>return patch_method<EOL> | Replays calls to a method located at import_path. These calls must occur after the start of a method for which there is a cache hit. E.g. after a method patched with patch() or cached with cache()
:param str import_path: The absolute import path for the method to monitor and replay as a string.
:rtype: function
:returns: The decorated method with all existing references to the target replaced with a recorder to replay it | f2735:m8 |
def patch_lazy(import_path, rvalue=UNDEFINED, side_effect=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, ctxt=UNDEFINED): | def patch_method(unpatched_method):<EOL><INDENT>context = get_context(unpatched_method)<EOL>getter, attribute = _get_target(import_path)<EOL>klass = getter()<EOL>getattr_path = "<STR_LIT:.>".join(import_path.split('<STR_LIT:.>')[<NUM_LIT:0>:-<NUM_LIT:1>] + ['<STR_LIT>'])<EOL>def wrapper(wrapped_method, instance, attr):<EOL><INDENT>lazy_loaded = wrapped_method.original(instance, attr)<EOL>if attr != attribute:<EOL><INDENT>return lazy_loaded<EOL><DEDENT>return get_replacement_method(lazy_loaded,<EOL>side_effect=side_effect,<EOL>rvalue=rvalue,<EOL>ignore=ignore,<EOL>callback=callback,<EOL>context=context)<EOL><DEDENT>@patch(getattr_path, side_effect=WrappedMethod(klass.__getattr__, wrapper), ctxt=context)<EOL>def patched_method(*args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return unpatched_method(*args, **kwargs)<EOL><DEDENT>finally:<EOL><INDENT>context.exit()<EOL><DEDENT><DEDENT>return patched_method<EOL><DEDENT>return patch_method<EOL> | Patches lazy-loaded methods of classes. Patching at the class definition overrides the __getattr__ method for the class with a new version that patches any callables returned by __getattr__ with a key matching the last element of the dot path given
:param str import_path: The absolute path to the lazy-loaded method to patch. It can be either abstract, or defined by calling __getattr__
:param mixed rvalue: The value that should be immediately returned without executing the target.
:param mixed side_effect: The side effect to execute. Either a callable with the same parameters as the target, or an exception.
:param caliendo.Ignore ignore: The parameters that should be ignored when determining cachekeys. These are typically the dynamic values such as datetime.datetime.now() or a setting from an environment specific file.
:param function callback: The callback function to execute when
:param function callback: A pickleable callback to execute when the patched method is called and the cache is hit. (has to have been cached the first time).
:param caliendo.hooks.Context ctxt: The context this patch should be executed under. Generally reserved for internal use. The vast majority of use cases should leave this parameter alone.
:returns: The patched calling method. | f2735:m9 |
def fetch( hash ): | res = select_io( hash )<EOL>if res:<EOL><INDENT>p = { '<STR_LIT>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>', '<STR_LIT:args>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>' }<EOL>for packet in res:<EOL><INDENT>hash, stack, methodname, returnval, args, packet_num = packet<EOL>p['<STR_LIT>'] = p['<STR_LIT>'] + methodname<EOL>p['<STR_LIT>'] = p['<STR_LIT>'] + returnval<EOL>p['<STR_LIT:args>'] = p['<STR_LIT:args>'] + args<EOL>p['<STR_LIT>'] = p['<STR_LIT>'] + stack<EOL><DEDENT>return CallDescriptor( hash = hash,<EOL>stack = p['<STR_LIT>'],<EOL>method = p['<STR_LIT>'],<EOL>returnval = pickle.loads( str( p['<STR_LIT>'] ) ),<EOL>args = pickle.loads( str( p['<STR_LIT:args>'] ) ) )<EOL><DEDENT>return None<EOL> | Fetches CallDescriptor from the local database given a hash key representing the call. If it doesn't exist returns None.
:param str hash: The sha1 hexdigest to look the CallDescriptor up by.
:rtype: CallDescriptor corresponding to the hash passed or None if it wasn't found. | f2736:m0 |
def __init__( self, hash='<STR_LIT>', stack='<STR_LIT>', method='<STR_LIT>', returnval='<STR_LIT>', args='<STR_LIT>', kwargs='<STR_LIT>' ): | self.hash = hash<EOL>self.stack = stack<EOL>self.methodname = method<EOL>self.returnval = returnval<EOL>self.args = args<EOL>self.kwargs = kwargs<EOL> | CallDescriptor initialiser.
:param str hash: A hash of the method, order of the call, and arguments.
:param str method: The name of the method being called.
:param mixed returnval: The return value of the method. If this isn't pickle-able there will be a problem.
:param mixed args: The arguments for the method. If these aren't pickle-able there will be a problem. | f2736:c1:m0 |
def save( self ): | packets = self.__enumerate_packets( )<EOL>delete_io( self.hash )<EOL>for packet in packets:<EOL><INDENT>packet['<STR_LIT>'] = self.hash<EOL>insert_io( packet )<EOL><DEDENT>return self<EOL> | Save method for the CallDescriptor.
If the CallDescriptor matches a past CallDescriptor it updates the existing
database record corresponding to the hash. If it doesn't already exist it'll
be INSERT'd. | f2736:c1:m4 |
def send_and_assert_email(self, html_template_name=None): | kwargs = {<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT:to>': ['<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': html_template_name,<EOL>}<EOL>incuna_mail.send(**kwargs)<EOL>self.assertEqual(len(mail.outbox), <NUM_LIT:1>)<EOL>email = mail.outbox[<NUM_LIT:0>]<EOL>self.assertEqual(email.to, kwargs['<STR_LIT:to>'])<EOL>self.assertEqual(email.from_email, kwargs['<STR_LIT>'])<EOL>self.assertEqual(email.cc, kwargs['<STR_LIT>'])<EOL>self.assertEqual(email.bcc, kwargs['<STR_LIT>'])<EOL>self.assertEqual(email.subject, kwargs['<STR_LIT>'])<EOL>self.assertEqual(email.reply_to, kwargs['<STR_LIT>'])<EOL>return email<EOL> | Runs send() on proper input and checks the result. | f2739:c0:m0 |
def send(template_name, sender=None, to=None, cc=None, bcc=None, subject='<STR_LIT>',<EOL>attachments=(), html_template_name=None, context=None, headers=None,<EOL>reply_to=None): | to, cc, bcc, reply_to = map(listify, [to, cc, bcc, reply_to])<EOL>if sender is None:<EOL><INDENT>sender = getattr(settings, '<STR_LIT>', settings.SERVER_EMAIL)<EOL><DEDENT>attachment_list = [[a.name, a.read(), a.content_type] for a in attachments]<EOL>email_kwargs = {<EOL>'<STR_LIT>': sender,<EOL>'<STR_LIT:to>': to,<EOL>'<STR_LIT>': cc,<EOL>'<STR_LIT>': bcc,<EOL>'<STR_LIT>': six.text_type(subject),<EOL>'<STR_LIT>': attachment_list,<EOL>'<STR_LIT>': reply_to,<EOL>'<STR_LIT>': headers or {},<EOL>}<EOL>text_content = render_to_string(template_name, context)<EOL>email_kwargs['<STR_LIT:body>'] = text_content<EOL>if html_template_name is None:<EOL><INDENT>msg = EmailMessage(**email_kwargs)<EOL><DEDENT>else:<EOL><INDENT>msg = EmailMultiAlternatives(**email_kwargs)<EOL>html_content = render_to_string(html_template_name, context)<EOL>msg.attach_alternative(html_content, '<STR_LIT>')<EOL><DEDENT>msg.send()<EOL> | Render and send an email. `template_name` is a plaintext template.
If `html_template_name` is passed then a multipart email will be sent using
`template_name` for the text part and `html_template_name` for the HTML part.
The context will include any `context` specified.
If no `sender` is specified then the `DEFAULT_FROM_EMAIL` or `SERVER_EMAIL`
setting will be used.
Extra email headers can be passed in to `headers` as a dictionary. | f2740:m1 |
def create_experiment(self): | return self.post_data("<STR_LIT>", params = {})<EOL> | Create an experiment | f2744:c0:m1 |
def get_all_experiments(self): | return self.get_data("<STR_LIT>")<EOL> | This function returns a list of all experiments. | f2744:c0:m2 |
def get_experiment(self, id): | return self.get_data("<STR_LIT>" + str(id))<EOL> | This function returns data from an experiment. | f2744:c0:m3 |
def get_all_items(self): | return self.get_data("<STR_LIT>")<EOL> | Return all items | f2744:c0:m4 |
def get_item(self, id): | return self.get_data("<STR_LIT>" + str(id))<EOL> | Get data from an item | f2744:c0:m5 |
def post_experiment(self, id, params): | return self.post_data("<STR_LIT>" + str(id), params)<EOL> | Change an experiment title/body/date | f2744:c0:m6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.