def _show_response(n, d): global n_known_response_times global n_unknown_response_times global times_d global tot_response_time global trace global verbose # Calculate response time. t1 = times_d.get(n) t2 = time.perf_counter() if t1 is None or n is None: response_time_s = '???' n_unknown_response_times += 1 else: response_time = t2 - t1 tot_response_time += response_time n_known_response_times += 1 response_time_s = f"{response_time:3.2}" if not trace and not verbose: return action = d.get('action') if not verbose: print(f"id: {d.get('id', '---'):3} d: {sorted(d)}") return if action == 'open_file': g.printObj( d, tag=f"{tag}: got: open-file response time: {response_time_s}") elif action == 'get_all_commands': commands = d.get('commands') print(f"{tag}: got: get_all_commands {len(commands)}") else: print(f"{tag}: got: {d}")
def createMenusFromConfigList(self, aList): ''' Create menus from aList. The 'top' menu has already been created. ''' # Called from createMenuBar. trace = False and not g.unitTesting trace_list = False if trace and trace_list: g.trace('=====') g.printObj(aList) c = self.c for z in aList: kind, val, val2 = z if kind.startswith('@menu'): name = kind[len('@menu'):].strip() if not self.handleSpecialMenus(name, parentName=None): # Fix #528: Don't create duplicate menu items. menu = self.createNewMenu(name) # Create top-level menu. if menu: self.createMenuFromConfigList(name, val, level=0) else: g.trace('no menu', name) else: self.error('%s %s not valid outside @menu tree' % (kind, val)) aList = c.config.getOpenWith() if aList: # a list of dicts. self.createOpenWithMenuFromTable(aList)
def test_all_doctests(self): fails_list = [] # List of files with failing doctests. files_list = [] # List of files containing a doctest. n = 0 # Total doctests found for module in ('core', 'plugins', 'unittests'): module_path = os.path.join(leo_dir, module) self.assertTrue(os.path.exists(module_path), msg=repr(module_path)) path = os.path.join(module_path, '**', '*.py') files = glob.glob(path, recursive=True) files = [z for z in files if not z.endswith('__init__.py')] for f in files: # Exclude two problematic files. if 'dtest.py' in f or 'javascript.py' in f: continue fails, count = doctest.testfile(f, False) n += count if count: files_list.append(f) if fails: # pragma: no cover fails_list.append(f) print(f"{fails} failures in {g.shortFileName(f)}") self.assertEqual(fails_list, []) if 0: g.trace(f"{n} doctests found in {len(files_list)} file{g.plural(len(files_list))}") g.printObj(files_list, tag="files containing any doctest") g.printObj(fails_list, tag="files containing a failed doctest")
def loadLayouts(self, tag, keys, reloading=False): """loadLayouts - Load the outline's layout :Parameters: - `tag`: from hook event - `keys`: from hook event - `reloading`: True if this is not the initial load, see below When called from the `after-create-leo-frame2` hook this defaults to False. When called from the `resotre-layout` command, this is set True, and the layout the outline had *when first loaded* is restored. Useful if you want to temporarily switch to a different layout and then back, without having to remember the original layouts name. """ trace = 'layouts' in g.app.debug c = self.c if not (g.app and g.app.db): return # Can happen when running from the Leo bridge. if c != keys.get('c'): return d = g.app.db.get('ns_layouts') or {} if trace: g.trace(tag) g.printObj(keys, tag="keys") layout = c.config.getData("free-layout-layout") if layout: layout = json.loads('\n'.join(layout)) name = c.db.get('_ns_layout') if name: if reloading: name = c.free_layout.original_layout c.db['_ns_layout'] = name else: c.free_layout.original_layout = name if layout: g.es("NOTE: embedded layout in @settings/@data free-layout-layout " "overrides saved layout " + name) else: layout = d.get(name) # EKR: Create commands that will load each layout. if d: for name in sorted(d.keys()): def func(event): layout = d.get(name) if layout: c.free_layout.get_top_splitter().load_layout(c, layout) else: g.trace('no layout', name) name_s = name.strip().lower().replace(' ', '-') commandName = f"free-layout-load-{name_s}" c.k.registerCommand(commandName, func) # Careful: we could be unit testing or in the Leo bridge. if layout: splitter = c.free_layout.get_top_splitter() if splitter: splitter.load_layout(c, layout)
def test_setup(self): c = self.c assert self.x assert self.p if 0: self.dump_tree() if 0: for p in c.all_positions(): g.printObj(p.b, tag=p.h)
def doEnter(self, event): # set cursor to end of line to avoid line splitting trace = False and not g.unitTesting textCursor = self.textCursor() position = len(self.document().toPlainText()) textCursor.setPosition(position) self.setTextCursor(textCursor) lines = [] block = self.document().lastBlock() # #792: python_console plugin doesn't handle copy/paste properly. while block: line = g.toUnicode(block.text()) block = block.previous() done = g.match(line, 0, '>>>') if done: line = line[4:] # remove marker lines.insert(0, line.rstrip()) if done: break if trace: g.trace() g.printObj(lines) self.historyIndex = -1 if len(lines) > 1: # #792: python_console plugin doesn't handle copy/paste properly. self.append('') self.command = '\n'.join(lines).rstrip() + '\n' self.interpreter.runIt(self.command) self.command = '' self.marker() return if self.customCommands(line): return None self.haveLine = bool(line) if self.haveLine: self.history.insert(0, line) if line[-1] == ':': self.multiLine = True g.trace(self.haveLine, self.multiLine, repr(line)) if self.haveLine: if self.multiLine: self.command += line + '\n' # + command and line self.append('') else: self.command = line self.append('') self.interpreter.runIt(self.command) self.command = '' else: if self.multiLine: self.append('') self.interpreter.runIt(self.command) self.command = '' self.multiLine = False # back to single line else: # Do nothing. self.append('') self.marker() return None
def doEnter(self, event): # set cursor to end of line to avoid line splitting trace = False and not g.unitTesting textCursor = self.textCursor() position = len(self.document().toPlainText()) textCursor.setPosition(position) self.setTextCursor(textCursor) lines = [] block = self.document().lastBlock() # #792: python_console plugin doesn't handle copy/paste properly. while block: line = g.toUnicode(block.text()) block = block.previous() done = g.match(line, 0, '>>>') if done: line = line [4:] # remove marker lines.insert(0, line.rstrip()) if done: break if trace: g.trace() g.printObj(lines) self.historyIndex = -1 if len(lines) > 1: # #792: python_console plugin doesn't handle copy/paste properly. self.append('') self.command = '\n'.join(lines).rstrip() + '\n' self.interpreter.runIt(self.command) self.command = '' self.marker() return if self.customCommands(line): return None self.haveLine = bool(line) if self.haveLine: self.history.insert(0, line) if line[-1] == ':': self.multiLine = True g.trace(self.haveLine, self.multiLine, repr(line)) if self.haveLine: if self.multiLine: self.command += line + '\n' # + command and line self.append('') else: self.command = line self.append('') self.interpreter.runIt(self.command) self.command = '' else: if self.multiLine: self.append('') self.interpreter.runIt(self.command) self.command = '' self.multiLine = False # back to single line else: # Do nothing. self.append('') self.marker() return None
def set_ua(self, p, key, val): '''Set p.v.u''' trace = False and not g.unitTesting if trace: g.trace(p.h, key) g.printObj(val) d = p.v.u d2 = d.get('ipynb') or {} d2 [key] = val d ['ipynb'] = d2 p.v.u = d
def load_layout(self, c, layout, level=0): trace = 'layouts' in g.app.debug if trace: g.trace('level', level) tag = f"layout: {c.shortFileName()}" g.printObj(layout, tag=tag) if isQt6: Orientations = QtCore.Qt.Orientations if layout['orientation'] == 1: self.setOrientation(Orientations.Horizontal) else: self.setOrientation(Orientations.Vertical) else: self.setOrientation(layout['orientation']) found = 0 if level == 0: for i in self.self_and_descendants(): for n in range(i.count()): i.widget(n)._in_layout = False for content_layout in layout['content']: if isinstance(content_layout, dict): new = NestedSplitter(root=self.root, parent=self) new._in_layout = True self.insert(found, new) found += 1 new.load_layout(c, content_layout, level + 1) else: provided = self.get_provided(content_layout) if provided: self.insert(found, provided) provided._in_layout = True found += 1 else: print(f"No provider for {content_layout}") self.prune_empty() if self.count() != len(layout['sizes']): not_in_layout = set() for i in self.self_and_descendants(): for n in range(i.count()): c = i.widget(n) if not (hasattr(c, '_in_layout') and c._in_layout): not_in_layout.add(c) for i in not_in_layout: self.close_or_keep(i) self.prune_empty() if self.count() == len(layout['sizes']): self.setSizes(layout['sizes']) else: print(f"Wrong pane count at level {level:d}, " f"count:{self.count():d}, " f"sizes:{len(layout['sizes']):d}") self.equalize_sizes()
def dump_tree(self, root, tag=None): """ Like LeoUnitTest.dump_tree. """ d = self.vnode_info if hasattr(self, 'vnode_info') else {} if tag: print(tag) for p in root.self_and_subtree(): print('') print('level:', p.level(), p.h) lines = d[p.v]['lines'] if p.v in d else g.splitLines(p.v.b) g.printObj(lines)
def check(self, unused_s, parent): '''True if perfect import checks pass.''' if g.app.suppressImportChecks: g.app.suppressImportChecks = False return True c = self.c sfn = g.shortFileName(self.root.h) s1 = g.toUnicode(self.file_s, self.encoding) s2 = self.trial_write() lines1, lines2 = g.splitLines(s1), g.splitLines(s2) if 0: # An excellent trace for debugging. g.trace(c.shortFileName()) g.printObj(lines1, tag='lines1') g.printObj(lines2, tag='lines2') if self.strict: # Ignore blank lines only. # Adding nodes may add blank lines. lines1 = self.strip_blank_lines(lines1) lines2 = self.strip_blank_lines(lines2) else: # Ignore blank lines and leading whitespace. # Importing may regularize whitespace, and that's good. lines1 = self.strip_all(lines1) lines2 = self.strip_all(lines2) # Forgive trailing whitespace problems in the last line. # This is not the same as clean_last_lines. if lines1 and lines2 and lines1 != lines2: lines1[-1] = lines1[-1].rstrip() + '\n' lines2[-1] = lines2[-1].rstrip() + '\n' # self.trace_lines(lines1, lines2, parent) ok = lines1 == lines2 if not ok and not self.strict: # Issue an error only if something *other than* lws is amiss. lines1, lines2 = self.strip_lws(lines1), self.strip_lws(lines2) ok = lines1 == lines2 if ok and not g.unitTesting: print('warning: leading whitespace changed in:', self.root.h) if not ok: self.show_failure(lines1, lines2, sfn) # self.trace_lines(lines1, lines2, parent) # Ensure that the unit tests fail when they should. # Unit tests do not generate errors unless the mismatch line does not match. if g.app.unitTesting: d = g.app.unitTestDict d['result'] = ok if not ok: d['fail'] = g.callers() # Used in a unit test. c.importCommands.errors += 1 return ok
def run(self, p): """Run mypy on all Python @<file> nodes in c.p's tree.""" c = self.c if not mypy: print('install mypy with `pip install mypy`') return root = p.copy() # Make sure Leo is on sys.path. leo_path = g.os_path_finalize_join(g.app.loadDir, '..') if leo_path not in sys.path: sys.path.append(leo_path) roots = g.findRootsWithPredicate(c, root, predicate=None) g.printObj([z.h for z in roots], tag='mypy.run') self.check_all(roots)
def check(self, unused_s, parent): '''True if perfect import checks pass.''' if g.app.suppressImportChecks: g.app.suppressImportChecks = False return True c = self.c sfn = g.shortFileName(self.root.h) s1 = g.toUnicode(self.file_s, self.encoding) s2 = self.trial_write() lines1, lines2 = g.splitLines(s1), g.splitLines(s2) if 0: # An excellent trace for debugging. g.trace(c.shortFileName()) g.printObj(lines1, tag='lines1') g.printObj(lines2, tag='lines2') if self.strict: # Ignore blank lines only. # Adding nodes may add blank lines. lines1 = self.strip_blank_lines(lines1) lines2 = self.strip_blank_lines(lines2) else: # Ignore blank lines and leading whitespace. # Importing may regularize whitespace, and that's good. lines1 = self.strip_all(lines1) lines2 = self.strip_all(lines2) # Forgive trailing whitespace problems in the last line. # This is not the same as clean_last_lines. if lines1 and lines2 and lines1 != lines2: lines1[-1] = lines1[-1].rstrip()+'\n' lines2[-1] = lines2[-1].rstrip()+'\n' # self.trace_lines(lines1, lines2, parent) ok = lines1 == lines2 if not ok and not self.strict: # Issue an error only if something *other than* lws is amiss. lines1, lines2 = self.strip_lws(lines1), self.strip_lws(lines2) ok = lines1 == lines2 if ok and not g.unitTesting: print('warning: leading whitespace changed in:', self.root.h) if not ok: self.show_failure(lines1, lines2, sfn) # self.trace_lines(lines1, lines2, parent) # Ensure that the unit tests fail when they should. # Unit tests do not generate errors unless the mismatch line does not match. if g.app.unitTesting: d = g.app.unitTestDict d['result'] = ok if not ok: d['fail'] = g.callers() # Used in a unit test. c.importCommands.errors += 1 return ok
def gen_lines(self, s, parent): ''' Non-recursively parse all lines of s into parent, creating descendant nodes as needed. ''' self.tail_p = None prev_state = self.state_class() target = PythonTarget(parent, prev_state) stack = [target, target] self.decorator_lines = [] self.inject_lines_ivar(parent) lines = g.splitLines(s) self.skip = 0 first = True for i, line in enumerate(lines): new_state = self.scan_line(line, prev_state) top = stack[-1] if self.skip > 0: self.skip -= 1 elif self.starts_decorator(i, lines, new_state): pass # Sets self.skip and self.decorator_lines. elif self.starts_block(i, lines, new_state, prev_state, stack): first = False self.tail_p = None self.start_new_block(i, lines, new_state, prev_state, stack) elif first: if self.is_ws_line(line): p = self.tail_p or top.p self.add_line(p, line) else: first = False h = 'Declarations' self.gen_ref(line, parent, target) p = self.create_child_node(parent, body=line, headline=h) stack.append(PythonTarget(p, new_state)) elif self.ends_block(line, new_state, prev_state, stack): first = False self.tail_p = self.end_block(i, lines, new_state, prev_state, stack) else: p = self.tail_p or top.p self.add_line(p, line) prev_state = new_state if self.skip: g.trace('can not happen: self.skip > 0', color='red') if self.decorator_lines: g.trace('can not happen: unused decorator lines...', color='red') g.printObj(self.decorator_lines)
def gen_lines(self, s, parent): ''' Non-recursively parse all lines of s into parent, creating descendant nodes as needed. ''' tail_p = None prev_state = self.state_class() target = PythonTarget(parent, prev_state) stack = [target, target] self.decorator_lines = [] self.inject_lines_ivar(parent) lines = g.splitLines(s) self.skip = 0 first = True for i, line in enumerate(lines): new_state = self.scan_line(line, prev_state) top = stack[-1] if self.skip > 0: self.skip -= 1 elif self.starts_decorator(i, lines, new_state): pass # Sets self.skip and self.decorator_lines. elif self.starts_block(i, lines, new_state, prev_state, stack): first = False tail_p = None self.start_new_block(i, lines, new_state, prev_state, stack) elif first: if self.is_ws_line(line): p = tail_p or top.p self.add_line(p, line) else: first = False h = 'Declarations' self.gen_ref(line, parent, target) p = self.create_child_node(parent, body=line, headline=h) stack.append(PythonTarget(p, new_state)) elif self.ends_block(line, new_state, prev_state, stack): first = False tail_p = self.end_block(i, lines, new_state, prev_state, stack) else: p = tail_p or top.p self.add_line(p, line) prev_state = new_state if self.skip: g.trace('can not happen: self.skip > 0', color='red') if self.decorator_lines: g.trace('can not happen: unused decorator lines...', color='red') g.printObj(self.decorator_lines)
def dump_pyzo_menus(self): ''' Add pyzo's menus to Leo's 'Pyzo' menu. To do: Suppress translations. ''' main_window = g.app.gui.hidden_main_window menuBar = main_window.menuBar() #@+<< menu dumps >> #@+node:ekr.20190426075514.1: *4* << menu dumps >> # pylint: disable=no-member # pyzo.icons *does* exist. if 0: g.trace('menuBar.children()...') for child in menuBar.children(): g.pr(child) # pyzo.core.menu.FileMenu, etc. if 0: g.trace('menuBar.actions()...') for action in menuBar.actions(): g.pr(action) if 0: g.trace('pyzo.icons...') for key, icon in pyzo.icons.items(): g.pr('%30s %0x' % (key, id(icon))) # # Show icons that exist in pyzo.icons. if 0: g.printObj(pyzo.icons, tag='pyzo.icons') if 0: values = list(pyzo.icons.values()) # g.printObj(values, tag='pyzo.icons.values()') g.pr('Action icons in pyzo.icons...') for key, menu in menuBar._menumap.items(): # Keys are menu names, values are menus. for action in menu.actions(): if action.icon() in values: g.pr('FOUND icon: id=%s', id(action.icon())) # # Dump all menus. if 0: for key, menu in menuBar._menumap.items(): # Keys are menu names, values are menus. g.pr('MENU: %s' % key) for action in menu.actions(): g.pr('action: %015x icon: %015x text: %s' % (id(action), id(action.icon()), action.text())) g.pr('')
def dump_list(heading, aList): if heading: print('\n%s...\n' % heading) for aTuple in aList: key, val = aTuple if g.isString(val): if key.endswith(('leo_expanded', 'leo_marked')): if val: print('%30s:' % key) g.printObj(val.split(',')) else: print('%30s: []' % key) else: print('%30s: %s' % (key, val)) elif isinstance(val, (int, float)): print('%30s: %s' % (key, val)) else: print('%30s:' % key) g.printObj(val)
def check(self, unused_s, parent): """True if perfect import checks pass.""" if g.app.suppressImportChecks: g.app.suppressImportChecks = False return True c = self.c sfn = g.shortFileName(self.root.h) s1 = g.toUnicode(self.file_s, self.encoding) s2 = self.trial_write() lines1, lines2 = g.splitLines(s1), g.splitLines(s2) if 0: # An excellent trace for debugging. g.trace(c.shortFileName()) g.printObj(lines1, tag='lines1') g.printObj(lines2, tag='lines2') if self.strict: # Ignore blank lines only. # Adding nodes may add blank lines. lines1 = self.strip_blank_lines(lines1) lines2 = self.strip_blank_lines(lines2) else: # Ignore blank lines and leading whitespace. # Importing may regularize whitespace, and that's good. lines1 = self.strip_all(lines1) lines2 = self.strip_all(lines2) # Forgive trailing whitespace problems in the last line. # This is not the same as clean_last_lines. if lines1 and lines2 and lines1 != lines2: lines1[-1] = lines1[-1].rstrip() + '\n' lines2[-1] = lines2[-1].rstrip() + '\n' # self.trace_lines(lines1, lines2, parent) ok = lines1 == lines2 if not ok and not self.strict: # Issue an error only if something *other than* lws is amiss. lines1, lines2 = self.strip_lws(lines1), self.strip_lws(lines2) ok = lines1 == lines2 if ok and not g.unitTesting: print('warning: leading whitespace changed in:', self.root.h) if not ok: self.show_failure(lines1, lines2, sfn) if g.unitTesting: assert False, 'Perfect import failed!' return ok
def dump_list(heading, aList): if heading: print(f'\n{heading}...\n') for aTuple in aList: key, val = aTuple if isinstance(val, str): if key.startswith('windowState'): print(key) elif key.endswith(('leo_expanded', 'leo_marked')): if val: print(f"{key:30}:") g.printObj(val.split(',')) else: print(f"{key:30}: []") else: print(f"{key:30}: {val}") elif isinstance(val, (int, float)): print(f"{key:30}: {val}") else: print(f"{key:30}:") g.printObj(val)
def show_failure(self, lines1, lines2, sfn): """Print the failing lines, with surrounding context.""" if not g.unitTesting: g.es('@auto failed:', sfn, color='red') n1, n2 = len(lines1), len(lines2) print('\n===== PERFECT IMPORT FAILED =====', sfn) print('len(s1): %s len(s2): %s' % (n1, n2)) n_min = min(n1, n2) for i in range(n_min): line1, line2 = lines1[i], lines2[i] if line1 != line2: print('first mismatched line: %s' % (i + 1)) print('Expected...') print(''.join(self.context_lines(lines1, i))) print('Got...') print(''.join(self.context_lines(lines2, i))) break else: lines_s = 'n2' if n1 > n2 else 'n1' print(f"missing tail lines in {lines_s}") g.printObj(lines1, tag='lines1') g.printObj(lines2, tag='lines2')
def checkForChangedNodes(self, child_tuple, fileName, parent_v): ''' Update the outline described by child_tuple, including all descendants. ''' h, junk_b, gnx, grand_children = child_tuple child_v = self.c.fileCommands.gnxDict.get(gnx) if child_v: self.reportIfNodeChanged(child_tuple, child_v, fileName, parent_v) for grand_child in grand_children: self.checkForChangedNodes(grand_child, fileName, child_v) gnxes_in_cache = set(x[2] for x in grand_children) for_removal = [(i, v) for i, v in enumerate(child_v.children) if v.gnx not in gnxes_in_cache] for i, v in reversed(for_removal): v._cutLink(i, child_v) # # sort children in the order from cache for i, grand_child in enumerate(grand_children): gnx = grand_child[2] v = self.c.fileCommands.gnxDict.get(gnx) if i < len(child_v.children): child_v.children[i] = v elif i == len(child_v.children): g.trace('Warning: dubious cache: please check %s' % fileName) child_v.children.append(v) else: g.trace('Corrupted cache. Use --no-cache') g.printObj(child_v.children) raise IndexError else: # If the outline is out of sync, there may be write errors later, # but the user should be handle them easily enough. isClone, child_v = self.fastAddLastChild(fileName, gnx, parent_v) self.createOutlineFromCacheList(child_v, child_tuple, fileName, top=False)
def runLegacyTest(self, c, p): '''run a legacy rst test.''' rc = c.rstCommands fn = p.h source_p = g.findNodeInTree(c, p, 'source') # source_s1 = source_p.firstChild().b expected_p = g.findNodeInTree(c, p, 'expected') expected_source = expected_p.firstChild().b root = source_p.firstChild() rc.http_server_support = True # Override setting for testing. # # Compute the result. rc.nodeNumber = 0 source = rc.write_rst_tree(root, fn) html = rc.writeToDocutils(p, source, ext='.html') # # Tests... # Don't bother testing the html. It will depend on docutils. if 0: g.printObj(g.splitLines(source), tag='source') g.printObj(g.splitLines(expected_source), tag='expected source') self.assertEqual(expected_source, source, msg='expected_s != got_s') assert html and html.startswith('<?xml') and html.strip().endswith('</html>')
def show_status(self) -> None: """Show status for debugging.""" g.trace('BPM.pid', repr(self.pid)) g.trace('BPM.lock', repr(self.lock)) g.trace('BPM.timer', repr(self.timer), 'active:', self.timer.isActive()) g.printObj(self.data, tag='BPM.data') g.printObj(self.process_queue, tag='BPM.process_queue') g.printObj(self.process_return_data, tag='BPM.process_return_data')
def find_tail(self, p): """ Find the tail (trailing unindented) lines. return head, tail """ lines = self.get_lines(p)[:] tail = [] # First, find all potentially tail lines, including blank lines. while lines: line = lines.pop() if line.lstrip() == line or not line.strip(): tail.append(line) else: break # Next, remove leading blank lines from the tail. while tail: line = tail[-1] if line.strip(): break else: tail.pop(0) if 0: g.printObj(lines, tag=f"lines: find_tail: {p.h}") g.printObj(tail, tag=f"tail: find_tail: {p.h}")
def compute_dicts(self, c1, c2): '''Compute inserted, deleted, changed dictionaries.''' trace = False and not g.unitTesting d1 = {v.fileIndex: v for v in c1.all_unique_nodes()} d2 = {v.fileIndex: v for v in c2.all_unique_nodes()} if trace: g.trace('len(d1)', len(d1.keys())) g.trace('len(d2)', len(d2.keys())) added = {key: d2.get(key) for key in d2 if not d1.get(key)} deleted = {key: d1.get(key) for key in d1 if not d2.get(key)} changed = {} for key in d1: if key in d2: v1 = d1.get(key) v2 = d2.get(key) assert v1 and v2 assert v1.context != v2.context if v1.h != v2.h or v1.b != v2.b: changed[key] = (v1, v2) if trace: for kind, d in (('added', added), ('deleted', deleted), ('changed', changed)): g.trace(kind) g.printObj(d) return added, deleted, changed
def _get_action_list(): """ Return all callable public methods of the server. In effect, these are unit tests. """ import inspect import os server = leoserver.LeoServer() # file_name = "xyzzy.leo" file_name = g.os_path_finalize_join(g.app.loadDir, '..', 'test', 'test.leo') assert os.path.exists(file_name), repr(file_name) log = False exclude_names = [ # Find methods... 'replace_all', 'replace_then_find', 'clone_find_all', 'clone_find_all_flattened', 'clone_find_tag', 'find_all', 'find_def', 'find_next', 'find_previous', 'find_var', 'tag_children', # Other methods 'set_body', 'error', 'replace', 'delete_node', 'cut_node', # dangerous. 'click_button', 'get_buttons', 'remove_button', # Require plugins. 'save_file', # way too dangerous! # 'set_selection', # Not ready yet. 'open_file', 'close_file', # Done by hand. 'import_any_file', 'insert_child_named_node', 'insert_named_node', 'set_ask_result', 'set_opened_file', 'set_search_settings', 'set_selection', 'shut_down', # Don't shut down the server. ] head = [ # ("apply_config", {"config": {"whatever": True}}), ("!error", {}), # ("bad_server_command", {}), ("!open_file", { "filename": file_name, "log": log }), ] head_names = [name for (name, package) in head] tail = [ # ("get_body_length", {}), # All responses now contain len(p.b). ("!find_all", { "find_text": "def" }), ("!get_ua", { "log": log }), ("!get_parent", { "log": log }), ("!get_children", { "log": log }), ("!set_body", { "body": "new body" }), ("!set_headline", { "name": "new headline", 'gnx': "ekr.20061008140603" }), ("contractAllHeadlines", {}), # normal leo command ("!insert_node", {}), ("!contract_node", {}), ("!close_file", { "forced": True }), # forced flag set to true because it was modified ("!get_all_leo_commands", {}), ("!get_all_server_commands", {}), ("!shut_down", {}), ] tail_names = [name for (name, package) in tail] # Add all remaining methods to the middle. tests = inspect.getmembers(server, inspect.ismethod) test_names = sorted( [name for (name, value) in tests if not name.startswith('_')]) middle: List = [("!" + z, {}) for z in test_names if z not in head_names + tail_names + exclude_names] middle_names = [name for (name, package) in middle] # type:ignore all_tests = head + middle + tail # type:ignore if 0: g.printObj(middle_names, tag='middle_names') all_names = sorted([name for (name, package) in all_tests]) g.printObj(all_names, tag='all_names') return all_tests
def get_new_dict(self, context): ''' Return a *general* state dictionary for the given context. Subclasses may override... ''' trace = 'importers' in g.app.debug comment, block1, block2 = self.single_comment, self.block1, self.block2 def add_key(d, key, data): aList = d.get(key, []) aList.append(data) d[key] = aList if context: d = { # key kind pattern ends? '\\': [ ('len+1', '\\', None), ], '"': [ ('len', '"', context == '"'), ], "'": [ ('len', "'", context == "'"), ], } if block1 and block2: add_key(d, block2[0], ('len', block2, True)) # #1717. else: # Not in any context. d = { # key kind pattern new-ctx deltas '\\': [ ('len+1', '\\', context, None), ], '<': [ ('<<<', '<<<', '<<<', None), ], '"': [ ('len', '"', '"', None), ], "'": [ ('len', "'", "'", None), ], '{': [ ('len', '{', context, (1, 0, 0)), ], '}': [ ('len', '}', context, (-1, 0, 0)), ], '(': [ ('len', '(', context, (0, 1, 0)), ], ')': [ ('len', ')', context, (0, -1, 0)), ], '[': [ ('len', '[', context, (0, 0, 1)), ], ']': [ ('len', ']', context, (0, 0, -1)), ], } if comment: add_key(d, comment[0], ('all', comment, '', None)) if block1 and block2: add_key(d, block1[0], ('len', block1, block1, None)) if trace: g.trace(f"{comment!r} {block1!r} {block2!r}") g.printObj(d, tag=f"scan table for context {context!r}") return d
def _get_action_list(): """ Return all callable public methods of the server. In effect, these are unit tests. """ import inspect import os server = leoserver.LeoServer() # file_name = "xyzzy.leo" file_name = g.os_path_finalize_join(g.app.loadDir, '..', 'test', 'test.leo') assert os.path.exists(file_name), repr(file_name) log = False exclude_names = [ # Dangerous at present. 'delete_node', 'cut_node', 'save_file', # Require plugins. 'click_button', 'get_buttons', 'remove_button', # Not ready yet. 'set_selection', ] head = [ ("get_sign_on", {}), # ("apply_config", {"config": {"whatever": True}}), ("error", {}), # ("bad_server_command", {}), ("open_file", { "filename": file_name, "log": log }), ] head_names = [name for (name, package) in head] tail = [ # ("get_body_length", {}), # All responses now contain len(p.b). ("find_all", { "find_text": "def" }), ("get_ua", { "log": log }), ("get_parent", { "log": log }), ("get_children", { "log": log }), ("set_body", { "body": "new body" }), ("set_headline", { "headline": "new headline" }), ("execute-leo-command", { "leo-command-name": "contract-all" }), ("insert_node", { "headline": "inserted headline" }), ("contract_node", {}), ("close_file", { "filename": file_name }), ("get_all_leo_commands", {}), ("get_all_server_commands", {}), ("shut_down", {}), ] tail_names = [name for (name, package) in tail] # Add all remaining methods to the middle. tests = inspect.getmembers(server, inspect.ismethod) test_names = sorted( [name for (name, value) in tests if not name.startswith('_')]) middle = [(z, {}) for z in test_names if z not in head_names + tail_names + exclude_names] middle_names = [name for (name, package) in middle] all_tests = head + middle + tail if 0: g.printObj(middle_names, tag='middle_names') all_names = sorted([name for (name, package) in all_tests]) g.printObj(all_names, tag='all_names') return all_tests
def print_layout_c(checked, splitter=splitter): layout = splitter.top().get_layout() g.printObj(layout)
def show(obj, tag, dump): print(f"{tag}...\n") if dump: g.printObj(obj) else: print(obj)