def souptest_fragment(fragment):
 souptest_doctype = getattr(souptest_fragment, 'souptest_doctype', None)
 if (souptest_doctype is None):
  with open(ENTITY_DTD_PATH, 'r') as ent_file:
   souptest_doctype = (SOUPTEST_DOCTYPE_FMT % ent_file.read())
  souptest_fragment.souptest_doctype = souptest_doctype
 if ('<![CDATA' in fragment):
  raise SoupUnexpectedCDataSectionError(fragment)
 documentized_fragment = ('%s<div>%s</div>' % (souptest_doctype, fragment))
 s = StringIO(documentized_fragment)
 try:
  parser = lxml.etree.XMLParser()
  for node in lxml.etree.parse(s, parser).iter():
   souptest_sniff_node(node)
 except lxml.etree.XMLSyntaxError:
  (type_, value, trace) = sys.exc_info()
  if value.msg.startswith('xmlParseCharRef: invalid xmlChar '):
   raise SoupUnsupportedEntityError, (value,), trace
  undef_ent = re.match(UNDEFINED_ENTITY_RE, value.msg)
  if undef_ent:
   raise SoupUnsupportedEntityError, (value, undef_ent.group(1)), trace
  raise SoupSyntaxError, (value,), trace

def souptest_fragment ( fragment ) : souptest_doctype = getattr ( souptest_fragment , 'souptest_doctype' , None ) if ( souptest_doctype is None ) : with open ( ENTITY_DTD_PATH , 'r' ) as ent_file : souptest_doctype = ( SOUPTEST_DOCTYPE_FMT % ent_file . read ( ) ) souptest_fragment . souptest_doctype = souptest_doctype if ( '<![CDATA' in fragment ) : raise SoupUnexpectedCDataSectionError ( fragment ) documentized_fragment = ( '%s<div>%s</div>' % ( souptest_doctype , fragment ) ) s = StringIO ( documentized_fragment ) try : parser = lxml . etree . XMLParser ( ) for node in lxml . etree . parse ( s , parser ) . iter ( ) : souptest_sniff_node ( node ) except lxml . etree . XMLSyntaxError : ( type_ , value , trace ) = sys . exc_info ( ) if value . msg . startswith ( 'xmlParseCharRef: invalid xmlChar ' ) : raise SoupUnsupportedEntityError , ( value , ) , trace undef_ent = re . match ( UNDEFINED_ENTITY_RE , value . msg ) if undef_ent : raise SoupUnsupportedEntityError , ( value , undef_ent . group ( 1 ) ) , trace raise SoupSyntaxError , ( value , ) , trace
check if an html fragment is sane and safe to embed .