Best Python code snippet using assertpy_python
xml_driver.py
Source:xml_driver.py
...9 This is the base structure that handles the tree created by XMLElement10 and XMLHandler. Overriding __getattr__ allows us to chain queries on11 a list in order to traverse the tree.12 """13 def contents_of(self, tag, default=['']):14 res = []15 for item in self:16 res.extend( item.contents_of(tag) )17 return ChainList(res) if res else default18 def __getattr__(self, key):19 res = []20 scope = deque(self)21 while scope:22 current = scope.popleft()23 if current._name == key: res.append(current)24 else: scope.extend(current.children)25 return ChainList(res)26class XMLElement(object):27 """28 Represents XML elements from a document. These will assist29 us in representing an XML document as a Python object.30 Heavily inspired from: https://github.com/stchris/untangle/blob/master/untangle.py31 """32 def __init__(self, name, attributes):33 self._name = name34 self._attributes = attributes35 self.content = []36 self.children = ChainList()37 self.is_root = False38 def __iter__(self):39 yield self40 def __nonzero__(self):41 return self.is_root or self._name is not None42 def __getitem__(self, key):43 return self.get_attribute(key)44 def __getattr__(self, key):45 res = []46 scope = deque(self.children)47 while scope:48 current = scope.popleft()49 if current._name == key: res.append(current)50 else: scope.extend(current.children)51 if res:52 self.__dict__[key] = ChainList(res)53 return ChainList(res)54 else:55 return ChainList('')56 def contents_of(self, key, default=ChainList('')):57 candidates = self.__getattr__(key)58 if candidates:59 return [x.get_content() for x in candidates]60 else:61 return default62 def get_content(self):63 if len(self.content) == 1:64 return self.content[0]65 else: return self.content66 def add_child(self, child):67 self.children.append(child)68 def get_attribute(self, key):69 return self._attributes.get(key, None)70 def get_xmlelements(self, name):71 return filter(lambda x: x._name == name, self.children) \72 if name else \73 self.children74class XMLHandler(handler.ContentHandler):75 """76 SAX Handler to create the Python object while parsing77 """78 def __init__(self):79 self.root = XMLElement(None, None)80 self.root.is_root = True81 self.elements = ChainList()82 def startElement(self, name, attributes):83 name = name.replace('-','_').replace('.','_').replace(':','_')84 xmlelem = XMLElement(name, dict(attributes.items()))85 if self.elements:86 self.elements[-1].add_child(xmlelem)87 else:88 self.root.add_child(xmlelem)89 self.elements.append(xmlelem)90 def endElement(self, name):91 if self.elements:92 self.elements.pop()93 def characters(self, content):94 if content.strip():95 if self.elements[-1]._name == 'sub':96 newtxt = u"<sub>"+content+u"</sub>"97 self.elements[-2].content.append(newtxt)98 else:99 self.elements[-1].content.append(saxutils.unescape(content))100class Patent(object):101 def __init__(self, filename):102 xh = XMLHandler()103 parser = make_parser()104 parser.setContentHandler(xh)105 parser.setFeature(handler.feature_external_ges, False)106 parser.parse(filename)107 self.xml = xh.root.us_patent_grant.us_bibliographic_data_grant108 self.country = self.xml.publication_reference.contents_of('country')[0]109 self.patent = self.xml.publication_reference.contents_of('doc_number')[0]110 self.kind = self.xml.publication_reference.contents_of('kind')[0]111 self.date_grant = self.xml.publication_reference.contents_of('date')[0]112 self.pat_type = self.xml.application_reference[0].get_attribute('appl-type')113 self.date_app = self.xml.application_reference.contents_of('date')[0]114 self.country_app = self.xml.application_reference.contents_of('country')[0]115 self.patent_app = self.xml.application_reference.contents_of('doc_number')[0]116 self.code_app = self.xml.contents_of('us_application_series_code')[0]117 self.clm_num = self.xml.contents_of('number_of_claims')[0]118 self.classes = self._classes()119 self.abstract = self.xml.contents_of('abstract','')120 self.invention_title = self.xml.contents_of('invention_title')[0]121 self.asg_list = self._asg_list()122 self.cit_list = self._cit_list()123 self.rel_list = self._rel_list()124 self.inv_list = self._inv_list()125 self.law_list = self._law_list()126 def has_content(self, l):127 return any(filter(lambda x: x, l))128 def _classes(self):129 main = self.xml.classification_national.contents_of('main_classification')130 further = self.xml.classification_national.contents_of('further_classification')131 it = [main[0] if self.has_content(main) else []]132 if self.has_content(further):133 it.extend(further)134 return [ [x[:3].replace(' ',''), x[3:].replace(' ','')] for x in it]135 def _asg_list(self):136 doc = self.xml.assignees.assignee137 data = []138 if not doc: return []139 if doc.first_name:140 data = [1]141 data.extend(doc.contents_of('last_name'))142 data.extend(doc.contents_of('first_name'))143 else:144 data = [0]145 data.extend(doc.contents_of('orgname'))146 data.extend(doc.contents_of('role'))147 for tag in ['street','city','state','country','postcode']:148 data.extend(doc.addressbook.address.contents_of(tag))149 data.extend(doc.nationality.contents_of('country'))150 data.extend(doc.residence.contents_of('country'))151 return [data]152 def _escape_html_nosub(self, string):153 lt = re.compile('<(?!/?sub>)')154 gt = re.compile('(?=.)*(?<!sub)>')155 string = string.replace('&','&')156 string = re.sub(lt,"<",string)157 string = re.sub(gt,">",string)158 return string159 def _extend_padding(self, ls_of_ls, padding=''):160 """161 Takes in a lists of lists, returns a new list of lists162 where each list is padded up to the length of the longest163 list by [padding] (defaults to the empty string)164 """165 maxlen = max(map(len, ls_of_ls))166 newls = []167 for ls in ls_of_ls:168 if len(ls) != maxlen:169 ls.extend([padding]*(maxlen - len(ls)))170 newls.append(ls)171 return newls172 def _flatten(self, ls_of_ls):173 """174 Takes in a list of lists, returns a new list of lists175 where list `i` contains the `i`th element from the original176 set of lists.177 """178 return map(list, list(izip(*ls_of_ls)))179 #TODO: fix text encodings 180 def _cit_list(self):181 res = []182 cits = self.xml.references_cited.citation183 record = cits.contents_of('category')184 res.append(record)185 if cits.patcit:186 for tag in ['country','doc_number','date','kind','name']:187 res.append(cits.patcit.contents_of(tag))188 res[0].extend(self._extend_padding(res[1:]))189 res.append( [''] * max(map(len, res)))190 contacts = self._flatten(res)191 last_records = record[len(contacts):]192 if cits.othercit:193 for rec,cit in zip(last_records,cits.contents_of('othercit')):194 tmp = [rec, '', '', '', '' ,'']195 s = ''.join([self._escape_html_nosub(x) for x in cit])196 tmp.append(s)197 contacts.append(tmp)198 return contacts199 def _rel_list(self):200 res = []201 for tag in ['continuation_in_part','continuation','division','reissue']:202 if not self.xml.__getattr__(tag):203 continue204 tag = tag.replace('_','-')205 if self.xml.relation.child_doc:206 tmp = [tag, -1]207 for nested in ['doc_number','country','kind']:208 tmp.extend(self.xml.relation.child_doc.contents_of(nested))209 res.append(tmp)210 if self.xml.relation.parent_doc:211 tmp = [tag, 1]212 for nested in ['doc_number','country','kind','date','parent_status']:213 data = self.xml.relation.parent_doc.contents_of(nested)214 tmp.append(data[0] if isinstance(data, list) else data)215 res.append(tmp)216 if self.xml.relation.parent_doc.parent_grant_document:217 tmp = [tag, 1]218 for nested in ['doc_number','country','kind','date','parent_status']:219 tmp.extend(self.xml.relation.parent_grant_document.contents_of(nested))220 res.append(tmp)221 if self.xml.relation.parent_doc.parent_pct_document:222 tmp = [tag, 1]223 for nested in ['doc_number','country','kind','date','parent_status']:224 tmp.extend(self.xml.relation.parent_pct_document.contents_of(nested))225 res.append(tmp)226 if res: break227 for tag in ['related-publication','us-provisional-application']:228 if not self.xml.__getattr__(tag):229 continue230 if self.xml.document_id:231 tmp = [tag, 0]232 for nested in ['doc_number','country','kind']:233 tmp.extend(self.xml.document_id.contents_of(nested))234 res.append(tmp)235 if res: break236 return res237 def _inv_list(self):238 doc = self.xml.parties.applicant239 if not doc: return []240 res = []241 res.append(doc.addressbook.contents_of('last_name'))242 res.append(doc.addressbook.contents_of('first_name'))243 for tag in ['street','city','state','country','postcode']:244 data = doc.addressbook.address.contents_of(tag)245 if any(map(lambda x: isinstance(x, list), data)):246 data = [''.join(x) for x in data]247 res.append(data)248 res.append(doc.nationality.contents_of('country'))249 res.append(doc.residence.contents_of('country'))250 maxlen = max(map(len, res))251 res = [x*maxlen if len(x) != maxlen else x for x in res]252 return self._flatten(res)253 def _law_list(self):254 doc = self.xml.parties.agents255 if not doc: return []256 res = []257 for agent in doc.agent:258 tmp = []259 for tag in ['last_name','first_name','country','orgname']:260 data = agent.contents_of(tag)261 tmp.extend([''.join(x) for x in data] if data else [''])262 res.append(tmp)...
convert-e2e-test.py
Source:convert-e2e-test.py
...8def prepare_test_directory(test_dir):9 if os.path.exists(test_dir):10 shutil.rmtree(test_dir)11 os.makedirs(test_dir)12def contents_of(*elements):13 path = os.path.join(*elements)14 with open(path) as file_to_read:15 return file_to_read.read()16# TODO: Add tests for image in right place, image title17class ConverterTest(TestCase):18 def test_convert_creates_markdown_from_branch_titles(self):19 test_dir = './data/test/'20 prepare_test_directory(test_dir)21 shutil.copy('data/OTW-Afternoondemos.mm', 'data/test/OTW-Afternoondemos.mm')22 converter = Converter('data/test/OTW-Afternoondemos.mm')23 converter.convert_map()24 md = contents_of(test_dir, 'manuscript','Chapter0.txt')25 assert_that(md, contains_string('{frontmatter}\n\n#Introduction\n\n'))26 md = contents_of(test_dir, 'manuscript','Chapter1.txt')27 assert_that(md, contains_string('{mainmatter}\n\n#Richard Bowman\n\n'))28 assert_that(md, contains_string('\n\n##3d Printed Platform for Microscopy\n\n'))29 md = contents_of(test_dir, 'manuscript','Chapter3.txt')30 assert_that(md, contains_string('\n\n#Josie Hughes and James Ritchie'))31 assert_that(md, contains_string('\n{width=30%, float=right}\n'))32 md = contents_of(test_dir, 'manuscript','Chapter5.txt')33 assert_that(md, contains_string('\n\nPratap is a year 10 student at the Perse School, Cambridge. \n\n')) ## space!34 script = contents_of(test_dir, 'copy-images.sh')35 assert_that(script, contains_string('#! /usr/bin/bash\n'))36 assert_that(script, contains_string('cp ../../../Dropbox/rareblog/images/opentechworkshop/josie.jpg data/test/manuscript/images/\n'))37if __name__ == '__main__':...
test_util.py
Source:test_util.py
...9 def __call__(self, tokens):10 tokens.push(self.ch)11 def __repr__(self):12 return f"[Thing {self.ch}]"13 def contents_of(e):14 return ''.join([str(t) for t in e.another(on_eof='exhaust')])15 with expander_on_string("") as e:16 e.push('wombat')17 e.push(Thing('3'))18 e.push(Thing('2'))19 put_internal_after_other_internals(e, Thing('1'))20 assert contents_of(e)=='231wombat', \21 'pushes after other internals'22 with expander_on_string("") as e:23 e.push(Thing('3'))24 e.push(Thing('2'))25 put_internal_after_other_internals(e, Thing('1'))26 assert contents_of(e)=='231', 'eof is a non-internal'27 with expander_on_string("") as e:28 e.push(yex.parse.Letter('q'))29 e.push(Thing('3'))30 e.push(Thing('2'))31 put_internal_after_other_internals(e, Thing('1'))32 assert contents_of(e)=='231q', \33 'non-internal tokens aren\'t internal'34 with expander_on_string("") as e:35 put_internal_after_other_internals(e, Thing('1'))36 assert contents_of(e)=='1', 'works on empty string'37 with expander_on_string("") as e:38 e.push('wombat')39 put_internal_after_other_internals(e, Thing('1'))40 assert contents_of(e)=='1wombat', \...
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!!