Best Python code snippet using pytest-benchmark
build_manpage.py
Source:build_manpage.py  
1#!/usr/bin/env python32from datetime import date3from io import StringIO4from lxml import etree5import markdown6from markdown.extensions import Extension7import re8import sys9import yaml10# Prevent our markdown parser from trying to help by interpreting things in angle brackets as HTML tags.11class EscapeHtml(Extension):12  def extendMarkdown(self, md, md_globals):13    del md.preprocessors['html_block']14    del md.inlinePatterns['html']15class RoffWalker(object):16  def __init__(self, tree, output=sys.stdout):17    self.tree = tree18    self.target = output19    self.f = StringIO()20  def walk(self):21    self._walk(self.tree, parent_tag=None)22    # We don't want to start lines with \. because that can confuse man23    # For lines that start with \., we need to prefix them with \& so it24    # knows not to treat that line as a directive25    data = re.sub(r'^\\\.', r'\&.', self.f.getvalue(), flags=re.MULTILINE)26    self.target.write(data)27  def _ul_is_special(self, root):28    if len(root) != 1:29      return False30    child = root[0]31    if child.tag != 'li':32      return False33    msg = ''.join(child.itertext()).strip()34    return msg.endswith(':')35  def _walk_child(self, root):36    if len(root) > 0:37      self._walk(root[0], parent_tag=root.tag)38  def _write_element(self, root, ensure_newline=True):39    if root.text is not None:40      text = self._sanitize(root.text)41      self.__write_raw(text)42    self._walk_child(root)43    self._write_tail(root, ensure_newline=ensure_newline)44  def _write_tail(self, root, ensure_newline=False, inline=False):45    if root.tail is not None:46      if inline or root.tail != '\n':47        text = self._sanitize(root.tail)48        if text.endswith('\n'):49          ensure_newline = False50        self.__write_raw(text)51    if ensure_newline:52      self.__write_raw('\n')53  def _walk(self, root, parent_tag=None):54    last_tag = None55    while root is not None:56      if root.tag == 'h1':57        self.__write_cmd('.TH "JQ" "1" "{}" "" ""'.format(date.today().strftime('%B %Y')))58        self.__write_cmd('.SH "NAME"')59        # TODO: properly parse this60        self.__write_raw(r'\fBjq\fR \- Command\-line JSON processor' + "\n")61      elif root.tag == 'h2':62        self.__write_cmd('.SH "{}"'.format(''.join(root.itertext()).strip()))63      elif root.tag == 'h3':64        text = ''.join(root.itertext()).strip()65        self.__write_cmd('.SS "{}"'.format(self._h3_sanitize(text)))66      elif root.tag == 'p':67        if last_tag not in ['h2', 'h3'] and parent_tag not in ['li']:68          self.__write_cmd('.P')69        self._write_element(root, ensure_newline=(parent_tag != 'li'))70      elif root.tag == 'ul':71        if self._ul_is_special(root):72          li = root[0]73          self.__write_cmd('.TP')74          self._write_element(li)75          next = root.getnext()76          while next is not None and next.tag == 'p':77            if next.getnext() is not None and next.getnext().tag == 'pre':78              # we don't want to .IP these, because it'll look funny with the code indent79              break80            self.__write_cmd('.IP')81            self._write_element(next)82            root = next83            next = root.getnext()84        else:85          self._walk_child(root)86          self._write_tail(root)87          # A pre tag after the end of a list doesn't want two of the indentation commands88          if root.getnext() is None or root.getnext().tag != 'pre':89            self.__write_cmd('.IP "" 0')90      elif root.tag == 'li':91        self.__write_cmd(r'.IP "\(bu" 4')92        if root.text is not None and root.text.strip() != '':93          text = self._sanitize(root.text)94          self.__write_raw(text)95        self._walk_child(root)96        self._write_tail(root, ensure_newline=True)97      elif root.tag == 'strong':98        if root.text is not None:99          text = self._sanitize(root.text)100          self.__write_raw('\\fB{}\\fR'.format(text))101        self._write_tail(root, inline=True)102      elif root.tag == 'em':103        if root.text is not None:104          text = self._sanitize(root.text)105          self.__write_raw('\\fI{}\\fR'.format(text))106        self._write_tail(root, inline=True)107      elif root.tag == 'code':108        if root.text is not None:109          text = self._code_sanitize(root.text)110          self.__write_raw('\\fB{}\\fR'.format(text))111        self._write_tail(root, inline=True)112      elif root.tag == 'pre':113        self.__write_cmd('.IP "" 4')114        self.__write_cmd('.nf\n') # extra newline for spacing reasons115        next = root116        first = True117        while next is not None and next.tag == 'pre':118          if not first:119            self.__write_raw('\n')120          text = ''.join(next.itertext(with_tail=False))121          self.__write_raw(self._pre_sanitize(text))122          first = False123          root = next124          next = next.getnext()125        self.__write_cmd('.fi')126        self.__write_cmd('.IP "" 0')127      else:128        self._walk_child(root)129      last_tag = root.tag130      root = root.getnext()131  def _base_sanitize(self, text):132    text = re.sub(r'\\', r'\\e', text)133    text = re.sub(r'\.', r'\\.', text)134    text = re.sub("'", r"\'", text)135    text = re.sub('-', r'\-', text)136    return text137  def _pre_sanitize(self, text):138    return self._base_sanitize(text)139  def _code_sanitize(self, text):140    text = self._base_sanitize(text)141    text = re.sub(r'\s', ' ', text)142    return text143  def _h3_sanitize(self, text):144    text = self._base_sanitize(text)145    text = re.sub(' \n|\n ', ' ', text)146    text = re.sub('\n', ' ', text)147    return text148  def _sanitize(self, text):149    text = self._base_sanitize(text)150    text = re.sub(r'<([^>]+)>', r'\\fI\1\\fR', text)151    text = re.sub(r' +', ' ', text)152    text = re.sub('\n', ' ', text)153    return text154  def __write_cmd(self, dat):155    print('.', dat, sep='\n', file=self.f)156    pass157  def __write_raw(self, dat):158    print(dat, sep='', end='', file=self.f)159    pass160def load_yml_file(fn):161  with open(fn) as f:162    return yaml.load(f)163def dedent_body(body):164  lines = [re.sub(r'^  (\S)', r'\1', l) for l in body.split('\n')]165  return '\n'.join(lines)166def convert_manual_to_markdown():167  f = StringIO()168  manual = load_yml_file("content/manual/manual.yml")169  f.write(manual.get('manpage_intro', '\n'))170  f.write(dedent_body(manual.get('body', '\n')))171  for section in manual.get('sections', []):172    f.write('## {}\n'.format(section.get('title', '').upper()))173    f.write(dedent_body(section.get('body', '\n')))174    f.write('\n')175    for entry in section.get('entries', []):176      f.write('### {}\n'.format(entry.get('title', '')))177      f.write(dedent_body(entry.get('body', '\n')))178      f.write('\n')179      if entry.get('examples') is not None:180        f.write("~~~~\n")181        first = True182        for example in entry.get('examples'):183          if not first:184            f.write('\n')185          f.write("jq '{}'\n".format(example.get('program', '')))186          f.write("   {}\n".format(example.get('input', '')))187          output = [str(x) for x in example.get('output', [])]188          f.write("=> {}\n".format(', '.join(output)))189          first = False190        f.write("~~~~\n")191    f.write('\n')192  f.write(manual.get('manpage_epilogue', ''))193  return f.getvalue()194# Convert manual.yml to our special markdown format195markdown_data = convert_manual_to_markdown()196# Convert markdown to html197html_data = markdown.markdown(markdown_data, extensions=[EscapeHtml(), 'fenced_code'])198# Parse the html into a tree so we can walk it199tr = etree.HTML(html_data, etree.HTMLParser())200# Convert the markdown to ROFF...pytest_plugin.py
Source:pytest_plugin.py  
...68        tr = terminalreporter69        tr.section("Jupyter notebooks")70        for nb_path, reps in self._reports_by_nb.items():71            tr.section(nb_path.name)72            tr.ensure_newline()73            tr.write_line(f"Path: {str(nb_path)}")74            tr.ensure_newline()75            tr.write_line("Test outcomes:")76            tr.ensure_newline()77            for rep in reps: 78                outcome_summary = self._get_test_outcome_summary(rep)79                test_loc_summary = self._get_test_location_summary(rep)80                tr.write_line(f"{outcome_summary}\t{test_loc_summary}")81plugin = NBCheck(82    nb_paths=_get_nb_paths(search_root_dir=Path("."))...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
